diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 175e1940a..c92383278 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -27871,3 +27871,22 @@ - `avatar-image-2057.test.ts` 的「其后只有一份迁移」改为两份(注明原值/新值/原因)。 - 关联记录:BUG-2067、BUG-1872、BUG-1971。 - 修复版本:`claude/seconds-2074`。 + +## BUG-2072 | 报告写好了没有人告诉用户:离开报告页或切到别的标签页之后,只能自己回去看 + +- 状态:fixed-pending-verify(待测试环境真机确认;系统通知弹出来的样子要负责人在自己的浏览器里看一次)。 +- 首次发现 / 最近更新:2026-11-20 / 2026-11-20。 +- 触发与现象:个人报告约三分钟、年运和合盘更久。开始弹窗写着「可以先去别的页面」,但去了别的页面之后,报告写好没有任何提示;标签页切到后台也一样。负责人 2026-11-20 确认原型:提醒默认就有,不让用户选,只出现浏览器自己的权限询问。 +- 触发条件:开始生成任意一种报告后离开它的页面,或把标签页放到后台。 +- 根因:进度是各页面自己轮询的,用的是「标签页一到后台就停」的轮询;离开那个页面就没有人再问状态。全站没有带按钮的提示,没有改标题和系统通知的代码。唯一能问状态的接口 `GET /api/reports/:id` 在报告写好后会带回整份正文,不适合在后台反复问。 +- 修复: + 1. 新接口 `GET /api/reports/status?ids=`:一次最多 10 个,只回 `id / status / reportType` 三项,用登录用户自己的身份读(不用服务端身份,BUG-2057 的教训),再按用户过滤;别人的或不存在的报告不出现在结果里。不动数据库。 + 2. 应用外壳里挂一个不画任何东西的 `ReportReminderWatcher`:三处「开始」成功后登记这份报告(存在本机浏览器里,读写都容错,存不了就只在当前页面记着),之后每 10 秒问一次,标签页在后台时 30 秒一次;没有在等的报告就完全不问;写好、失败或查不到就不再问。 + 3. 不重复问:报告页、年运页、「我的报告」列表本来就自己轮询,它们把看到的状态告诉外壳,外壳 30 秒内不再问这一份;页面当着用户的面看到写好,就什么都不提醒。 + 4. 三层提醒:系统提示加「查看」(`notifyAction`,6 秒,回到这份报告自己的页面时不出);标签页在后台时把标题换成「报告好了,Jyotisha」,回到标签页恢复;浏览器允许时再发一条系统通知,点它回到这份报告。文字只有报告的种类,没有名字和出生资料。失败时说「没有写成,点数已退回」。 + 5. 权限只问一次:在点「开始」的那一次点击里调浏览器自己的询问,不等它;用户答过或关掉之后不再问;不支持通知、非安全页面、被嵌在别的页面里都直接跳过。没有任何开关和说明行。 + 6. 多个标签页同时开着:先看到写好的那个提醒,其余的不重复;系统通知按报告 id 合并。 +- 这一版做不到的:本站的标签页全部关掉后收不到;iPhone 的 Safari 只有添加到主屏幕的网站能发系统通知(前两层照常);换了设备或清了浏览器数据后,之前开始的报告不会被接着等。问答的回答这次没有做提醒。 +- 验证与防复发:`frontend/tests/report-reminders-2072.test.ts`(14 条):接口未登录 401、只回本人的、不回正文、超过 10 个 400;登记、刷新后接着等、存储被禁用时照常、写好只提醒一次、后台标签页出标题和通知、页面自己在轮询时不重复问、两个标签页只提醒一次;权限只在点击里问一次;标题能恢复;外壳的组件不使用「后台就停」的轮询;没有提醒开关。真实的权限询问、后台定时器的实际间隔和通知的样子本机验证不了。 +- 关联记录:BUG-2046(开始弹窗与进度卡)、BUG-2056(操作结果用系统提示)、BUG-2057(用登录用户身份读)。 +- 修复版本:`claude/reminders-2072`。 diff --git a/frontend/DESIGN.md b/frontend/DESIGN.md index 96d81f9b1..15954ace7 100644 --- a/frontend/DESIGN.md +++ b/frontend/DESIGN.md @@ -636,6 +636,7 @@ Action results and errors never take page layout. They are toasts from `src/lib/ - **Look:** a compact `--color-canvas` card, 1px `--color-border`, `--radius-lg`, `--shadow-elevated`, body-sm text, a coloured icon (success `--color-success`, error `--color-danger`, info `--color-ink-secondary`). No left bar, no tinted background. - **How long:** success and info 3s; errors 6s with a close button on the right; the staging fixed login code 10s. Messages from one surface share an id, so a new one replaces the last instead of stacking (login uses `auth-notice` / `auth-error`; typing dismisses the stale error). - **Above modal dialogs:** a toast raised while a modal `` is open (反馈与投诉, 导出, 协议更新, 那一刻的天空) moves the toaster into the top layer as a manual popover, re-shown on every toast, so it is never under the dialog's backdrop. +- **A toast with a button (BUG-2072):** `notifyAction(message, { label, onClick })` for a result the user may want to open, such as a report that finished while they were on another page (「个人报告好了」 + 「查看」). Six seconds, the product's quiet outline button on the right, never a row in the page. The same moment also changes the tab title (「报告好了,Jyotisha」, restored on return) and, in a background tab when the browser allows it, shows a system notification. Reminders have no setting; the only question is the browser's own permission dialog, asked once inside the click that starts a report (`lib/report-reminders.ts`). - **Errors held in flow state** (the birth-time guided flow) are said through ``: once per new message, id = message. - **What stays in the page:** states that are the page's content, not a report about an action — a pane that failed to load with its own 重试 (chart, ephemeris, report list, report detail, the home bootstrap error, billing packages / payment status); empty states; the failed reply inside a conversation (`.error-message`) and the stopped-reply line; rectification progress and gap notes; the feedback dialog's done panel; a field's own validation inside the evidence draft card. What remains of `.form-error` is plain `--color-danger` caption text, no bar and no background; `.form-success` is gone. diff --git a/frontend/src/app/(app)/layout.tsx b/frontend/src/app/(app)/layout.tsx index 97d74f3be..5ae2fb815 100644 --- a/frontend/src/app/(app)/layout.tsx +++ b/frontend/src/app/(app)/layout.tsx @@ -7,6 +7,7 @@ import { usePathname, useRouter } from "next/navigation"; import { AccountDeletionGate } from "@/components/account-deletion-gate"; import { AppSidebar } from "@/components/app-sidebar"; import { LegalConsentGate } from "@/components/legal/legal-consent-gate"; +import { ReportReminderWatcher } from "@/components/report-reminder-watcher"; import { PageCurtain } from "@/components/page-curtain"; import { PageSwitch } from "@/components/shell-motion"; import { ShellFrame } from "@/components/shell-frame"; @@ -86,6 +87,8 @@ function AppShell({ children }: { children: ReactNode }) { onConfirm={sessionActions.confirmDeletion} /> + {/* A report that finishes while the user is elsewhere says so (BUG-2072). */} + diff --git a/frontend/src/app/api/reports/status/route.ts b/frontend/src/app/api/reports/status/route.ts new file mode 100644 index 000000000..2d05f2a99 --- /dev/null +++ b/frontend/src/app/api/reports/status/route.ts @@ -0,0 +1,28 @@ +import { NextResponse } from "next/server"; + +import { readReportStatuses } from "@/lib/report-status-server"; +import { sanitizedErrorReason } from "@/lib/safe-error-reason"; +import { isSupabaseConfigurationError } from "@/lib/supabase/config"; +import { createServerSupabaseClient } from "@/lib/supabase/server"; + +export const runtime = "nodejs"; + +/** The state of a few reports the viewer is waiting for (BUG-2072). No report body. */ +export async function GET(request: Request) { + try { + const supabase = await createServerSupabaseClient(); + const { data: { user }, error } = await supabase.auth.getUser(); + const result = await readReportStatuses({ + userId: error || !user ? null : user.id, + supabase, + ids: new URL(request.url).searchParams.get("ids"), + }); + return NextResponse.json(result.body, { status: result.status, headers: { "Cache-Control": "no-store" } }); + } catch (error) { + if (isSupabaseConfigurationError(error)) { + return NextResponse.json({ error: "数据库尚未配置", code: "DATABASE_NOT_CONFIGURED" }, { status: 503 }); + } + console.error(`[reports] status read failed reason=${sanitizedErrorReason(error)}`); + return NextResponse.json({ error: "报告状态暂时读不到" }, { status: 500 }); + } +} diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 7e6be23ee..dc417014c 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -609,6 +609,9 @@ button:disabled:where(:not([data-slot="button"])) { cursor: default; opacity: .4 [data-sonner-toast][data-type="error"] { padding-right: 36px !important; } [data-sonner-toast] [data-close-button] { left: auto !important; right: 8px !important; top: 50% !important; transform: translateY(-50%) !important; border: 0 !important; background: transparent !important; color: var(--color-ink-tertiary) !important; } [data-sonner-toast] [data-close-button]:hover { color: var(--color-ink) !important; } +/* BUG-2072: the button on a toast (「查看」) is the product's quiet outline button, not sonner's dark chip. */ +[data-sonner-toast] [data-button] { height: 28px !important; margin-left: auto !important; padding: 0 12px !important; border: 1px solid var(--color-border) !important; border-radius: var(--radius-md) !important; background: transparent !important; color: var(--color-ink) !important; font-size: var(--type-body-sm) !important; font-weight: 600 !important; white-space: nowrap; } +[data-sonner-toast] [data-button]:hover { background: var(--color-canvas-muted) !important; } /* The toaster host once it has joined the top layer above a modal dialog (liftToastsAboveModal): a zero-size, transparent anchor; the list inside keeps its own fixed position. */ diff --git a/frontend/src/components/annual/annual-report-page.tsx b/frontend/src/components/annual/annual-report-page.tsx index 1f49c4697..f9112822f 100644 --- a/frontend/src/components/annual/annual-report-page.tsx +++ b/frontend/src/components/annual/annual-report-page.tsx @@ -25,6 +25,7 @@ import { useVisibilityAwarePoll } from "@/hooks/use-visibility-aware-poll"; import { accountDialogHref } from "@/lib/account-dialog-intent"; import { reportPriceLine, reportStartErrorFor } from "@/lib/report-start-copy"; import { notifyError } from "@/lib/notify"; +import { askNotificationPermissionOnce, reportStatusesSeen, watchStartedReport } from "@/lib/report-reminders"; import { readCurrentSubjectId, useCurrentSubjectReady, useCurrentSubjectScope } from "@/lib/current-subject"; import { dragScroll } from "@/lib/drag-scroll"; import { ANNUAL_PRAVESHA_NOTE, ANNUAL_PRAVESHA_TITLE, annualAppendixDisplayLines, annualAppendixDisplayTitle, type AnnualSnapshot } from "@/lib/annual-report-generate"; @@ -943,6 +944,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR if (!response.ok) return; const view = record(json.report); const status = view.status === "ready" || view.status === "failed" ? view.status : "generating"; + reportStatusesSeen([{ id, status }]); setReport({ id, status, annual: (json.annual as AnnualSnapshot | null) ?? null, ...(json.failureReason === "birth_input_changed" ? { failureReason: json.failureReason } : {}), @@ -968,6 +970,8 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR if (!overview || starting) return; setStarting(true); setStartError(null); + // BUG-2072: the browser's own question, once, inside this click. Not awaited. + askNotificationPermissionOnce(); try { const response = await fetch("/api/reports", { method: "POST", @@ -978,6 +982,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR const json = record(await response.json().catch(() => null)); const id = str(record(json.report).id); if (response.ok && id) { + watchStartedReport(id, "annual"); setReportId(id); setReport({ id, status: "generating", annual: null }); return; diff --git a/frontend/src/components/personal-report/generate-personal-report-button.tsx b/frontend/src/components/personal-report/generate-personal-report-button.tsx index 39f294974..3fd4d59d6 100644 --- a/frontend/src/components/personal-report/generate-personal-report-button.tsx +++ b/frontend/src/components/personal-report/generate-personal-report-button.tsx @@ -27,6 +27,7 @@ import { navigateAppPath } from "@/lib/app-navigation"; import { readPersonalReportStartOverview, type PersonalReportStartOverview } from "@/lib/personal-report-start"; import { notifyError } from "@/lib/notify"; +import { askNotificationPermissionOnce, watchStartedReport } from "@/lib/report-reminders"; import { reportStartErrorFor } from "@/lib/report-start-copy"; import { Button } from "@/components/ui/button"; @@ -235,6 +236,8 @@ export function GeneratePersonalReportButton({ inFlight.current = true; setSubmitting(true); setStartError(null); + // BUG-2072: the browser's own question, once, inside this click. Not awaited. + askNotificationPermissionOnce(); let navigating = false; try { const requestId = createReportRequestId(); @@ -257,6 +260,7 @@ export function GeneratePersonalReportButton({ } const outcome = classifyCreateResponse(response.status, json); if (outcome.kind === "navigate") { + watchStartedReport(outcome.reportId, "personal"); setOpen(false); if (onCreated) { onCreated(outcome.reportId); diff --git a/frontend/src/components/personal-report/personal-report-center.tsx b/frontend/src/components/personal-report/personal-report-center.tsx index eb530a9bb..a24cfec61 100644 --- a/frontend/src/components/personal-report/personal-report-center.tsx +++ b/frontend/src/components/personal-report/personal-report-center.tsx @@ -4,6 +4,7 @@ import { AppLink } from "@/components/app-link"; import { ChevronRight, FileText, Heart, Sun, type LucideIcon } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { notifyError } from "@/lib/notify"; +import { reportStatusesSeen } from "@/lib/report-reminders"; import { notifyOnboardingFactsChanged } from "@/lib/onboarding-signals"; import { SecondaryPageShell } from "@/components/secondary-page-shell"; @@ -191,6 +192,8 @@ export function PersonalReportCenter() { const generating = new Set(remembered.filter((report) => report.status === "generating").map((report) => report.id)); const finished = nextReports.filter((report) => report.status === "ready" && generating.has(report.id)); listedReports.current = { subjectId, reports: nextReports }; + // BUG-2072: this list polls its rows itself; the app shell's reminder does not ask about them again. + reportStatusesSeen(nextReports.map((report) => ({ id: report.id, status: report.status }))); if (finished.some((report) => report.reportType === "synastry_full")) notifyOnboardingFactsChanged("syn"); if (finished.some((report) => report.reportType !== "synastry_full" && report.reportType !== "annual_full")) notifyOnboardingFactsChanged("report"); setState(current => ({ phase: "ready", ...applyFirstReportPage(current, { reports: nextReports, nextCursor: snapshot.nextCursor }) })); diff --git a/frontend/src/components/personal-report/personal-report-page.tsx b/frontend/src/components/personal-report/personal-report-page.tsx index 4645b3603..86806b5c4 100644 --- a/frontend/src/components/personal-report/personal-report-page.tsx +++ b/frontend/src/components/personal-report/personal-report-page.tsx @@ -9,6 +9,7 @@ "use client"; +import { reportStatusesSeen } from "@/lib/report-reminders"; import type { BirthInputState } from "@/lib/birth-input-revision"; import { useCallback, useEffect, useRef, useState } from "react"; import { isRecord } from "@/lib/guards"; @@ -328,6 +329,14 @@ export const AWAY_GAP_MS = 5000; /** How often the timed-out screen checks whether the report has finished (BUG-1950). */ export const TIMED_OUT_POLL_MS = 20_000; +/** The report status a load result stands for, for the reminder; null when the load says nothing about it. */ +export function seenReportStatus(phase: ReportLoadState["phase"]): "generating" | "ready" | "failed" | null { + if (phase === "generating") return "generating"; + if (phase === "failed") return "failed"; + if (phase === "markdown-ready" || phase === "synastry-ready" || phase === "legacy-unavailable") return "ready"; + return null; +} + /** Time since the last tick when it is long enough to mean the tab was hidden; otherwise 0. */ export function awayGapMs(lastTickAt: number | null, now: number): number { if (lastTickAt === null) return 0; @@ -402,6 +411,9 @@ export function PersonalReportPage({ return; } const next = classifyReportEnvelope(response.status, json); + // BUG-2072: this page polls its report itself; tell the app shell's reminder what it saw. + const seen = seenReportStatus(next.phase); + if (seen) reportStatusesSeen([{ id: reportId, status: seen }]); if (next.phase === "synastry-ready") notifyOnboardingFactsChanged("syn"); else if (next.phase === "markdown-ready") notifyOnboardingFactsChanged("report"); if (next.phase === "generating") { diff --git a/frontend/src/components/report-reminder-watcher.tsx b/frontend/src/components/report-reminder-watcher.tsx new file mode 100644 index 000000000..9d0454a24 --- /dev/null +++ b/frontend/src/components/report-reminder-watcher.tsx @@ -0,0 +1,216 @@ +"use client"; + +import { useEffect } from "react"; + +import { navigateInApp } from "@/lib/app-navigation"; +import { notifyAction } from "@/lib/notify"; +import { + addWatchedReport, + createTitleReminder, + isOnReportPage, + readWatchedReports, + reminderLayers, + REPORT_SEEN_COVER_MS, + REPORT_SEEN_EVENT, + REPORT_WATCH_EVENT, + REPORT_WATCH_HIDDEN_POLL_MS, + REPORT_WATCH_POLL_MS, + REPORT_WATCH_STORAGE_KEY, + reportReminderHref, + reportReminderText, + reportsToAsk, + settleWatchedReports, + showReportNotification, + writeWatchedReports, + type ReportReminderEvent, + type ReportStatusAnswer, + type WatchedReport, +} from "@/lib/report-reminders"; + +type WatcherDeps = Readonly<{ + fetchStatuses: (ids: readonly string[]) => Promise; + isHidden: () => boolean; + now: () => number; + toast: (event: ReportReminderEvent) => void; + notify: (event: ReportReminderEvent) => void; + title: { show(): void; restore(): void }; + read: () => WatchedReport[]; + write: (reports: readonly WatchedReport[]) => void; +}>; + +/** + * The reminder's state machine, without React or timers (BUG-2072): the list of + * reports being waited for, what open pages already poll, and what to say once. + */ +export function createReportWatcher(deps: WatcherDeps) { + let watched: WatchedReport[] = deps.read(); + /** Ids this tab has seen in browser storage; one that left storage was settled by another tab. */ + const stored = new Set(watched.map((report) => report.id)); + const coveredUntil = new Map(); + let asking = false; + + function announce(events: readonly ReportReminderEvent[], seenByPage: boolean) { + if (events.length === 0) return; + const layers = reminderLayers({ seenByPage, hidden: deps.isHidden() }); + for (const event of events) { + if (layers.toast) deps.toast(event); + if (layers.background) deps.notify(event); + } + if (layers.background) deps.title.show(); + } + + function settle(answers: readonly ReportStatusAnswer[], asked: readonly string[], seenByPage: boolean) { + const result = settleWatchedReports(watched, answers, asked); + if (result.remaining.length === watched.length) return; + // With several tabs open the first one to see the report finish says so; the others stay quiet. + const inStorage = new Set(deps.read().map((report) => report.id)); + const mine = result.events.filter((event) => !stored.has(event.report.id) || inStorage.has(event.report.id)); + watched = result.remaining; + deps.write(watched); + announce(mine, seenByPage); + } + + return { + watched: () => watched, + add(report: WatchedReport) { + watched = addWatchedReport(watched, report); + if (deps.read().some((row) => row.id === report.id)) stored.add(report.id); + }, + /** Another tab changed the stored list: it started a report, or one finished there. */ + sync() { + const next = deps.read(); + const ids = new Set(next.map((report) => report.id)); + // What this tab holds only in memory (storage refused the write) stays. + watched = next.concat(watched.filter((report) => !ids.has(report.id) && !stored.has(report.id))); + for (const id of ids) stored.add(id); + }, + /** A page that polls reports itself says what it saw. */ + seen(answers: readonly ReportStatusAnswer[]) { + const mine = answers.filter((answer) => watched.some((report) => report.id === answer.id)); + if (mine.length === 0) return; + const until = deps.now() + REPORT_SEEN_COVER_MS; + for (const answer of mine) coveredUntil.set(answer.id, until); + settle(mine, mine.map((answer) => answer.id), true); + }, + async poll() { + if (asking || watched.length === 0) return; + const ids = reportsToAsk(watched, coveredUntil, deps.now()); + if (ids.length === 0) return; + asking = true; + try { + const answers = await deps.fetchStatuses(ids); + if (answers) settle(answers, ids, false); + } finally { + asking = false; + } + }, + interval: () => (deps.isHidden() ? REPORT_WATCH_HIDDEN_POLL_MS : REPORT_WATCH_POLL_MS), + }; +} + +async function fetchReportStatuses(ids: readonly string[]): Promise { + try { + const response = await fetch(`/api/reports/status?ids=${ids.map(encodeURIComponent).join(",")}`, { + credentials: "same-origin", + cache: "no-store", + headers: { Accept: "application/json" }, + }); + if (!response.ok) return null; + const json = await response.json().catch(() => null) as { reports?: unknown } | null; + if (!json || !Array.isArray(json.reports)) return null; + return json.reports.flatMap((row) => { + const value = row as { id?: unknown; status?: unknown } | null; + return value && typeof value.id === "string" && typeof value.status === "string" + ? [{ id: value.id, status: value.status }] + : []; + }); + } catch { + // Offline or a deploy in progress: ask again on the next tick. + return null; + } +} + +/** + * Mounted once in the app shell, so every signed-in page has it. It renders + * nothing: a finished report is a toast, the tab title and (in a background tab, + * when the browser allows it) a system notification. There is no setting. + * + * It keeps asking while the tab is in the background, which is the whole point, + * so it does not use the visibility-aware poll the pages use. + */ +export function ReportReminderWatcher({ signedIn }: { signedIn: boolean }) { + useEffect(() => { + if (!signedIn || typeof window === "undefined") return; + const title = createTitleReminder(); + const watcher = createReportWatcher({ + fetchStatuses: fetchReportStatuses, + isHidden: () => document.hidden, + now: () => Date.now(), + toast: (event) => { + const href = reportReminderHref(event.report); + // Coming back to the report's own page: the page already shows it. + if (isOnReportPage(event.report, window.location.pathname, window.location.search)) return; + notifyAction( + reportReminderText(event.report.kind, event.outcome), + { label: "查看", onClick: () => navigateInApp(href) }, + { id: `report-reminder:${event.report.id}`, tone: event.outcome === "ready" ? "success" : "error" }, + ); + }, + notify: (event) => { showReportNotification(event, (href) => navigateInApp(href)); }, + title, + read: () => readWatchedReports(), + write: (reports) => writeWatchedReports(reports), + }); + + let timer: number | null = null; + let stopped = false; + const schedule = () => { + if (timer !== null) window.clearTimeout(timer); + timer = null; + if (stopped || watcher.watched().length === 0) return; + timer = window.setTimeout(() => { + void watcher.poll().finally(schedule); + }, watcher.interval()); + }; + const onWatch = (event: Event) => { + const report = (event as CustomEvent).detail; + if (report && typeof report.id === "string") watcher.add(report); + schedule(); + }; + const onSeen = (event: Event) => { + const answers = (event as CustomEvent).detail; + if (Array.isArray(answers)) watcher.seen(answers); + }; + const onStorage = (event: StorageEvent) => { + if (event.key !== REPORT_WATCH_STORAGE_KEY) return; + watcher.sync(); + schedule(); + }; + const onVisibility = () => { + if (document.hidden) { + schedule(); + return; + } + title.restore(); + void watcher.poll().finally(schedule); + }; + window.addEventListener(REPORT_WATCH_EVENT, onWatch); + window.addEventListener(REPORT_SEEN_EVENT, onSeen); + window.addEventListener("storage", onStorage); + window.addEventListener("focus", title.restore); + document.addEventListener("visibilitychange", onVisibility); + // A reload in the middle of a wait: ask once now, then keep the cadence. + void watcher.poll().finally(schedule); + return () => { + stopped = true; + if (timer !== null) window.clearTimeout(timer); + window.removeEventListener(REPORT_WATCH_EVENT, onWatch); + window.removeEventListener(REPORT_SEEN_EVENT, onSeen); + window.removeEventListener("storage", onStorage); + window.removeEventListener("focus", title.restore); + document.removeEventListener("visibilitychange", onVisibility); + title.restore(); + }; + }, [signedIn]); + return null; +} diff --git a/frontend/src/components/synastry/synastry-picker.tsx b/frontend/src/components/synastry/synastry-picker.tsx index 1c298126c..5912f75cb 100644 --- a/frontend/src/components/synastry/synastry-picker.tsx +++ b/frontend/src/components/synastry/synastry-picker.tsx @@ -17,6 +17,7 @@ import type { Profile } from "@/lib/home-types"; import { missingOtherProfileStep, readProfile } from "@/lib/home-profile"; import { notifyOnboardingFactsChanged } from "@/lib/onboarding-signals"; import { notifyError } from "@/lib/notify"; +import { askNotificationPermissionOnce, watchStartedReport } from "@/lib/report-reminders"; import { peopleCityLabel, peopleDisplayName } from "@/lib/people-archive-view"; import { PROFILE_GENDER_LABELS, parseProfileGender } from "@/lib/profile-gender"; import { MAX_SAVED_SUBJECTS } from "@/lib/subject-birth"; @@ -220,6 +221,8 @@ export function SynastryPicker() { return; } setBusy(true); + // BUG-2072: the browser's own question, once, inside this click. Not awaited. + askNotificationPermissionOnce(); try { const response = await fetch("/api/reports", { method: "POST", @@ -235,6 +238,7 @@ export function SynastryPicker() { a: people.find((person) => person.id === left)?.name ?? "", b: people.find((person) => person.id === right)?.name ?? "", }; + watchStartedReport(payload.report.id, "synastry"); sessionStorage.setItem(`synastry-wait:${payload.report.id}`, JSON.stringify(pair)); window.location.assign(`/synastry/${payload.report.id}`); } finally { diff --git a/frontend/src/lib/notify.ts b/frontend/src/lib/notify.ts index cc6d42bf4..aa4955a6e 100644 --- a/frontend/src/lib/notify.ts +++ b/frontend/src/lib/notify.ts @@ -8,6 +8,8 @@ import { toast } from "sonner"; * page; see DESIGN.md「提示与报错」. */ export const NOTICE_DURATION_MS = { success: 3_000, info: 3_000, error: 6_000 } as const; +/** A toast that carries a way to act on it (「查看」) stays as long as an error does. */ +export const ACTION_NOTICE_DURATION_MS = 6_000; export type NoticeOptions = Readonly<{ /** Same id → the new message replaces the old one instead of stacking. */ @@ -64,6 +66,25 @@ export function notifyError(message: string, extra?: NoticeOptions) { toast.error(message, options("error", extra)); } +/** + * A result the user may want to open (BUG-2072: a report that finished while + * they were elsewhere). Still a toast: the button sits on it, never in the page. + */ +export function notifyAction( + message: string, + action: Readonly<{ label: string; onClick: () => void }>, + extra: NoticeOptions & Readonly<{ tone?: "success" | "error" }> = {}, +) { + if (!message.trim()) return; + liftToastsAboveModal(); + const show = extra.tone === "error" ? toast.error : toast.success; + show(message, { + duration: extra.duration ?? ACTION_NOTICE_DURATION_MS, + action: { label: action.label, onClick: () => action.onClick() }, + ...(extra.id ? { id: extra.id } : {}), + }); +} + export function dismissNotice(id: string) { toast.dismiss(id); } diff --git a/frontend/src/lib/report-reminders.ts b/frontend/src/lib/report-reminders.ts new file mode 100644 index 000000000..e2074c716 --- /dev/null +++ b/frontend/src/lib/report-reminders.ts @@ -0,0 +1,301 @@ +/** + * Task-done reminders for reports (BUG-2072, product 2026-11-20). + * + * A report is written by the server queue, so it finishes whether or not its + * page is open. This module is everything the reminder needs outside React: + * which reports this viewer is waiting for (per-viewer browser storage, the + * page works without it), what a status answer means for them, and the three + * ways to say "it is done": a toast with 「查看」, the tab title, and a system + * notification when the tab is in the background and the browser allows it. + * + * Product rulings: reminders are on by default and have no setting; the only + * question the user ever sees is the browser's own permission dialog, asked + * once inside the click that starts a report. Reminder text names the kind of + * report and nothing else, because a system notification shows on lock screens. + */ + +export type ReportReminderKind = "personal" | "annual" | "synastry"; +export type WatchedReport = Readonly<{ id: string; kind: ReportReminderKind; startedAt: number }>; +export type ReportStatusAnswer = Readonly<{ id: string; status: string }>; +export type ReportReminderOutcome = "ready" | "failed"; +export type ReportReminderEvent = Readonly<{ report: WatchedReport; outcome: ReportReminderOutcome }>; + +export const REPORT_WATCH_STORAGE_KEY = "jyotisha.report-watch.v1"; +export const NOTIFICATION_ASKED_STORAGE_KEY = "jyotisha.notification-asked.v1"; +/** The page (or another tab) announces what it starts and what it sees. */ +export const REPORT_WATCH_EVENT = "jyotisha:report-watch"; +export const REPORT_SEEN_EVENT = "jyotisha:report-seen"; +export const REPORT_WATCH_LIMIT = 10; +/** A report still "generating" a day later is not something to keep asking about. */ +export const REPORT_WATCH_MAX_AGE_MS = 24 * 60 * 60 * 1000; +export const REPORT_WATCH_POLL_MS = 10_000; +/** Background tabs are asked less often; browsers throttle their timers anyway. */ +export const REPORT_WATCH_HIDDEN_POLL_MS = 30_000; +/** + * A page that shows a report polls it itself. What it reports here covers the + * report for this long, so the watcher does not ask about it a second time. + * The slowest page poll is 20 s (the personal report's timed-out screen). + */ +export const REPORT_SEEN_COVER_MS = 30_000; +export const REMINDER_TITLE = "报告好了,Jyotisha"; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function isReportId(value: unknown): value is string { + return typeof value === "string" && UUID.test(value); +} + +export function reportReminderKind(reportType: unknown): ReportReminderKind { + if (reportType === "annual_full") return "annual"; + if (reportType === "synastry_full") return "synastry"; + return "personal"; +} + +export function reportReminderHref(report: Pick): string { + const id = encodeURIComponent(report.id); + if (report.kind === "annual") return `/reports/annual?report=${id}`; + return report.kind === "synastry" ? `/synastry/${id}` : `/reports/${id}`; +} + +/** The viewer is already looking at this report's page, which shows the result itself. */ +export function isOnReportPage(report: Pick, pathname: string, search: string): boolean { + if (report.kind === "annual") { + if (pathname !== "/reports/annual") return false; + const open = new URLSearchParams(search).get("report"); + // A year that was just started keeps the plain address until it is reopened. + return open === null || open === report.id; + } + return pathname === reportReminderHref(report); +} + +const KIND_NAME: Record = { personal: "个人报告", annual: "年运", synastry: "合盘报告" }; + +/** One sentence per outcome, used by the toast and the system notification alike. */ +export function reportReminderText(kind: ReportReminderKind, outcome: ReportReminderOutcome): string { + return outcome === "ready" ? `${KIND_NAME[kind]}好了` : `${KIND_NAME[kind]}没有写成,点数已退回`; +} + +function settled(status: string): ReportReminderOutcome | null { + return status === "ready" || status === "failed" ? status : null; +} + +function validWatched(value: unknown, now: number): WatchedReport | null { + if (!value || typeof value !== "object") return null; + const row = value as Record; + if (!isReportId(row.id)) return null; + if (row.kind !== "personal" && row.kind !== "annual" && row.kind !== "synastry") return null; + if (typeof row.startedAt !== "number" || !Number.isFinite(row.startedAt)) return null; + if (now - row.startedAt > REPORT_WATCH_MAX_AGE_MS) return null; + return { id: row.id, kind: row.kind, startedAt: row.startedAt }; +} + +type StorageLike = Pick; + +function browserStorage(): StorageLike | null { + try { + return typeof window === "undefined" ? null : window.localStorage; + } catch { + return null; + } +} + +export function parseWatchedReports(raw: string | null, now: number): WatchedReport[] { + if (!raw) return []; + try { + const parsed: unknown = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + const seen = new Set(); + const rows: WatchedReport[] = []; + for (const value of parsed) { + const row = validWatched(value, now); + if (!row || seen.has(row.id)) continue; + seen.add(row.id); + rows.push(row); + } + return rows.slice(-REPORT_WATCH_LIMIT); + } catch { + return []; + } +} + +export function readWatchedReports(now = Date.now(), storage: StorageLike | null = browserStorage()): WatchedReport[] { + try { + return storage ? parseWatchedReports(storage.getItem(REPORT_WATCH_STORAGE_KEY), now) : []; + } catch { + return []; + } +} + +export function writeWatchedReports(reports: readonly WatchedReport[], storage: StorageLike | null = browserStorage()): void { + try { + if (!storage) return; + if (reports.length === 0) storage.removeItem(REPORT_WATCH_STORAGE_KEY); + else storage.setItem(REPORT_WATCH_STORAGE_KEY, JSON.stringify(reports.slice(-REPORT_WATCH_LIMIT))); + } catch { + // Private windows and blocked site data: the watcher keeps its list in memory. + } +} + +export function addWatchedReport(list: readonly WatchedReport[], report: WatchedReport): WatchedReport[] { + if (list.some((row) => row.id === report.id)) return [...list]; + return [...list, report].slice(-REPORT_WATCH_LIMIT); +} + +/** + * What a status answer means. A settled report leaves the list and yields one + * event; a report the server no longer returns (deleted, or not this account's) + * leaves quietly; the rest keep waiting. + */ +export function settleWatchedReports( + watched: readonly WatchedReport[], + answers: readonly ReportStatusAnswer[], + asked: readonly string[], +): { remaining: WatchedReport[]; events: ReportReminderEvent[] } { + const byId = new Map(answers.map((answer) => [answer.id, answer.status])); + const askedIds = new Set(asked); + const remaining: WatchedReport[] = []; + const events: ReportReminderEvent[] = []; + for (const report of watched) { + if (!askedIds.has(report.id)) { + remaining.push(report); + continue; + } + const status = byId.get(report.id); + if (status === undefined) continue; + const outcome = settled(status); + if (outcome) events.push({ report, outcome }); + else remaining.push(report); + } + return { remaining, events }; +} + +/** Reports the watcher has to ask about itself: the ones no open page is polling. */ +export function reportsToAsk( + watched: readonly WatchedReport[], + coveredUntil: ReadonlyMap, + now: number, +): string[] { + return watched.filter((report) => (coveredUntil.get(report.id) ?? 0) <= now).map((report) => report.id); +} + +/** + * Which layers a finished report gets. + * - A page that shows the report saw it finish while the tab was visible: nothing, the page changed itself. + * - Otherwise a toast with 「查看」; and when the tab is in the background, the tab title and a system notification. + */ +export function reminderLayers(input: { seenByPage: boolean; hidden: boolean }): { toast: boolean; background: boolean } { + if (input.seenByPage && !input.hidden) return { toast: false, background: false }; + return { toast: !input.seenByPage, background: input.hidden }; +} + +function dispatch(name: string, detail: unknown): void { + try { + if (typeof window === "undefined" || typeof CustomEvent !== "function") return; + window.dispatchEvent(new CustomEvent(name, { detail })); + } catch { + // A reminder never breaks the action that asked for it. + } +} + +/** Called where a report is started: the app shell keeps asking until it is written. */ +export function watchStartedReport(id: unknown, kind: ReportReminderKind, now = Date.now()): void { + if (!isReportId(id)) return; + const report: WatchedReport = { id, kind, startedAt: now }; + writeWatchedReports(addWatchedReport(readWatchedReports(now), report)); + dispatch(REPORT_WATCH_EVENT, report); +} + +/** Called by a page that polls reports itself, with what it just saw. */ +export function reportStatusesSeen(answers: readonly ReportStatusAnswer[]): void { + const rows = answers.filter((answer) => isReportId(answer.id) && typeof answer.status === "string"); + if (rows.length > 0) dispatch(REPORT_SEEN_EVENT, rows); +} + +type NotificationApi = { + permission?: string; + requestPermission?: () => unknown; +}; + +function notificationApi(): (NotificationApi & (new (title: string, options?: NotificationOptions) => Notification)) | null { + try { + if (typeof window === "undefined" || !("Notification" in window)) return null; + // Browsers refuse notifications on insecure pages; an embedded page must not ask at all. + if (window.isSecureContext === false) return null; + if (window.self !== window.top) return null; + return window.Notification as never; + } catch { + return null; + } +} + +let askedWithoutStorage = false; + +/** + * The browser's own permission dialog, once per browser, inside the click that + * starts a report. Never awaited: it must not hold up the start. A viewer who + * answered (either way) or dismissed it is not asked again. + */ +export function askNotificationPermissionOnce(storage: StorageLike | null = browserStorage(), api: NotificationApi | null = notificationApi()): boolean { + try { + if (!api || api.permission !== "default" || typeof api.requestPermission !== "function") return false; + // Without browser storage the page still remembers for as long as it lives. + if (!storage && askedWithoutStorage) return false; + if (!storage) askedWithoutStorage = true; + if (storage) { + if (storage.getItem(NOTIFICATION_ASKED_STORAGE_KEY)) return false; + storage.setItem(NOTIFICATION_ASKED_STORAGE_KEY, "1"); + } + const asked = api.requestPermission(); + if (asked && typeof (asked as Promise).catch === "function") void (asked as Promise).catch(() => undefined); + return true; + } catch { + return false; + } +} + +/** A system notification for a finished report; false when the browser does not allow one. */ +export function showReportNotification(event: ReportReminderEvent, open: (href: string) => void): boolean { + try { + const api = notificationApi(); + if (!api || api.permission !== "granted") return false; + const notification = new api(reportReminderText(event.report.kind, event.outcome), { + body: "Jyotisha", + // One notification per report, however many tabs are open. + tag: `report:${event.report.id}`, + }); + notification.onclick = () => { + try { + window.focus(); + notification.close(); + } catch { + // Focus is a courtesy. + } + open(reportReminderHref(event.report)); + }; + return true; + } catch { + return false; + } +} + +/** + * The tab title while a finished report waits in a background tab. The page's + * own title comes back when the tab is looked at again (or the app shell goes away). + */ +export function createTitleReminder(doc: Pick | null = typeof document === "undefined" ? null : document) { + let original: string | null = null; + return { + show() { + if (!doc || original !== null) return; + original = doc.title; + doc.title = REMINDER_TITLE; + }, + restore() { + if (!doc || original === null) return; + // A page that set its own title meanwhile keeps it. + if (doc.title === REMINDER_TITLE) doc.title = original; + original = null; + }, + active: () => original !== null, + }; +} diff --git a/frontend/src/lib/report-status-server.ts b/frontend/src/lib/report-status-server.ts new file mode 100644 index 000000000..a3a8c3a82 --- /dev/null +++ b/frontend/src/lib/report-status-server.ts @@ -0,0 +1,44 @@ +import type { DataQueryBuilder } from "@/lib/db/data-client"; +import { isReportId, REPORT_WATCH_LIMIT } from "@/lib/report-reminders"; + +export type ReportStatusResponse = { status: number; body: Record }; + +type UserClient = { from(table: string): { select(columns: string): DataQueryBuilder } }; + +/** + * GET /api/reports/status?ids=a,b (BUG-2072): the state of a few reports, for + * the app shell's "is it written yet" check. Three small columns per report; + * the report body never travels here (GET /api/reports/:id returns hundreds of KB + * once a report is ready). + * + * Read as the signed-in user, never with the service identity (the BUG-2057 + * lesson: a service read of a user table can fail silently), and filtered by + * the user's id on top of row-level security. An id that is unknown or belongs + * to someone else is simply absent from the answer. + */ +export async function readReportStatuses(input: { + userId: string | null; + supabase: unknown; + ids: string | null; +}): Promise { + if (!input.userId) return { status: 401, body: { error: "请先登录" } }; + const asked = (input.ids ?? "").split(",").map((id) => id.trim()).filter(Boolean); + if (asked.length > REPORT_WATCH_LIMIT) return { status: 400, body: { error: "报告状态请求无效" } }; + const ids = [...new Set(asked.filter(isReportId))]; + if (ids.length === 0) return { status: 200, body: { reports: [] } }; + const found = await (input.supabase as UserClient) + .from("personal_reports") + .select("id,status,report_type") + .eq("user_id", input.userId) + .in("id", ids); + if (found.error) throw found.error; + const rows = Array.isArray(found.data) ? found.data as Array> : []; + const reports = rows + .filter((row) => typeof row.id === "string" && ids.includes(row.id)) + .map((row) => ({ + id: row.id as string, + status: row.status === "ready" || row.status === "failed" ? row.status : "generating", + reportType: typeof row.report_type === "string" ? row.report_type : "personal_full", + })); + return { status: 200, body: { reports } }; +} diff --git a/frontend/tests/report-reminders-2072.test.ts b/frontend/tests/report-reminders-2072.test.ts new file mode 100644 index 000000000..ea1555781 --- /dev/null +++ b/frontend/tests/report-reminders-2072.test.ts @@ -0,0 +1,399 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +import { createReportWatcher } from "../src/components/report-reminder-watcher.tsx"; +import { + askNotificationPermissionOnce, + createTitleReminder, + isOnReportPage, + NOTIFICATION_ASKED_STORAGE_KEY, + parseWatchedReports, + readWatchedReports, + reminderLayers, + REMINDER_TITLE, + REPORT_SEEN_COVER_MS, + REPORT_WATCH_HIDDEN_POLL_MS, + REPORT_WATCH_MAX_AGE_MS, + REPORT_WATCH_POLL_MS, + REPORT_WATCH_STORAGE_KEY, + reportReminderHref, + reportReminderKind, + reportReminderText, + reportsToAsk, + settleWatchedReports, + writeWatchedReports, + type ReportReminderEvent, + type ReportStatusAnswer, + type WatchedReport, +} from "../src/lib/report-reminders.ts"; +import { readReportStatuses } from "../src/lib/report-status-server.ts"; + +const read = (path: string) => readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); +const A = "aaaaaaaa-0000-4000-8000-000000000001"; +const B = "bbbbbbbb-0000-4000-8000-000000000002"; +const C = "cccccccc-0000-4000-8000-000000000003"; +const NOW = 1_800_000_000_000; + +function memoryStorage(initial: Record = {}) { + const map = new Map(Object.entries(initial)); + return { + map, + getItem: (key: string) => map.get(key) ?? null, + setItem: (key: string, value: string) => { map.set(key, value); }, + removeItem: (key: string) => { map.delete(key); }, + }; +} +const brokenStorage = { + getItem() { throw new Error("blocked"); }, + setItem() { throw new Error("blocked"); }, + removeItem() { throw new Error("blocked"); }, +}; + +/** personal_reports as the signed-in user sees it: only rows the filters let through. */ +function reportsClient(rows: Array<{ id: string; user_id: string; status: string; report_type: string; markdown?: string }>) { + const calls: Array<{ table: string; columns: string; user?: unknown; ids?: readonly unknown[] }> = []; + return { + calls, + from(table: string) { + const call: (typeof calls)[number] = { table, columns: "" }; + calls.push(call); + const api = { + select(columns: string) { call.columns = columns; return api; }, + eq(column: string, value: unknown) { if (column === "user_id") call.user = value; return api; }, + in(column: string, value: readonly unknown[]) { if (column === "id") call.ids = value; return api; }, + then(resolve: (value: { data: unknown; error: null }) => unknown) { + const data = rows.filter((row) => row.user_id === call.user && (call.ids ?? []).includes(row.id)); + return Promise.resolve({ data, error: null }).then(resolve); + }, + }; + return api; + }, + }; +} + +test("BUG-2072 status route: signed-out is 401, only the caller's own reports come back, unknown ids are ignored", async () => { + const client = reportsClient([ + { id: A, user_id: "me", status: "generating", report_type: "personal_full", markdown: "body" }, + { id: B, user_id: "someone-else", status: "ready", report_type: "annual_full" }, + { id: C, user_id: "me", status: "ready", report_type: "synastry_full" }, + ]); + assert.equal((await readReportStatuses({ userId: null, supabase: client, ids: A })).status, 401); + assert.equal(client.calls.length, 0, "a signed-out request never reaches the table"); + + const answer = await readReportStatuses({ userId: "me", supabase: client, ids: `${A},${B},${C},not-an-id,dddddddd-0000-4000-8000-000000000004` }); + assert.equal(answer.status, 200); + assert.deepEqual(answer.body, { reports: [ + { id: A, status: "generating", reportType: "personal_full" }, + { id: C, status: "ready", reportType: "synastry_full" }, + ] }); + const call = client.calls[0]!; + assert.equal(call.table, "personal_reports"); + // No report body, title or birth data: three small columns. + assert.equal(call.columns, "id,status,report_type"); + assert.equal(call.user, "me"); + assert.ok(!(call.ids ?? []).includes("not-an-id")); + + assert.deepEqual((await readReportStatuses({ userId: "me", supabase: client, ids: null })).body, { reports: [] }); + assert.deepEqual((await readReportStatuses({ userId: "me", supabase: client, ids: "nope" })).body, { reports: [] }); + const many = Array.from({ length: 11 }, (_, index) => `aaaaaaaa-0000-4000-8000-0000000000${String(index).padStart(2, "0")}`).join(","); + assert.equal((await readReportStatuses({ userId: "me", supabase: client, ids: many })).status, 400); + + // An unexpected status reads as still writing, never as done. + const odd = reportsClient([{ id: A, user_id: "me", status: "queued", report_type: "personal_full" }]); + assert.deepEqual((await readReportStatuses({ userId: "me", supabase: odd, ids: A })).body, { reports: [{ id: A, status: "generating", reportType: "personal_full" }] }); +}); + +test("BUG-2072 status route reads as the signed-in user, never with the service identity", () => { + const route = read("src/app/api/reports/status/route.ts"); + const core = read("src/lib/report-status-server.ts"); + assert.doesNotMatch(route + core, /createAdminSupabaseClient|supabase\/admin/); + assert.match(route, /createServerSupabaseClient\(\)/); + assert.match(route, /supabase\.auth\.getUser\(\)/); + assert.match(route, /"Cache-Control": "no-store"/); + assert.match(core, /\.eq\("user_id", input\.userId\)/); +}); + +test("BUG-2072 the waiting list survives a reload, tolerates bad or blocked storage, and forgets day-old entries", () => { + const storage = memoryStorage(); + const list: WatchedReport[] = [{ id: A, kind: "personal", startedAt: NOW }, { id: B, kind: "annual", startedAt: NOW }]; + writeWatchedReports(list, storage); + assert.deepEqual(readWatchedReports(NOW + 1000, storage), list); + assert.deepEqual(readWatchedReports(NOW + REPORT_WATCH_MAX_AGE_MS + 1, storage), []); + writeWatchedReports([], storage); + assert.equal(storage.map.has(REPORT_WATCH_STORAGE_KEY), false); + + assert.deepEqual(parseWatchedReports("{not json", NOW), []); + assert.deepEqual(parseWatchedReports(JSON.stringify({ id: A }), NOW), []); + assert.deepEqual(parseWatchedReports(JSON.stringify([ + { id: "x", kind: "personal", startedAt: NOW }, + { id: A, kind: "weekly", startedAt: NOW }, + { id: A, kind: "synastry", startedAt: NOW }, + { id: A, kind: "synastry", startedAt: NOW }, + ]), NOW), [{ id: A, kind: "synastry", startedAt: NOW }]); + + assert.deepEqual(readWatchedReports(NOW, brokenStorage), []); + assert.doesNotThrow(() => writeWatchedReports(list, brokenStorage)); + assert.deepEqual(readWatchedReports(NOW, null), []); +}); + +test("BUG-2072 copy and links: the kind of report and nothing else", () => { + assert.equal(reportReminderKind("personal_full"), "personal"); + assert.equal(reportReminderKind("personal_thematic"), "personal"); + assert.equal(reportReminderKind("annual_full"), "annual"); + assert.equal(reportReminderKind("synastry_full"), "synastry"); + assert.equal(reportReminderText("personal", "ready"), "个人报告好了"); + assert.equal(reportReminderText("annual", "ready"), "年运好了"); + assert.equal(reportReminderText("synastry", "ready"), "合盘报告好了"); + assert.equal(reportReminderText("personal", "failed"), "个人报告没有写成,点数已退回"); + assert.equal(reportReminderHref({ id: A, kind: "personal" }), `/reports/${A}`); + assert.equal(reportReminderHref({ id: A, kind: "annual" }), `/reports/annual?report=${A}`); + assert.equal(reportReminderHref({ id: A, kind: "synastry" }), `/synastry/${A}`); + assert.equal(isOnReportPage({ id: A, kind: "personal" }, `/reports/${A}`, ""), true); + assert.equal(isOnReportPage({ id: A, kind: "personal" }, "/reports", ""), false); + assert.equal(isOnReportPage({ id: A, kind: "annual" }, "/reports/annual", ""), true); + assert.equal(isOnReportPage({ id: A, kind: "annual" }, "/reports/annual", `?report=${B}`), false); + assert.equal(isOnReportPage({ id: A, kind: "synastry" }, `/synastry/${B}`, ""), false); +}); + +test("BUG-2072 a status answer settles reports once; a report the server no longer returns leaves quietly", () => { + const watched: WatchedReport[] = [ + { id: A, kind: "personal", startedAt: NOW }, + { id: B, kind: "annual", startedAt: NOW }, + { id: C, kind: "synastry", startedAt: NOW }, + ]; + const first = settleWatchedReports(watched, [{ id: A, status: "generating" }, { id: B, status: "ready" }], [A, B]); + assert.deepEqual(first.remaining.map((report) => report.id), [A, C], "C was not asked about, so it keeps waiting"); + assert.deepEqual(first.events, [{ report: watched[1], outcome: "ready" }]); + const second = settleWatchedReports(first.remaining, [{ id: C, status: "failed" }], [A, C]); + assert.deepEqual(second.remaining, [], "A is gone on the server: dropped without a reminder"); + assert.deepEqual(second.events, [{ report: watched[2], outcome: "failed" }]); + + assert.deepEqual(reminderLayers({ seenByPage: true, hidden: false }), { toast: false, background: false }); + assert.deepEqual(reminderLayers({ seenByPage: false, hidden: false }), { toast: true, background: false }); + assert.deepEqual(reminderLayers({ seenByPage: false, hidden: true }), { toast: true, background: true }); + assert.deepEqual(reminderLayers({ seenByPage: true, hidden: true }), { toast: false, background: true }); + + const covered = new Map([[A, NOW + 5]]); + assert.deepEqual(reportsToAsk(watched, covered, NOW), [B, C]); + assert.deepEqual(reportsToAsk(watched, covered, NOW + 6), [A, B, C]); +}); + +function harness(options: { stored?: WatchedReport[]; storageWorks?: boolean } = {}) { + let stored: WatchedReport[] = options.stored ?? []; + const works = options.storageWorks !== false; + const state = { hidden: false, now: NOW, answers: [] as ReportStatusAnswer[] | null, asked: [] as string[][] }; + const toasts: ReportReminderEvent[] = []; + const notifications: ReportReminderEvent[] = []; + const title = { shown: 0, restored: 0 }; + const watcher = createReportWatcher({ + fetchStatuses: async (ids) => { state.asked.push([...ids]); return state.answers; }, + isHidden: () => state.hidden, + now: () => state.now, + toast: (event) => { toasts.push(event); }, + notify: (event) => { notifications.push(event); }, + title: { show: () => { title.shown += 1; }, restore: () => { title.restored += 1; } }, + read: () => (works ? stored : []), + write: (reports) => { if (works) stored = [...reports]; }, + }); + return { + watcher, state, toasts, notifications, title, + stored: () => stored, + setStored: (reports: WatchedReport[]) => { stored = reports; }, + start(report: WatchedReport) { + if (works) stored = [...stored, report]; + watcher.add(report); + }, + }; +} + +test("BUG-2072 watcher: a started report is asked about until it is written, then announced once and dropped", async () => { + const h = harness(); + await h.watcher.poll(); + assert.deepEqual(h.state.asked, [], "nothing to wait for: no request at all"); + + h.start({ id: A, kind: "personal", startedAt: NOW }); + h.state.answers = [{ id: A, status: "generating" }]; + await h.watcher.poll(); + assert.deepEqual(h.state.asked, [[A]]); + assert.equal(h.toasts.length, 0); + + h.state.answers = [{ id: A, status: "ready" }]; + await h.watcher.poll(); + assert.deepEqual(h.toasts.map((event) => [event.report.id, event.outcome]), [[A, "ready"]]); + assert.equal(h.notifications.length, 0, "a visible tab gets the toast only"); + assert.equal(h.title.shown, 0); + assert.deepEqual(h.watcher.watched(), []); + assert.deepEqual(h.stored(), []); + + await h.watcher.poll(); + assert.equal(h.state.asked.length, 2, "a settled report is never asked about again"); + assert.equal(h.toasts.length, 1); +}); + +test("BUG-2072 watcher: resumes after a reload from storage, and works in memory when storage is blocked", async () => { + const resumed = harness({ stored: [{ id: B, kind: "annual", startedAt: NOW }] }); + resumed.state.answers = [{ id: B, status: "failed" }]; + await resumed.watcher.poll(); + assert.deepEqual(resumed.toasts.map((event) => [event.report.kind, event.outcome]), [["annual", "failed"]]); + + const blocked = harness({ storageWorks: false }); + blocked.start({ id: A, kind: "synastry", startedAt: NOW }); + blocked.state.answers = [{ id: A, status: "ready" }]; + await blocked.watcher.poll(); + assert.equal(blocked.toasts.length, 1); + + const offline = harness({ stored: [{ id: A, kind: "personal", startedAt: NOW }] }); + offline.state.answers = null; + await offline.watcher.poll(); + assert.equal(offline.watcher.watched().length, 1, "a failed status request changes nothing"); +}); + +test("BUG-2072 watcher: a background tab gets the title and the system notification; it asks less often", async () => { + const h = harness(); + assert.equal(h.watcher.interval(), REPORT_WATCH_POLL_MS); + h.state.hidden = true; + assert.equal(h.watcher.interval(), REPORT_WATCH_HIDDEN_POLL_MS); + assert.ok(REPORT_WATCH_HIDDEN_POLL_MS > REPORT_WATCH_POLL_MS); + h.start({ id: A, kind: "personal", startedAt: NOW }); + h.state.answers = [{ id: A, status: "ready" }]; + await h.watcher.poll(); + assert.equal(h.notifications.length, 1); + assert.equal(h.title.shown, 1); + assert.equal(h.toasts.length, 1, "the toast waits for the user's return"); +}); + +test("BUG-2072 watcher: a page that polls the report covers it, so it is not asked about twice", async () => { + const h = harness(); + h.start({ id: A, kind: "personal", startedAt: NOW }); + h.start({ id: B, kind: "annual", startedAt: NOW }); + h.watcher.seen([{ id: A, status: "generating" }, { id: C, status: "ready" }]); + h.state.answers = [{ id: B, status: "generating" }]; + await h.watcher.poll(); + assert.deepEqual(h.state.asked, [[B]], "A is the open page's to poll"); + + // The page stops reporting (tab hidden, or the user left it): the cover runs out. + h.state.now = NOW + REPORT_SEEN_COVER_MS + 1; + h.state.answers = [{ id: A, status: "generating" }, { id: B, status: "generating" }]; + await h.watcher.poll(); + assert.deepEqual(h.state.asked[1], [A, B]); + + // The page sees its report finish in front of the user: nothing is said. + h.watcher.seen([{ id: A, status: "ready" }]); + assert.equal(h.toasts.length, 0); + assert.equal(h.notifications.length, 0); + assert.deepEqual(h.watcher.watched().map((report) => report.id), [B]); + + // A page that keeps polling in a background tab still gets the background layers. + h.state.hidden = true; + h.watcher.seen([{ id: B, status: "ready" }]); + assert.equal(h.toasts.length, 0); + assert.equal(h.notifications.length, 1); + assert.equal(h.title.shown, 1); +}); + +test("BUG-2072 watcher: with two tabs open only the first one to see it finish announces it", async () => { + const report: WatchedReport = { id: A, kind: "personal", startedAt: NOW }; + const h = harness({ stored: [report] }); + // The other tab settled the report and removed it from storage. + h.setStored([]); + h.state.answers = [{ id: A, status: "ready" }]; + await h.watcher.poll(); + assert.equal(h.toasts.length, 0); + assert.deepEqual(h.watcher.watched(), []); + + const synced = harness({ stored: [report] }); + synced.setStored([{ id: B, kind: "annual", startedAt: NOW }]); + synced.watcher.sync(); + assert.deepEqual(synced.watcher.watched().map((row) => row.id), [B], "the storage event carries the other tab's list"); +}); + +test("BUG-2072 permission: asked once, only from the default state, never awaited, never again after any answer", () => { + let calls = 0; + const storage = memoryStorage(); + const api = { permission: "default", requestPermission: () => { calls += 1; return Promise.reject(new Error("dismissed")); } }; + assert.equal(askNotificationPermissionOnce(storage, api), true); + assert.equal(calls, 1); + assert.equal(storage.map.get(NOTIFICATION_ASKED_STORAGE_KEY), "1"); + // Dismissed leaves the browser at "default": the product still does not ask again. + assert.equal(askNotificationPermissionOnce(storage, api), false); + assert.equal(calls, 1); + + for (const permission of ["denied", "granted"]) { + assert.equal(askNotificationPermissionOnce(memoryStorage(), { permission, requestPermission: () => { calls += 1; } }), false); + } + assert.equal(calls, 1); + // No Notification support, an old callback-style API, a throwing API, blocked storage. + assert.equal(askNotificationPermissionOnce(memoryStorage(), null), false); + assert.equal(askNotificationPermissionOnce(memoryStorage(), { permission: "default" }), false); + assert.equal(askNotificationPermissionOnce(memoryStorage(), { permission: "default", requestPermission: () => undefined }), true); + assert.equal(askNotificationPermissionOnce(memoryStorage(), { permission: "default", requestPermission: () => { throw new Error("no"); } }), false); + assert.equal(askNotificationPermissionOnce(brokenStorage, api), false, "storage that throws: do not risk asking on every start"); +}); + +test("BUG-2072 title: changed while the reminder waits, restored once, a page's own new title is kept", () => { + const doc = { title: "我的报告" }; + const reminder = createTitleReminder(doc); + reminder.restore(); + assert.equal(doc.title, "我的报告"); + reminder.show(); + reminder.show(); + assert.equal(doc.title, REMINDER_TITLE); + assert.equal(reminder.active(), true); + reminder.restore(); + assert.equal(doc.title, "我的报告"); + assert.equal(reminder.active(), false); + reminder.show(); + doc.title = "年运"; + reminder.restore(); + assert.equal(doc.title, "年运"); + assert.doesNotThrow(() => { const none = createTitleReminder(null); none.show(); none.restore(); }); +}); + +test("BUG-2072 wiring: three starts register and ask inside the click; pages report what they poll; no setting anywhere", () => { + const starts = [ + ["src/components/personal-report/generate-personal-report-button.tsx", /watchStartedReport\(outcome\.reportId, "personal"\)/], + ["src/components/annual/annual-report-page.tsx", /watchStartedReport\(id, "annual"\)/], + ["src/components/synastry/synastry-picker.tsx", /watchStartedReport\(payload\.report\.id, "synastry"\)/], + ] as const; + for (const [path, registered] of starts) { + const source = read(path); + assert.match(source, registered, path); + // Inside the click handler, before the request, and not awaited. + const ask = source.indexOf("askNotificationPermissionOnce();"); + assert.ok(ask > 0 && ask < source.indexOf('fetch("/api/reports", {'), path); + assert.doesNotMatch(source, /await askNotificationPermissionOnce/); + assert.equal(source.split("askNotificationPermissionOnce(").length - 1, 1, path); + } + // Nowhere else asks: not on page load, not in the shell. + const watcher = read("src/components/report-reminder-watcher.tsx"); + assert.doesNotMatch(watcher, /requestPermission|askNotificationPermissionOnce/); + // The watcher has to keep asking in a background tab. + assert.doesNotMatch(watcher, /useVisibilityAwarePoll/); + assert.match(read("src/app/(app)/layout.tsx"), //); + + assert.match(read("src/components/personal-report/personal-report-page.tsx"), /reportStatusesSeen\(\[\{ id: reportId, status: seen \}\]\)/); + assert.match(read("src/components/annual/annual-report-page.tsx"), /reportStatusesSeen\(\[\{ id, status \}\]\)/); + assert.match(read("src/components/personal-report/personal-report-center.tsx"), /reportStatusesSeen\(nextReports\.map/); + + // Product 2026-11-20: reminders are on by default, there is no switch and no how-to row. + for (const path of ["src/components/app-sidebar.tsx", "src/components/billing-panel.tsx"]) { + let source = ""; + try { source = read(path); } catch { continue; } + assert.doesNotMatch(source, /Notification\b|report-reminders|提醒开关|怎么打开/, path); + } + const reminders = read("src/lib/report-reminders.ts"); + // The system notification carries the kind of report only. + assert.match(reminders, /body: "Jyotisha"/); + assert.match(reminders, /tag: `report:\$\{event\.report\.id\}`/); + assert.match(reminders, /window\.isSecureContext === false/); + assert.match(reminders, /window\.self !== window\.top/); +}); + +test("BUG-2072 the action toast is still a toast: sonner, six seconds, a button on it", () => { + const notify = read("src/lib/notify.ts"); + assert.match(notify, /export const ACTION_NOTICE_DURATION_MS = 6_000;/); + assert.match(notify, /action: \{ label: action\.label, onClick: \(\) => action\.onClick\(\) \}/); + assert.match(read("src/app/globals.css"), /\[data-sonner-toast\] \[data-button\] \{[^}]*background: transparent !important;/); + assert.match(read("src/components/report-reminder-watcher.tsx"), /label: "查看"/); +});