diff --git a/.claude/skills/factory-report/SKILL.md b/.claude/skills/factory-report/SKILL.md
index 03e05596..27a84704 100644
--- a/.claude/skills/factory-report/SKILL.md
+++ b/.claude/skills/factory-report/SKILL.md
@@ -6,7 +6,8 @@ argument-hint:
# Station: report
-**In:** a factory PR whose Zoom run is done (or that no Zoom-client spec covers).
+**In:** a factory PR whose Zoom run is done, or that needs none (no Zoom-client spec covers
+it, or the change reaches no part of the Zoom-only surface, CLAUDE.md).
**Out:** the PR body as the report, PR out of draft, label `ready-for-review`.
1. **Gather:** the issue, the plan, `.factory/oracles/.json`, `git diff --stat
@@ -16,7 +17,8 @@ argument-hint:
2. **Write the body** in the shape of `.github/pull_request_template.md`, the way PR #128
reads: Why from the issue's problem and evidence; What changes behaviour first; Testing
with real counts; Evidence from `run.md`, quoting non-pixel proof (request lines, KV,
- localStorage) since screenshots stay local in `test-runs/`; Not verified listing every ⏭
+ localStorage) since screenshots stay local in `test-runs/`, or, with no run, the Playwright
+ tests that stood in and why no real run was needed (the station's note); Not verified listing every ⏭
and anything else not run; Look here first with 1–3 file:line links to the hunks most
worth a human's read (riskHigh paths first).
3. **Publish:** `scripts/factory/gh.sh pr edit --body-file …`, `gh.sh pr ready `,
diff --git a/.claude/skills/factory-zoom/SKILL.md b/.claude/skills/factory-zoom/SKILL.md
index dfab510f..38469587 100644
--- a/.claude/skills/factory-zoom/SKILL.md
+++ b/.claude/skills/factory-zoom/SKILL.md
@@ -1,6 +1,6 @@
---
name: factory-zoom
-description: Factory station "zoom" (this Mac only). Take the dev lock, deploy a factory PR's branch to dev, run the Zoom-client specs its diff touches in the real Zoom client with the zoom-app-testing skill, record the evidence, restore dev, then run factory-report. Use for "/factory-zoom ", the daily scheduled Zoom run, or when scripts/factory/state.mjs says next is zoom.
+description: Factory station "zoom" (this Mac only). Take the dev lock, deploy a factory PR's branch to dev, run the Zoom-client specs its diff touches in the real Zoom client with the zoom-app-testing skill when the change reaches the Zoom-only surface (CLAUDE.md), record the evidence, restore dev, then run factory-report. Use for "/factory-zoom ", the daily scheduled Zoom run, or when scripts/factory/state.mjs says next is zoom.
argument-hint: | next
---
@@ -15,7 +15,11 @@ re-verified, then `factory-report`. Needs this Mac: `cliclick`, the Zoom client,
2. **Lock.** One Mac, one Zoom client, one dev host. If any open PR has `zoom:testing`, end
(busy). Otherwise add `zoom:testing` to this PR.
3. **Which specs.** Check out the branch, pull, `node scripts/factory/stop-gate.mjs --hits`.
- None → note "no Zoom-client spec covers this change" and skip to step 7.
+ Keep the hits whose change reaches the Zoom-only surface (CLAUDE.md "When a change needs
+ the real Zoom client"); when you can't tell, keep it. For each hit you drop, add the spec's
+ review note (the Playwright tests that stand in for its moved steps), commit and push it.
+ None left → note "no Zoom-client spec needs a real run for this change" with the reason, and
+ skip to step 7.
4. **Deploy.** Apply each spec's `needs` (flag values) to `env.dev.vars` in `wrangler.jsonc`
without committing, then `npm run cf:deploy:dev`. Note the version id it prints.
5. **Run** the specs with the `zoom-app-testing` skill, run name `--`: its
diff --git a/.claude/skills/zoom-app-testing/SKILL.md b/.claude/skills/zoom-app-testing/SKILL.md
index 87e10d6a..7a647f30 100644
--- a/.claude/skills/zoom-app-testing/SKILL.md
+++ b/.claude/skills/zoom-app-testing/SKILL.md
@@ -1,6 +1,6 @@
---
name: zoom-app-testing
-description: Drive the real Zoom desktop client (plus the web app and Worker logs) to run Toastmusters Timer manual test plans end to end, with screenshots and a timestamped run log as proof. Use this whenever the user wants to test, verify, QA, smoke-test or "click through" the Zoom app or a feature on dev/staging inside Zoom — e.g. "test the dev branch in my Zoom client", "run the club pro test plan", "check the badge on real video", "verify FINISH uploads", "automate the manual testing" — even if they don't say "skill" or name cliclick. Also use it unasked right after implementing a change whose files a Zoom-client spec `covers`: running those specs is part of done (CLAUDE.md), not a separate request. Also use it to plan which steps of a test plan can run unattended versus which need the user.
+description: Drive the real Zoom desktop client (plus the web app and Worker logs) to run Toastmusters Timer manual test plans end to end, with screenshots and a timestamped run log as proof. Use this whenever the user wants to test, verify, QA, smoke-test or "click through" the Zoom app or a feature on dev/staging inside Zoom — e.g. "test the dev branch in my Zoom client", "run the club pro test plan", "check the badge on real video", "verify FINISH uploads", "automate the manual testing" — even if they don't say "skill" or name cliclick. Also use it unasked right after implementing a change that touches files a Zoom-client spec `covers` and reaches the Zoom-only surface (CLAUDE.md, "When a change needs the real Zoom client"): running those specs is then part of done, not a separate request. A change that reaches none of it gets Playwright and a review note instead, not a Zoom run. Also use it to plan which steps of a test plan can run unattended versus which need the user.
---
# Zoom app testing (Toastmusters Timer)
@@ -21,7 +21,8 @@ directory `$S` below). Project facts — hosts, Worker name, KV ids, CLI, test p
The source of truth for *what to test* is `e2e/zoom-client/` (read its `README.md` for the
format, then `INDEX.md`). Pick the specs the user asked for, or those whose `covers` files
-changed (`npm run test:specs -- --stale`). Steps are already tagged `auto`/`human`. Honour
+changed in a way that reaches the Zoom-only surface (CLAUDE.md); before a release, every spec
+that `npm run test:specs -- --stale` lists. Steps are already tagged `auto`/`human`. Honour
each spec's `needs` (deploy, gate value) in preflight. If the code and a spec disagree, say so
in the run log and fix the spec in the same branch; don't test from memory. After a run,
update the spec's `verified_at` (git sha tested) and `verified_on`, mark failed specs
diff --git a/.claude/skills/zoom-app-testing/references/gotchas.md b/.claude/skills/zoom-app-testing/references/gotchas.md
index c2b4844c..97cbe8cd 100644
--- a/.claude/skills/zoom-app-testing/references/gotchas.md
+++ b/.claude/skills/zoom-app-testing/references/gotchas.md
@@ -11,6 +11,10 @@ Each of these cost time in the 2026-09-28 Club Pro run. Grouped by where they bi
symlink; use ⌘⇧G or drag from `open -R`) **and** the Claude Code binary
(`~/Library/Application Support/Claude/claude-code//claude.app` — quote the space;
re-add after Claude updates). Restart Claude.
+- **A locked screen looks like a working one to the tools** (2026-11-30): `screencapture`
+ writes a file (all black), `open -a zoom.us` starts Zoom, and no window ever appears.
+ `preflight.sh` now reports it and `zoom-up.sh` exits 2 before launching Zoom. Run preflight
+ before deploying or flipping flags for a run, so a locked Mac costs nothing to find out.
- **Sleep** kills everything: tail stream, scratchpad files, even the Zoom meeting. Keep the
display awake for the whole run.
- After a session restart the shell may default to **Node 20**; wrangler refuses it. The
@@ -44,6 +48,19 @@ Each of these cost time in the 2026-09-28 Club Pro run. Grouped by where they bi
click again. Worse while a Zoom dialog is pending. `click.sh --activate` does both.
- **Dropdowns / toggles**: single click only — a double click opens and closes them.
- **Page Down doesn't scroll** the webview and cliclick can't scroll → `scroll.sh`.
+- **Never chain clicks through a dialog without looking** (2026-11-30). After a text or number
+ field had focus, the next click on a button often only takes the focus (Add role, Save
+ Changes, a confirm's Clear All, Read with AI): the dialog stays open and every later click
+ and keystroke in the chain goes to it. The club survey does the same from the other side:
+ it opens a few seconds after FINISH and swallows what follows. Snap after each dialog step
+ (a 560 px copy is enough to tell) and click again when nothing changed.
+- **`pbcopy` follows the shell's locale** (2026-11-30). Under the C locale a file's "–" and
+ curly quotes reach the webview as mojibake. Use `LC_ALL=en_US.UTF-8 pbcopy < file`. A picture
+ goes on the clipboard with `osascript -e 'set the clipboard to (read (POSIX file "") as
+ «class PNGf»)'`. Save the user's clipboard first and put it back at the end.
+- **A file input opens the macOS file dialog over Zoom** (2026-11-30). ⌘⇧G, type the path,
+ Return selects the file; then click Open. Zoom stays the frontmost app throughout, so
+ `click.sh` works on the dialog.
- Zoom opens external links through `marketplace.zoom.us/z/`; for hosts not on the
app's Domain Allow List it stops at "Accessing Untrusted Web Site". Read the final URL with
`osascript -e 'tell application "Google Chrome" to get URL of active tab of front window'`
diff --git a/.claude/skills/zoom-app-testing/references/toastmusters.md b/.claude/skills/zoom-app-testing/references/toastmusters.md
index 26044dec..f3a92ca9 100644
--- a/.claude/skills/zoom-app-testing/references/toastmusters.md
+++ b/.claude/skills/zoom-app-testing/references/toastmusters.md
@@ -23,14 +23,23 @@ club lapse. Flipping it for a spec's `needs` is pre-approved (CLAUDE.md "Standin
revert + redeploy at the end — while `"1"`, other dev testers without Pro are refused sync.
## Club tooling
-- `node scripts/club-cli.mjs pending|create|show|rotate --env dev …` (`create` also takes
- `--customer cus_…` to link Stripe).
-- Useful keys: `club:`, `club-by-code:`, `club-member::zoom:`,
- `club-device::`, `club-pending:`.
-- Device state lives in `localStorage`: `toastmaster_club` (token, ver, plan, role…),
- `toastmaster_club_presets`, `toastmaster_club_outbox` (speeches not yet uploaded).
-- The admin console only recognises a Zoom sign-in in a browser that has also activated the
- club code (open `/pro/` first) — see `docs/plans/08-club-pro-bugfix-plan.md` #1.
+- `node scripts/club-cli.mjs pending|create|show|rotate|backfill-club-of --env dev …`
+ (`create` also takes `--customer cus_…` to link Stripe; `rotate --club `;
+ `backfill-club-of` is dry until `--apply`).
+- Since #167 a club belongs to Zoom accounts: a signed-in, approved account joins with the
+ code (3 places besides the owner, the count kept by the `ClubPlaces` Durable Object), and
+ the club follows that account. There is no club token, no `X-Club` header and no
+ `club-device:` row; every club request carries the session (Bearer in Zoom, cookie on the
+ web).
+- Useful keys: `club:` (`ownerUid`), `club-by-code:`, `club-member::zoom:`
+ (`{role,…}`, or `{blockedAt,…}` when blocked), `club-of:zoom:` (`{clubId, at}`),
+ `club-pending:`.
+- Device state lives in `localStorage`: `toastmaster_club` (the account's copy: uid, ver,
+ plan, role, isOwner…), `toastmaster_club_presets`, `toastmaster_club_outbox` (speeches not
+ yet uploaded); sessionStorage `toastmaster_pending_club_code` holds a code a guest typed
+ before approving the app.
+- The admin console's Zoom door is the account's own club (`club-of`), so signing in with
+ Zoom in any browser is enough; the billing-address link is the other door.
## Test plans and past runs
- `e2e/zoom-client/` — **versioned specs, the source of truth** (see its README and INDEX).
diff --git a/.claude/skills/zoom-app-testing/scripts/_env.sh b/.claude/skills/zoom-app-testing/scripts/_env.sh
index f08c633f..06c0d6c0 100755
--- a/.claude/skills/zoom-app-testing/scripts/_env.sh
+++ b/.claude/skills/zoom-app-testing/scripts/_env.sh
@@ -7,4 +7,9 @@ BIN="$ROOT/test-runs/.bin"
for n in "$HOME"/.nvm/versions/node/v2[2-9]*/bin /opt/homebrew/opt/node@2[2-9]/bin; do
[ -x "$n/node" ] && { export PATH="$n:$PATH"; break; }
done
+# True while the Mac's screen is locked. A locked screen still lets screencapture
+# write a file (all black) and lets Zoom launch, but shows no window and takes no
+# clicks; unlocking is the user's to do. Seen 2026-11-30: a run got as far as
+# deploying and launching Zoom before a black screenshot gave it away.
+screen_locked() { ioreg -n Root -d1 -a 2>/dev/null | grep -A1 CGSSessionScreenIsLocked | grep -q ' '; }
need_run() { [ -n "$RUN" ] && [ -d "$RUN" ] || { echo "No active run — start one with new-run.sh " >&2; exit 1; }; }
diff --git a/.claude/skills/zoom-app-testing/scripts/preflight.sh b/.claude/skills/zoom-app-testing/scripts/preflight.sh
index ba8756b0..a2dab63a 100755
--- a/.claude/skills/zoom-app-testing/scripts/preflight.sh
+++ b/.claude/skills/zoom-app-testing/scripts/preflight.sh
@@ -4,6 +4,8 @@
source "$(dirname "$0")/_env.sh"
KV=""; [ "$1" = "--kv" ] && KV=$2
fail=0; ok(){ echo "✅ $1"; }; bad(){ echo "❌ $1"; echo " fix: $2"; fail=1; }; warn(){ echo "⚠️ $1"; [ -n "$2" ] && echo " note: $2"; }
+screen_locked && bad "the Mac's screen is locked: Zoom can show no window and take no clicks" "the user has to unlock it (human-only). The run is blocked until then: don't deploy or flip flags for it yet" \
+ || ok "screen unlocked"
T=$(mktemp -t zt).png
screencapture -x "$T" 2>/dev/null && [ -s "$T" ] && ok "Screen Recording (screencapture works)" \
|| bad "screencapture fails ('could not create image from display')" "System Settings → Privacy & Security → Screen & System Audio Recording → enable Claude, then quit & reopen Claude"
diff --git a/.claude/skills/zoom-app-testing/scripts/zoom-up.sh b/.claude/skills/zoom-app-testing/scripts/zoom-up.sh
index d34fffc3..d06a62cf 100755
--- a/.claude/skills/zoom-app-testing/scripts/zoom-up.sh
+++ b/.claude/skills/zoom-app-testing/scripts/zoom-up.sh
@@ -21,6 +21,7 @@ front() { osascript -e 'tell application "System Events" to get name of first pr
wait_for() { local n=$1; shift; for _ in {1..$n}; do "$@" && return 0; sleep 1; done; return 1; }
in_meeting && { echo "✅ Zoom meeting already open"; exit 0; }
+screen_locked && { echo "⏸ the Mac's screen is locked — unlocking is a human step. Zoom not launched."; exit 2; }
if ! pgrep -x zoom.us >/dev/null; then
open -a zoom.us || { echo "❌ could not launch zoom.us"; exit 1; }
diff --git a/.dev.vars.example b/.dev.vars.example
index 5ededeb9..d2de2d62 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -28,3 +28,10 @@ STRIPE_SECRET_KEY=
# Signing secret of the webhook endpoint (`stripe listen --forward-to localhost:8787/api/stripe/webhook`
# prints one for local dev).
STRIPE_WEBHOOK_SECRET=
+# Table Topics theme search (worker/tabletopics-match.js), free OpenRouter models
+# only. Empty: /tabletopics/api/match answers 503 and the page uses its offline
+# keyword match. The Pro agenda import (worker/agenda-import.js) uses the same
+# key as its fallback when Workers AI fails; its first choice is the `AI`
+# binding in wrangler.jsonc, which needs no secret but always calls the real
+# service, even under `wrangler dev`.
+OPENROUTER_API_KEY=
diff --git a/.factory/README.md b/.factory/README.md
index bd2cd840..0fc31b7b 100644
--- a/.factory/README.md
+++ b/.factory/README.md
@@ -90,6 +90,12 @@ They run Claude Code on Opus 5.5 at high effort (`--model claude-opus-5-5 --effo
`claude_args`). With `CLAUDE_CODE_OAUTH_TOKEN` they use the account's Claude subscription, so
each run counts against the same usage limits as interactive sessions.
+`factory-build.yml` gives the Claude step the job's own token (`github_token`) instead of the
+Claude App token. The App token expires after 60 minutes, and a build runs longer; past that
+hour the station can't push, label or comment, and ends without a word. Commits pushed with
+the job token don't start CI, so a factory PR's checks stay on the oracle commit until the
+Zoom station pushes from the Mac. Verify runs the whole suite inside the build anyway.
+
`master` is the default branch, so `factory-plan.yml` and `factory-build.yml` must be
identical on `dev` and `master`: issue-label events run the default branch's copy, and the
Claude action skips a workflow that differs from it (the run then fails at "Check the station
diff --git a/.factory/oracles/160.json b/.factory/oracles/160.json
new file mode 100644
index 00000000..d3a15bf7
--- /dev/null
+++ b/.factory/oracles/160.json
@@ -0,0 +1,17 @@
+{
+ "issue": 160,
+ "files": [
+ "packages/shared/__tests__/appLinks.test.js",
+ "worker/routing.test.js",
+ "apps/web/src/pages/Landing.test.jsx",
+ "apps/web/src/components/Footer.test.jsx",
+ "apps/web/src/staticPages.patron.test.js",
+ "apps/zoom-app/src/components/Footer.test.jsx",
+ "apps/zoom-app/src/components/ProComingSoon.test.jsx",
+ "apps/zoom-app/src/b/TopBar.test.jsx",
+ "apps/zoom-app/src/b/NewLookShell.test.jsx",
+ "e2e/web.patron-link.spec.js",
+ "e2e/zoom.new-look.spec.js",
+ "e2e/zoom.pro-coming-soon.spec.js"
+ ]
+}
diff --git a/.factory/oracles/167.json b/.factory/oracles/167.json
new file mode 100644
index 00000000..025b1c45
--- /dev/null
+++ b/.factory/oracles/167.json
@@ -0,0 +1,21 @@
+{
+ "issue": 167,
+ "files": [
+ "worker/club-places-fake.js",
+ "worker/club-membership-helpers.js",
+ "worker/club-places.test.js",
+ "worker/club-membership.test.js",
+ "worker/club-membership-admin.test.js",
+ "worker/no-club-token.test.js",
+ "packages/shared/__tests__/clubAccount.test.js",
+ "packages/shared/__tests__/clubOutbox.test.js",
+ "apps/zoom-app/src/components/UpgradeModal.clubJoin.test.jsx",
+ "apps/zoom-app/src/utils/zoomIdentity.refresh.test.js",
+ "apps/zoom-app/src/main.clubOrder.test.jsx",
+ "apps/web/src/pages/ProActivate.test.jsx",
+ "apps/web/src/components/ClubCodeSection.test.jsx",
+ "apps/web/src/pages/ClubAdmin.members.test.jsx",
+ "e2e/zoom.club-join.spec.js",
+ "e2e/web.club-join.spec.js"
+ ]
+}
diff --git a/.factory/oracles/168.json b/.factory/oracles/168.json
new file mode 100644
index 00000000..a4ba5ff0
--- /dev/null
+++ b/.factory/oracles/168.json
@@ -0,0 +1,17 @@
+{
+ "issue": 168,
+ "files": [
+ "packages/shared/__tests__/speakerEntry.test.js",
+ "packages/shared/__tests__/storage.test.js",
+ "packages/shared/__tests__/profileMerge.test.js",
+ "apps/zoom-app/src/context/TimerContext.test.jsx",
+ "apps/web/src/context/TimerContext.test.jsx",
+ "apps/zoom-app/src/hooks/useLiveTimer.test.jsx",
+ "apps/zoom-app/src/components/LiveTab.speakerEntry.test.jsx",
+ "apps/zoom-app/src/b/TimerTab.speakerEntry.test.jsx",
+ "apps/web/src/components/LiveTab.speakerEntry.test.jsx",
+ "e2e/zoom.speaker-entry.spec.js",
+ "e2e/zoom.new-look.speakers.spec.js",
+ "e2e/web.speaker-entry.spec.js"
+ ]
+}
diff --git a/.factory/oracles/80.json b/.factory/oracles/80.json
new file mode 100644
index 00000000..47109075
--- /dev/null
+++ b/.factory/oracles/80.json
@@ -0,0 +1,22 @@
+{
+ "issue": 80,
+ "files": [
+ "worker/durable-object-fake.js",
+ "worker/polls.test.js",
+ "worker/polls-zoom.test.js",
+ "worker/club-poll-template.test.js",
+ "worker/club-meetings.test.js",
+ "worker/club-share.test.js",
+ "worker/routing.test.js",
+ "worker/csp.test.js",
+ "worker/gating.test.js",
+ "packages/shared/__tests__/polls.test.js",
+ "packages/shared/__tests__/profileMerge.test.js",
+ "packages/shared/__tests__/reportImage.test.js",
+ "packages/shared/__tests__/clubArchive.test.js",
+ "apps/zoom-app/src/utils/zoomSdk.test.js",
+ "apps/zoom-app/src/components/PollTab.test.jsx",
+ "apps/zoom-app/src/components/TimerStage.test.jsx",
+ "e2e/zoom.meeting-polls.spec.js"
+ ]
+}
diff --git a/.factory/plans/160-patron-coffee-link.md b/.factory/plans/160-patron-coffee-link.md
new file mode 100644
index 00000000..8be213bc
--- /dev/null
+++ b/.factory/plans/160-patron-coffee-link.md
@@ -0,0 +1,188 @@
+# Monetization: add a "Buy Me a Coffee" patron option alongside Pro (#160)
+
+## Problem
+Pro is the only way to pay for Toastmusters today. People who like the free timer and want to
+say thanks, without needing Pro's features, have no way to do it. The issue asks for a low-key
+"Buy Me a Coffee" patron link that sits beside Pro, never replaces it and never locks anything.
+
+Plan review (2026-11-28) widened it: the link also goes in the Zoom app, in both looks, in one
+footer that is always visible. Feedback and Review merge into one item to make room, so "Buy me
+a coffee" and "Upgrade to Pro" can show their full text.
+
+## Findings
+Nothing donation-related exists yet. A search for coffee, ko-fi, donat, sponsor, patron and tip
+only finds "Coffee break" agenda fixtures and the "not sponsored by Toastmasters International"
+disclaimer.
+
+**External link constants.** These belong in `packages/shared/appLinks.js`. Its header (:1-3)
+says it holds "external links that more than one component needs". Two examples:
+`ZOOM_MARKETPLACE_REVIEW_URL` (:9) and `TUTORIALS_URL` (:32). The file is re-exported from
+`packages/shared/index.js:9`.
+
+**Landing page footer** (`apps/web/src/pages/Landing.jsx:985-1037`):
+- It has four columns: Resources, Legal, Get Started and Tools. Under them is the copyright line (:1036).
+- External links use `target="_blank" rel="noopener noreferrer"` with `onClick={trackCta(cta, 'footer')}` (e.g. :1016). `trackCta` is at :605 and sends `cta_clicked`.
+
+**Web timer footer** (`apps/web/src/components/Footer.jsx:40-70`, mounted at
+`apps/web/src/pages/TimerApp.jsx:119`):
+- It holds three icon links: Add to Zoom, Send Us Feedback and Leave a Review.
+- Each external link already uses `target="_blank" rel="noopener noreferrer"` and `trackEvent('cta_clicked', { …, location: 'timer-footer' })` (:47).
+- At the panel's 480 px width its labels already wrap to two lines; a fourth item does not make it taller (measured 2026-11-28).
+
+**Static pages.** All 13 pages in `apps/web/public/*.html` (the 11 SEO pages, `404.html` and
+`tutorials.html`) hand-copy one `` with 16-20 links. `/support` is
+`apps/zoom-app/public/support.html` (rewritten in `worker/index.js:36-41`). It has no footer, and
+it is the support URL on the Marketplace listing, so Zoom reviewers see it.
+
+**Zoom app, classic footer** (`apps/zoom-app/src/components/Footer.jsx:84-133`): Send Us
+Feedback, Review, then the Pro slot (Upgrade / Pro once released, `ProComingSoon` before). The
+comment at :84 says labels must stay short in the 400 px panel. Measured in the real footer:
+- "Feedback · Upgrade to Pro · Buy me a coffee" inline at today's padding needs 435 px: it does not fit 400.
+- Adding a fourth item, even an icon-only cup, wraps "Send Us Feedback" onto two lines.
+- Three equal columns with the icon above a 12 px label fit every full label at 360 px.
+
+**Zoom app, new look (design B)** has no footer:
+- The top row holds the section switch, the Pro chip (`b/ProChip.jsx`) and the ⋯ menu (`b/TopBar.jsx`).
+- The ⋯ menu's help group holds How-to videos, Send feedback and Rate the app (`b/MoreMenu.jsx:154-166`).
+- `e2e/zoom.new-look.spec.js` checks the classic look's footer is visible (:29), asserts the new look has none (:40) and lists the exact ⋯ items (:236-245).
+
+**Zoom app: opening a link.**
+- External URLs open through `openExternalUrl` (`apps/zoom-app/src/utils/zoomSdk.js:2176`), which calls `zoomSdk.openUrl`.
+- `openUrl` only opens domains on the Marketplace Domain Allow List. `www.toastmusters.com` is on it (`appLinks.js:20-23`, review of 2026-10). `buymeacoffee.com` is not.
+- So the Zoom app opens `https://www.toastmusters.com/coffee`, and the Worker redirects that to the Buy Me a Coffee page. No new allow-list review is needed.
+- Zoom requires the listing to disclose paid features (`docs/BILLING.md:199-203`). A voluntary tip unlocks nothing, so it is not a paid feature, but a reviewer may ask about it.
+
+**Reports.**
+- None of the three Report tabs has a footer: web `ReportTab.jsx`, Zoom classic `ReportTab.jsx` and `b/ReportTabB.jsx`.
+- The exported image and the hosted `/r/` page end with "Timed with Toastmusters Timer" (`packages/shared/reportImage.js:38`, `worker/club-share.js:305-308`).
+
+**Content Security Policy (CSP).** A plain `` link and a Worker redirect need no CSP change.
+The official BMC floating widget would need `script-src` and `frame-src` changes to `ROOT_CSP`
+(`worker/index.js:25-26`), both `vercel.json` copies and `worker/csp.test.js`.
+
+**Tests in this area.**
+- Web: `Landing.test.jsx` checks footer links (:265, :276); `components/Footer.test.jsx` checks Add to Zoom (:19) and the review link (:26, :34).
+- Zoom classic: `components/Footer.test.jsx` and `ProComingSoon.test.jsx`; `e2e/zoom.pro-coming-soon.spec.js:14-16, :40-43` find the Pro button inside `footer`.
+- Zoom new look: `b/TopBar.test.jsx` (:91, :104 the ⋯ menu), `b/NewLookShell.test.jsx`, `e2e/zoom.new-look.spec.js`.
+- Zoom-client specs whose `covers` this touches: `pro-coming-soon.md` (Footer.jsx, ProComingSoon.jsx), `pro-launch.md` (Footer.jsx), `new-look.md` (all of `apps/zoom-app/src/b`).
+
+## Approach
+One stacked footer in every Zoom panel, plain links on the web. The design is on the Claude
+Design canvas "Zoom panel footer: coffee and Pro" (https://claude.ai/artifact/RaGBTy2ZkiB6J1Jp4Nsp7E),
+boards "Old look · stacked footer", "New look · stacked footer" and "New look at 360 px ·
+Feedback opened".
+
+1. **Constants** in `packages/shared/appLinks.js`:
+ - `PATRON_URL = 'https://buymeacoffee.com/shuhao'`: the web links use it directly.
+ - `PATRON_REDIRECT_URL = 'https://www.toastmusters.com/coffee'`: the Zoom app opens this, because only the toastmusters.com domain is allow-listed.
+ - Doc comments: a thank-you only, unlocks nothing.
+2. **Worker** (`worker/index.js`): `GET /coffee` returns a 302 to `PATRON_URL`. It is a 302, not a 301, so browsers don't cache it and the target can change later. It sits next to the other clean-URL routes and before the static asset fallback.
+3. **Zoom footer** (`apps/zoom-app/src/components/Footer.jsx`), restyled as three equal columns, left to right: Feedback, the Pro slot, Buy me a coffee. Each column is a button with an 18 px icon above a 12 px label, at least 48 px tall.
+ - **Feedback** (MessageSquare) opens a small menu above it with two items:
+ - "Send feedback" opens today's `FeedbackModal` and keeps `feedback_button_clicked`.
+ - "Rate the app" runs today's `handleReviewClick`: `review_prompt_accepted` with `source: 'footer'`, and `markPromptAnswered(REVIEW_PROMPT)` only once the listing opened.
+ - The menu closes on Escape, on an outside click and after a choice.
+ - **The Pro slot**, in the middle, keeps today's logic:
+ - Pro not released: `ProComingSoon`, restyled to the column, lock icon, label "Pro coming soon".
+ - Released, free plan: "Upgrade to Pro" (Sparkles, blue).
+ - Pro plan: "Pro" (amber).
+ - The red "New" dot and the preloaded Upgrade dialog stay as they are.
+ - **Buy me a coffee** (Coffee), on the right, calls `openExternalUrl(PATRON_REDIRECT_URL)` and sends `cta_clicked` `{ cta: 'patron', location: 'zoom-footer', look: 'classic' | 'new' }`. If the open fails, a toast says to visit buymeacoffee.com/shuhao.
+4. **New look** gets the same `Footer` at the bottom of `b/NewLookShell.jsx`, with `look="new"`:
+ - `b/TopBar.jsx` drops the Pro chip, since the footer's Pro slot replaces it. `b/ProChip.jsx` is removed if nothing else uses it.
+ - `b/MoreMenu.jsx` drops "Send feedback" and "Rate the app". It keeps How-to videos, Your plan, Join my club with a code, Roles & timing rules and Clear the timer from my video.
+5. **Landing footer**, Get Started column (`Landing.jsx:1014-1019`): add "Buy me a coffee".
+ - `href={PATRON_URL}`, `target="_blank"`, `rel="noopener noreferrer"`, `onClick={trackCta('patron', 'footer')}`.
+ - Same classes as its neighbours, with no button styling.
+6. **Web timer footer** (`apps/web/src/components/Footer.jsx`): add a fourth link after "Leave a Review".
+ - Lucide `Coffee` icon and the text "Buy me a coffee", with the same classes and `rel` as its neighbours.
+ - `trackEvent('cta_clicked', { cta: 'patron', location: 'timer-footer', page: '/timer/app' })`.
+7. **Static pages**: add the same "Buy me a coffee" link (`PATRON_URL`, new tab, `rel="noopener noreferrer"`) to the footer of each of the 13 pages in `apps/web/public/*.html`, and as one line on `apps/zoom-app/public/support.html`.
+8. No flag, no billing or entitlement change, no CSP change. Nothing is gated.
+
+Rejected:
+- **Four inline footer buttons:** they don't fit 400 px; "Send Us Feedback" wraps (measured).
+- **Inline footer with an icon-only Feedback:** 364 px, so it fits 400 but not a 360 px panel.
+- **Coffee only in the new look's ⋯ menu:** it hides the link behind a click. Owner's call: everything visible in a footer in both looks.
+- **Opening buymeacoffee.com straight from Zoom:** it needs a new allow-list review. The toastmusters.com redirect avoids that.
+- **BMC floating widget:** third-party script and frame exceptions in three CSP copies, and a bubble on every page.
+- **Report tab, exported image or share page:** reports go to whole clubs, so an ask there reads as a nag.
+- **Recurring tiers or patron perks:** any perk turns the link into a second paywall. Thanks only.
+- **A feature flag:** a static link has nothing to roll back that a revert can't. Flags also touch `worker/flags.js` (riskHigh).
+
+## Acceptance criteria
+- AC-1: Given the landing page at `/`, when the footer renders, then a "Buy me a coffee" link points at `PATRON_URL` with `target="_blank"` and `rel="noopener noreferrer"`.
+- AC-2: Given the landing page, when a visitor clicks "Buy me a coffee", then `cta_clicked` is sent with `{ cta: 'patron', location: 'footer', page: '/' }`.
+- AC-3: Given the web timer at `/timer/app`, when the footer renders, then a "Buy me a coffee" link points at `PATRON_URL` with `target="_blank"` and `rel="noopener noreferrer"`, after "Leave a Review", and Add to Zoom, Send Us Feedback and Leave a Review are still there.
+- AC-4: Given the web timer, when someone clicks "Buy me a coffee", then `cta_clicked` is sent with `{ cta: 'patron', location: 'timer-footer', page: '/timer/app' }`.
+- AC-5: `PATRON_URL` is `https://buymeacoffee.com/shuhao` and `PATRON_REDIRECT_URL` is `https://www.toastmusters.com/coffee`, both exported from `@toastmaster-timer/shared`.
+- AC-6 (nothing gated): Given someone who never clicked the link, then the timer, agenda and report flows in both looks and on the web behave as before.
+- AC-7 (one footer, both looks):
+ - Given the Zoom panel in the classic look or the new look, at 360 px and at 400 px wide, then a footer shows three equal columns, left to right: Feedback, the Pro slot, and Buy me a coffee.
+ - Each label shows in full on one line, and nothing scrolls sideways.
+- AC-8 (new look clean-up): Given the new look, then the top row has no Pro chip, and the ⋯ menu has no "Send feedback" or "Rate the app" but still has its other items.
+- AC-9 (merged Feedback):
+ - When someone presses Feedback, then a menu opens with "Send feedback" and "Rate the app".
+ - "Send feedback" opens the feedback form and sends `feedback_button_clicked`.
+ - "Rate the app" opens the Marketplace listing and sends `review_prompt_accepted` with `source: 'footer'`. It marks the review prompt answered only if the listing opened.
+ - Escape or a click outside closes the menu.
+- AC-10 (coffee in Zoom):
+ - When someone presses "Buy me a coffee" in the Zoom panel, then `openExternalUrl` is called with `PATRON_REDIRECT_URL`, and `cta_clicked` is sent with `{ cta: 'patron', location: 'zoom-footer', look }`.
+ - If the open fails, a toast names buymeacoffee.com/shuhao.
+- AC-11 (Pro slot):
+ - Given the `pro` flag off, the slot shows "Pro coming soon" with today's locked popover.
+ - Given it on and a free plan, the slot shows "Upgrade to Pro", which opens the Upgrade dialog.
+ - Given a Pro plan, the slot shows "Pro".
+ - The "New" dot behaves as today.
+- AC-12: A GET of `/coffee` on the main site returns a 302 whose `Location` is `PATRON_URL`.
+- AC-13: `/support` shows a "Buy me a coffee" link to `PATRON_URL` that opens in a new tab.
+- AC-14: Each of the 13 pages in `apps/web/public/*.html` has a "Buy me a coffee" link to `PATRON_URL` in its footer, with `target="_blank"` and `rel="noopener noreferrer"`.
+
+## Test list
+| AC | Unit | Playwright | Zoom-client spec |
+|---|---|---|---|
+| AC-1, AC-2 | `Landing.test.jsx`: new cases for the link and its `trackEvent` | NEW `e2e/web.patron-link.spec.js`: `/` footer link href, target, rel | none: `Landing.jsx` is not covered |
+| AC-3, AC-4 | web `components/Footer.test.jsx`: new cases (attributes, order, event); :19, :26, :34 stay green | `e2e/web.patron-link.spec.js`: `/timer/app` footer link | none |
+| AC-5 | `packages/shared/__tests__/appLinks.test.js`: both constants and their exports | — | none |
+| AC-6 | existing suites unchanged | `web.timer-flow`, `web.report-flow`, `web.agenda-flow`, `zoom.new-look` flow tests stay green | — |
+| AC-7 | zoom `components/Footer.test.jsx`: three items in order (Feedback, Pro slot, Buy me a coffee), full labels; `b/NewLookShell.test.jsx`: footer present | `e2e/zoom.new-look.spec.js` :40 changes from "no footer" to "footer with three items in order", at 360 and 400; the classic look's check at :29 gains the same order; no sideways scroll | `new-look.md`, `pro-coming-soon.md`: steps updated to the new footer, checked in the real client |
+| AC-8 | `b/TopBar.test.jsx` :91, :104 updated (no chip, fewer items) | `zoom.new-look.spec.js` :236-245 item list updated | `new-look.md` |
+| AC-9 | zoom `Footer.test.jsx`: menu opens, each item's handler and events, Escape closes | NEW case in `e2e/zoom.new-look.spec.js`: Feedback → both items visible | `new-look.md` and `pro-launch.md` step for Rate the app opening the Marketplace |
+| AC-10 | zoom `Footer.test.jsx`: `openExternalUrl` called with `PATRON_REDIRECT_URL`; failure → toast | — | new step in `new-look.md`: Buy me a coffee opens the browser on the BMC page (via /coffee) |
+| AC-11 | `ProComingSoon.test.jsx` and zoom `Footer.test.jsx` (three plan states) | `e2e/zoom.pro-coming-soon.spec.js` :14-16, :40-43 updated to the new labels | `pro-coming-soon.md`, `pro-launch.md` |
+| AC-12 | `worker/routing.test.js`: `/coffee` → 302, `Location` = `PATRON_URL` | — | none |
+| AC-13, AC-14 | NEW `apps/web/src/staticPages.patron.test.js`: reads each of the 13 html files and `support.html`, asserts the link and its attributes | — | none |
+
+## Risk
+**Medium.** The web part is low: static links and one constant. The Zoom part changes the panel
+layout in both looks:
+- The new look gains a footer.
+- The Pro chip moves from the top row to the footer.
+- Two ⋯ items move into the merged Feedback menu.
+
+That touches the Pro entry point people use today, so the Zoom station must run `new-look.md`,
+`pro-coming-soon.md` and `pro-launch.md` in the real client. No `config.json` `riskHigh` path is
+touched: `worker/index.js` gets one redirect route, and billing, entitlements, flags and the CSP
+are unchanged.
+
+Watch for:
+- **The redirect.** `/coffee` must be routed before the static asset fallback and must not catch the `zoom.` host's sidebar routing.
+- **The listing.** A Zoom reviewer may ask about the tip link at the next review (`docs/BILLING.md:199-203`). It unlocks nothing, so the listing needs no paid-feature line, but have that answer ready.
+- **Ownership.** `buymeacoffee.com/shuhao` exists and belongs to the owner (confirmed 2026-11-28).
+
+## Open questions
+Answered by the owner on 2026-11-28.
+- **Q1: Platform.** Buy Me a Coffee, Ko-fi or GitHub Sponsors?
+ **Answer: Buy Me a Coffee.**
+- **Q2: The account and handle.** Which BMC page does `PATRON_URL` point at?
+ **Answer: `https://buymeacoffee.com/shuhao`.** The page exists and is the owner's.
+- **Q3: One-time or recurring, and perks?**
+ **Answer: set on the Buy Me a Coffee page itself, not in our code.** We only link to the page; no perks in the app.
+- **Q4: The Zoom app.**
+ **Answer: yes, in both looks, always visible.** One stacked footer, left to right: Feedback (Send feedback and Rate the app merged), the Pro slot, and Buy me a coffee, all with full labels. The new look's Pro chip and its ⋯ Send feedback and Rate the app move into it. Design: Claude Design canvas "Zoom panel footer: coffee and Pro". The Zoom app reaches the page through the allow-listed `www.toastmusters.com/coffee` redirect.
+- **Q5: Placement on the web.**
+ **Answer: everywhere.** The landing footer, the web timer footer, `/support` and the 13 static pages.
+- **Q6: Wording.**
+ **Answer: "Buy me a coffee"**, with no extra note.
+- **Q7: Acceptance criteria.**
+ **Answer: rewritten above (AC-1 to AC-14) from these answers.** Confirm, or edit them before adding `plan:approved`.
diff --git a/.factory/plans/167-club-account-invites.md b/.factory/plans/167-club-account-invites.md
new file mode 100644
index 00000000..cba9b501
--- /dev/null
+++ b/.factory/plans/167-club-account-invites.md
@@ -0,0 +1,581 @@
+# Clubs: an invite code for up to 3 other Zoom accounts, and club Pro follows the account (#167)
+
+## Problem
+Club Pro belongs to a device today. A browser or Zoom webview types the code, gets a 24 h club
+token (`X-Club`) and a `club-device:` row. Pro drops when the token expires, the webview is
+cleared or the person changes computer, and a code admits any number of devices with or
+without an account. Club Pro should belong to Zoom accounts: one code per club, 3 places
+besides the owner, one club per account, and nothing stored per device. Production has no
+club records (2026-11-06), so no migration is needed.
+
+**Review applied (2026-11-21).** The answers to Q1–Q10 on PR #169 are folded in below; see
+"Decisions". They change four things from the first draft:
+- The owner (the account that pays) can't leave or be removed.
+- Remove lets the account rejoin with the code.
+- A new **Block** in the console's "…" menu keeps an account out.
+- The 3-place cap is made atomic with a Durable Object.
+
+## Findings
+Read on `dev` 26c4477. Supersedes the plan on `factory/146-club-membership-zoom-account`,
+which kept device tokens.
+
+**Worker: joining and state** (`worker/club.js`)
+- `handleClubActivate` (254-296), in order: throttle by IP (38-48, 429 at 260), then
+ `normalizeCode`, then `club-by-code:`, then `resolveAccess` with no uid (277; not entitled
+ → `invalid_code`). Only then `readSession` (282), which is optional. Then `attachDevice`
+ (286-292). The session is never required.
+- `attachDevice` (326-360) writes the device row and carries its own `revokedAt` (331-341).
+ It writes a member row only when it is missing (349-357) and never reads
+ `member.revokedAt`. That is the revocation hole. There is no cap and no one-club check.
+- `verifiedClubId` (233-245) checks the device row only.
+- `handleClubCreate` (382-422) calls `attachDevice` (401), so the creator gets a device row
+ and a token too.
+- `handleClubLeave` (439-452) deletes this device's row and leaves the member row.
+- `handleClubState` (463-496), `GET /api/club`: device row missing or revoked → 403 (475).
+ Re-mints the token (489-493).
+- `buildClubState` (179-218) never touches devices. It returns `code`/`shareUrl` to admins
+ only (209-210).
+- `CLUB_DOORS` (509) are activate, create, magic-link and manage. `pro` gates them (525-528).
+
+**Worker: the token and its readers**
+- `worker/club-token.js`: `mintClubToken` (47), `verifyClubToken` (79-118), TTL 24 h (23),
+ `readClubHeader` (138).
+- `readClub` (`worker/auth.js:137-141`) is HMAC only. Every reader of `X-Club` already has the
+ session uid, except the speech, history and share routes:
+
+ | Site | Today | Uid? |
+ |---|---|---|
+ | `assets.js:84`, `profile.js:69` | `verifiedClubId(readClub)` then `resolveAccess` | required |
+ | `club-presets.js:139-156`, `club-cards.js:154-176` (`requirePublisher`) | same, plus `canPublish` | required |
+ | `club-cards.js:265` `handleCardDownload` | `readClub()?.clubId`, else the admin context | no |
+ | `club-meetings.js:221-236` `appendSpeech` | `verifiedClubId`, no uid by design | no |
+ | `club-meetings.js:278`, `:358` list and read | claims.clubId, HMAC only | no |
+ | `club-share.js:122-135` | `verifiedClubId` | no |
+ | `club-admin-routes.js:94-131` `readAdminContext` | session uid plus X-Club claims, else `club-admin-of` | yes |
+ | `session.js:98`, `me.js:48` | `resolveAccess({uid, clubId: readClub()?.clubId})` | yes |
+
+- `resolveAccess` (`worker/entitlements.js:233-261`) takes the club id from its caller and
+ never looks one up by uid. Grace and lapse live in `subscriptionGrantsAccess` (60-74) and
+ stay as they are.
+
+**Worker: members, admin, code**
+- Keys (`worker/club-admin.js`):
+ - `club-device:` 141
+ - `club-member::zoom:` 142, holding `{role, displayName, addedAt, revokedAt}`
+ - `club-admin-of:zoom:` 162-181, admins only and single-valued
+ - No uid→club index exists for other members.
+- `readMemberRole` (200-212) treats a revoked row as no role.
+- `createClubFromPending` (242-293) writes the buyer's admin member row when `pending.uid` is
+ set. The club record has no owner uid, only `stripeCustomerId` and `billingEmail`. The
+ owner's uid can be found through `stripe:customer:` (`worker/billing.js`
+ `lookupUidByCustomer`, 56).
+- `rotateClubCode` (309-344) revokes every device row unless `revokeDevices === false`
+ (325-341). Its only caller is `scripts/club-cli.mjs` `rotate` (313-318).
+- `club-admin-routes.js`:
+ - `handleClubRoster` (192-282) groups device rows by uid; `guestDevices` at 231-233.
+ - `handleMemberRole` (315-371): `revoked` sets `revokedAt` (341-349); any other role
+ restores, with no cap check; `last_admin` 409 at 336-339; device cascade at 357-368.
+ - `handleMemberName` (388-414) creates a member row when it is missing. With a cap, that
+ would take a place without a join.
+ - `handleDeviceRevoke` (423-442); dispatched at 608-612.
+- `club-create.js` `createClubForSubscriber` (59-121) is called from three places: the
+ checkout webhook (`stripe-webhook.js:97-117`), `/api/club/create` and `club-cli.mjs create`.
+
+**Shared** (`packages/shared/club.js`)
+- `readStored` (94-104) rejects an entry with no `clubToken`.
+- `clubDeviceId` (125-136) and `clubHeaders` (668-671).
+- `toCacheEntry` (699-722) has no uid, so the cache isn't tied to an account.
+- `initClubFromCache` (740-744) sets Pro before the first paint.
+- `refreshClub` (915-971):
+ - skips when the cache is under 24 h old (920);
+ - on 401/403/404 calls `leaveClub()` (939-942), which also POSTs leave.
+- `activateClub` (780-824) sends `{code, deviceId}` and maps unknown errors to
+ `invalid_code`.
+- `leaveClub` (986-1030).
+- Raw `X-Club` is built in `clubCards.js:57-67` and `:148-172`. `clubHeaders` is used by:
+ - `clubPresets.js:252-263`;
+ - `clubArchive.js` `getJson` 531-540, `shareMeeting` 604-626 and `uploadOne` 349-374;
+ - `profileSync.js:138`, `cardAssetSync.js:103` and `entitlement.js:92`;
+ - `apps/zoom-app/src/utils/zoomIdentity.js:55`;
+ - `apps/web/src/pages/ClubAdmin.jsx` 29-42 and 397-399.
+- **Speech outbox:**
+ - `recordSpeech` (`clubArchive.js:281-310`) queues only with a `clubToken`.
+ - `drainOutbox` (466-508) stops without one (479) and **drops the entry on any non-5xx
+ status, including 401** (497-501). That is how an offline or early speech is lost.
+
+**Zoom app**
+- `main.jsx` runs `initClubFromCache()` at 17, before render.
+- `refreshClub` (53) and `drainOutbox` (71) run at module load, before
+ `resolveZoomIdentity()` (78) has a session (#164).
+- `setEntitlement(entitlement ?? FREE)` (82) overwrites club Pro when the session call fails
+ (offline).
+- `zoomIdentity.js` `resolveZoomIdentity` (146-151) is single-flight, with no re-resolve.
+ - Auth status is `unauthenticated` | `authenticated` (guest mode) | `authorized`
+ (`zoomSdk.js:2236-2238`).
+ - The SDK exposes no uid. Only the Worker can decrypt the app context, so offline the client
+ can tell signed out from signed in, but not which account (see Q3).
+ - The Worker answers a guest with `identified:false, isGuest:true` and no token
+ (`session.js:83-86`).
+- `promptZoomAuthorize` (`zoomSdk.js:1957-1971`) is used only by
+ `ZoomConnectionNotice.jsx:251-258`.
+- `UpgradeModal.jsx`:
+ - `handleActivate` 196-220 (`club_code_rejected` 207, `club_code_activated` 212-218 with
+ `is_guest`);
+ - `handleLeave` 222-227, no confirm;
+ - code form 313-342, with "No sign-in needed." at 319;
+ - joined state 346-385, "This device is on Pro through" at 352 and "Leave this club on this
+ device" at 375-380;
+ - guest branch 468-478.
+- The admin's code goes through `renderClubSetup` (`packages/ui/ClubSetupCard.jsx`, 286-302).
+- Design B reaches the same modal through `b/MoreMenu.jsx` (140-145, "Join my club with a
+ code"), `b/ProChip.jsx` and `b/ReportTabB.jsx`.
+
+**Web**
+- `main.jsx:44` refreshes the club next to `startWebSession` (39) without waiting for it.
+- `webIdentity.js:32` fetches `/api/me` without X-Club, then calls
+ `setEntitlement(identity.entitlement ?? FREE)` (80).
+- `ProActivate.jsx` activates on load (35-58) with no sign-in, and its copy is "on Pro in this
+ browser" (94).
+- `ClubCodeSection.jsx`: activate 42-67; leave 69-74 with no confirm; "No sign-in needed."
+ at 117.
+- `ClubAdmin.jsx`:
+ - `MemberRow` 126-210, with "No access" in the role select at 186-197 and no confirm;
+ - `DeviceRow` 212-233, `handleDevice` 565-581;
+ - "N devices · N people" 629-632;
+ - "Guest devices" 658-673.
+- `signInUrl(returnTo)` (`webIdentity.js:59-61`) and `sanitizeReturnTo`
+ (`worker/auth.js:180`) already carry `/pro/` through sign-in.
+
+**Analytics**: client only. `club_code_rejected.reason` is the server's `error`. Events are
+listed in `docs/CLUBS.md:336-345`.
+
+**Tests today**
+- Worker:
+ - `club.test.js`: activate 112-281, state 283, leave 367, verifiedClubId 405, rotate 443
+ - `club-token.test.js`
+ - `club-admin-routes.test.js`: roster 238, role 281 (cascade 297), devices 399
+ - `gating.test.js`: club devices 132, revoked device 198
+ - `club-presets`, `club-cards`, `club-meetings` and `club-share` tests, which all use an
+ `activated` token helper
+ - `club-create.test.js:232`
+ - `flags.test.js` 753-810
+ - `session.test.js`, `me.test.js`
+- Shared: `packages/shared/__tests__/club.test.js` (cache 70, activate 112, refresh 234,
+ leave 526), `clubArchive.test.js`, `clubCards.test.js`, `clubPresets.test.js`.
+- Zoom: `UpgradeModal.test.jsx` (code entry 76, activated device 227), `b/Phase3.test.jsx`,
+ `b/TopBar.test.jsx`, `zoomIdentity.test.js`.
+- Web: `ClubAdmin.test.jsx` (roster 119, guest device revoke 204), `Account.test.jsx:373`,
+ `FlagGate.test.jsx:64-88`. There is no ProActivate or ClubCodeSection test.
+- Playwright: `zoom.club-pro-gate`, `zoom.stage-badge` and `zoom.new-look` seed
+ `toastmaster_club` with `clubToken` and a fresh `lastRefreshAt`, so `/api/club` is never
+ called. No spec covers joining or leaving.
+- Zoom-client specs:
+ - `club-card-sets` (CC-03 to CC-09 use a second device "B" that types the code),
+ `club-pro-gate` and `club-renewal-reminder` (CR-02/03 force a refresh on the web app as a
+ second device) all cover `packages/shared/club.js`.
+ - `club-card-sets` also covers `apps/zoom-app/src/main.jsx`.
+ - `new-look.md:185-187` quotes "This device is on Pro".
+ - Nothing covers `worker/club.js`, `UpgradeModal.jsx`, `ClubAdmin.jsx`, `ProActivate.jsx`
+ or `ClubCodeSection.jsx`. `pro-club` is not migrated.
+ - `.claude/skills/zoom-app-testing/references/toastmusters.md` lists one test Zoom account.
+
+## Approach
+One PR, landed as ordered commits: Worker, then shared, then the apps, then docs and specs.
+A Worker without `X-Club` breaks old bundles, so it can't ship alone; production has no clubs,
+so nothing breaks there.
+
+**Worker**
+1. **Account index and lookup** (`club-admin.js`).
+ - `clubOfKey(uid)` = `club-of:zoom:` → `{ clubId, at }`, single-valued (one club per
+ account).
+ - `memberClub(env, uid)` reads the index, then the club record and the member row. It
+ returns `{ clubId, club, role }`, or null when any is missing, the row is blocked, or the
+ row is a legacy `revokedAt` one. A dangling index entry is deleted on read.
+ - The index replaces `club-admin-of` for the admin door. Stop writing `club-admin-of`;
+ leave old keys alone.
+2. **Owner** (Q1, Q12).
+ - `createClubFromPending` writes `ownerUid: pending.uid` on the club record.
+ - For a record without it, `clubOwnerUid(env, club)` falls back to
+ `lookupUidByCustomer(stripeCustomerId)`.
+ - Create, checkout and CLI `create --uid` write the owner's admin row and index, as today.
+ - The owner is fixed: they can't leave, be removed, be blocked, or change role. Each of
+ those requests answers `409 owner`. The owner never takes one of the 3 places.
+ - `buildClubState` returns `isOwner` for the caller.
+ - A club with no known owner (CLI create without `--uid`, no Stripe match) keeps the
+ `last_admin` rule as its only guard.
+3. **Places, atomic** (Q8). A new SQLite-backed Durable Object, `ClubPlaces`
+ (`worker/club-places.js`), one per club (`idFromName(clubId)`), holds the set of uids
+ that hold a place.
+ - Methods:
+ - `claim(uid)` → `{ ok, placesUsed }` or `{ full, placesUsed }`. Already in the set
+ counts as `ok` and takes no new place.
+ - `release(uid)`.
+ - `count()`.
+ - The check and the add run on an in-memory set, synchronously, before any `await`; only
+ then is the set written to storage. Concurrent claims can't interleave, in the runtime
+ or in a unit test with a fake storage.
+ - On first use it seeds the set once from KV inside `blockConcurrencyWhile`: live member
+ rows, not blocked, not the owner. Existing dev clubs need no CLI step for this.
+ - `CLUB_PLACES = 3`. `placesUsed` everywhere (activate, state, roster) comes from
+ `count()`.
+ - If the DO can't be reached, activate answers `503 try_again` and joins nobody: no
+ fallback to an uncounted write. The client shows its existing network-error message.
+ - `wrangler.jsonc`: a `durable_objects` binding `CLUB_PLACES` at the top level **and**
+ in `env.dev` (bindings aren't inherited), plus a migration with
+ `new_sqlite_classes: ["ClubPlaces"]`. Check the current wrangler docs for where
+ `migrations` goes with environments. `worker/index.js` exports the class.
+ - Order inside activate: claim the place, then write the member row and index. If the KV
+ write fails, release the place.
+4. **Activate** (`handleClubActivate`): throttle, then **session required** (`401
+ sign_in_required`, before the code lookup), then code, then entitled. Then, in order:
+
+ | Case | Answer |
+ |---|---|
+ | Own live member row, or the owner | success, no extra place |
+ | Blocked row (`blockedAt`) | 400 `invalid_code` (Q11) |
+ | `memberClub(uid)` is another club | 409 `already_in_club` with `clubName` |
+ | `ClubPlaces.claim(uid)` says `full` | 409 `full` with `placesUsed`, `placesTotal` |
+ | Otherwise (including a removed account, Q2) | write the member row (`role:'member'`) and the index |
+
+ A legacy row with `revokedAt` and no `blockedAt` counts as no row, so that account joins
+ like anyone else.
+
+ Success returns `buildClubState(...)` plus `placesUsed`. No token, no device row, no
+ `deviceId` in the body. `attachDevice` and `readDeviceId` go.
+5. **State, leave, create.**
+ - `GET /api/club` needs a session (401 otherwise). It finds the club with
+ `memberClub(uid)`; no club, removed or blocked → 404 `no_club`.
+ - `buildClubState` adds `placesUsed`/`placesTotal` for admins, next to `code`.
+ - `POST /api/club/leave` needs a session. The owner gets `409 owner`. Otherwise it deletes
+ the member row and the index, releases the place, and clears `club-admin-of`. The last
+ admin is still refused with `409 last_admin` (`activeAdmins`).
+ - `/api/club/create` drops `attachDevice` and the token.
+6. **Every `readClub` site uses `memberClub(sessionUid)`**:
+ - assets, profile, presets, cards (upload, publish, download);
+ - meetings (append, list, read) and share;
+ - the admin door;
+ - `session.js:98` and `me.js:48`. The entitlement there now carries `club` for every
+ member, which is what makes Pro follow the account on first paint.
+
+ `appendSpeech`, list, read and share now need a session; a non-member gets 403. Delete
+ `worker/club-token.js`, its test, and `readClub` in `auth.js`.
+7. **Admin.**
+ - The roster lists people with no devices. `counts` becomes `{ people, placesUsed,
+ placesTotal }`, and each member has `isOwner`. Blocked accounts come back in a separate
+ `blocked` list (`uid`, `displayName`, `blockedAt`).
+ - `handleMemberRole`:
+ - `revoked` now means **Remove** (Q2, Q5). It deletes the member row and the index and
+ releases the place. The account can rejoin with the code while a place is free. The
+ device cascade goes.
+ - Any other role only changes the role of a live row. There is no "restore" any more,
+ because a removed person has no row.
+ - On the owner it answers `409 owner` (Q1, Q12).
+ - **Block** (Q2), new: `POST /api/club/admin/members//block` with
+ `{ blocked: true | false }`, admins only, routed next to `role` and `name` in
+ `handleClubAdminRoutes`.
+ - `true` keeps or creates the row as `{ displayName, blockedAt, blockedBy }` with no
+ role. It deletes the index and releases the place. Works whether or not the account is
+ a member now, so an admin can also block someone who already left.
+ - `false` (Unblock) deletes the blocked row. The account can then join with the code
+ like anyone else; it is not put back in automatically.
+ - On the owner it answers `409 owner`.
+ - `memberClub`, `readMemberRole` and `activeAdmins` treat a blocked row as no member.
+ - `handleMemberName` only renames existing rows (404 otherwise).
+ - Remove `handleDeviceRevoke` and its route.
+8. **Code rotation.** `rotateClubCode` stops touching devices; members and blocks stay. CLI:
+ - `rotate` prints the new code only;
+ - `prune-devices` goes;
+ - `backfill-admin-index` becomes `backfill-club-of`. It writes the index from live member
+ rows, newest first, deletes legacy `revokedAt` rows, and reports any account in two
+ clubs. Run it once on dev.
+
+**Shared** (`packages/shared/club.js` and its users)
+9. **Cache tied to an account.**
+ - The entry drops `clubToken` and gains `uid`. `readStored` keys on `club.id` and drops an
+ old token-shaped entry.
+ - `clubDeviceId`, `clubHeaders` and the `X-Club` uses in `clubCards.js`, `clubPresets.js`,
+ `clubArchive.js`, `profileSync.js`, `cardAssetSync.js` and `entitlement.js` go. Each
+ request sends the Bearer (Zoom) or the cookie (web).
+10. **Startup.** `initClubFromCache` no longer sets Pro before the first paint (Q4). A new
+ `syncClubWithIdentity({ identified, uid, authStatus, reachable, entitlement, getToken })`
+ runs after identity resolves:
+
+ | Identity | What happens |
+ |---|---|
+ | Identified, same uid as the cache, or no cache, and the session says a club exists | `refreshClub` (`GET /api/club`); its answer replaces the cache |
+ | Identified, and the session's entitlement has no `club` | clear the cache (a refusal) |
+ | Identified with a different uid | clear the cache first |
+ | Session unreachable, Zoom status `authorized` | keep the cache and apply its plan |
+ | Signed out, or guest mode | never apply the cache |
+
+ `refreshClub` loses the 24 h skip; it is one GET per open, for members only. 401/403/404
+ clear the cache locally through a new `forgetClub()` and send no leave POST.
+11. **Join and leave.**
+ - `activateClub(code, { getToken })` returns the server's reason, including the new ones
+ plus `clubName`, `placesUsed` and `placesTotal`.
+ - `leaveClub()` POSTs with the session and clears only after a 2xx; `last_admin` and
+ `owner` come back as errors.
+ - The cached club carries `isOwner`, so both apps can hide Leave for the owner.
+12. **Outbox.**
+ - `recordSpeech` queues when `club.club?.id` and `clubFeaturesOn`.
+ - `drainOutbox` waits for a session token (no token → keep the queue).
+ - It keeps entries on network errors, 5xx and **401**, and drops them on 400/403/404.
+ - Both apps call it after identity resolves.
+
+**Zoom app**
+13. **`main.jsx`.**
+ - `refreshClub` and `drainOutbox` leave module load and run in the
+ `resolveZoomIdentity().then`, through `syncClubWithIdentity`.
+ - An unreachable session no longer sets FREE over club Pro.
+ - `zoomIdentity.js` gains `refreshZoomIdentity()` (drops the single-flight promise and
+ resolves again) for after an approval.
+14. **`UpgradeModal.jsx`** (the classic and design-B entry points share it).
+ - The code form, by auth status:
+ - `unauthenticated`: "Sign in to Zoom, then open the timer again to join your club",
+ and nothing is sent.
+ - `authenticated` (guest mode): "Approve Toastmusters Timer in Zoom to join your club",
+ with an **Approve** button (`promptZoomAuthorize`). The typed code is kept in
+ sessionStorage `toastmaster_pending_club_code`. It is sent once
+ `refreshZoomIdentity()` reports `authorized`, in this panel or on the next load, then
+ cleared.
+ - `authorized`: send.
+ - Errors:
+ - `full`: "This club's Pro is full (3 of 3). Ask the person who shared the code to free
+ a place."
+ - `already_in_club`: "You're already in . Leave it to join another club."
+ - Joined copy: "You're on Pro through ".
+ - **Leave**, with a confirm: "Leave ? You'll lose its Pro on every computer where
+ you're signed in." `last_admin` shows the existing message. The owner sees no Leave
+ (Q1); they end the club by cancelling the subscription.
+ - Admins (the owner included) see "N of 3 places used" beside the code: a `placesUsed`
+ prop on `packages/ui/ClubSetupCard.jsx` (Q9).
+
+**Web**
+15. **`main.jsx` and `webIdentity.js`.** Refresh the club and drain the outbox after
+ `startWebSession` resolves, through `syncClubWithIdentity` (`reachable` false when
+ `/api/me` fails). An `/api/me` failure doesn't set FREE over club Pro.
+16. **`ProActivate.jsx` and `ClubCodeSection.jsx`.**
+ - Signed out: "Sign in with Zoom to join", a link to `signInUrl('/pro/')`. It comes
+ back to `/pro/` and joins.
+ - The new error copy as in step 14, "You're on Pro through ", and Leave with the same
+ confirm. The owner sees no Leave.
+17. **`ClubAdmin.jsx`.**
+ - A people-only roster with "N of 3 places used". The owner is marked and isn't counted.
+ - The device rows, "Guest devices" and "N devices" go.
+ - **Owner row** (Q1, Q12): an "Owner" label where the role select would be, and no "…"
+ menu.
+ - The role select's "No access" becomes **Remove**, with a confirm (Q5): "Remove ?
+ They lose the club's Pro at their next open and the place is freed. They can rejoin
+ with the code; to keep them out, use Block." A removed person drops off the roster;
+ there is no "Removed" state.
+ - **Block** (Q2): a "…" (more options) button on each non-owner row opens a small menu
+ with **Block**. Use the existing menu component in `apps/web` if there is one;
+ otherwise a native `` menu. Confirm: "Block ? They lose the club's Pro
+ at their next open, the place is freed, and the code won't let them back in until you
+ unblock them."
+ - A **Blocked** section under the people list, shown only when it isn't empty. Each row
+ has the name and **Unblock**, with no confirm, since nothing is lost.
+ - Console API calls send the cookie only.
+
+**Analytics**
+- `club_code_rejected.reason` adds `full`, `sign_in_required`, `approve_required` and
+ `already_in_club`. `approve_required` is decided on the client before any send.
+ `sign_in_required` comes from the client too, or from the server if a session-less request
+ slips through. `full` and `already_in_club` come from the server.
+- `club_code_activated` adds `places_used` and drops `is_guest`. `club_left` is unchanged.
+- `club_access_revoked` (the console's Remove) is unchanged. New: `club_member_blocked` and
+ `club_member_unblocked`, from the console, with the usual `club_id` and `surface`.
+- `docs/CLUBS.md` lists the props.
+
+**Docs:** rewrite the membership parts of `docs/CLUBS.md` (3-6, 11-32, 51-127, 156-220,
+277-289, 336-345), adding the owner rules, Remove versus Block, and the `ClubPlaces` Durable
+Object. Also `docs/BILLING.md` 33-41 and 102-108, `docs/ZOOM_LISTING_PRO.md` 21-26 and
+118-120 (drop "no sign-in"), `docs/ZOOM_TEST_PLAN.md` P4 (258-268, 383-401), and the test
+references file (`club-device`, `X-Club`, how the device joins).
+
+**Rejected**
+- Keep device tokens with a grace period plus a restore route (#145, #161): the issue drops
+ devices entirely.
+- Accept a rare 4th place from two simultaneous joins (the first draft's Q8 default): the
+ review asked to prevent it where possible, and a Durable Object does.
+- A count on the club record: KV has no transaction, and webhook writes to the club record
+ would race a counter.
+- Write the member row, then list and back out if over 3: KV list can lag up to 60 s, so
+ the check can miss the other join.
+- D1 for the place count: a whole database for one counter per club. A Durable Object per
+ club is smaller.
+- Keep a removed account out until an admin restores it (the first draft's Q2 default): the
+ review wants Remove to allow rejoining, with Block as the separate, rarer action.
+- Apply the cache before the first paint and correct it after the session: that briefly shows
+ a different account's club, which AC-8 forbids.
+- Keep `club-admin-of` beside `club-of`: two indexes for one fact.
+- A guest-join release flag (as #146 planned): the issue drops guest joins outright, and
+ `FLAGS_FORCE="1"` would turn it on on dev.
+
+## Acceptance criteria
+From the issue, with the review applied: AC-3 and AC-4 changed, and AC-11 and AC-12 are new.
+IDs kept.
+- **AC-1** (joining):
+ - **a.** Given a signed-in Zoom user who approved the app, when they enter a valid code for
+ a club with a free place, then they join, the timer shows the club's Pro, and the console
+ lists them.
+ - **b.** Given a user signed out of Zoom, when they enter a code, then no request goes out,
+ they see "Sign in to Zoom, then open the timer again to join your club", and the free
+ timer works.
+ - **c.** Given a user in guest mode, when they enter a code, then they see "Approve
+ Toastmusters Timer in Zoom to join your club" with an Approve button. After approving,
+ the typed code is sent without retyping.
+ - **d.** Given a signed-out browser, when it opens `/pro/` or enters a code on
+ Account, then it shows "Sign in with Zoom to join". After sign-in it returns to
+ `/pro/` and joins.
+- **AC-2** (follows the account):
+ - Given a member, when they open the timer on another computer or the web, signed in to the
+ same account, then they have the club's Pro with no code. That holds after clearing
+ storage too.
+ - Given a different account on a member's computer, then it gets nothing from the club.
+- **AC-3** (3 places):
+ - Given the owner plus 3 members, when a 4th account enters the code, then it isn't joined
+ and sees "This club's Pro is full (3 of 3). Ask the person who shared the code to free a
+ place."
+ - Given 2 free places, when 3 or more accounts enter the code at the same moment, then
+ exactly 2 join and the rest see the full message. The cap is never exceeded.
+ - Admins (the owner included) see "N of 3 places used" next to the code, in the console
+ and in the Zoom Pro panel. Members and editors don't.
+ - Re-entering the code as a member uses no place.
+ - A freed place admits the next account.
+- **AC-4** (leave and remove): Given a member (not the owner) who chooses Leave (Zoom or
+ web), or whom an admin removes in the console, after a confirm:
+ - they lose the club's Pro wherever they're signed in, at their next open;
+ - the console drops them and the place is free;
+ - they can join again by entering the code, while a place is free;
+ - the last admin can't leave or be removed (only matters for a club with no known owner).
+- **AC-5** (one club): Given an account in a club, when it enters another club's code, then it
+ isn't joined and sees "You're already in . Leave it to join another club."
+- **AC-6** (new code): Given the CLI replaces the code, then the old code admits nobody and
+ every member keeps access.
+- **AC-7** (no device bindings):
+ - Given any join, open, leave, removal or code change, then the Worker reads and writes no
+ `club-device:` record and no request carries `X-Club`.
+ - The console lists people only, with no per-device revoke.
+ - No screen says "No sign-in needed" or "This device is on Pro"; the joined state reads
+ "You're on Pro through ".
+- **AC-8** (startup and offline):
+ - No club request goes out before the Zoom session exists.
+ - With the server unreachable, the saved copy keeps the club's Pro. The next answer
+ replaces it and a refusal clears it.
+ - The copy is never used for a different account or a signed-out user.
+ - A speech finished offline or before the session uploads later and isn't dropped.
+- **AC-9** (unchanged features): shared presets and the club card set, the brand kit, the
+ archive, roles (only admins see the code), grace, lapse and renewal, the `pro` flag, the
+ code format and rate limit, the console email link, and club creation at checkout and with
+ "Set up my club" all keep working for members who joined by account.
+- **AC-10** (analytics):
+ - `club_code_rejected.reason` gains `full`, `sign_in_required`, `approve_required` and
+ `already_in_club`.
+ - `club_code_activated` gains `places_used`.
+ - Block and Unblock send `club_member_blocked` and `club_member_unblocked`.
+- **AC-11** (block):
+ - Given an admin who chooses Block for a member from the row's "…" menu, after a confirm:
+ the member loses the club's Pro at their next open, the place is free, and the console
+ lists them under Blocked.
+ - Given a blocked account, when it enters the code, then it isn't joined and sees "That
+ code isn't active" (Q11).
+ - Given an admin who chooses Unblock, then the account leaves the Blocked list and can join
+ with the code while a place is free. It isn't put back automatically.
+- **AC-12** (owner):
+ - The owner (the account that paid) has no Leave in the Zoom app or on the web.
+ - In the console, the owner's row says "Owner", with no role select and no "…" menu.
+ - The Worker refuses to remove, block, change the role of, or leave for the owner
+ (`409 owner`), whoever asks.
+ - The owner never takes one of the 3 places.
+
+## Test list
+| AC | Unit | Playwright | Zoom-client spec |
+|---|---|---|---|
+| AC-1a | `worker/club.test.js` activate: member row and `club-of` written, state returned without `clubToken`; `UpgradeModal.test.jsx` authorized send | `e2e/zoom.club-join.spec.js` NEW: join shows "You're on Pro through" | `club-membership` CM-01 NEW |
+| AC-1b | `club.test.js`: no session → 401 `sign_in_required` before code lookup; `UpgradeModal.test.jsx` unauthenticated: no fetch, copy | `zoom.club-join` signed-out case | CM-09 NEW (human: sign out of Zoom) |
+| AC-1c | `UpgradeModal.test.jsx` guest: Approve calls `promptZoomAuthorize`, pending code sent after `refreshZoomIdentity` → authorized; `zoomIdentity.test.js` `refreshZoomIdentity` | `zoom.club-join` guest case | CM-10 NEW (human: remove the app grant) |
+| AC-1d | `apps/web/src/pages/ProActivate.test.jsx` NEW, `ClubCodeSection` in `Account.test.jsx` | `e2e/web.club-join.spec.js` NEW: signed-out `/pro/` links to `/api/auth/zoom/start?returnTo=/pro/`, signed-in joins | CM-11 NEW (web, human sign-in if the browser has no cookie) |
+| AC-2 | `worker/session.test.js`, `me.test.js`: entitlement carries the member's club from the uid with no header; `packages/shared/__tests__/club.test.js` `syncClubWithIdentity`: no cache plus a club in the session → refresh; other uid → clear | `zoom.club-join`: empty storage, session mock with club → Pro | CM-02 NEW (clear the webview's storage, or the web app as the same account) |
+| AC-3 | `club.test.js`: 4th → 409 `full`; owner not counted; re-entry idempotent; freed place admits; `club.test.js` `placesUsed` from the DO; `worker/club-places.test.js` NEW: 5 parallel `claim`s on 3 free places → exactly 3 `ok`, a repeated uid takes no place, `release` frees, the first-use seed skips the owner and blocked rows; activate answers 503 when the DO throws and writes no member row; `ClubAdmin.test.jsx` and `UpgradeModal.test.jsx` "N of 3 places used", hidden for members and editors | `zoom.club-join` full message | CM-03 (KV-seeded members), CM-04 NEW |
+| AC-4 | `club.test.js` leave (member row and index gone, place released, `last_admin` 409 for a club without an owner); `club-admin-routes.test.js` remove deletes the row and index and releases the place, and the removed account's next activate joins; shared `leaveClub` / `forgetClub`; confirm in `UpgradeModal.test.jsx`, `Account.test.jsx`, `ClubAdmin.test.jsx` (Remove copy mentions Block) | `zoom.club-join` leave confirm | CM-05, CM-06 NEW (CM-06 ends with the removed account rejoining); `club-card-sets` CC-07 edited |
+| AC-5 | `club.test.js` 409 `already_in_club` with name; UI copy test | `zoom.club-join` | CM-07 NEW |
+| AC-6 | `club.test.js` `rotateClubCode`: members kept, old code invalid, no device writes | — | CM-08 NEW (CLI `rotate --env dev`) |
+| AC-7 | `gating.test.js` rewritten for members; grep test `worker/no-club-token.test.js` NEW (no `club-device:`/`x-club` in `worker/`, `packages/shared`, `apps/*/src`, `X-Club` absent from requests); copy assertions in modal, Account and ProActivate tests | existing club specs reseeded without `clubToken` | CM-01/CM-06 evidence (worker tail has no `x-club`) |
+| AC-8 | `packages/shared/__tests__/club.test.js`: unreachable + authorized keeps the cache, signed-out/guest never applies it, refusal clears; `clubArchive.test.js`: 401 and no-token keep the entry, drain waits for the token; `apps/zoom-app` main-order test, or `zoomIdentity` hook test that no club fetch precedes the session | `zoom.club-pro-gate.spec.js` edited: the session mock delays and `/api/club` is asserted to come after it | CM-12 NEW (worker tail order); CM-13 NEW (human: Wi-Fi off) |
+| AC-9 | presets, cards, meetings, share, assets, profile, `club-create` tests moved from token helpers to a member-session helper; `entitlements.test.js` unchanged | `zoom.club-pro-gate`, `zoom.stage-badge` and `zoom.new-look` reseeded (uid, no token, `/api/club` mocked) | `club-card-sets` (B = second Zoom account: CC-03, CC-06, CC-07, CC-08, CC-09 edited), `club-pro-gate` (wording), `club-renewal-reminder` (CR-02/03: reopen instead of `lastRefreshAt` 0), `stage-club-badge` (no change; run) |
+| AC-10 | `UpgradeModal.test.jsx` and web tests assert `reason` and `places_used`; `ClubAdmin.test.jsx` asserts `club_member_blocked` / `club_member_unblocked` | — | CM-01/CM-03/CM-14 PostHog evidence |
+| AC-11 | `club-admin-routes.test.js`: block deletes the index, releases the place, keeps a `blockedAt` row, works on a non-member uid, admins only; blocked activate → 400 `invalid_code`; unblock deletes the row and the next activate joins; `memberClub` and `activeAdmins` ignore blocked rows; `ClubAdmin.test.jsx`: "…" menu → Block → confirm, the Blocked section, Unblock | — | CM-14 NEW (Block a KV-seeded member in the console, then check KV and the place count); CM-15 NEW (human, second account: blocked code entry refused, then Unblock and rejoin) |
+| AC-12 | `club.test.js`: owner leave → 409 `owner`; owner activate takes no place; `club-admin-routes.test.js`: role, remove and block on the owner → 409 `owner`; `UpgradeModal.test.jsx` and `Account.test.jsx`: no Leave when `isOwner`; `ClubAdmin.test.jsx`: owner row has "Owner", no select, no "…" | — | CM-16 NEW (the test account's Pro panel has no Leave; its console row says "Owner". ⏭ with the reason if the test account isn't the dev club's owner) |
+
+The specs also get these edits:
+- `new-look.md:185-187`: the joined copy.
+- `INDEX.md`: add the `club-membership` row, and note under `pro-club` that P4 is now
+ `club-membership`.
+- `club-membership.md` `covers`: `worker/club.js`, `worker/club-admin.js`,
+ `worker/club-admin-routes.js`, `worker/club-places.js`, `packages/shared/club.js`,
+ `apps/zoom-app/src/components/UpgradeModal.jsx`, `apps/zoom-app/src/main.jsx`,
+ `apps/zoom-app/src/utils/zoomIdentity.js`, `apps/web/src/pages/ProActivate.jsx`,
+ `apps/web/src/components/ClubCodeSection.jsx`, `apps/web/src/pages/ClubAdmin.jsx`,
+ `scripts/club-cli.mjs`.
+
+## Risk
+**high.** This changes who may use a club, how removal works, and the entitlement every club
+route checks.
+
+- `riskHigh` paths touched:
+ - `worker/auth.js` (`readClub` removed)
+ - `worker/club-token.js` (deleted)
+ - `worker/session.js`
+ - `worker/entitlements.js`, only if `resolveAccess` gains a uid-to-club lookup. The plan
+ keeps that lookup in `memberClub` at the callers, so ideally this file is untouched.
+ - `wrangler.jsonc`: the first Durable Object in this Worker, with a migration.
+- **Durable Object migration.** A migration can't simply be reverted: removing the class
+ later needs its own `deleted_classes` migration. The binding must be declared in both the
+ top level and `env.dev`, or one Worker deploys without it. The dev deploy in the Zoom
+ station is the first real check; it must show `ClubPlaces` in the deploy output.
+- Breaking on dev:
+ - Old bundles that send `X-Club` lose club features until they reload.
+ - Device-only (guest) joins are dropped.
+ - Members with a uid need `club-cli backfill-club-of --env dev` after deploy.
+ - Legacy `revokedAt` rows become "removed" (can rejoin), not blocked.
+- Production must still have zero `club:` records before release. Check that as part of the
+ release.
+- The place count is exact (the DO). The roster's people list still comes from KV list, so
+ a join can take a few seconds to appear there.
+- Design B (#153–#156, merged) wraps `UpgradeModal.jsx`. Any open design-B PR rebases on
+ this.
+- Large diff. Ordered commits (Worker → shared → apps → docs and specs) keep review
+ tractable.
+
+## Decisions (review on PR #169, 2026-11-21)
+- **Q1. Owner.** The owner (the account that paid) can't leave or be removed. Only invited
+ accounts can leave or be removed. The owner never counts toward the 3. → Approach 2, AC-12.
+- **Q2. Removed accounts.** A removed account **can** rejoin with the code (it takes a place
+ again). For keeping someone out, the console gets a separate **Block**, by account, tucked
+ in a row's "…" menu because it's rare. → Approach 7 and 17, AC-4, AC-11.
+- **Q3. Offline.** As drafted: offline, the cache applies only while Zoom says `authorized`,
+ and the first reachable session with another uid clears it. The leftover gap (a second
+ authorized account opening offline on the same webview) is accepted; users of this app
+ are expected to be online.
+- **Q4. First paint.** Yes: club Pro appears once identity resolves, not before render.
+- **Q5. Console removal.** Yes: the role select's "No access" becomes "Remove", with a
+ confirm. Per Q2, a removed person drops off the roster; there's no "Removed" state.
+- **Q6. Second test account.** As drafted: steps needing a second Zoom account are `human`,
+ and ⏭ with the reason if none is available.
+- **Q7. Dev data.** Yes: run `club-cli backfill-club-of --env dev` after the dev deploy.
+- **Q8. Place-cap race.** Prevent it: the `ClubPlaces` Durable Object serializes place
+ claims, so simultaneous joins can't make a 4th place. → Approach 3, AC-3.
+- **Q9. Who sees "N of 3 places used".** Admins only, which includes the owner.
+- **Q10. Speeches from non-members.** Yes: they stay on the device, as for any free user.
+
+## Open questions
+New from applying the review; the default is used if nobody answers.
+- **Q11. What does a blocked account see when it enters the code?** Default: the generic
+ "That code isn't active" (`invalid_code`), the same as a wrong code. It doesn't tell the
+ person they were blocked. Alternative: a `blocked` reason with "You can't join this club.
+ Ask its admin."
+- **Q12. Can the owner's role be changed?** Q1 says the owner can't be removed; demoting
+ them to member would also lock them out of the console of the club they pay for. Default:
+ the owner's role is fixed at admin, and the console shows "Owner" in place of the role
+ select.
diff --git a/.factory/plans/168-on-the-spot-speakers.md b/.factory/plans/168-on-the-spot-speakers.md
new file mode 100644
index 00000000..85fb1e30
--- /dev/null
+++ b/.factory/plans/168-on-the-spot-speakers.md
@@ -0,0 +1,249 @@
+# Zoom timer: on-the-spot speakers — insert position, explicit edit-vs-add, role write-back (#168)
+
+## Problem
+Table Topics speakers are picked on the spot. In the Zoom app a new speaker lands at the end of
+the agenda, Enter on the name field renames or adds depending on state the user cannot see, and a
+role change updates the timer but not the agenda row. The issue's three decisions (Nov 21) fix
+the rules; this plan carries them out.
+
+**Scope: every surface where a speaker is named.** Every acceptance criterion holds in the **old
+look** (Live tab panel and the full-screen stage), the **new look** (design B, behind `new_look`)
+and the **web app's Live tab** (instruction from the owner, Nov 25: both looks, and the web stays in
+sync). The web has one look and no stage, so the stage criteria don't apply there. Shared logic
+and one set of labels keep the three from drifting apart.
+
+## Decisions (owner, Nov 25)
+- **Q2: adding never interferes with a running timer.** A speaker added while a speech is in
+ progress (running, or paused with time on the clock) goes into the agenda but is not loaded, and
+ the timer, its label, the colour and the video overlay are untouched. They come up when the
+ running speech is finished (FINISH already advances to the next row). *Consequence:* with the
+ Table Topics block row running, a speaker added then waits behind it and the display does not
+ switch to their 1–2 min timer until the block is finished or reset. Switching at once is what the
+ Table Topics section mode would do, which the issue puts out of scope.
+- **Q9 (Nov 26): speakers added during one speech keep the order added.** With B running, adding D
+ and then E gives B, D, E, not B, E, D: each one waits behind the speakers already waiting. The
+ button names the row they go behind ("Add a speaker after D"). With no speech in progress the new
+ speaker still goes on the timer right after the row shown (AC-1).
+- **Q6: the web follows the Zoom app** (controls, rules, two settings, wording), in this issue.
+- **Q1, Q4, Q5: the defaults** (settings under a collapsed "Speaker options"; the Agenda tab's own
+ add form keeps appending; both settings sync across devices).
+- **Q3:** the new speaker starts with the role on the clock, shown and changeable in the add panel.
+- **The control (Q7 → Q8, settled on mockup version 5).** No mode switch: a switch reads as more
+ tabs next to the Agenda / Timer / Report tabs. Instead:
+ - **Status is a dot, never a button:** "On the agenda · 2 of 3" or "Not on the agenda", plus
+ "Unsaved changes" while an edit is pending.
+ - **Every action says what tapping it will do**, not what the state is: "Update Jordan on the
+ agenda", "Add Dana after Jordan", "Switch to quick timing", "Save Dana to the agenda", "Back
+ to agenda (next: Jordan, Table Topics)".
+ - **At most one filled button** at a time: Update, or Add inside the add panel. Every other
+ action is a secondary text action in the accent colour, with a round leading icon, a trailing
+ "›" and a one-line note of the result (⇄ Switch to quick timing · "Jordan stays on the agenda,
+ not ticked off"; ↩ Back to agenda; + Add a speaker after Jordan; + Save Dana to the agenda;
+ ↶ Undo changes). No bare underlined links.
+ - **Edit in place covers name and role.** Both are staged; the Update button lists every change
+ ("name Jordan → Dana · role → Table Topics Speech") and "Undo changes" sits under it. Nothing on
+ the agenda or the clock changes until Update (or Enter). The old look gets this visible Update
+ button, not only Enter.
+ - **Adding is its own small panel** ("+ Add a speaker after Jordan"), with its own name and role
+ and one button. It never touches the speaker on the clock.
+ - **Quick timing needs no mode.** With no row loaded the field just labels the timer; with a row
+ loaded, "Switch to quick timing" lets go of it and "Back to agenda (next: …)" returns.
+ - **START never writes to the agenda.** FINISH records every timed speech in the Timer's Report
+ and club history, agenda or not.
+
+## Findings
+The logic is already shared in the Zoom app; the pickers are not.
+
+- **Shared logic (Zoom)**: `apps/zoom-app/src/hooks/useLiveTimer.js` — `handleAddSpeaker` (~517),
+ `handleRenameSpeaker` (~538), `handleRoleChange` (544). Both looks call these.
+ `handleAddSpeaker` passes `role: selectedRole` and `{ activate: true }`; `activate` resets the
+ timer, which is what Q2 rules out while a speech is in progress.
+- **Append only**: `addToAgenda` in `apps/zoom-app/src/context/TimerContext.jsx:410` does
+ `setAgenda(prev => [...prev, newItem])`; the web copy is `apps/web/src/context/TimerContext.jsx:201`.
+ Its other callers (Agenda tab form via `useAgendaEditor.js:115`, bulk imports) build the running
+ order and must keep appending.
+- **Role never reaches the row**: `handleRoleChange` ends in `setCurrentSpeaker(...)` only.
+ `updateAgendaItem` (TimerContext:444, web :219) already writes name, role and rules to a row and
+ the current speaker; nothing in the Live tab calls it. Break detaches the row on purpose
+ (`clearActiveSpeaker`, useLiveTimer:~555) and stays that way.
+- **FINISH records any timed speech**: `finishCurrentSpeech` (TimerContext:559-586) adds the report
+ and the club record whenever there is a current speaker with time on the clock, and ticks off a
+ row only if one is loaded. Quick timing needs nothing new here.
+- **Old look, Enter is implicit** — `components/SpeakerInput.jsx:82-93` (`pendingRename` when a
+ row is loaded, `pendingAdd` when none is; hint text at :245-252) and, on the stage,
+ `components/StageSpeakerPicker.jsx:57-58, 82-87, 136-139` (same rule). `TimerStage.jsx:242`
+ mounts the stage picker for **both** looks.
+- **New look, Enter always adds** — `b/SpeakerPicker.jsx:79-80, 105-111`: Enter picks an exact match
+ or adds; Rename exists only as a list row below the Add row. So the two looks already disagree on
+ what Enter does with a row loaded.
+- **Typing relabels the timer**: in the old look, typing in the name field updates the current
+ speaker's label at once (`handleSpeakerChange` → `updateSpeakerName`). With staged edits, a loaded
+ speaker's label changes on Update instead; a quick timing still relabels as you type.
+- **Web** (`apps/web/src/components/LiveTab.jsx:140-190`, `SpeakerInput.jsx`): typing only labels
+ the timer; picking a suggestion copies name and role and does **not** load the agenda row, so the
+ Live tab has no "loaded row" at all (only the Agenda tab's load button sets `activeSpeakerId`);
+ the web context has no `renameAgendaSpeaker`. The web also syncs settings through
+ `profileSync` / `SYNCED_KEYS`, so one new key reaches both apps.
+- **Likely reason the 1–2 min timer never shows** (inferred from the code, not reproduced): the new
+ slot takes `selectedRole`, which with the block row loaded is the block's own role, so the
+ display stays on the 5–10 min block thresholds.
+- **Settings**: persisted booleans live in `packages/shared/storage.js` (e.g.
+ `REVEAL_FACE_WHEN_IDLE`, :27, :255-277) and sync via `packages/shared/profileMerge.js`
+ `SYNCED_KEYS`. `packages/shared` holds no React, so each app builds its own UI.
+- **Specs**: `e2e/zoom-client/timer-core.md` covers `LiveTab.jsx` (Zoom and web), `useLiveTimer.js`,
+ `TimerContext.jsx` but not `SpeakerInput.jsx` or `StageSpeakerPicker.jsx`; `new-look.md` covers
+ `apps/zoom-app/src/b` and `TimerStage.jsx`. Last IDs: TC-13, NL-20.
+- **Overlap**: draft PR #143 (#80) edits `LiveTab.jsx`, `TimerStage.jsx`, `App.jsx`; it is already
+ conflicting with `dev` (74 commits behind). #169 does not touch these files.
+
+## Approach
+Smallest change that meets the criteria:
+
+1. **Pure logic, labels and two settings in `packages/shared/speakerEntry.js`.**
+ - `insertAfter(agenda, afterId, item)`: append when `afterId` is null or not found.
+ - `addPlan({ speechActive, insertPosition, anchorId })` → `{ insertAfter, activate }`, where the
+ anchor is the loaded row, or the row let go of for a quick timing; `activate` is false while a
+ speech is in progress.
+ - `afterQueue(agenda, anchorId, waitingIds)` → the row to insert after: the anchor, then past the
+ unbroken run of speakers already added without going on the timer (Q9). Both contexts keep
+ `waitingSpeakerIds` (recorded by `addToAgenda` when `insertAfter` is set and `activate` is not).
+ - `pendingChanges({ row, name, role })` → `{ name?, role? }` or null.
+ - `actionLabels(state)` → the exact button and status strings, so all three surfaces say the
+ same words ("Update Jordan on the agenda", "Back to agenda (next: Jordan, Table Topics)" …).
+ - Settings in `storage.js` with load/save: `speakerInsertPosition` (`'afterActive'` default |
+ `'end'`) and `speakerEnterAction` (`'update'` default | `'add'`). Both keys join `SYNCED_KEYS`.
+2. **`addToAgenda(speaker, { activate, insertAfter })`** in both contexts: `insertAfter` is an
+ agenda id; absent means append, so the Agenda tab and imports are unchanged. The web context also
+ gains `renameAgendaSpeaker`, mirroring the Zoom one.
+3. **One speaker model per app, built from those functions.** Zoom: in `useLiveTimer` (both looks).
+ Web: in `LiveTab.jsx`.
+ - `loadedRow` (from `activeSpeakerId`) and `releasedRowId` (the row let go of for a quick timing).
+ - Staged edits: `draftName`, `draftRole` while a row is loaded. `handleUpdate()` writes both with
+ `updateAgendaItem` (name, role, rules), so the row and the clock change together;
+ `handleUndo()` resets the drafts. Choosing Break still detaches at once (Zoom), as today.
+ - Quick timing (no row loaded): name and role apply to the clock directly, as today, and never to
+ the agenda. `handleSwitchToQuickTiming()` calls `clearActiveSpeaker` and remembers the row;
+ `handleBackToAgenda()` loads it again.
+ - `handleSaveToAgenda()` inserts the quick-timed name with its role, via `addPlan`.
+ - `handleAddSpeaker(name, role)` (the panel) inserts via `addPlan` and loads only when no speech is
+ in progress; otherwise a toast says the speaker comes up after this speech.
+ - Enter: in the name field it does what the primary button does (Update by default; with the
+ setting on "add", the primary button becomes "Add after "); with no row loaded it
+ does nothing. In the add panel it adds.
+ - Picking a guest from "In this meeting" opens the add panel with the name filled in; picking an
+ agenda row loads it (as today). On the web, picking an agenda suggestion now loads the row.
+ - A typed name that exactly matches an agenda row is still never added a second time.
+4. **UI, same parts and words on every surface.** A status dot under the name field; the contextual
+ buttons (Update + Undo changes, Switch to quick timing, Save to the agenda, Back to agenda); and
+ "+ Add a speaker after " opening the add panel.
+ - Old look: `SpeakerInput.jsx` (panel); `StageSpeakerPicker.jsx` (stage, compact: status dot,
+ field, the Update button when there are changes, "+ Add", with quick timing and Back to agenda
+ in its dropdown).
+ - New look: `b/TimerCard.jsx` speaker chip carries the status; `b/SpeakerPicker.jsx` popover holds
+ the field, buttons, add panel and the Agenda / In this meeting lists. The card's role chip edits
+ the speaker on the clock (staged for a loaded row, like the old look's role picker).
+ - Web: `SpeakerInput.jsx` and `LiveTab.jsx`.
+5. **Settings UI.** Zoom: one `SpeakerEntryOptions` component used by both looks, collapsed
+ "Speaker options" under the old look's name field and at the foot of the new look's speaker
+ popover (the stage reads the settings, shows none). Web: the same two options under its name field.
+6. **Specs.** Add TC-14 (old look) to `timer-core.md` and NL-21 (new look) to `new-look.md`; add
+ `SpeakerInput.jsx` and `StageSpeakerPicker.jsx` to `timer-core.md` `covers`. Run TC-14 with
+ FLAGS_FORCE `"1,new_look=0"` and NL-21 with `"1,pro=0"`. The web is covered by Playwright
+ (`e2e/web.*`), since the Zoom client does not host it.
+
+Rejected: a mode switch, two- or three-way (reads as more tabs); writing a role change to the row at
+once (the button would no longer say everything it saves); a "section mode" (out of scope); making
+the Agenda tab form follow the insert setting (it builds the running order); a shared React component
+(`packages/shared` has none).
+
+## Acceptance criteria
+Each criterion holds in the **old look** (panel and stage), the **new look** and the **web Live
+tab** (no stage there); the tests below run the same steps through each.
+
+- AC-1: Given the agenda [A, B, C] with B loaded, no speech in progress and the insert setting at its
+ default, when a new speaker D is added from the add panel, then the agenda is [A, B, D, C], D is
+ loaded, and the timer shows D's role rules.
+- AC-2: Given the same agenda and the setting on "at the end", when D is added, then the agenda is
+ [A, B, C, D] and D is loaded.
+- AC-3: Given no row is loaded and none was let go of, when a speaker is added, then they go to the
+ end, whichever setting is on.
+- AC-4: Given either setting is changed on one surface, when the user opens another surface or
+ reloads, then the same value shows, and both keys are in the synced profile keys.
+- AC-5: Given a row is loaded, then a status dot reads "On the agenda · of "; with
+ none loaded it reads "Not on the agenda". The status is not a button. Every action's label names
+ what tapping it does, with the words from `actionLabels`; at most one filled button shows at a
+ time, and every other action is an icon text action with its one-line result note.
+- AC-6: Given B is loaded and the user changes the name to "Dana", then nothing changes on the
+ agenda or the clock and the status adds "Unsaved changes", until they tap "Update B on the
+ agenda" (or press Enter); then B is renamed on both and keeps its place. "Undo changes" puts the
+ fields back with nothing saved.
+- AC-7: Given B is loaded, when the user taps "+ Add a speaker after B", then a panel opens with its
+ own name and role (the role starts as the one on the clock); "Add D after B" inserts per AC-1/AC-2,
+ and the panel never changes B's row or the clock.
+- AC-8: Given the Enter setting is at its default, Enter in the name field does what the Update
+ button does, and Enter in the add panel adds. With the setting on "add", changing a loaded
+ speaker's name makes "Add after B" the primary button (Update stays beside it) and Enter
+ adds; B is unchanged. With no row loaded, Enter in the name field does nothing under either setting.
+- AC-9: Given B is loaded, when the role is changed (with or without a name change), then the Update
+ button lists every change ("name B → Dana · role → Table Topics Speech"); tapping it writes the
+ name, the role and its rules to B's row and to the clock together, and the Agenda tab shows them.
+ Choosing Break still detaches B at once and leaves the row untouched.
+- AC-10: Given the add panel is open, when its role is changed, then the clock's role and B's row
+ stay as they were, and the Add button names the role ("as Table Topics Speech").
+- AC-11: Given the same sequence of actions on each surface, then the agenda and the timer end up
+ identical (a parity test over the shared functions and each surface's handlers, plus the
+ real-client steps).
+- AC-12: Given the web Live tab, then it has the same controls and rules as the Zoom app (status
+ dot, staged Update with Undo, add panel, quick timing, Back to agenda, both settings synced with
+ the Zoom app), and picking an agenda suggestion loads its row.
+- AC-13: Given B is running (or paused with time on the clock) and the user adds D, then D is
+ inserted per AC-1/AC-2 but not loaded, B's timer, label, colour and overlay are untouched, and
+ finishing B moves to D.
+- AC-14: Given B is loaded, when the user taps "Switch to quick timing", then the timer lets go of B
+ (B stays on the agenda, not ticked off), the name field labels the timer only, and a timed speech
+ is recorded in the Timer's Report on FINISH with the agenda unchanged; "Back to agenda (next: B,
+ B's role)" loads B again.
+- AC-15: Given no row is loaded and a name is typed, when the user taps "Save to the agenda",
+ then it is inserted with the role shown, after the row let go of or at the end (per AC-1–AC-3), and
+ loaded unless a speech is in progress.
+- AC-16: Given any state, when START is pressed, then no agenda row is added or changed.
+- AC-17: Given B is running (or paused with time on the clock) and the user adds D, then E, then the
+ agenda reads B, D, E (E behind D, not in front), the button after the first add reads "Add a
+ speaker after D", and finishing B then D moves to D then E. The order holds across a tab switch and
+ when a third speaker is added while D is the one speaking. With no speech in progress a new
+ speaker goes on the timer right after the row shown, as in AC-1.
+
+## Test list
+| AC | Unit | Playwright | Zoom-client spec |
+|---|---|---|---|
+| AC-1, 2, 3 | `packages/shared/__tests__/speakerEntry.test.js` (NEW); both `TimerContext.test.jsx` (`insertAfter`); `useLiveTimer.test.jsx` | `e2e/zoom.timer-flow.spec.js` (old look); `e2e/zoom.new-look.spec.js`; `e2e/web.agenda-flow.spec.js` | TC-14 (NEW, old look); NL-21 (NEW, new look) |
+| AC-4 | `packages/shared/__tests__/storage.test.js`; `profileMerge.test.js` | `e2e/zoom.new-look.spec.js` (value shared by both looks) | NL-21 |
+| AC-5 | `speakerEntry.test.js` (`actionLabels`); zoom `SpeakerInput.test.jsx`, `StageSpeakerPicker.test.jsx`; `b/TimerCard.test.jsx`, `b/Phase3.test.jsx`; web `SpeakerInput.test.jsx` | the three above | TC-14, NL-21 |
+| AC-6, 9 | `speakerEntry.test.js` (`pendingChanges`); `useLiveTimer.test.jsx`; both `TimerContext.test.jsx`; web `LiveTab.test.jsx` | the three above | TC-14, NL-21 |
+| AC-7, 10 | zoom `SpeakerInput.test.jsx`, `StageSpeakerPicker.test.jsx`; `b/Phase3.test.jsx`; web `SpeakerInput.test.jsx` | the three above | TC-14, NL-21 |
+| AC-8 | `useLiveTimer.test.jsx`; web `LiveTab.test.jsx`; the component tests above | `e2e/zoom.timer-flow.spec.js`; `e2e/web.timer-flow.spec.js` | TC-14 |
+| AC-11 | `useLiveTimer.test.jsx` and web `LiveTab.test.jsx` run one sequence through `speakerEntry` | — | TC-14 and NL-21 end states compared in `run.md` |
+| AC-12 | web `SpeakerInput.test.jsx`, `LiveTab.test.jsx`, `TimerContext.test.jsx` | `e2e/web.timer-flow.spec.js`, `e2e/web.agenda-flow.spec.js` | — |
+| AC-13 | `speakerEntry.test.js` (`addPlan`); `useLiveTimer.test.jsx`; web `LiveTab.test.jsx` | `e2e/zoom.timer-flow.spec.js`; `e2e/web.timer-flow.spec.js` | TC-14 (add while running, real video colour unchanged) |
+| AC-14, 15 | `useLiveTimer.test.jsx`; both `TimerContext.test.jsx` (report on FINISH without a row); web `LiveTab.test.jsx` | `e2e/zoom.timer-flow.spec.js`; `e2e/zoom.new-look.spec.js`; `e2e/web.report-flow.spec.js` | TC-14, NL-21 |
+| AC-16 | `useLiveTimer.test.jsx`; web `LiveTab.test.jsx` | `e2e/zoom.timer-flow.spec.js` | TC-14 |
+| AC-17 | `speakerEntry.queue.test.js` (`afterQueue`, labels); `useLiveTimer.speakerState.test.jsx`; web `LiveTab.speakerState.test.jsx` | — | TC-14 step 4, NL-21 step 3 |
+
+## Risk
+**Low.** No `config.json` `riskHigh` path is touched (`packages/shared/storage.js` and
+`profileMerge.js` are not on the list). Size is **medium-large**: three surfaces, two apps. Watch:
+- **Behaviour changes users will notice**: with nothing loaded, Enter no longer adds the typed name
+ to the agenda (Zoom); a loaded speaker's name and role change on Update, not as you type or pick;
+ in the new look, Enter with a row loaded updates instead of adding. Each is visible on screen (the
+ status dot, the button's label), and the Enter setting restores adding.
+- **Web picks load the row**: on the web, choosing a suggestion now loads its agenda row (as in
+ Zoom), so FINISH ticks it off and advances; before, it only copied the name.
+- **Synced keys**: two more keys in `SYNCED_KEYS`; `profileMerge.test.js` lists them.
+- **Merge conflicts**: new props on `TimerStage.jsx` (to pass the handlers to the stage picker)
+ overlap draft PR #143. Whichever merges second rebases; #143 already conflicts with `dev`.
+
+This is the third open factory PR while `wipLimit` is 2: started on the owner's explicit
+instruction, Nov 25.
+
+## Open questions
+None. Answered Nov 25: Q1–Q8 as under Decisions.
diff --git a/.factory/plans/80-meeting-polls.md b/.factory/plans/80-meeting-polls.md
new file mode 100644
index 00000000..d5521174
--- /dev/null
+++ b/.factory/plans/80-meeting-polls.md
@@ -0,0 +1,422 @@
+# Meeting polls: vote for Best Table Topics Speaker, Best Speaker, and Best Evaluator (#80)
+
+## Problem
+Clubs end most meetings by voting for the best Table Topics speaker, best speaker and best
+evaluator. Today they count votes by hand or set up a Zoom poll separately, even though the
+timer already knows who spoke in each role. #80 asks for a Pro-only ballot built from this
+meeting's timed speakers. Running a poll is Pro; voting is free. Votes come in three ways,
+shipped together: in the Zoom app after "Invite everyone" (the primary path, review Q3), a web
+link `/vote/` (the backup), and a native Zoom poll (host only), whose results are fetched
+after the meeting. Club and personal templates hold the ballot setup. Winners show on the
+Report tab, the report image and the shared `/r/` page.
+
+**Review applied (2026-11-15).** Q1 Durable Object. Q2 Zoom app only. Q3 in-Zoom voting with a
+verified Zoom identity first, web link as backup with a per-poll-and-IP limiter (~120/min,
+fails open). Q4 the dev Marketplace app has every scope, SDK API, webhook and Guest Mode
+Testing, so MP-04 and the Zoom-poll and invite steps run for real. Q5 native results are
+fetched after the meeting with a short-lived encrypted refresh token. Q6 winners on the
+report image and `/r/`. Q7 owner is the creating uid. Q8 zero votes means no winner.
+
+## Findings
+The earlier spec `docs/issues/meeting-polls.md` (38cc6e8) proposed splitting A and B. The
+issue overrides that: A and B ship together (decided 2026-11-13). No code exists yet:
+`git log -S` finds nothing for poll, vote or ballot, and nothing calls `sendMessageToChat`.
+
+**Client (Zoom app)**
+- **Tabs:** the tab list is `apps/zoom-app/src/components/NavTabs.jsx:8-12`. Tabs are
+ lazy-loaded and rendered at `App.jsx:13-15,38-40`. Web: `apps/web/src/components/NavTabs.jsx:5-9`
+ and `pages/TimerApp.jsx:114-118`.
+- **Reports:** `toastmaster_reports` (`packages/shared/storage.js:20`). Each entry is
+ `{speechId, name, role, duration, color, comments, disqualified, finishedAt}`
+ (`addReport`, zoom `TimerContext.jsx:539-552`). "This meeting" means the reports since the
+ last Clear, plus the club archive's `meetingId`
+ (`deriveMeetingId`, `packages/shared/clubArchive.js:218`).
+- **Roles:** the built-ins `Table Topics Speech`, `Standard Speech` and `Table Topics
+ Evaluation` are defined at `packages/shared/timingRules.js:3-12`. `DEFAULT_CUSTOM_RULES` is
+ at `:17`. `roleOptions` is at zoom `TimerContext.jsx:166-174`.
+- **Adding a role:** `addRoleRules(role, rules)` is at `:597-609`. Edit Rules adds a role
+ through `ensureForked` first (`EditRulesModal.jsx:265-276`, `clubPresets.js:232`). Without
+ that call, a club device writes the role to personal keys while the club's list stays
+ active.
+- **Pro gating:** `useEntitlement()` returns `isPro` (`hooks/useEntitlement.js:19-28`).
+ `useSoundsAccess()` (`hooks/useSounds.js:32-39`) is the pattern for
+ `{usable, lockReason: 'pro'|'unreleased'}`. `UpgradeModal source=…` is at
+ `components/UpgradeModal.jsx:92`, used as in `SoundsModal.jsx:43-115`.
+- **Stage view:** `components/TimerStage.jsx` is a React DOM overlay, mounted from
+ `LiveTab.jsx:980-1009` and shared with `shareApp`/`appPopout`. A winners panel there is
+ plain React, with no canvas work.
+- **SDK capabilities:** they come from `USED_SDK_APIS` (`utils/zoomSdk.js:78-109`).
+ `zoomSdk.test.js:1351-1355` checks the list against the `zoomSdk.*` calls in both
+ directions.
+- **SDK state:** `getUserContext` gives `role` (`readZoomUserSummary`, `:2260-2280`).
+ `getMeetingContext` is not used yet.
+- **Settings sync:** the allowlist is `SYNCED_KEYS` (`packages/shared/profileMerge.js:28-43`).
+ Keys must be written through `persist` (`storage.js:7-16`) or the sync never sees them.
+- **Club template precedent:**
+ - Publish: `publishPresets` → `PUT /api/club/presets` (`clubPresets.js:251`,
+ `worker/club-presets.js:132-187`). The handler checks session, club, entitled and
+ admin/editor, writes `club-presets:`, then bumps `club:.ver`.
+ - Members: `refreshClub` (`packages/shared/club.js:868`, `:906-914`) saves the new
+ versioned content when `ver` changes. `buildClubState` (`worker/club.js:179-218`)
+ returns it.
+ - Lapsed plan: `clubPresetsAvailable()` returns false when the club is not entitled
+ (`clubPresets.js:71-76`).
+ - Newest analogue: club cards (`worker/club-cards.js:154-219`, 25536fe).
+- **Club archive:**
+ - Storage: `meeting::…` headers and `speech:::`
+ keys (`worker/club-meetings.js:19-30`).
+ - Caveat: `compactMeeting` (`:178-185`) and `readMeeting` (`:393-402`) copy only the fields
+ they list. A `polls` field in the header would be dropped, so results need their own key
+ and must be merged in both places.
+ - Client upload goes through the outbox (`recordSpeech`, `clubArchive.js:281`).
+
+**Worker**
+- **Routing:** API routes are an if-chain at `worker/index.js:136-232`. On the `zoom.` host,
+ `routeAssets` turns every path into the Zoom app (`:371-377`), so the voting link must
+ use the `www.` host.
+- **Public page precedent:** `/r/` (`index.js:309-311`, `club-share.js:31,48-70,351-391`)
+ is a Worker-rendered page with an unguessable 16-character token, `noindex` and a real 404.
+ `ROOT_CSP` (`index.js:21-22`) already allows a same-origin form plus inline script.
+- **Storage:** only KV `PROFILES` and R2 `CARD_ASSETS` exist (`wrangler.jsonc:79-95`). There
+ is no D1 and no Durable Object.
+ - KV has no compare-and-swap, and `list()` is eventually consistent for about 60 s across
+ edges.
+ - So a KV tally made right after Close can miss the last votes, which would make the
+ revealed winner wrong.
+- **Auth:** `readSession` returns `{uid}` (`auth.js:110-122`). Pro is checked with
+ `resolveAccess(...).entitled`, which returns 402 `upgrade_required` (`profile.js:69-73`).
+ Release flags are listed in `FLAG_FALLBACKS` (`worker/flags.js:27-45`), and `flags.test.js`
+ catches drift.
+- **Zoom REST:**
+ - No scopes are set in code; they live in the Marketplace config.
+ - `exchangeZoomCode` (`auth.js:411-436`) drops the refresh token. No user token is stored.
+ - The only in-client code flow is PKCE through `zoomSdk.authorize`, in contact capture
+ (`worker/contact.js:20,143-185`).
+ - Zoom's `mid` reaches the Worker as a string (`zoom-context.js:133`). Zoom documents
+ `mid` as the meeting UUID, but `POST /meetings/{meetingId}/polls` takes the numeric
+ meeting ID, so the client sends `getMeetingContext().meetingID`.
+- **Verified identity (Q3):** `decryptAppContext(value, ZOOM_CLIENT_SECRET)`
+ (`zoom-context.js:95`) returns `{uid, mid, typ, exp}` or null. Guests decrypt fine with
+ `uid: null`. The client reads the context with `readAppContext()` (`zoomSdk.js:2215`) and
+ sends it in the body, as `/api/zoom/session` does (`session.js:72`).
+- **Webhook (Q5):** `meeting.started` / `meeting.ended` are only sent to PostHog today
+ (`zoom-webhook.js:142-152`). The payload has `object.id` (numeric) and `object.uuid`.
+- **Secrets:** `SESSION_SIGNING_KEY` is deliberately separate from `ZOOM_CLIENT_SECRET`
+ (`session-token.js:14-16`). Crypto uses `node:crypto` (nodejs_compat).
+- **Shared page and image (Q6):** `/r/` renders from the club meeting record
+ (`club-share.js:237,351`), so polls merged into `readMeeting` reach it. The PNG is drawn
+ client-side by `packages/shared/reportImage.js` from the reports list.
+- **Invite (Q3):** `sendAppInvitationToAllParticipants` is in `@zoom/appssdk` and not used
+ yet. It carries no payload, so the invited app must find the poll itself.
+
+**Tests and specs**
+- No Zoom-client spec covers `App.jsx`, `NavTabs.jsx`, `ReportTab.jsx`, `TimerStage.jsx`,
+ `club-presets` or `club-meetings`.
+- `zoomSdk.js` is covered by `timer-core` and `contact-capture`.
+- `packages/shared/club.js` and `main.jsx` are covered by `club-card-sets`.
+- `TimerContext.jsx` is covered by `timer-core` and `agenda-import`.
+- Playwright stubs `**/api/zoom/session` for Pro with `page.route`
+ (`e2e/zoom.timer-sounds.spec.js:7-29`).
+- `e2e/zoom.timer-flow.spec.js:125` walks through the tabs, so it changes when a tab is added.
+
+## Approach
+This is one PR, as the issue requires. It is built in the commit order below so a reviewer
+can read it in layers. Everything sits behind a new release flag `polls` (default `false`),
+and the native Zoom poll has its own flag `polls_zoom`. That flag stays off in production
+until Zoom approves the new scopes.
+
+1. **Shared logic** (`packages/shared/polls.js`, pure functions):
+ - `defaultBallot()`: Table Topics Speech, Standard Speech and Table Topics Evaluation,
+ 3 empty slots each.
+ - `ballotFromTemplate(template, reports, roleNames)`: each category's candidates are the
+ distinct `name`s from this meeting's reports in its role, in timing order. A category
+ with none gets `slots` empty entries.
+ - `normalizeTemplate`, with the keys `categories[{role, label?, slots}]` and
+ `options{postToChat, showOnStage, expiryHours}`.
+ - `winners(counts)`: everyone tied at the top count wins, and a category with zero votes
+ has no winner.
+ - Storage keys:
+ - `toastmaster_poll_template`: personal, added to `SYNCED_KEYS`.
+ - `toastmaster_club_poll_template`: the club copy, saved by `refreshClub` when `ver`
+ changes.
+ - `toastmaster_poll_draft`: this meeting's edited ballot, local only.
+ - `toastmaster_poll_results`: local, cleared with the reports.
+ - `activePollTemplate()` returns the club template when `clubPresetsAvailable()`, else
+ the personal one, else the default. A one-meeting edit only writes the draft.
+2. **Worker** (`worker/polls.js`, plus a Durable Object `PollRoom` with one instance per
+ poll):
+ - Routes:
+ - `POST /api/polls` (session + Pro) creates the poll. Body: `{ballot, expiryHours,
+ context}`. The owner's `context` is decrypted and its `mid` is recorded as the poll's
+ meeting; with no verifiable `mid` the poll still works by link only. It also writes
+ KV `poll-by-mid:` → id (TTL = expiry) so invited participants can find
+ it. Returns a 16-character Crockford id (the `/r/` token code); expiry defaults to
+ 24 h. The ballot holds candidate names and labels only.
+ - `POST /api/polls/current` (public): body `{context}`. Decrypts it and returns the
+ open poll's ballot for that `mid`, or 404. This is how an invited app finds the poll.
+ - `GET /api/polls//ballot` (public).
+ - `POST /api/polls//votes` (public): body `{choices{catIndex:candIndex}, context?,
+ device?}`. The voter key and path are decided server-side:
+ - `context` decrypts with a `uid` and its `mid` matches the poll → key `uid:`,
+ path `zoom`;
+ - `context` decrypts with no `uid` (guest) and a matching `mid` → key from `device`,
+ path `guest`;
+ - a `context` whose `mid` doesn't match → 403 `wrong_meeting`; an undecryptable
+ context → 400;
+ - no `context` (the web link) → key from `device`, path `link`, behind the limiter.
+ The DO refuses a category this key already voted in (409). Keys are stored hashed.
+ - `GET /api/polls//results` (owner only): `{counts, byPath{zoom,guest,link},
+ status, zoom?}`.
+ - `POST /api/polls//close` (owner only). It returns `{counts, byPath, winners}`
+ and deletes the `poll-by-mid` index.
+ - **Link limiter:** `POLL_VOTE_LIMITER` (`unsafe.bindings` ratelimit, like
+ `CLUB_ACTIVATE_LIMITER`), key `:`, 120 per 60 s, only on the `link` path.
+ A limiter error lets the vote through.
+ - The DO keeps strongly consistent counts, so the totals at Close are final. It deletes
+ its storage with an alarm at expiry.
+ - `GET /vote/` on the `www.` host is a Worker-rendered page, like `/r/`. It has
+ `noindex` and a device token in `localStorage`. Its help text says one vote per device
+ is not proof against deliberate double voting.
+ - It shows a closed or expired message and a real 404.
+3. **Club template:**
+ - Route: `PUT /api/club/poll-template`, built on the `requirePublisher` checks from
+ `club-cards.js`. The handler stores `club-poll-template:` and bumps `ver`.
+ - Delivery: `buildClubState` returns `pollTemplate`, and `refreshClub` saves it.
+ - Lapsed plan: the key stays stored but unused, the same as presets.
+4. **Archive:**
+ - Client: Close appends `{pollId, closedAt, categories[{role, label, counts, winners}]}`
+ to the local results. For a club device it also queues them through the outbox.
+ - Worker: `POST /api/club/meetings//polls` (club token, like speeches) writes
+ `poll:::`. `readMeeting` and `compactMeeting` merge it.
+ - Each stored category keeps `byPath` counts beside the totals.
+ - **Report image (Q6):** `reportImage.js` draws a "Winners" block (one row per category,
+ tied names joined) under the speeches when results exist; `reportImageHeight` grows
+ with it.
+ - **Shared page (Q6):** `renderSharePage` shows the meeting's poll winners per category
+ from `meeting.polls`. A category with no votes shows "No votes".
+5. **Zoom app UI:** a **POLL** tab after REPORT (`components/PollTab.jsx`). It is hidden
+ unless `flag('polls')`. On a free plan, setup is locked with `UpgradeModal source="polls"`,
+ but the voting view is not (Q3).
+ - **Vote view (any plan, `components/PollVote.jsx`):** on load and when the POLL tab
+ opens, the app calls `POST /api/polls/current` with its app context. If a poll is open
+ for this meeting and this device isn't its owner, the app shows a "Vote now" banner and
+ the POLL tab opens on the ballot. The vote is sent with the context (path `zoom` or
+ `guest`). After voting: "Thanks, your vote is in", with no counts.
+ - **Setup:**
+ - Category rows with a role select of `roleOptions`, an optional label, and
+ add/remove category.
+ - Candidates per category: add, remove, rename.
+ - "New role…" goes through `ensureForked` → `addRoleRules(name, DEFAULT_CUSTOM_RULES)`
+ → `role_added`, the same as Edit Rules.
+ - "Save as my template". An admin or editor also gets "Publish to club".
+ - **Open:**
+ - Creates the poll (sending the owner's app context) and shows the link with Copy.
+ - **"Invite everyone"** calls `sendAppInvitationToAllParticipants`. It is the primary
+ action; a failure shows a toast pointing at the link.
+ - Posts the link to chat with `sendMessageToChat` when `postToChat` is on. If that
+ fails it falls back to Copy with a toast.
+ - Add `sendMessageToChat`, `sendAppInvitationToAllParticipants` and
+ `getMeetingContext` to `USED_SDK_APIS` as optional.
+ - **Live:** counts every 5 s while the tab is open (`GET results`), shown only in this
+ sidebar, with a small "in Zoom / guest / link" split.
+ - **Close & reveal:**
+ - Winners per category. Ties show every tied name.
+ - "Show on Stage" sets a winners panel in `TimerStage.jsx`. It only shows the poll
+ owner's own Stage.
+ - The results card appears on ReportTab.
+6. **Native Zoom poll (B):** "Create as Zoom poll" shows only when `flag('polls_zoom')` and
+ `getUserContext().role === 'host'`.
+ - **Click:** `zoomSdk.authorize` (PKCE, as in contact capture) runs, then
+ `POST /api/polls/zoom` with `{code, verifier, meetingId}`.
+ - **Worker:** exchanges the code, then calls `GET /meetings/{id}`. It refuses `type 1`
+ (instant) with a clear reason, then calls `POST /meetings/{id}/polls` with one
+ single-choice question per category. The request may also carry `pollId` so the native
+ poll is linked to the app poll.
+ - **Results after the meeting (Q5):**
+ - `exchangeZoomCode` gains an option to return the refresh token (default unchanged:
+ dropped).
+ - The refresh token is encrypted with AES-256-GCM under a key derived by HKDF-SHA256
+ from `SESSION_SIGNING_KEY` with info `toastmusters/zoom-poll-refresh/v1` (no new
+ secret; rotating the signing key just orphans pending fetches). It is stored only in
+ that poll's `PollRoom` DO, with the numeric meeting id and the meeting UUID from
+ `GET /meetings/{id}`. KV `zoom-poll-by-meeting:` → pollId, TTL 24 h.
+ - `meeting.ended` in `zoom-webhook.js` looks up that key and tells the DO; the DO sets
+ an alarm 5 min later (Zoom's processing delay). The alarm refreshes the token, calls
+ `GET /past_meetings/{uuid}/polls` (UUID double-encoded when it starts with `/` or
+ contains `//`), stores the results in the poll as `zoom`, and **deletes the token**.
+ An empty or 404 answer retries at +15 min and +60 min, then gives up and deletes the
+ token. Every path deletes the token by 24 h after creation at the latest.
+ - Zoom rotates refresh tokens (the old one stops working once used), so while a
+ retry is pending the rotated token replaces the stored one, encrypted the same way.
+ It is still deleted on success, after the last retry, or at 24 h.
+ - The owner's client reads `zoom` from `GET results` (Report tab, on open) and merges
+ it into local results; on a club device it queues the archive upload (step 4).
+ Poll storage for a native poll lives 7 days so the owner can collect the results.
+ - **Copy:** the UI states Zoom's limits. Only the host can use it. It needs Zoom Pro and
+ polling turned on, and only works on scheduled meetings. The host launches the poll and
+ shares results in Zoom's own window; the app shows the results after the meeting.
+ - **Scopes:** `meeting:write:poll`, `meeting:read:meeting`,
+ `meeting:read:list_poll_results` (added to the dev app; prod needs a Marketplace review).
+7. **Docs:** `docs/CLUBS.md` (template, archive key, events), `docs/FEATURE_FLAGS.md` and
+ `docs/ZOOM_TEST_PLAN.md` P5 (Pro list plus the new scopes for the reviewer).
+8. **Analytics:** `poll_opened`, `poll_invite_sent`, `poll_vote_cast` (Worker, with `path`
+ and no person data), `poll_closed`, `poll_template_published`, `zoom_poll_created` and
+ `zoom_poll_results_fetched`.
+
+**Rejected**
+- KV-only votes: a tally right after Close can miss the last votes because KV is eventually
+ consistent.
+- D1: needs a migrations directory and gives nothing a per-poll DO doesn't.
+- A web link as the only vote path: one vote per device is easy to game; a verified Zoom
+ `uid` is the stronger key (Q3). The link stays as the backup.
+- A per-IP limit of 30/min: it would refuse a hybrid club voting from one room's Wi-Fi.
+- A new secret for the refresh-token key: HKDF from `SESSION_SIGNING_KEY` keeps the keys
+ separate without a deploy-time secret step.
+- Keeping the refresh token after the fetch: it is deleted right after, 24 h at the latest.
+- Rendering the vote page in the web SPA: the page would load the whole web bundle on a
+ phone, while `/r/` already shows the Worker-HTML pattern.
+- A `results` field on the meeting header: it would be dropped by compaction.
+
+## Acceptance criteria
+- AC-1: Given a free plan with `polls` on, when the POLL tab opens, then the setup is locked
+ and "Upgrade to Pro" opens the upgrade modal. The Worker answers `POST /api/polls` with 402.
+ Voting is never locked: a free-plan participant can vote (AC-14).
+- AC-2: Given no template, when a new poll is set up, then it has Table Topics Speech,
+ Standard Speech and Table Topics Evaluation, 3 slots each.
+- AC-3: Categories and candidates can be added and removed. A category's role can be set to
+ any entry in `roleOptions`, custom roles included.
+- AC-4: A role created from the poll screen appears in `roleOptions` with
+ `DEFAULT_CUSTOM_RULES`. On a club device it goes through `ensureForked`, as in Edit Rules.
+- AC-5: Given reports with speakers timed as Table Topics Speech, when the ballot is built,
+ then those names, deduplicated in timing order, are that category's candidates. A category
+ with nobody timed shows its empty slots. Candidates can be renamed, added and removed
+ before opening.
+- AC-6: Given an open poll, when someone opens `/vote/` in a browser with no Zoom
+ sign-in, then they see the ballot and can vote. A second vote from the same device token in
+ the same category gets 409, and the counts are unchanged. Unknown or expired ids get 404.
+ A closed poll refuses votes. Link votes are limited per poll and IP to 120 per minute
+ (429 beyond); if the limiter throws, the vote is accepted.
+- AC-7: Results are readable only by the poll's owner; other sessions get 403 and
+ anonymous callers get 401. The vote page never shows counts. The owner's tab updates counts
+ while the poll is open.
+- AC-8: When the owner closes the poll, then each category shows only its winners, and every
+ candidate tied at the top count is a winner. "Show on Stage" puts the winners on the
+ owner's Stage view.
+- AC-9: Closed results appear on the Report tab. For a club device they are stored under the
+ club meeting and returned by `GET /api/club/meetings/`, including after compaction.
+- AC-10: An admin or editor publishes the template. A member's device gets it on the next
+ `refreshClub`. Editing the ballot for one meeting changes neither the club template nor the
+ member's stored copy. A member gets 403 on publish. On a lapsed club the template stays
+ stored but is not used.
+- AC-11: A Pro user without a club saves a personal template that syncs through
+ `/api/profile` (`toastmaster_poll_template` in `SYNCED_KEYS`).
+- AC-12: Opening a poll posts the voting link to chat with `sendMessageToChat` when
+ `postToChat` is on, and always shows Copy link. A failed post falls back to Copy with a
+ toast. `sendMessageToChat` is an optional capability.
+- AC-13 (B): "Create as Zoom poll" shows only for the host with `polls_zoom` on, and explains
+ Zoom's limits. On an instant meeting the Worker refuses, and the app says why. On a
+ scheduled meeting it creates one single-choice question per category, with the candidates
+ as answers. The host's refresh token is stored only encrypted (AES-GCM), only in that
+ poll's DO, never in KV or logs.
+- AC-14 (in-Zoom vote): Given an open poll created in meeting M, when a participant in M
+ opens the app (any plan, including free and guest), then the app finds the poll through
+ `POST /api/polls/current` and shows the ballot. A signed-in participant's vote is keyed by
+ their verified `uid`: a second vote in the same category from the same Zoom account, even
+ on another device, gets 409. A guest's vote is keyed by device token. A context whose `mid`
+ isn't M gets 403; an undecryptable context gets 400. Each vote records its path
+ (`zoom`/`guest`/`link`), and the owner's results show counts split by path.
+- AC-15 (invite): The owner's "Invite everyone" calls `sendAppInvitationToAllParticipants`;
+ a refusal or error shows a toast pointing at Copy link. The API is an optional capability
+ in `USED_SDK_APIS`, as is `getMeetingContext`.
+- AC-16 (native results, Q5): Given a native poll created for meeting N, when Zoom sends
+ `meeting.ended` for N, then 5 min later the DO refreshes the token, fetches
+ `GET /past_meetings/{uuid}/polls`, stores per-question answer counts as the poll's `zoom`
+ results and deletes the token. Empty/404 retries at +15 and +60 min, then deletes the
+ token. With no `meeting.ended`, the token is deleted 24 h after creation. The owner's
+ Report tab then shows those results and, on a club device, archives them.
+- AC-17 (Q6): Given a meeting with closed poll results, the report image draws a Winners
+ block (ties joined, "No votes" for an empty category) and the shared `/r/` page lists each
+ category's winners. Without poll results both look exactly as today.
+
+## Test list
+| AC | Unit | Playwright | Zoom-client (NEW spec `meeting-polls`) |
+|---|---|---|---|
+| AC-1 | `PollTab.test.jsx`, `worker/polls.test.js` (402), `gating.test.js` | `zoom.meeting-polls` (free plan, locked) | MP-01 |
+| AC-2 | `packages/shared/__tests__/polls.test.js` | `zoom.meeting-polls` | MP-02 |
+| AC-3 | `PollTab.test.jsx` | `zoom.meeting-polls` | MP-03 |
+| AC-4 | `PollTab.test.jsx` (ensureForked + addRoleRules) | — | MP-03 |
+| AC-5 | `polls.test.js` (`ballotFromTemplate`) | `zoom.meeting-polls` (seeded reports) | MP-02 |
+| AC-6 | `worker/polls.test.js` (DO, double vote, expiry, closed), `routing.test.js` (`/vote/`), `csp.test.js` | `zoom.meeting-polls` (vote page against routed API) | MP-05 (human: second device votes) |
+| AC-7 | `worker/polls.test.js` (401/403) | — | MP-06 |
+| AC-8 | `polls.test.js` (`winners`, ties), `PollTab.test.jsx`, `TimerStage.test.jsx` | `zoom.meeting-polls` | MP-07, MP-08 (Stage on real share) |
+| AC-9 | `club-meetings.test.js`, `clubArchive.test.js` | — | MP-09 |
+| AC-10 | `worker/club-poll-template.test.js`, `club.test.js` (`pollTemplate` in state), `packages/shared` club refresh test | — | MP-10, MP-11 |
+| AC-11 | `profileMerge.test.js` | — | MP-12 |
+| AC-12 | `zoomSdk.test.js` (USED_SDK_APIS), `PollTab.test.jsx` | — | MP-04 (human: confirm the chat message, since it sends a message) |
+| AC-13 | `worker/polls-zoom.test.js` (fetch mocked; token encrypted, not in KV), `PollTab.test.jsx` (host only) | — | MP-13, MP-14 (Zoom authorization prompt; real, the dev app has the scopes) |
+| AC-14 | `worker/polls.test.js` (context paths, uid de-dupe across devices, wrong `mid`, guest), `PollVote.test.jsx` (free plan not locked) | `zoom.meeting-polls` (vote view with a stubbed `current`) | MP-15 (open poll found in the owner's own meeting), MP-16 (human: a second participant votes in Zoom), MP-17 (human: a guest votes; setup has `defaults write ZoomChat enableGuestModeTesting true`) |
+| AC-15 | `zoomSdk.test.js` (USED_SDK_APIS), `PollTab.test.jsx` (invite + failure toast) | — | MP-15 (human: confirm the invite reaches the second participant and opens the app) |
+| AC-16 | `worker/polls-zoom.test.js` (alarm, retries, token deleted on every path, UUID encoding), `zoom-webhook.test.js` (`meeting.ended` → DO) | — | MP-18 (end the meeting, results appear on Report after the delay) |
+| AC-17 | `reportImage.test.js` (winners block, height), `club-share.test.js` (winners on `/r/`) | — | MP-19 (report image and `/r/` show winners) |
+
+Existing specs to update:
+- `e2e/zoom.timer-flow.spec.js:125`: the tab walk.
+- `timer-core`: `zoomSdk.js` capabilities, a re-run with no step change.
+- `club-card-sets`: `club.js` and `main.jsx` refresh, a re-run with no step change.
+- `INDEX.md`: add `meeting-polls` to the table and the run order, after `club-card-sets`.
+- Any existing spec whose `covers` lists `zoom-webhook.js`, `reportImage.js`,
+ `club-share.js` or `ReportTab.jsx`: review its steps for the winners block (re-run only
+ if no step changes).
+- `meeting-polls` setup: the dev app's SDK Status in the Debug Panel (as CC-00) shows
+ `sendMessageToChat`, `getMeetingContext`, `sendAppInvitationToAllParticipants`,
+ `authorize`, `onAuthorized` and `promptAuthorize` granted; a scheduled (not instant) test
+ meeting for MP-13/MP-14/MP-18; the guest device runs
+ `defaults write ZoomChat enableGuestModeTesting true` and restarts Zoom.
+
+## Risk
+**High.**
+- New public, unauthenticated write endpoints (votes, `polls/current`) and a new storage
+ primitive (a Durable Object binding plus migration in `wrangler.jsonc`, both envs).
+- **A stored Zoom credential (Q5):** the host's refresh token is kept for up to 24 h,
+ encrypted with AES-256-GCM under an HKDF key from `SESSION_SIGNING_KEY`, in that poll's
+ DO only. While a retry is pending, Zoom's rotated token replaces it (the old one is dead
+ once used). It is deleted right after the results fetch, after the last retry, or by 24 h,
+ whichever comes first. It is never logged or returned to a client.
+- Votes trust Zoom's encrypted app context for identity and meeting match; a forged or
+ replayed context fails `decryptAppContext` (expiry is enforced there).
+- `meeting.ended` webhook now does work beyond analytics; it still answers within Zoom's 3 s
+ (the DO call is in `ctx.waitUntil`).
+- New Zoom OAuth scopes and SDK APIs, and a Marketplace re-review before `polls_zoom` can be
+ on in production.
+- Changes to the club state payload, archive compaction, the report image and `/r/`.
+
+riskHigh paths touched:
+- `wrangler.jsonc` (the DO binding and migration, plus `POLL_VOTE_LIMITER`).
+- `worker/flags.js` (`polls` and `polls_zoom`).
+- `worker/auth.js`: `exchangeZoomCode` gains an opt-in to return the refresh token; every
+ existing caller keeps dropping it.
+- `worker/zoom-webhook.js`: `meeting.ended` forwards to the poll DO.
+
+Mitigations:
+- Both flags default off.
+- The native poll stays dark in production until Zoom approves the scopes.
+- No personal data in the vote URL or the stored votes: uids and device tokens are hashed
+ in the DO.
+- Expiry deletes poll storage; the token has its own shorter deadline.
+
+Size: the largest factory PR so far, at roughly 40–50 files. The commit order above keeps it
+reviewable.
+
+## Open questions
+All answered by ShuhaoZQGG on the PR (2026-11-14); kept here as the record.
+- Q1. Vote storage → **Durable Object**, one `PollRoom` per poll.
+- Q2. Web app → **Zoom app only** in this PR; shared code and the Worker serve both.
+- Q3. Rate limit → **in-Zoom voting with a verified identity is the primary path**; the web
+ link is the backup, limited per poll and IP to ~120/min, failing open.
+- Q4. Marketplace → **done on the dev app** (scopes, SDK APIs, webhooks, Guest Mode Testing).
+ Run MP-04, MP-13–MP-18 for real; ⏭ only for a setting that is still missing at the run.
+- Q5. Native results → **in this PR**, short-lived encrypted refresh token, triggered by
+ `meeting.ended` after a delay.
+- Q6. Report image and `/r/` → **show winners** in this PR.
+- Q7. Owner → **the creating uid**.
+- Q8. Zero votes → **"No votes", no winner**.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1b520880..fd49d8aa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -49,8 +49,10 @@ jobs:
run: node scripts/factory/check-oracle.mjs --base origin/${{ github.base_ref || 'dev' }}
- name: Build
run: npm run build
- - name: Install Playwright browser
- run: npx playwright install --with-deps chromium
+ # WebKit for the zoom-webkit project: the Zoom specs again in the engine of Zoom's macOS
+ # client (playwright.config.js).
+ - name: Install Playwright browsers
+ run: npx playwright install --with-deps chromium webkit
- name: Web e2e
run: npm run test:e2e
- uses: actions/upload-artifact@v4
diff --git a/CLAUDE.md b/CLAUDE.md
index 0daa84e4..c30639a1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,7 +6,9 @@ Dev is the `dev` branch, production is `master`.
## Commands
- `npm test` — vitest across all projects
-- `npm run test:e2e` — Playwright (`e2e/*.spec.js`, plain browser, Zoom SDK mocked)
+- `npm run test:e2e` — Playwright (`e2e/*.spec.js`, plain browser, Zoom SDK mocked). The Zoom
+ specs run twice, in Chromium (`zoom`) and WebKit (`zoom-webkit`): Zoom shows apps in Chromium
+ on Windows and WKWebView on macOS. First run: `npx playwright install chromium webkit`.
- `npm run test:specs` — validate the Zoom-client specs (below)
- `npm run cf:deploy:dev` — build and deploy the dev Worker
@@ -14,7 +16,7 @@ Dev is the `dev` branch, production is `master`.
| Layer | Where | Proves |
|---|---|---|
| Unit | `*.test.js` beside the code | logic |
-| Web e2e | `e2e/*.spec.js` | UI in a plain browser |
+| Web e2e | `e2e/*.spec.js` | UI in a plain browser: Chromium, and WebKit too for `zoom.*` |
| Zoom-client specs | `e2e/zoom-client/*.md` | the real Zoom client: SDK bridge, real video, Zoom dialogs |
| Reviewer plan | `docs/ZOOM_TEST_PLAN.md` | Marketplace reviewers only; a subset, not our source of truth |
@@ -26,8 +28,8 @@ anything the real Zoom client shows, that means the matching spec in `e2e/zoom-c
3. If no spec covers the area, add one from `_template.md` and list it in `INDEX.md`.
4. Run `npm run test:specs`. It fails on malformed specs and dangling `covers` paths.
5. Do not touch `verified_at` / `verified_on` unless you actually ran the spec. Those record a
- real run, not an edit. Running it is part of done (below); `status: stale` means a run was
- blocked, not skipped.
+ real run, not an edit. Whether the change needs that run is the next section; `status: stale`
+ means a run was blocked, not skipped.
Read `e2e/zoom-client/README.md` for the spec format. To run the specs against the real Zoom
client, use the `zoom-app-testing` skill; it starts from `e2e/zoom-client/INDEX.md`.
@@ -36,14 +38,38 @@ last edited ("drift"). Review the spec against the change and commit it; don't b
`--no-verify` to get around it. Before a release, run `npm run test:specs -- --stale --strict`
and rerun any spec it lists (changed since last real run).
+## When a change needs the real Zoom client
+A run in the real client takes the user's Mac, so run a covering spec there only when the change
+reaches the Zoom-only surface. That is more than a call to the Zoom Apps SDK:
+- **The SDK bridge**: a call to the SDK (`apps/zoom-app/src/utils/zoomSdk.js` and its callers),
+ or a change in what a call is given or when it runs: the card image, a badge, the colours and
+ thresholds that reach the video, the tick that pushes them, FINISH and RESET.
+- **Zoom's embedded browser**, where it differs from Chrome: the clipboard, a pasted file or
+ picture, the file dialog, drag and drop, opening a link (Zoom's Domain Allow List), `confirm`
+ and `alert`, sound, the camera.
+- **How the app loads and signs in inside Zoom**: the Worker's `zoom.` host, its routing and
+ headers, the app context and session token, OAuth and app authorization, the app's
+ capabilities, the `/zoom` build and its base path.
+
+Judge by what the changed lines reach, not by the file: a covered file that imports the SDK can
+change without touching any of this (`TimerContext.jsx`'s agenda import functions, for one).
+Anything else (logic, data, wording, an ordinary panel change) is proven by unit tests and
+Playwright, which mocks the SDK. Then still review each covering spec against the change and fix
+its steps, add a note naming the Playwright test that stands in for each moved step, and leave
+`verified_at`, `verified_on` and `status` alone. The release check above gives those specs their
+real run, so a batch of such changes costs one Zoom session. If you can't tell which side a
+change is on, say which item might apply and ask; a factory station, which can't ask, runs it.
+
## Definition of done
A change is done when all of these hold, not when the code compiles:
1. `npm test`, `npm run test:e2e` and `npm run test:specs` pass.
-2. Every Zoom-client spec whose `covers` includes a changed file ran in the real Zoom client
- (`zoom-app-testing` skill) against this branch deployed to dev. Its `test-runs//run.md`
- shows each step ✅, or ⏭ for a `human` step with the reason. Run it yourself right after
- implementing; don't stop to ask whether to test.
-3. The PR body follows `.github/pull_request_template.md` and links the run.
+2. If the change reaches the Zoom-only surface (above), every Zoom-client spec whose `covers`
+ includes a changed file ran in the real Zoom client (`zoom-app-testing` skill) against this
+ branch deployed to dev. Its `test-runs//run.md` shows each step ✅, or ⏭ for a `human`
+ step with the reason. Run it yourself right after implementing; don't stop to ask whether to
+ test. If it doesn't, each such spec carries the review note above instead.
+3. The PR body follows `.github/pull_request_template.md` and links the run, or says which
+ Playwright tests stood in and why no real run was needed.
Stop short of step 2 only when blocked: the Mac is in use, Zoom wants a sign-in or app
authorization, or the deploy fails. Then set the spec's `status: stale`, write what blocked it
diff --git a/apps/table-topics/README.md b/apps/table-topics/README.md
index 6d7e41d8..0a731009 100644
--- a/apps/table-topics/README.md
+++ b/apps/table-topics/README.md
@@ -8,3 +8,6 @@ Static site + Cloudflare Worker. Full documentation: [`docs/TABLE_TOPICS.md`](..
- Tests: `npx vitest run --root apps/table-topics`.
- Deploy: deployed by the timer Workers' Cloudflare Workers Builds on `master`/`dev` (see `docs/TABLE_TOPICS.md`);
manual: `npm run cf:deploy:dev` / `cf:deploy:prod`.
+- Theme of the day: `src/lib/themeMatch.js` (offline quick match on `content/tags.json` and question text,
+ plus the shortlist queue) and the Worker's
+ `/tabletopics/api/match` (`worker/tabletopics-match.js`, free OpenRouter models, secret `OPENROUTER_API_KEY`).
diff --git a/apps/table-topics/content/GENERATION_PROMPT.md b/apps/table-topics/content/GENERATION_PROMPT.md
index 243a04ef..9ac2ec32 100644
--- a/apps/table-topics/content/GENERATION_PROMPT.md
+++ b/apps/table-topics/content/GENERATION_PROMPT.md
@@ -53,6 +53,32 @@ weak questions is a separate, human-led task driven by usage analytics.
- New `added` = today's date.
- Keep the file's existing key order (`id`, `text`, `added`) and two-space JSON
indentation. Do not reformat untouched lines.
+- Give every new question its theme tags in `content/tags.json` (next section),
+ one line per id, appended after the last id of the same category.
+
+## Theme tags
+
+`content/tags.json` maps each question id to 5–8 theme tags. The "theme of the
+day" search uses them when the LLM ranking is unavailable, so a question without
+tags is still listed but is harder to find by theme. Tags are lowercase English
+words or two-word phrases a Table Topics Master might type as the meeting's
+theme and be glad to see this question for. Mix three kinds:
+
+- 2–3 **abstract themes** the question really serves, even if the word is not in
+ the text (e.g. gratitude, forgiveness, second chance, courage, belonging,
+ change, patience).
+- 2–3 **concrete topics** it is about (e.g. ocean, beach, boss, first job,
+ grandparent, kitchen, rain, music, airport).
+- 1–2 **near-synonyms or related words** a Master might type instead (e.g. for a
+ travel mishap: "trip gone wrong"; for a mentor: "role model").
+
+Rules: singular nouns where natural; reuse a tag already in the file when it
+fits rather than a near-variant ("first job", not "first employment"); no
+category names as tags ("hypothetical", "icebreaker", "would you rather"); no
+tag that fits most of the bank ("life", "people", "time", "memory", "choice")
+unless it is the point; precision over volume. The validator checks the shape
+(5–8 unique tags, lowercase letters, spaces and hyphens, at most 30 characters)
+and lists questions that have no tags.
## Steps
@@ -60,14 +86,15 @@ weak questions is a separate, human-led task driven by usage analytics.
list the existing ones so you avoid near-duplicates, then write up to `N`
new ones that widen the range of angles
(time frames, senses, people, places, emotions, "why" vs "how" vs "when").
-2. Append them and run, from the repo root:
+2. Append them, add their tags to `content/tags.json`, and run, from the repo root:
```
npm run validate:tabletopics
npx vitest run --project apps/table-topics
```
- Fix every reported problem and rerun until both pass.
+ Fix every reported problem and rerun until both pass. The validator also
+ warns about questions with no tags: tag the ones you added.
3. Create branch `content/tt-questions-YYYY-MM-DD`, commit
`content(tabletopics): + questions for YYYY-MM-DD`, push, and open a
pull request against `master` titled the same, whose body lists the number
diff --git a/apps/table-topics/content/tags.json b/apps/table-topics/content/tags.json
new file mode 100644
index 00000000..eb3a9c61
--- /dev/null
+++ b/apps/table-topics/content/tags.json
@@ -0,0 +1,1221 @@
+{
+ "icebreakers-001": ["gratitude", "joy", "small pleasure", "this week", "smile", "happiness"],
+ "icebreakers-002": ["self-awareness", "friendship", "honesty", "best friend", "self-image", "personality"],
+ "icebreakers-003": ["home", "comfort", "routine", "living room", "kitchen", "habit"],
+ "icebreakers-004": ["courage", "new experience", "curiosity", "growth", "first time", "trying new things"],
+ "icebreakers-005": ["mentor", "gratitude", "learning", "skill", "teacher", "role model"],
+ "icebreakers-006": ["rest", "relaxation", "balance", "weekend", "sunday", "leisure"],
+ "icebreakers-007": ["mood", "music", "energy", "song", "theme song", "soundtrack"],
+ "icebreakers-008": ["calm", "solitude", "stress relief", "nature", "walk", "retreat"],
+ "icebreakers-009": ["identity", "misconception", "first impression", "self-awareness", "stereotype", "surprise"],
+ "icebreakers-010": ["joy", "memory", "friendship", "evening", "gratitude", "good times"],
+ "icebreakers-011": ["dream", "passion", "curiosity", "hobby", "freedom", "bucket list"],
+ "icebreakers-012": ["encouragement", "kindness", "self-worth", "compliment", "praise", "gratitude"],
+ "icebreakers-013": ["identity", "family", "heritage", "name", "nickname", "origin story"],
+ "icebreakers-014": ["authenticity", "identity", "belonging", "comfort", "true self", "confidence"],
+ "icebreakers-015": ["food", "comfort", "joy", "favorite meal", "craving", "cooking"],
+ "icebreakers-016": ["celebration", "achievement", "self-care", "reward", "pride", "treat"],
+ "icebreakers-017": ["comfort", "calm", "sound", "rain", "nostalgia", "noise"],
+ "icebreakers-018": ["gratitude", "travel", "commute", "journey", "mindfulness", "morning"],
+ "icebreakers-019": ["time", "priorities", "rest", "passion", "balance", "extra hour"],
+ "icebreakers-020": ["anticipation", "hope", "excitement", "future", "plans", "event"],
+ "icebreakers-021": ["identity", "personality", "nature", "season", "autumn", "summer"],
+ "icebreakers-022": ["gratitude", "joy", "small pleasure", "contentment", "comfort", "happiness"],
+ "icebreakers-023": ["tradition", "self-care", "ritual", "routine", "personal habit", "uniqueness"],
+ "icebreakers-024": ["gratitude", "mindfulness", "joy", "memory", "today", "savoring"],
+ "icebreakers-025": ["curiosity", "connection", "self-expression", "conversation", "listening", "being heard"],
+ "icebreakers-026": ["memory", "sentimental", "keepsake", "pocket", "story", "talisman"],
+ "icebreakers-027": ["quirk", "surprise", "habit", "personality", "first impression", "routine"],
+ "icebreakers-028": ["wisdom", "kindness", "advice", "stranger", "serendipity", "life lesson"],
+ "icebreakers-029": ["humor", "laughter", "joy", "comedy", "funny moment", "happiness"],
+ "icebreakers-030": ["decision", "gratitude", "choice", "satisfaction", "regret", "good call"],
+ "icebreakers-031": ["observation", "shyness", "first impression", "networking", "social anxiety", "awareness"],
+ "icebreakers-032": ["accomplishment", "productivity", "satisfaction", "chore", "to-do list", "routine"],
+ "icebreakers-033": ["memory", "sentimental", "desk", "workplace", "story", "keepsake"],
+ "icebreakers-034": ["energy", "communication", "routine", "morning", "night owl", "chatty"],
+ "icebreakers-035": ["public speaking", "confidence", "nerves", "ritual", "preparation", "courage"],
+ "icebreakers-036": ["commute", "routine", "gratitude", "travel", "train", "mindfulness"],
+ "icebreakers-037": ["kindness", "compliment", "encouragement", "surprise", "generosity", "praise"],
+ "icebreakers-038": ["comfort", "self-care", "resilience", "hard times", "coping", "bad day"],
+ "icebreakers-039": ["values", "priorities", "emergency", "sentimental", "keepsake", "survival"],
+ "icebreakers-040": ["conversation", "connection", "party", "socializing", "curiosity", "small talk"],
+ "icebreakers-041": ["kindness", "stranger", "gratitude", "generosity", "encouragement", "compliment"],
+ "icebreakers-042": ["gratitude", "mindfulness", "joy", "today", "savoring", "memory"],
+ "icebreakers-043": ["belonging", "comfort", "welcome", "social ease", "new group", "friendliness"],
+ "icebreakers-044": ["memory", "mindfulness", "detail", "gratitude", "today", "nostalgia"],
+ "icebreakers-045": ["sound", "mindfulness", "memory", "morning", "comfort", "noise"],
+ "icebreakers-046": ["growth", "skill", "surprise", "progress", "effortless", "improvement"],
+ "icebreakers-047": ["joy", "small pleasure", "simplicity", "gratitude", "shopping", "money", "bargain"],
+ "icebreakers-048": ["good news", "celebration", "sharing", "connection", "best friend", "phone call", "inner circle"],
+ "icebreakers-049": ["serendipity", "learning", "discovery", "skill", "hobby", "happy accident", "hidden talent"],
+ "icebreakers-050": ["small win", "pride", "achievement", "satisfaction", "morning", "progress", "small victory"],
+ "icebreakers-051": ["kindness", "connection", "joy", "stranger", "smile", "mood", "small gesture"],
+ "icebreakers-052": ["routine", "ritual", "comfort", "home", "front door", "homecoming", "unwinding"],
+ "icebreakers-053": ["kindness", "belonging", "hospitality", "welcome", "stranger", "small gesture", "newcomer"],
+ "icebreakers-054": ["music", "song", "earworm", "catchy tune", "playlist", "mood", "this week"],
+ "icebreakers-055": ["curiosity", "connection", "culture", "small talk", "conversation starter", "question", "hometown"],
+ "icebreakers-056": ["identity", "first impression", "assumption", "misunderstanding", "misconception", "quirk", "personality"],
+ "icebreakers-057": ["storytelling", "story", "sentimental", "observation", "keepsake", "object", "possession"],
+ "icebreakers-058": ["humor", "laughter", "connection", "first impression", "joke", "banter", "funny"],
+ "icebreakers-059": ["risk", "courage", "small win", "success", "comfort zone", "trying new things", "growth"],
+ "icebreakers-060": ["morning routine", "priorities", "boundaries", "morning", "routine", "habit", "self-care"],
+ "icebreakers-061": ["quirk", "communication", "personality", "language", "word", "saying", "identity"],
+ "childhood-memories-001": ["play", "nostalgia", "game", "fun", "friendship", "joy"],
+ "childhood-memories-002": ["mentor", "role model", "influence", "neighbor", "teacher", "gratitude"],
+ "childhood-memories-003": ["home", "hometown", "neighborhood", "sensory memory", "street", "nostalgia"],
+ "childhood-memories-004": ["pride", "achievement", "confidence", "self-esteem", "first time", "accomplishment"],
+ "childhood-memories-005": ["tradition", "family", "nostalgia", "holiday", "longing", "ritual"],
+ "childhood-memories-006": ["summer", "friendship", "play", "freedom", "outdoors", "carefree"],
+ "childhood-memories-007": ["money", "independence", "saving", "first purchase", "responsibility", "patience"],
+ "childhood-memories-008": ["fear", "courage", "humor", "growing up", "bedtime", "monster"],
+ "childhood-memories-009": ["wisdom", "grandparent", "elder", "legacy", "life lesson", "gratitude"],
+ "childhood-memories-010": ["disillusionment", "parent", "growing up", "forgiveness", "family", "maturity"],
+ "childhood-memories-011": ["dream", "ambition", "career", "disappointment", "change", "aspiration"],
+ "childhood-memories-012": ["nostalgia", "scent", "sensory memory", "home", "childhood home", "kitchen"],
+ "childhood-memories-013": ["hiding place", "play", "secret", "imagination", "hide and seek", "privacy"],
+ "childhood-memories-014": ["birthday", "celebration", "family", "tradition", "party", "cake"],
+ "childhood-memories-015": ["advice", "self-compassion", "growth", "wisdom", "younger self", "letter"],
+ "childhood-memories-016": ["story", "imagination", "reading", "book", "bedtime story", "worldview"],
+ "childhood-memories-017": ["mischief", "mistake", "consequence", "learning", "trouble", "growing up"],
+ "childhood-memories-018": ["friendship", "best friend", "play", "loyalty", "nostalgia", "school"],
+ "childhood-memories-019": ["nostalgia", "home", "sentimental", "loss", "toy", "keepsake"],
+ "childhood-memories-020": ["independence", "growing up", "freedom", "courage", "milestone", "self-reliance"],
+ "childhood-memories-021": ["sibling", "family", "relationship", "change", "cousin", "bond"],
+ "childhood-memories-022": ["routine", "family", "school", "morning", "breakfast", "home"],
+ "childhood-memories-023": ["creativity", "friendship", "play", "imagination", "secret language", "rules"],
+ "childhood-memories-024": ["chore", "creativity", "play", "work ethic", "fun", "family"],
+ "childhood-memories-025": ["identity", "bedroom", "self-expression", "nostalgia", "home", "personality"],
+ "childhood-memories-026": ["toy", "nostalgia", "attachment", "loss", "sentimental", "favorite thing"],
+ "childhood-memories-027": ["road trip", "family", "adventure", "vacation", "car ride", "travel"],
+ "childhood-memories-028": ["discipline", "respect", "mentor", "authority", "teacher", "grandparent"],
+ "childhood-memories-029": ["family", "gathering", "celebration", "noise", "holiday", "chaos"],
+ "childhood-memories-030": ["teacher", "words of wisdom", "impact", "school", "mentor", "encouragement"],
+ "childhood-memories-031": ["friendship", "conflict", "argument", "play", "rivalry", "school"],
+ "childhood-memories-032": ["rebellion", "rules", "mischief", "courage", "growing up", "independence"],
+ "childhood-memories-033": ["kitchen", "family", "morning", "sound", "home", "breakfast"],
+ "childhood-memories-034": ["responsibility", "trust", "growing up", "maturity", "chore", "pride"],
+ "childhood-memories-035": ["play", "game", "playground", "friendship", "street", "imagination"],
+ "childhood-memories-036": ["relative", "grandparent", "sensory memory", "nostalgia", "house", "family visit"],
+ "childhood-memories-037": ["friendship", "belonging", "understanding", "empathy", "connection", "best friend"],
+ "childhood-memories-038": ["family", "storytelling", "memory", "tradition", "exaggeration", "legacy"],
+ "childhood-memories-039": ["snack", "nostalgia", "food", "comfort", "sensory memory", "treat"],
+ "childhood-memories-040": ["neighbor", "community", "belonging", "found family", "kindness", "neighborhood"],
+ "childhood-memories-041": ["family", "wisdom", "values", "upbringing", "saying", "influence"],
+ "childhood-memories-042": ["friendship", "regret", "reconnection", "lost touch", "nostalgia", "longing"],
+ "childhood-memories-043": ["family", "road trip", "debate", "car ride", "conversation", "values"],
+ "childhood-memories-044": ["road trip", "family car", "sensory memory", "nostalgia", "family", "journey"],
+ "childhood-memories-045": ["safety", "comfort", "love", "trust", "parent", "security"],
+ "childhood-memories-046": ["imagination", "creativity", "loneliness", "imaginary friend", "play", "companionship"],
+ "childhood-memories-047": ["tradition", "nostalgia", "celebration", "birthday", "family recipe", "special occasion", "treat"],
+ "childhood-memories-048": ["apology", "saying sorry", "respect", "humility", "accountability", "forgiveness", "role model", "teacher"],
+ "childhood-memories-049": ["secret", "honesty", "trust", "mischief", "rebellion", "parent", "confession"],
+ "childhood-memories-050": ["play", "nostalgia", "community", "friendship", "game", "neighborhood", "summer", "fad"],
+ "childhood-memories-051": ["storytelling", "adventure", "risk", "mischief", "injury", "scar", "accident"],
+ "childhood-memories-052": ["home", "nostalgia", "community", "front porch", "doorway", "childhood home", "neighborhood", "growing up"],
+ "childhood-memories-053": ["honesty", "truth", "innocence", "white lie", "family", "belief", "myth", "funny story"],
+ "childhood-memories-054": ["negotiation", "persuasion", "mischief", "chore", "sibling", "bribe", "bargaining"],
+ "childhood-memories-055": ["mischief", "rebellion", "temptation", "curiosity", "neighbor", "yard", "rule breaking", "forbidden fruit"],
+ "childhood-memories-056": ["nostalgia", "home", "familiarity", "observation", "window", "view", "bedroom", "childhood home"],
+ "childhood-memories-057": ["rebellion", "mischief", "independence", "rule", "rule breaking", "disobedience", "secret", "parent"],
+ "childhood-memories-058": ["innocence", "imagination", "belief", "misconception", "childhood", "growing up", "perspective", "truth"],
+ "childhood-memories-059": ["sound", "neighborhood", "childhood", "nostalgia", "sensory memory", "home", "memory"],
+ "childhood-memories-060": ["rules", "family", "upbringing", "authority", "tradition", "childhood", "household"],
+ "childhood-memories-061": ["gift", "birthday", "surprise", "childhood", "joy", "gratitude", "special occasion"],
+ "travel-places-001": ["expectation", "surprise", "travel", "discovery", "perspective", "first impression"],
+ "travel-places-002": ["food", "culture", "travel", "meal", "memory", "hospitality"],
+ "travel-places-003": ["decision", "planning", "vacation", "time off", "preferences", "destination"],
+ "travel-places-004": ["serendipity", "getting lost", "adventure", "detour", "discovery", "surprise"],
+ "travel-places-005": ["stranger", "connection", "travel", "friendship", "encounter", "storytelling"],
+ "travel-places-006": ["belonging", "home", "comfort", "roots", "community", "place"],
+ "travel-places-007": ["exploration", "spontaneity", "city", "freedom", "wandering", "adventure"],
+ "travel-places-008": ["transportation", "personality", "travel", "train", "journey", "self-awareness"],
+ "travel-places-009": ["awe", "scenery", "nature", "view", "wonder", "mountain"],
+ "travel-places-010": ["identity", "change", "moving", "roots", "home", "belonging"],
+ "travel-places-011": ["packing", "quirk", "travel", "habit", "essentials", "preparation"],
+ "travel-places-012": ["self-discovery", "growth", "journey", "travel", "lesson", "adventure"],
+ "travel-places-013": ["dream", "adventure", "relocation", "expat", "freedom", "destination"],
+ "travel-places-014": ["nostalgia", "longing", "home", "moving", "former home", "belonging"],
+ "travel-places-015": ["resilience", "travel mishap", "adventure", "trip gone wrong", "humor", "silver lining"],
+ "travel-places-016": ["observation", "first impression", "arrival", "detail", "awareness", "travel"],
+ "travel-places-017": ["nostalgia", "return", "memory", "revisit", "hope", "longing"],
+ "travel-places-018": ["city", "solo travel", "arrival", "evening", "exploration", "routine"],
+ "travel-places-019": ["souvenir", "memory", "sentimental", "keepsake", "gift", "story"],
+ "travel-places-020": ["peace", "calm", "nature", "solitude", "retreat", "happy place"],
+ "travel-places-021": ["hometown", "local knowledge", "hospitality", "hidden gem", "sharing", "pride"],
+ "travel-places-022": ["friendship", "companionship", "travel buddy", "trust", "adventure", "compatibility"],
+ "travel-places-023": ["patience", "waiting", "delay", "airport", "boredom", "travel"],
+ "travel-places-024": ["culture", "custom", "surprise", "tradition", "travel", "etiquette"],
+ "travel-places-025": ["airport", "waiting", "layover", "rest", "travel", "comfort"],
+ "travel-places-026": ["journey", "train", "bus", "memory", "public transit", "scenery"],
+ "travel-places-027": ["travel mishap", "humor", "storytelling", "trip gone wrong", "adventure", "resilience"],
+ "travel-places-028": ["routine", "arrival", "habit", "hotel", "unpacking", "settling in"],
+ "travel-places-029": ["belonging", "familiarity", "home", "city", "connection", "small town"],
+ "travel-places-030": ["adaptability", "resilience", "plans", "improvisation", "trip gone wrong", "flexibility"],
+ "travel-places-031": ["rule", "habit", "travel", "discipline", "principle", "preparation"],
+ "travel-places-032": ["exhaustion", "humor", "sleep", "travel", "airport", "strange place"],
+ "travel-places-033": ["food", "street food", "market", "culture", "memory", "travel"],
+ "travel-places-034": ["goodbye", "change", "letting go", "attachment", "moving", "decision"],
+ "travel-places-035": ["quiet", "peace", "solitude", "nature", "stillness", "remote place"],
+ "travel-places-036": ["border", "adventure", "surprise", "passport", "checkpoint", "travel story"],
+ "travel-places-037": ["nostalgia", "sensory memory", "airport", "train station", "departure", "smell"],
+ "travel-places-038": ["slow down", "small town", "change of mind", "simplicity", "rest", "mindfulness"],
+ "travel-places-039": ["music", "road trip", "playlist", "mood", "driving", "journey"],
+ "travel-places-040": ["connection", "family", "arrival", "friendship", "check in", "call home"],
+ "travel-places-041": ["local", "advice", "hospitality", "city", "insider tip", "guide"],
+ "travel-places-042": ["patience", "transportation", "delay", "resilience", "journey", "commute"],
+ "travel-places-043": ["lesson learned", "packing", "preparation", "trip gone wrong", "adaptation", "mistake"],
+ "travel-places-044": ["arrival", "sensory memory", "sound", "travel", "first impression", "journey"],
+ "travel-places-045": ["serendipity", "kindness", "stranger", "directions", "getting lost", "hospitality"],
+ "travel-places-046": ["morning", "arrival", "routine", "exploration", "breakfast", "new city"],
+ "travel-places-047": ["friendship", "serendipity", "connection", "solo travel", "stranger", "travel", "unlikely friendship"],
+ "travel-places-048": ["simplicity", "peace", "contentment", "slowing down", "small town", "village", "slow living", "travel"],
+ "travel-places-049": ["home", "comfort", "homecoming", "homesickness", "comfort food", "craving", "meal", "travel"],
+ "travel-places-050": ["serendipity", "spontaneity", "surprise", "discovery", "detour", "road trip", "travel", "happy accident"],
+ "travel-places-051": ["regret", "missed opportunity", "hindsight", "photo", "photography", "camera", "travel"],
+ "travel-places-052": ["culture", "communication", "respect", "curiosity", "language", "foreign language", "word", "travel"],
+ "travel-places-053": ["efficiency", "design", "public transit", "public transport", "subway", "train", "city", "commute"],
+ "travel-places-054": ["adventure", "hospitality", "culture", "manners", "open-mindedness", "exotic food", "guest", "travel"],
+ "travel-places-055": ["friendship", "serendipity", "silver lining", "waiting", "flight delay", "airport", "stranger", "unlikely friendship"],
+ "travel-places-056": ["regret", "missed opportunity", "hindsight", "souvenir", "keepsake", "shopping", "travel"],
+ "travel-places-057": ["serendipity", "culture", "discovery", "surprise", "tradition", "festival", "local custom", "travel"],
+ "travel-places-058": ["coziness", "comfort", "relaxation", "rain", "rainy day", "weather", "city", "travel"],
+ "travel-places-059": ["airport", "familiarity", "train station", "travel", "transition", "comfort", "journey"],
+ "travel-places-060": ["hotel", "check in", "settling in", "routine", "comfort", "habit", "travel"],
+ "travel-places-061": ["road trip", "driving", "reflection", "solitude", "journey", "self-reflection", "scenery"],
+ "work-career-001": ["first job", "learning", "beginnings", "teenager", "work ethic", "lesson"],
+ "work-career-002": ["colleague", "teamwork", "role model", "collaboration", "coworker", "admiration"],
+ "work-career-003": ["decision", "change", "career", "quitting", "resignation", "new chapter"],
+ "work-career-004": ["regret", "advice", "wisdom", "career advice", "hindsight", "listening"],
+ "work-career-005": ["pride", "achievement", "accomplishment", "career", "success", "milestone"],
+ "work-career-006": ["skill", "surprise", "past job", "transferable skill", "learning", "experience"],
+ "work-career-007": ["fulfillment", "work-life", "routine", "satisfaction", "productivity", "workday"],
+ "work-career-008": ["conflict", "deadline", "colleague", "patience", "accountability", "teamwork"],
+ "work-career-009": ["dream", "passion", "calling", "career change", "purpose", "money"],
+ "work-career-010": ["mistake", "failure", "learning", "growth", "resilience", "humility"],
+ "work-career-011": ["success", "change", "values", "ambition", "maturity", "perspective"],
+ "work-career-012": ["change", "new job", "beginnings", "nerves", "onboarding", "adaptation"],
+ "work-career-013": ["boundaries", "courage", "decision", "assertiveness", "no", "integrity"],
+ "work-career-014": ["opportunity", "mentor", "gratitude", "first break", "trust", "beginnings"],
+ "work-career-015": ["meeting", "productivity", "communication", "teamwork", "agenda", "value"],
+ "work-career-016": ["energy", "motivation", "focus", "boredom", "routine", "productivity"],
+ "work-career-017": ["values", "self-awareness", "dislike", "preference", "career", "dealbreaker"],
+ "work-career-018": ["boss", "role model", "leadership", "influence", "manager", "lesson"],
+ "work-career-019": ["work-life balance", "boundaries", "balance", "self-care", "routine", "burnout"],
+ "work-career-020": ["advice", "wisdom", "career choice", "mentor", "youth", "guidance"],
+ "work-career-021": ["interview", "surprise", "job hunting", "nerves", "unexpected", "story"],
+ "work-career-022": ["retirement", "dream", "future", "freedom", "leisure", "aging"],
+ "work-career-023": ["interview", "self-promotion", "regret", "preparation", "strengths", "job hunting"],
+ "work-career-024": ["resilience", "public speaking", "presentation", "failure", "recovery", "self-compassion"],
+ "work-career-025": ["ritual", "focus", "morning", "routine", "productivity", "habit"],
+ "work-career-026": ["interview", "humor", "surprise", "job hunting", "unexpected question", "story"],
+ "work-career-027": ["celebration", "achievement", "project", "teamwork", "reward", "milestone"],
+ "work-career-028": ["passion", "guilty pleasure", "task", "satisfaction", "hidden joy", "work"],
+ "work-career-029": ["tradition", "workplace culture", "team building", "company culture", "morale", "ritual"],
+ "work-career-030": ["success", "project", "teamwork", "completion", "satisfaction", "milestone"],
+ "work-career-031": ["stress", "advice", "coworker", "coping", "mentor", "resilience"],
+ "work-career-032": ["feedback", "customer", "praise", "client", "recognition", "service"],
+ "work-career-033": ["overtime", "recovery", "burnout", "rest", "work-life balance", "self-care"],
+ "work-career-034": ["workplace culture", "learning", "unwritten rule", "adaptation", "office politics", "norms"],
+ "work-career-035": ["kindness", "gratitude", "stranger", "coworker", "generosity", "support"],
+ "work-career-036": ["expertise", "explanation", "communication", "job", "simplicity", "tacit knowledge"],
+ "work-career-037": ["raise", "promotion", "negotiation", "timing", "courage", "self-worth"],
+ "work-career-038": ["first boss", "regret", "gratitude", "letter", "closure", "beginnings"],
+ "work-career-039": ["perk", "gratitude", "workplace culture", "small gesture", "past job", "appreciation"],
+ "work-career-040": ["recovery", "resilience", "monday", "burnout", "routine", "fresh start"],
+ "work-career-041": ["decision", "project", "priorities", "self-reflection", "workload", "boundaries"],
+ "work-career-042": ["teamwork", "habit", "coworker", "team culture", "influence", "quiet leadership"],
+ "work-career-043": ["new job", "beginnings", "onboarding", "first impression", "expectations", "change"],
+ "work-career-044": ["pride", "quiet pride", "achievement", "recognition", "humility", "accomplishment"],
+ "work-career-045": ["mentor", "gratitude", "thank you", "regret", "role model", "appreciation"],
+ "work-career-046": ["nerves", "preparation", "meeting", "routine", "focus", "public speaking"],
+ "work-career-047": ["lesson", "growth", "resilience", "adversity", "boss", "manager", "difficult people", "workplace"],
+ "work-career-048": ["priorities", "values", "trade-off", "job satisfaction", "perks", "quitting", "career change", "decision-making"],
+ "work-career-049": ["productivity", "routine", "planning", "control", "time management", "monday", "to-do list", "fresh start"],
+ "work-career-050": ["friendship", "loyalty", "connection", "colleague", "work friend", "workplace", "lasting friendship"],
+ "work-career-051": ["mentor", "teaching", "priorities", "new hire", "onboarding", "training", "first day", "newcomer"],
+ "work-career-052": ["priorities", "boundaries", "time management", "work-life balance", "email", "inbox", "urgency", "procrastination"],
+ "work-career-053": ["focus", "productivity", "mood", "music", "silence", "office", "soundtrack", "background music"],
+ "work-career-054": ["passion", "purpose", "motivation", "fulfillment", "job satisfaction", "dream job", "calling"],
+ "work-career-055": ["recognition", "feedback", "pride", "appreciation", "client", "customer", "compliment", "praise"],
+ "work-career-056": ["recognition", "pride", "reputation", "validation", "praise", "compliment", "kind words", "feedback"],
+ "work-career-057": ["mentor", "teaching", "fundamentals", "expertise", "priorities", "beginner", "basics", "training"],
+ "work-career-058": ["perspective", "judgment", "self-awareness", "resilience", "bad week", "job satisfaction", "burnout", "rough patch"],
+ "work-career-059": ["bad day", "coping", "resilience", "routine", "stress", "reset", "workday"],
+ "work-career-060": ["coworker", "small habit", "colleague", "humor", "smile", "workplace", "quirk"],
+ "work-career-061": ["focus", "meeting", "recovery", "productivity", "time management", "discipline", "attention"],
+ "leadership-001": ["role model", "leadership", "admiration", "mentor", "character", "inspiration"],
+ "leadership-002": ["courage", "decision", "conflict", "conviction", "disagreement", "accountability"],
+ "leadership-003": ["leadership", "authority", "influence", "responsibility", "management", "character"],
+ "leadership-004": ["trust", "credibility", "relationship", "new team", "leadership", "authenticity"],
+ "leadership-005": ["failure", "learning", "humility", "mistake", "growth", "self-reflection"],
+ "leadership-006": ["followership", "humility", "teamwork", "collaboration", "trust", "leadership"],
+ "leadership-007": ["communication", "honesty", "bad news", "empathy", "transparency", "courage"],
+ "leadership-008": ["mentor", "role model", "quality", "guidance", "wisdom", "patience"],
+ "leadership-009": ["motivation", "encouragement", "empathy", "engagement", "coaching", "burnout"],
+ "leadership-010": ["first time", "responsibility", "leadership", "beginnings", "nerves", "pride"],
+ "leadership-011": ["humility", "accountability", "mistake", "vulnerability", "honesty", "apology"],
+ "leadership-012": ["feedback", "honesty", "courage", "growth", "criticism", "communication"],
+ "leadership-013": ["fairness", "decision", "conflict", "compromise", "justice", "negotiation"],
+ "leadership-014": ["small gesture", "kindness", "example", "admiration", "leadership", "role model"],
+ "leadership-015": ["decision", "conviction", "flexibility", "adaptability", "judgment", "open mind"],
+ "leadership-016": ["encouragement", "shyness", "voice", "inclusion", "coaching", "confidence"],
+ "leadership-017": ["change", "turnaround", "struggling team", "planning", "priorities", "rebuilding"],
+ "leadership-018": ["mentor", "teaching", "learning", "mentorship", "growth", "guidance"],
+ "leadership-019": ["calm", "pressure", "composure", "stress", "confidence", "crisis"],
+ "leadership-020": ["responsibility", "duty", "service", "trust", "leadership", "values"],
+ "leadership-021": ["stepping back", "growth", "delegation", "trust", "empowerment", "mentoring"],
+ "leadership-022": ["teamwork", "collaboration", "trust", "culture", "team health", "harmony"],
+ "leadership-023": ["structure", "freedom", "autonomy", "team management", "judgment", "balance"],
+ "leadership-024": ["humility", "learning", "generations", "young person", "mentor", "fresh perspective"],
+ "leadership-025": ["morale", "motivation", "perseverance", "team spirit", "encouragement", "resilience"],
+ "leadership-026": ["friendship", "boundaries", "promotion", "authority", "change", "relationship"],
+ "leadership-027": ["trust", "repair", "apology", "mistake", "accountability", "recovery"],
+ "leadership-028": ["bad boss", "lesson", "learning", "role model", "leadership", "mistake"],
+ "leadership-029": ["humility", "kindness", "feedback", "courage", "correction", "tact"],
+ "leadership-030": ["inclusion", "decision", "listening", "diversity", "consultation", "collaboration"],
+ "leadership-031": ["struggling project", "assessment", "priorities", "takeover", "diagnosis", "planning"],
+ "leadership-032": ["trust", "warning sign", "team morale", "leadership", "communication", "awareness"],
+ "leadership-033": ["coaching", "patience", "growth", "delegation", "struggle", "autonomy"],
+ "leadership-034": ["quiet leadership", "introvert", "humility", "influence", "role model", "example"],
+ "leadership-035": ["priorities", "advocacy", "courage", "team", "conflict", "judgment"],
+ "leadership-036": ["informal leadership", "influence", "character", "initiative", "role model", "observation"],
+ "leadership-037": ["humility", "experience", "respect", "authority", "seniority", "collaboration"],
+ "leadership-038": ["observation", "awareness", "preparation", "listening", "audience", "reading the room"],
+ "leadership-039": ["credit", "fairness", "humility", "teamwork", "recognition", "generosity"],
+ "leadership-040": ["risk", "courage", "worry", "decision", "accountability", "uncertainty"],
+ "leadership-041": ["courage", "quiet leadership", "bravery", "integrity", "role model", "conviction"],
+ "leadership-042": ["succession", "change", "humility", "letting go", "transition", "growth"],
+ "leadership-043": ["parent", "upbringing", "influence", "role model", "family", "values"],
+ "leadership-044": ["small gesture", "kindness", "respect", "perception", "leadership", "impact"],
+ "leadership-045": ["silence", "listening", "restraint", "patience", "wisdom", "quiet leadership"],
+ "leadership-046": ["stepping back", "humility", "mentor", "empowerment", "growth", "selflessness"],
+ "leadership-047": ["trust", "credibility", "confidence", "respect", "team", "judgment", "earning trust", "leadership"],
+ "leadership-048": ["loyalty", "disagreement", "compromise", "trust", "humility", "followership", "boss", "leadership"],
+ "leadership-049": ["boundaries", "vulnerability", "privacy", "authenticity", "transparency", "personal life", "oversharing", "team"],
+ "leadership-050": ["courage", "risk", "decision-making", "new leader", "first week", "new boss", "bold move", "first impression"],
+ "leadership-051": ["role model", "influence", "integrity", "credibility", "teaching", "coaching", "good example", "leadership"],
+ "leadership-052": ["listening", "curiosity", "humility", "new leader", "team", "question", "first impression", "new boss"],
+ "leadership-053": ["kindness", "tact", "feedback", "constructive criticism", "mistake", "being wrong", "boss", "respect"],
+ "leadership-054": ["procrastination", "courage", "regret", "hindsight", "decision", "indecision", "stepping up", "taking charge"],
+ "leadership-055": ["listening", "empathy", "self-awareness", "humility", "communication", "active listening", "emotional intelligence", "team"],
+ "leadership-056": ["trust", "judgment", "credibility", "character", "integrity", "track record", "reliability", "first impression"],
+ "leadership-057": ["accountability", "responsibility", "humility", "ownership", "failure", "team", "blame", "self-reflection"],
+ "leadership-058": ["patience", "role model", "influence", "calm", "admiration", "mentor", "parent", "teacher"],
+ "leadership-059": ["decision-making", "urgency", "judgment", "pressure", "timing", "leadership", "risk"],
+ "leadership-060": ["leadership", "humor", "quiet leadership", "influence", "informal leadership", "example", "funny story"],
+ "leadership-061": ["trust", "leadership", "first time", "responsibility", "beginnings", "stepping up", "confidence"],
+ "technology-001": ["dependence", "essentials", "gadget", "smartphone", "minimalism", "must-have"],
+ "technology-002": ["routine", "morning", "smartphone", "habit", "alarm clock", "daily ritual"],
+ "technology-003": ["open-mindedness", "adaptation", "resistance to change", "new gadget", "early skeptic", "conversion"],
+ "technology-004": ["frustration", "bad timing", "device failure", "crash", "dead battery", "murphy's law"],
+ "technology-005": ["dependence", "disconnection", "internet", "offline", "digital detox", "withdrawal"],
+ "technology-006": ["nostalgia", "affection", "old gadget", "retro tech", "walkman", "vintage"],
+ "technology-007": ["decision-making", "upgrade", "frugality", "old phone", "consumerism", "replacement"],
+ "technology-008": ["productivity", "efficiency", "app", "time saving", "tool", "workflow"],
+ "technology-009": ["connection", "family", "long distance", "video call", "messaging", "staying in touch"],
+ "technology-010": ["lost skills", "tradition", "navigation", "handwriting", "mental math", "forgotten craft"],
+ "technology-011": ["surprise", "innovation", "invention", "amazement", "progress", "breakthrough"],
+ "technology-012": ["balance", "digital detox", "screen time", "rest", "self-care", "unplugging"],
+ "technology-013": ["innovation", "problem solving", "invention", "annoyance", "creativity", "gadget idea"],
+ "technology-014": ["connection", "distance", "video call", "long distance", "friendship", "closeness"],
+ "technology-015": ["learning", "curiosity", "online video", "tutorial", "self-teaching", "how-to"],
+ "technology-016": ["comfort", "voice assistant", "awkwardness", "smart speaker", "talking", "new habits"],
+ "technology-017": ["regret", "invention", "social media", "unintended consequence", "pandora's box", "ethics"],
+ "technology-018": ["wisdom", "advice", "generational gap", "smartphone", "mentoring", "elder"],
+ "technology-019": ["memory", "nostalgia", "photography", "smartphone camera", "living in the moment", "souvenir"],
+ "technology-020": ["beginnings", "nostalgia", "first computer", "childhood", "early tech", "first phone"],
+ "technology-021": ["tradition", "craftsmanship", "handwriting", "analog", "preference", "manual work"],
+ "technology-022": ["future", "prediction", "foresight", "innovation", "gadget", "imagination"],
+ "technology-023": ["self-improvement", "habit", "discipline", "screen time", "doomscrolling", "bad habit"],
+ "technology-024": ["priorities", "focus", "notification", "attention", "boundaries", "distraction"],
+ "technology-025": ["nostalgia", "generational gap", "childhood", "dial-up", "old technology", "then and now"],
+ "technology-026": ["habit", "autopilot", "app", "smartphone", "routine", "daily use"],
+ "technology-027": ["change", "automation", "robot", "artificial intelligence", "work", "progress"],
+ "technology-028": ["humor", "curiosity", "search engine", "embarrassment", "internet", "google"],
+ "technology-029": ["organization", "planning", "productivity", "calendar", "digital tool", "routine"],
+ "technology-030": ["gratitude", "surprise", "assistance", "machine", "ai", "helpful gadget"],
+ "technology-031": ["nostalgia", "loss", "obsolescence", "letting go", "outdated gadget", "attachment"],
+ "technology-032": ["routine", "morning", "smartphone", "habit", "notification", "daily ritual"],
+ "technology-033": ["decision-making", "replacement", "upgrade", "frugality", "old device", "letting go"],
+ "technology-034": ["convenience", "commute", "navigation", "transit", "daily life", "podcast"],
+ "technology-035": ["patience", "slow loading", "frustration", "dial-up", "perseverance", "waiting"],
+ "technology-036": ["memory", "preservation", "digital clutter", "old photo", "archive", "keepsake"],
+ "technology-037": ["efficiency", "life hack", "keyboard shortcut", "tip", "productivity", "trick"],
+ "technology-038": ["stress", "annoyance", "notification", "anxiety", "ringtone", "sound"],
+ "technology-039": ["delegation", "chore", "robot", "laziness", "household", "automation"],
+ "technology-040": ["autocomplete", "ai", "writing", "authenticity", "voice", "machine"],
+ "technology-041": ["trust", "automation", "delegation", "self-driving car", "skepticism", "machine"],
+ "technology-042": ["reliability", "loyalty", "old gadget", "daily routine", "vintage", "durable"],
+ "technology-043": ["celebration", "connection", "social media", "good news", "sharing", "messaging"],
+ "technology-044": ["trust", "control", "delegation", "reluctance", "automation", "human touch"],
+ "technology-045": ["nostalgia", "attachment", "sentimental value", "old gadget", "hoarding", "keepsake"],
+ "technology-046": ["change", "update", "software", "small habit", "adaptation", "annoyance"],
+ "technology-047": ["simplicity", "surprise", "design", "innovation", "gadget", "app", "user-friendly"],
+ "technology-048": ["communication", "dependence", "adaptation", "writing", "autocorrect", "texting", "spelling", "artificial intelligence"],
+ "technology-049": ["frustration", "irony", "complexity", "annoyance", "gadget", "everyday task", "appliance", "tech fail"],
+ "technology-050": ["generation gap", "learning curve", "patience", "nostalgia", "adaptation", "parent", "technology", "tech support"],
+ "technology-051": ["education", "learning", "preparation", "future", "school", "digital literacy", "life skill"],
+ "technology-052": ["nostalgia", "communication", "change", "generation gap", "smartphone", "landline", "letter"],
+ "technology-053": ["regret", "spontaneity", "temptation", "gadget", "shopping", "impulse buy", "buyer's remorse", "money"],
+ "technology-054": ["privacy", "trust", "surveillance", "convenience", "smart speaker", "voice assistant", "smart home"],
+ "technology-055": ["curiosity", "distraction", "procrastination", "obsession", "internet", "rabbit hole", "deep dive", "this year"],
+ "technology-056": ["convenience", "simplicity", "surprise", "gadget", "errand", "shopping", "life hack", "game changer"],
+ "technology-057": ["habit", "routine", "change", "nostalgia", "adaptation", "progress", "technology", "obsolete"],
+ "technology-058": ["mindfulness", "boundaries", "attention", "priorities", "screen time", "evening", "digital detox", "discipline"],
+ "technology-059": ["expertise", "confidence", "mastery", "skill", "technology", "gadget", "pride"],
+ "technology-060": ["teaching", "elder", "patience", "phone", "smartphone", "generational gap", "family"],
+ "technology-061": ["clutter", "privacy", "organization", "explanation", "secret", "nostalgia", "technology"],
+ "food-drink-001": ["home", "nostalgia", "comfort food", "family recipe", "mother", "homesickness"],
+ "food-drink-002": ["memory", "nostalgia", "unforgettable meal", "restaurant", "special occasion", "delicious"],
+ "food-drink-003": ["learning", "kitchen", "cooking", "self-reliance", "avoidance", "beginner cook"],
+ "food-drink-004": ["change", "growing up", "childhood", "picky eater", "taste", "evolving"],
+ "food-drink-005": ["admiration", "mentor", "cook", "secret recipe", "kitchen", "role model"],
+ "food-drink-006": ["resourcefulness", "quick meal", "empty fridge", "improvisation", "simple food", "cooking"],
+ "food-drink-007": ["connection", "belonging", "shared meal", "strangers", "hospitality", "friendship"],
+ "food-drink-008": ["ritual", "relaxation", "evening", "tea", "wine", "winding down"],
+ "food-drink-009": ["humor", "failure", "kitchen", "cooking mishap", "burnt food", "resilience"],
+ "food-drink-010": ["independence", "comfort zone", "dining alone", "restaurant", "solitude", "confidence"],
+ "food-drink-011": ["tradition", "legacy", "heritage", "family", "recipe", "generation"],
+ "food-drink-012": ["appetite", "sensory", "kitchen", "aroma", "baking", "memory"],
+ "food-drink-013": ["quirk", "adventurous eating", "food combination", "guilty pleasure", "taste", "weird food"],
+ "food-drink-014": ["love", "gratitude", "being cared for", "home cooking", "restaurant", "kindness"],
+ "food-drink-015": ["admiration", "hospitality", "dinner party", "impress", "menu", "host"],
+ "food-drink-016": ["open-mindedness", "cuisine", "discovery", "changing your mind", "trying new things", "adventure"],
+ "food-drink-017": ["joy", "morning", "breakfast", "simple pleasure", "brunch", "ideal meal"],
+ "food-drink-018": ["habit", "mastery", "signature dish", "recipe", "routine", "kitchen"],
+ "food-drink-019": ["opinion", "frugality", "leftover", "waste", "kitchen", "chore"],
+ "food-drink-020": ["guilty pleasure", "snack", "privacy", "craving", "habit", "comfort"],
+ "food-drink-021": ["etiquette", "manners", "upbringing", "family", "lesson", "dinner table"],
+ "food-drink-022": ["opinion", "ingredient", "flavor", "cooking", "secret weapon", "seasoning"],
+ "food-drink-023": ["compassion", "support", "friendship", "comfort food", "caring", "cooking"],
+ "food-drink-024": ["perseverance", "learning", "cooking technique", "mastery", "kitchen", "patience"],
+ "food-drink-025": ["beginnings", "independence", "first dish", "accomplishment", "cooking", "first time"],
+ "food-drink-026": ["mortality", "favorite food", "last supper", "hypothetical", "priorities", "ultimate meal"],
+ "food-drink-027": ["travel", "memory", "spice", "place", "nostalgia", "sensory"],
+ "food-drink-028": ["decision-making", "overwhelm", "menu", "restaurant", "indecision", "ordering"],
+ "food-drink-029": ["decision-making", "restaurant", "standard", "test", "favorite dish", "first impression"],
+ "food-drink-030": ["temptation", "willpower", "craving", "diet", "guilty pleasure", "resolution"],
+ "food-drink-031": ["hospitality", "crowd", "solo cooking", "host", "entertaining", "cooking"],
+ "food-drink-032": ["nostalgia", "failure", "recipe", "restaurant", "homesickness", "elusive"],
+ "food-drink-033": ["opinion", "taste", "contrast", "flavor", "adventurous eating", "plate"],
+ "food-drink-034": ["tradition", "personalization", "family recipe", "creativity", "heritage", "adaptation"],
+ "food-drink-035": ["celebration", "joy", "festive food", "birthday", "holiday", "gathering"],
+ "food-drink-036": ["courage", "adventure", "flavor", "bold choice", "trying new things", "risk"],
+ "food-drink-037": ["self-care", "solitude", "solo cooking", "decision-making", "routine", "simple food"],
+ "food-drink-038": ["challenge", "humor", "eating challenge", "big portion", "restaurant", "dare"],
+ "food-drink-039": ["chaos", "humor", "kitchen", "noise", "busy kitchen", "cooking"],
+ "food-drink-040": ["opinion", "comfort", "comfort food", "definition", "emotion", "ordinary meal"],
+ "food-drink-041": ["self-care", "solitude", "secret", "private pleasure", "solo meal", "guilty pleasure"],
+ "food-drink-042": ["memory", "sensory", "sound", "sizzling", "kitchen", "nostalgia"],
+ "food-drink-043": ["love", "beginnings", "first taste", "childhood", "flavor", "nostalgia"],
+ "food-drink-044": ["reliability", "comfort", "favorite meal", "dependable", "comfort food", "satisfaction"],
+ "food-drink-045": ["nostalgia", "memory", "flavor", "a particular year", "time travel", "sensory"],
+ "food-drink-046": ["patience", "reward", "waiting", "worth it", "restaurant", "slow food"],
+ "food-drink-047": ["pride", "achievement", "learning", "independence", "cooking", "meal", "signature dish", "first time"],
+ "food-drink-048": ["failure", "persistence", "restaurant", "cooking", "recipe", "kitchen disaster", "home cooking"],
+ "food-drink-049": ["passion", "devotion", "craving", "favorite food", "comfort food", "restaurant", "bad weather"],
+ "food-drink-050": ["tradition", "independence", "creativity", "identity", "family recipe", "cooking", "family", "personal twist"],
+ "food-drink-051": ["connection", "sensory memory", "nostalgia", "conversation", "heart-to-heart", "drink", "coffee"],
+ "food-drink-052": ["curiosity", "observation", "first impression", "judgment", "kitchen", "guest", "nosiness", "quirk"],
+ "food-drink-053": ["embarrassment", "self-consciousness", "humor", "messy food", "table manners", "etiquette", "first date", "dining out"],
+ "food-drink-054": ["self-image", "authenticity", "insecurity", "fitting in", "sophistication", "drink", "cocktail", "wine"],
+ "food-drink-055": ["nostalgia", "comfort", "playfulness", "inner child", "comfort food", "cooking", "childhood favorite"],
+ "food-drink-056": ["creativity", "resourcefulness", "simplicity", "constraint", "ingredient", "cooking", "improvisation", "minimalism"],
+ "food-drink-057": ["guilty pleasure", "secret", "authenticity", "embarrassment", "flavor", "taste", "food", "indulgence"],
+ "food-drink-058": ["judgment", "standards", "first impression", "taste", "flavor", "seasoning", "food critic", "palate"],
+ "food-drink-059": ["cooking", "surprise", "pride", "achievement", "kitchen", "meal", "creativity"],
+ "food-drink-060": ["family", "rules", "tradition", "dinner", "etiquette", "manners", "habit"],
+ "food-drink-061": ["hospitality", "guest", "resourcefulness", "improvisation", "cooking", "last minute", "spontaneity"],
+ "hypotheticals-001": ["nostalgia", "second chance", "ordinary day", "time travel", "savoring", "memory lane"],
+ "hypotheticals-002": ["freedom", "priorities", "financial security", "universal basic income", "sabbatical", "purpose"],
+ "hypotheticals-003": ["learning", "language", "wish", "communication", "fluency", "travel"],
+ "hypotheticals-004": ["time", "freedom", "clock", "schedule", "routine", "deadline"],
+ "hypotheticals-005": ["regret", "advice", "past self", "wisdom", "letter", "hindsight"],
+ "hypotheticals-006": ["community", "creativity", "vision", "empty land", "town", "building"],
+ "hypotheticals-007": ["wonder", "animals", "talking animal", "curiosity", "pet", "communication"],
+ "hypotheticals-008": ["freedom", "invisibility", "privacy", "mischief", "superpower", "anonymity"],
+ "hypotheticals-009": ["teaching", "passion", "expertise", "class", "sharing knowledge", "mentor"],
+ "hypotheticals-010": ["mastery", "skill", "superpower", "ambition", "instant learning", "talent"],
+ "hypotheticals-011": ["wish", "fairness", "birth", "fantasy", "equality", "genie"],
+ "hypotheticals-012": ["society", "sleep", "imagination", "routine", "world", "coordination"],
+ "hypotheticals-013": ["empathy", "perspective", "neighbor", "swap", "curiosity", "learning"],
+ "hypotheticals-014": ["legacy", "time capsule", "future", "history", "memory", "keepsake"],
+ "hypotheticals-015": ["celebration", "invention", "holiday", "values", "creativity", "tradition"],
+ "hypotheticals-016": ["longevity", "time", "priorities", "legacy", "immortality", "long life"],
+ "hypotheticals-017": ["home", "story", "house", "self-reflection", "imagination", "memory"],
+ "hypotheticals-018": ["leadership", "community", "town", "improvement", "mayor", "civic"],
+ "hypotheticals-019": ["history", "curiosity", "time travel", "witness", "wonder", "past"],
+ "hypotheticals-020": ["change", "relocation", "adventure", "uprooting", "moving abroad", "new country"],
+ "hypotheticals-021": ["annoyance", "improvement", "daily life", "pet peeve", "wish", "irritation"],
+ "hypotheticals-022": ["honesty", "friendship", "truth", "lying", "trust", "relationships"],
+ "hypotheticals-023": ["time", "freedom", "pause", "superpower", "priorities", "free hour"],
+ "hypotheticals-024": ["courage", "freedom", "authenticity", "judgment", "self-expression", "confidence"],
+ "hypotheticals-025": ["time capsule", "future", "self-reflection", "keepsake", "memory", "gift to self"],
+ "hypotheticals-026": ["curiosity", "truth", "honesty", "question", "wisdom", "wish"],
+ "hypotheticals-027": ["imagination", "gravity", "daily life", "physics", "absurd", "routine"],
+ "hypotheticals-028": ["priorities", "emergency", "values", "evacuation", "possessions", "sentimental value"],
+ "hypotheticals-029": ["empathy", "work", "job swap", "curiosity", "perspective", "career"],
+ "hypotheticals-030": ["future", "self-reflection", "wisdom", "aging", "advice", "long-term"],
+ "hypotheticals-031": ["adaptation", "resilience", "senses", "hardship", "resourcefulness", "disability"],
+ "hypotheticals-032": ["home", "dream", "creativity", "room", "wish", "hobby"],
+ "hypotheticals-033": ["time", "priorities", "extra day", "work-life balance", "freedom", "weekend"],
+ "hypotheticals-034": ["empathy", "curiosity", "perspective", "swap", "stranger", "walk in their shoes"],
+ "hypotheticals-035": ["freedom", "imagination", "reflection", "mischief", "self", "absurd"],
+ "hypotheticals-036": ["travel", "adventure", "freedom", "teleportation", "destination", "wanderlust"],
+ "hypotheticals-037": ["courage", "regret", "second chance", "conversation", "redo", "hindsight"],
+ "hypotheticals-038": ["humor", "music", "personality", "entrance", "theme song", "self-expression"],
+ "hypotheticals-039": ["survival", "resourcefulness", "island", "building", "creativity", "priorities"],
+ "hypotheticals-040": ["savoring", "memory", "gratitude", "ordinary moment", "time", "happiness"],
+ "hypotheticals-041": ["creativity", "design", "everyday object", "innovation", "improvement", "problem solving"],
+ "hypotheticals-042": ["wonder", "nature", "plant", "curiosity", "garden", "communication"],
+ "hypotheticals-043": ["community", "town", "public space", "park", "improvement", "civic"],
+ "hypotheticals-044": ["memory", "gratitude", "nostalgia", "treasure", "cherished moment", "remembrance"],
+ "hypotheticals-045": ["freedom", "rest", "leisure", "secret", "free time", "simple pleasure"],
+ "hypotheticals-046": ["tradition", "community", "hometown", "celebration", "new custom", "belonging"],
+ "hypotheticals-047": ["imagination", "creativity", "invention", "physics", "science", "home", "house rules", "magic"],
+ "hypotheticals-048": ["routine", "adaptation", "rest", "morning", "sunrise", "sleep", "daylight saving", "early bird"],
+ "hypotheticals-049": ["curiosity", "understanding", "connection", "language", "foreign language", "translation", "superpower", "listening"],
+ "hypotheticals-050": ["imagination", "delegation", "productivity", "humor", "errand", "chore", "shadow", "to-do list"],
+ "hypotheticals-051": ["perception", "curiosity", "imagination", "awareness", "senses", "sixth sense", "superpower", "intuition"],
+ "hypotheticals-052": ["empathy", "perspective", "curiosity", "learning", "open-mindedness", "home", "house swap", "lifestyle"],
+ "hypotheticals-053": ["adventure", "curiosity", "exploration", "culture", "commute", "travel", "journey", "foreign country"],
+ "hypotheticals-054": ["resourcefulness", "improvisation", "hospitality", "pressure", "dinner party", "cooking", "guest", "last minute"],
+ "hypotheticals-055": ["sacrifice", "priorities", "simplicity", "dependence", "minimalism", "modern convenience", "technology", "giving up"],
+ "hypotheticals-056": ["self-improvement", "self-awareness", "discipline", "change", "growth", "habit", "bad habit", "resolution"],
+ "hypotheticals-057": ["community", "belonging", "imagination", "design", "neighborhood", "neighbor", "urban planning", "utopia"],
+ "hypotheticals-058": ["peace", "annoyance", "silence", "calm", "sound", "noise", "pet peeve"],
+ "hypotheticals-059": ["digital detox", "simplicity", "phone", "writing", "habit", "change", "unplugging"],
+ "hypotheticals-060": ["empathy", "emotion", "mood", "understanding", "superpower", "communication", "kindness"],
+ "hypotheticals-061": ["delegation", "time management", "priorities", "fantasy", "sibling", "chore", "productivity"],
+ "would-you-rather-001": ["home", "nature", "sea", "mountain", "lifestyle", "where to live"],
+ "would-you-rather-002": ["priorities", "time", "money", "balance", "work-life balance", "wealth"],
+ "would-you-rather-003": ["superpower", "flight", "invisibility", "freedom", "power", "fantasy"],
+ "would-you-rather-004": ["punctuality", "time", "early", "lateness", "habit", "discipline"],
+ "would-you-rather-005": ["exploration", "adventure", "ocean", "outer space", "curiosity", "discovery"],
+ "would-you-rather-006": ["loss", "music", "books", "art", "coping", "culture"],
+ "would-you-rather-007": ["regret", "memory", "best day", "worst day", "second chance", "erasing the past"],
+ "would-you-rather-008": ["humor", "wisdom", "personality", "social", "funny", "wise"],
+ "would-you-rather-009": ["family", "solitude", "dinner", "introvert", "extrovert", "gathering"],
+ "would-you-rather-010": ["surprise", "story", "ending", "spoiler", "curiosity", "suspense"],
+ "would-you-rather-011": ["talent", "language", "music", "instrument", "skill", "polyglot"],
+ "would-you-rather-012": ["work-life balance", "workweek", "schedule", "productivity", "job", "time"],
+ "would-you-rather-013": ["time travel", "past", "future", "curiosity", "history", "imagination"],
+ "would-you-rather-014": ["dependence", "sacrifice", "phone", "car", "technology", "transportation"],
+ "would-you-rather-015": ["comfort", "weather", "heat", "cold", "climate", "preference"],
+ "would-you-rather-016": ["time", "regret", "rewind", "pause", "control", "life"],
+ "would-you-rather-017": ["home", "city", "village", "lifestyle", "community", "where to live"],
+ "would-you-rather-018": ["food", "dessert", "breakfast", "sacrifice", "sweet tooth", "meal"],
+ "would-you-rather-019": ["fame", "respect", "recognition", "relationships", "legacy", "reputation"],
+ "would-you-rather-020": ["time", "weather", "curiosity", "planning", "knowledge", "forecast"],
+ "would-you-rather-021": ["learning", "teacher", "independence", "discipline", "self-teaching", "mentor"],
+ "would-you-rather-022": ["home", "garden", "library", "nature", "books", "dream house"],
+ "would-you-rather-023": ["memory", "imagination", "creativity", "mind", "gift", "superpower"],
+ "would-you-rather-024": ["belonging", "social", "party", "inclusion", "invitation", "loneliness"],
+ "would-you-rather-025": ["mastery", "expertise", "specialist", "generalist", "skill", "curiosity"],
+ "would-you-rather-026": ["honesty", "truth", "peace", "harmony", "conflict", "integrity"],
+ "would-you-rather-027": ["hardship", "comfort", "hot water", "electricity", "resourcefulness", "modern life"],
+ "would-you-rather-028": ["time", "energy", "productivity", "priorities", "balance", "vitality"],
+ "would-you-rather-029": ["cooking", "food", "kitchen", "convenience", "meal", "restaurant"],
+ "would-you-rather-030": ["rest", "weekend", "vacation", "work-life balance", "burnout", "break"],
+ "would-you-rather-031": ["patience", "confidence", "character", "virtue", "self-improvement", "personality"],
+ "would-you-rather-032": ["memory", "navigation", "ability", "superpower", "photographic memory", "direction"],
+ "would-you-rather-033": ["food", "routine", "variety", "breakfast", "habit", "meal"],
+ "would-you-rather-034": ["season", "weather", "climate", "change", "monotony", "nature"],
+ "would-you-rather-035": ["solitude", "company", "privacy", "social", "introvert", "alone time"],
+ "would-you-rather-036": ["party", "social", "timing", "arrival", "extrovert", "gathering"],
+ "would-you-rather-037": ["loss", "food", "music", "favorite", "sacrifice", "joy"],
+ "would-you-rather-038": ["sleep", "food", "sacrifice", "hunger", "superpower", "time"],
+ "would-you-rather-039": ["senses", "smell", "taste", "food", "loss", "sacrifice"],
+ "would-you-rather-040": ["travel", "planning", "spontaneity", "adventure", "vacation", "itinerary"],
+ "would-you-rather-041": ["giving", "receiving", "cooking", "generosity", "hospitality", "service"],
+ "would-you-rather-042": ["navigation", "time", "map", "clock", "coping", "modern life"],
+ "would-you-rather-043": ["noise", "silence", "environment", "peace", "adaptation", "year abroad"],
+ "would-you-rather-044": ["sleep", "morning", "routine", "habit", "energy", "early bird"],
+ "would-you-rather-045": ["decision-making", "advice", "independence", "trust", "guidance", "mentor"],
+ "would-you-rather-046": ["memory", "photo", "letter", "sentimental", "keepsake", "nostalgia"],
+ "would-you-rather-047": ["superpower", "hero", "personality", "introvert", "extrovert", "humility", "spotlight", "subtlety"],
+ "would-you-rather-048": ["sacrifice", "priorities", "digital detox", "social media", "television", "screen time", "entertainment", "giving up"],
+ "would-you-rather-049": ["preference", "personality", "comfort", "window seat", "aisle seat", "flying", "air travel"],
+ "would-you-rather-050": ["talent", "self-expression", "confidence", "performance", "singing", "dancing", "music", "karaoke"],
+ "would-you-rather-051": ["control", "power", "ego", "authority", "argument", "debate", "being right", "last word"],
+ "would-you-rather-052": ["sacrifice", "discipline", "health", "coping", "salt", "sugar", "diet", "sweet tooth"],
+ "would-you-rather-053": ["beauty", "wonder", "sacrifice", "sunset", "live music", "concert", "nature", "music"],
+ "would-you-rather-054": ["hospitality", "generosity", "tradition", "holiday", "family gathering", "host", "guest", "entertaining"],
+ "would-you-rather-055": ["superpower", "power", "control", "empathy", "privacy", "mind reading", "weather", "telepathy"],
+ "would-you-rather-056": ["planning", "preparation", "spontaneity", "flexibility", "control", "winging it", "improvisation"],
+ "would-you-rather-057": ["humor", "identity", "personality", "direction", "navigation", "getting lost", "laughter", "wit"],
+ "would-you-rather-058": ["sacrifice", "discipline", "willpower", "habit", "health", "sweets", "caffeine", "coffee"],
+ "would-you-rather-059": ["sound", "voice", "communication", "quiet", "noise", "annoyance", "humor"],
+ "would-you-rather-060": ["convenience", "exercise", "building", "habit", "transportation", "trade-off", "limits"],
+ "would-you-rather-061": ["home", "house", "window", "doorway", "openness", "design", "preference"],
+ "quotes-proverbs-001": ["perseverance", "patience", "consistency", "race", "determination", "tortoise and hare"],
+ "quotes-proverbs-002": ["integrity", "trust", "action", "character", "promise", "role model"],
+ "quotes-proverbs-003": ["routine", "morning", "productivity", "early bird", "discipline", "night owl"],
+ "quotes-proverbs-004": ["teamwork", "collaboration", "too many cooks", "kitchen", "group", "conflict"],
+ "quotes-proverbs-005": ["optimism", "resilience", "hardship", "silver lining", "hope", "bad news"],
+ "quotes-proverbs-006": ["practice", "mastery", "perseverance", "skill", "discipline", "improvement"],
+ "quotes-proverbs-007": ["first impression", "prejudice", "surprise", "appearance", "judgment", "assumption"],
+ "quotes-proverbs-008": ["beginnings", "courage", "journey", "first step", "progress", "motivation"],
+ "quotes-proverbs-009": ["honesty", "integrity", "consequence", "truth", "courage", "sacrifice"],
+ "quotes-proverbs-010": ["envy", "contentment", "gratitude", "comparison", "grass", "ambition"],
+ "quotes-proverbs-011": ["second chance", "procrastination", "delay", "accomplishment", "belated", "persistence"],
+ "quotes-proverbs-012": ["trade-off", "compromise", "choice", "sacrifice", "priorities", "acceptance"],
+ "quotes-proverbs-013": ["teamwork", "community", "cooperation", "help", "volunteering", "gratitude"],
+ "quotes-proverbs-014": ["determination", "perseverance", "stubbornness", "willpower", "resilience", "resolve"],
+ "quotes-proverbs-015": ["caution", "risk", "hesitation", "prudence", "planning", "fear"],
+ "quotes-proverbs-016": ["humor", "healing", "laughter", "wellbeing", "joy", "comfort"],
+ "quotes-proverbs-017": ["belonging", "home", "love", "roots", "heart", "family"],
+ "quotes-proverbs-018": ["courage", "risk", "boldness", "reward", "bravery", "leap of faith"],
+ "quotes-proverbs-019": ["teamwork", "collaboration", "partnership", "cooperation", "brainstorm", "mentor"],
+ "quotes-proverbs-020": ["quiet people", "depth", "introvert", "hidden talent", "wisdom", "character"],
+ "quotes-proverbs-021": ["storytelling", "photography", "memory", "image", "nostalgia", "visual"],
+ "quotes-proverbs-022": ["patience", "waiting", "reward", "hope", "anticipation", "persistence"],
+ "quotes-proverbs-023": ["karma", "consequence", "kindness", "fairness", "justice", "reciprocity"],
+ "quotes-proverbs-024": ["health", "habit", "routine", "wellness", "diet", "discipline"],
+ "quotes-proverbs-025": ["patience", "building", "perseverance", "long-term goal", "progress", "project"],
+ "quotes-proverbs-026": ["communication", "writing", "words", "persuasion", "peace", "speech"],
+ "quotes-proverbs-027": ["adaptation", "culture", "belonging", "travel", "newcomer", "fitting in"],
+ "quotes-proverbs-028": ["prevention", "planning", "procrastination", "maintenance", "foresight", "small problem"],
+ "quotes-proverbs-029": ["distance", "longing", "love", "absence", "relationship", "missing someone"],
+ "quotes-proverbs-030": ["speaking up", "assertiveness", "advocacy", "courage", "complaint", "self-advocacy"],
+ "quotes-proverbs-031": ["curiosity", "risk", "trouble", "adventure", "exploration", "mischief"],
+ "quotes-proverbs-032": ["creativity", "invention", "resourcefulness", "necessity", "problem solving", "improvisation"],
+ "quotes-proverbs-033": ["patience", "waiting", "anticipation", "time", "frustration", "impatience"],
+ "quotes-proverbs-034": ["friendship", "belonging", "similarity", "community", "social circle", "peer"],
+ "quotes-proverbs-035": ["tradition", "contentment", "change", "maintenance", "leave well alone", "simplicity"],
+ "quotes-proverbs-036": ["generosity", "charity", "family", "priorities", "compassion", "giving"],
+ "quotes-proverbs-037": ["acceptance", "compromise", "humility", "necessity", "settling", "hardship"],
+ "quotes-proverbs-038": ["planning", "preparation", "carefulness", "mistake", "measuring", "craftsmanship"],
+ "quotes-proverbs-039": ["frugality", "saving", "money", "thrift", "discipline", "budget"],
+ "quotes-proverbs-040": ["memory", "distance", "absence", "forgetting", "relationship", "attention"],
+ "quotes-proverbs-041": ["gratitude", "simple pleasure", "happiness", "contentment", "free things", "nature"],
+ "quotes-proverbs-042": ["consequence", "karma", "effort", "harvest", "patience", "responsibility"],
+ "quotes-proverbs-043": ["patience", "virtue", "waiting", "reward", "self-control", "persistence"],
+ "quotes-proverbs-044": ["risk", "security", "decision-making", "certainty", "caution", "gamble"],
+ "quotes-proverbs-045": ["risk", "diversification", "planning", "investing", "prudence", "backup plan"],
+ "quotes-proverbs-046": ["acceptance", "persuasion", "stubbornness", "influence", "letting go", "limits"],
+ "quotes-proverbs-047": ["knowledge", "learning", "empowerment", "growth", "education", "skill", "lifelong learning", "power"],
+ "quotes-proverbs-048": ["healing", "grief", "loss", "recovery", "resilience", "moving on", "heartbreak", "time"],
+ "quotes-proverbs-049": ["customer service", "customer", "respect", "fairness", "boundaries", "business", "retail", "conflict"],
+ "quotes-proverbs-050": ["procrastination", "regret", "beginnings", "fresh start", "long-term thinking", "getting started", "tree", "goal"],
+ "quotes-proverbs-051": ["overconfidence", "patience", "expectation", "disappointment", "humility", "assumption", "premature celebration"],
+ "quotes-proverbs-052": ["teamwork", "strength", "weakness", "reliability", "weakest link", "weak point", "collaboration"],
+ "quotes-proverbs-053": ["letting go", "acceptance", "regret", "resilience", "peace", "moving on", "mistake", "forgiveness"],
+ "quotes-proverbs-054": ["resilience", "optimism", "adversity", "silver lining", "setback", "resourcefulness", "comeback", "turning point"],
+ "quotes-proverbs-055": ["disappointment", "appearances", "deception", "judgment", "expectation", "hype", "first impression"],
+ "quotes-proverbs-056": ["opportunity", "timing", "decisiveness", "initiative", "risk", "carpe diem", "quick decision", "momentum"],
+ "quotes-proverbs-057": ["preparation", "prevention", "foresight", "caution", "planning", "worry", "backup plan", "emergency"],
+ "quotes-proverbs-058": ["momentum", "change", "freedom", "restlessness", "stagnation", "staying active", "keep moving", "wanderlust"],
+ "quotes-proverbs-059": ["productivity", "boredom", "temptation", "trouble", "discipline", "self-control", "work ethic"],
+ "quotes-proverbs-060": ["home", "comfort", "belonging", "happy place", "sanctuary", "security", "familiarity"],
+ "quotes-proverbs-061": ["family", "parent", "personality", "heritage", "identity", "inheritance", "upbringing"],
+ "storytelling-001": ["kindness", "gratitude", "generosity", "stranger", "good deed", "pay it forward"],
+ "storytelling-002": ["generosity", "gift", "thoughtfulness", "surprise", "giving", "present"],
+ "storytelling-003": ["getting lost", "adventure", "travel", "navigation", "detour", "trip gone wrong"],
+ "storytelling-004": ["resilience", "silver lining", "luck", "bad day", "disaster", "things working out"],
+ "storytelling-005": ["integrity", "promise", "commitment", "loyalty", "keeping your word", "trust"],
+ "storytelling-006": ["friendship", "belonging", "first meeting", "best friend", "connection"],
+ "storytelling-007": ["weather", "rain", "storm", "resourcefulness", "shelter", "getting caught out"],
+ "storytelling-008": ["cooking", "nervousness", "romance", "dinner", "kitchen", "first impression"],
+ "storytelling-009": ["misunderstanding", "communication", "conflict", "resolution", "mix-up", "miscommunication"],
+ "storytelling-010": ["loss", "persistence", "lost and found", "relief", "keepsake", "object"],
+ "storytelling-011": ["deadline", "pressure", "urgency", "racing", "time crunch", "last minute"],
+ "storytelling-012": ["adventure", "spontaneity", "surprise", "evening", "unexpected", "plans changing"],
+ "storytelling-013": ["courage", "bravery", "hero", "admiration", "role model", "inspiration"],
+ "storytelling-014": ["quick thinking", "resourcefulness", "trouble", "wit", "tight spot", "getting out of trouble"],
+ "storytelling-015": ["mistake", "repair", "home fix", "humility", "diy", "things going wrong"],
+ "storytelling-016": ["chance", "serendipity", "encounter", "fate", "meeting someone", "coincidence"],
+ "storytelling-017": ["opportunity", "risk", "hesitation", "doorway", "decision", "new beginning"],
+ "storytelling-018": ["haircut", "appearance", "embarrassment", "recovery", "humor", "hair"],
+ "storytelling-019": ["self-discovery", "confidence", "achievement", "surprise", "growth", "hidden strength"],
+ "storytelling-020": ["animal", "pet", "chaos", "humor", "dog", "mischief"],
+ "storytelling-021": ["communication", "regret", "courage", "letter", "hesitation", "writing"],
+ "storytelling-022": ["patience", "waiting", "delay", "airport", "memorable moment", "queue"],
+ "storytelling-023": ["secret", "temptation", "discretion", "trust", "surprise", "keeping quiet"],
+ "storytelling-024": ["patience", "waiting", "anticipation", "delay", "hospital", "long wait"],
+ "storytelling-025": ["surprise", "love", "family", "thoughtfulness", "gift", "delight"],
+ "storytelling-026": ["courage", "self-respect", "assertiveness", "boundaries", "confidence", "speaking up"],
+ "storytelling-027": ["surprise party", "celebration", "friendship", "teamwork", "planning", "birthday"],
+ "storytelling-028": ["gift", "oddity", "humor", "surprise", "present", "gratitude"],
+ "storytelling-029": ["favor", "adventure", "helping", "unexpected", "kindness", "snowball effect"],
+ "storytelling-030": ["fear", "courage", "self-talk", "challenge", "growth", "comfort zone"],
+ "storytelling-031": ["decision", "spontaneity", "fatigue", "sleep", "impulse", "bold choice"],
+ "storytelling-032": ["surprise", "irony", "humor", "friendship", "prank", "tables turned"],
+ "storytelling-033": ["road trip", "travel", "adventure", "spontaneity", "car", "journey"],
+ "storytelling-034": ["risk", "courage", "bold choice", "uncertainty", "gamble", "leap of faith"],
+ "storytelling-035": ["forgiveness", "healing", "letting go", "hurt", "reconciliation", "peace"],
+ "storytelling-036": ["neighbor", "favor", "community", "unexpected", "helping", "neighborhood"],
+ "storytelling-037": ["performance", "stage fright", "nervousness", "audience", "first time", "courage"],
+ "storytelling-038": ["borrowing", "trust", "broken", "friendship", "accident", "apology"],
+ "storytelling-039": ["coincidence", "fate", "serendipity", "small world", "strange", "chance"],
+ "storytelling-040": ["apology", "forgiveness", "humility", "reconciliation", "sorry", "relationship"],
+ "storytelling-041": ["avoidance", "courage", "procrastination", "growth", "trying something new", "fear"],
+ "storytelling-042": ["gift", "oddity", "humor", "giving", "creativity", "present"],
+ "storytelling-043": ["risk", "luck", "reward", "courage", "payoff", "gamble"],
+ "storytelling-044": ["self-discipline", "promise", "commitment", "personal goal", "integrity", "follow-through"],
+ "storytelling-045": ["kindness", "gratitude", "small gesture", "generosity", "stranger", "thoughtfulness"],
+ "storytelling-046": ["mistake", "getting lost", "navigation", "travel", "misdirection", "wrong turn"],
+ "storytelling-047": ["advice", "regret", "hindsight", "stubbornness", "life lesson", "listening", "wisdom"],
+ "storytelling-048": ["errand", "serendipity", "surprise", "ordinary day", "adventure", "chore", "shopping"],
+ "storytelling-049": ["phone call", "phone", "wrong number", "stranger", "surprise", "mystery", "strange encounter"],
+ "storytelling-050": ["improvisation", "public speaking", "speech", "quick thinking", "nerves", "spontaneity", "confidence"],
+ "storytelling-051": ["night shift", "late night", "night owl", "all-nighter", "midnight", "adventure", "exhaustion"],
+ "storytelling-052": ["waiting", "news", "patience", "uncertainty", "anxiety", "suspense", "hope"],
+ "storytelling-053": ["hobby", "hidden talent", "beginner's luck", "surprise", "discovery", "new experience", "confidence"],
+ "storytelling-054": ["pet", "animal", "stray", "adoption", "responsibility", "attachment", "commitment"],
+ "storytelling-055": ["party", "gathering", "late night", "night owl", "solitude", "quiet"],
+ "storytelling-056": ["white lie", "honesty", "embarrassment", "close call", "deception", "fib", "truth"],
+ "storytelling-057": ["favor", "odd request", "helping", "saying yes", "generosity", "kindness"],
+ "storytelling-058": ["risk", "courage", "hesitation", "cold feet", "leap", "fear", "opportunity"],
+ "storytelling-059": ["teaching", "hobby", "patience", "funny story", "sharing", "passion", "mishap"],
+ "storytelling-060": ["decision", "serendipity", "small gesture", "unexpected", "consequence", "story", "turning point"],
+ "storytelling-061": ["gift", "mistake", "mix-up", "sentimental", "generosity", "funny story", "keepsake"],
+ "persuasion-001": ["cooking", "life skill", "self-reliance", "kitchen", "food", "meal"],
+ "persuasion-002": ["morning", "routine", "productivity", "sunrise", "early bird", "day start"],
+ "persuasion-003": ["handwritten note", "communication", "thoughtfulness", "writing", "letter", "gratitude"],
+ "persuasion-004": ["city", "parks", "urban planning", "community", "green space", "parking"],
+ "persuasion-005": ["nap", "rest", "sleep", "health", "productivity", "self-care"],
+ "persuasion-006": ["hobby", "balance", "creativity", "passion", "leisure", "joy"],
+ "persuasion-007": ["food", "trying new things", "open-mindedness", "friendship", "picky eater", "persuasion"],
+ "persuasion-008": ["walking", "health", "commuting", "transport", "exercise", "outdoors"],
+ "persuasion-009": ["rules", "change", "reform", "common sense", "everyday life", "convention"],
+ "persuasion-010": ["boredom", "creativity", "rest", "mindfulness", "downtime", "imagination"],
+ "persuasion-011": ["phone", "digital detox", "technology", "unplugging", "balance", "screen time"],
+ "persuasion-012": ["board game", "video game", "fun", "games", "friendship", "leisure"],
+ "persuasion-013": ["window seat", "travel", "airplane", "flying", "view", "comfort"],
+ "persuasion-014": ["education", "school", "life skill", "cooking", "budgeting", "public speaking"],
+ "persuasion-015": ["calendar", "organization", "planning", "paper", "technology", "tradition"],
+ "persuasion-016": ["breakfast", "health", "food", "morning", "routine", "nutrition"],
+ "persuasion-017": ["boundaries", "saying no", "priorities", "self-care", "assertiveness", "time management"],
+ "persuasion-018": ["solo travel", "independence", "adventure", "self-discovery", "trip", "courage"],
+ "persuasion-019": ["plant", "nature", "home", "wellbeing", "gardening", "greenery"],
+ "persuasion-020": ["school", "education", "work-life balance", "family", "schedule", "parent"],
+ "persuasion-021": ["rest", "productivity", "stillness", "doing nothing", "balance", "relaxation"],
+ "persuasion-022": ["bed", "morning routine", "habit", "discipline", "tidiness", "small habit"],
+ "persuasion-023": ["public speaking", "courage", "communication", "growth", "confidence", "fear"],
+ "persuasion-024": ["quality", "quantity", "priorities", "minimalism", "craftsmanship", "simplicity"],
+ "persuasion-025": ["silence", "communication", "listening", "power", "pause", "stillness"],
+ "persuasion-026": ["journal", "reflection", "writing", "habit", "mindfulness", "self-awareness"],
+ "persuasion-027": ["solo travel", "independence", "adventure", "self-discovery", "trip", "courage"],
+ "persuasion-028": ["reading", "fiction", "empathy", "imagination", "books", "literature"],
+ "persuasion-029": ["hobby", "beginner", "humility", "growth", "trying something new", "failure"],
+ "persuasion-030": ["dinner", "family meal", "screen time", "connection", "table", "togetherness"],
+ "persuasion-031": ["experiences", "possessions", "materialism", "memories", "travel", "happiness"],
+ "persuasion-032": ["first aid", "safety", "preparedness", "life skill", "emergency", "responsibility"],
+ "persuasion-033": ["punctuality", "early", "respect", "preparation", "time management", "arriving"],
+ "persuasion-034": ["unplugging", "digital detox", "weekend", "phone", "rest", "technology"],
+ "persuasion-035": ["home repair", "diy", "self-reliance", "life skill", "tools", "handy"],
+ "persuasion-036": ["stairs", "exercise", "health", "small habit", "elevator", "fitness"],
+ "persuasion-037": ["gratitude", "journal", "habit", "positivity", "mindset", "daily practice"],
+ "persuasion-038": ["savings", "emergency fund", "finance", "security", "preparedness", "household budget"],
+ "persuasion-039": ["phone", "dinner", "presence", "manners", "connection", "technology"],
+ "persuasion-040": ["declutter", "closet", "tidiness", "minimalism", "organization", "letting go"],
+ "persuasion-041": ["listening", "debate", "empathy", "communication", "understanding", "argument"],
+ "persuasion-042": ["breakfast", "routine", "habit", "simplicity", "food", "consistency"],
+ "persuasion-043": ["slow mornings", "mindfulness", "routine", "calm", "morning", "stress"],
+ "persuasion-044": ["tools", "quality", "frugality", "home", "craftsmanship", "buying less"],
+ "persuasion-045": ["lunch", "routine", "habit", "simplicity", "food", "consistency"],
+ "persuasion-046": ["slow mornings", "morning", "calm", "routine", "stress", "mindfulness"],
+ "persuasion-047": ["board game", "card game", "game night", "chess", "mastery", "strategy", "play"],
+ "persuasion-048": ["poem", "poetry", "memorization", "recitation", "memory", "literature", "beauty"],
+ "persuasion-049": ["silence", "meditation", "mindfulness", "stillness", "calm", "self-care", "habit"],
+ "persuasion-050": ["public space", "silence", "peace", "noise", "park", "library", "sanctuary"],
+ "persuasion-051": ["repair", "diy", "life skill", "self-reliance", "sustainability", "waste", "thrift"],
+ "persuasion-052": ["recipe", "cooking", "signature dish", "kitchen", "mastery", "hospitality", "life skill"],
+ "persuasion-053": ["book", "bookshelf", "reading", "library", "curiosity", "possibility", "lifelong learning"],
+ "persuasion-054": ["stranger", "public transit", "commute", "small talk", "connection", "serendipity", "openness"],
+ "persuasion-055": ["slow travel", "travel", "journey", "vacation", "savoring", "slow down", "patience"],
+ "persuasion-056": ["small talk", "conversation", "conversation starter", "asking questions", "networking", "preparation", "awkward silence"],
+ "persuasion-057": ["scenic route", "detour", "commute", "journey", "slow down", "savoring", "beauty"],
+ "persuasion-058": ["letter", "handwriting", "snail mail", "thank-you note", "thoughtfulness", "keepsake", "connection"],
+ "persuasion-059": ["community", "neighborhood", "public space", "conversation", "connection", "loneliness", "togetherness"],
+ "persuasion-060": ["magic", "practice", "skill", "friendship", "encouragement", "hobby", "mastery"],
+ "persuasion-061": ["minimalism", "simplicity", "clutter", "home", "freedom", "household", "mindset"],
+ "seasons-celebrations-001": ["season", "nature", "energy", "outdoors", "vitality", "favorite time of year"],
+ "seasons-celebrations-002": ["spring", "warm weather", "celebration", "outdoors", "ritual", "sunshine"],
+ "seasons-celebrations-003": ["new year", "family", "tradition", "celebration", "resolution", "fresh start"],
+ "seasons-celebrations-004": ["childhood", "tradition", "celebration", "family", "nostalgia", "holiday"],
+ "seasons-celebrations-005": ["snow", "rain", "weather", "winter", "wonder", "nostalgia"],
+ "seasons-celebrations-006": ["autumn", "winter", "change", "daylight", "mood", "darkness"],
+ "seasons-celebrations-007": ["tradition", "creativity", "family", "legacy", "ritual", "influence"],
+ "seasons-celebrations-008": ["holiday food", "tradition", "family", "anticipation", "feast", "comfort food"],
+ "seasons-celebrations-009": ["festival", "community", "creativity", "celebration", "design", "event planning"],
+ "seasons-celebrations-010": ["birthday", "celebration", "joy", "friends", "memory", "special occasion"],
+ "seasons-celebrations-011": ["difficulty", "coping", "resilience", "winter", "calendar", "hard season"],
+ "seasons-celebrations-012": ["sound", "smell", "nostalgia", "season", "senses", "memory"],
+ "seasons-celebrations-013": ["summer", "solstice", "daylight", "celebration", "outdoors", "summer solstice"],
+ "seasons-celebrations-014": ["overrated", "celebration", "opinion", "holiday", "alternative", "commercialism"],
+ "seasons-celebrations-015": ["weather", "contrarian", "rain", "cold", "appreciation", "unpopular opinion"],
+ "seasons-celebrations-016": ["change", "aging", "celebration", "tradition", "growing up", "evolution"],
+ "seasons-celebrations-017": ["new year's eve", "reflection", "tradition", "ritual", "celebration", "year-end"],
+ "seasons-celebrations-018": ["anniversary", "remembering", "relationship", "milestone", "celebration", "commemoration"],
+ "seasons-celebrations-019": ["summer", "heat", "coping", "cooling off", "weather", "hot day"],
+ "seasons-celebrations-020": ["gift", "giving", "generosity", "tradition", "holiday", "values"],
+ "seasons-celebrations-021": ["chore", "season", "home", "satisfaction", "yard work", "routine"],
+ "seasons-celebrations-022": ["homesickness", "distance", "tradition", "celebration", "expat", "connection"],
+ "seasons-celebrations-023": ["goodbye", "ritual", "season", "closure", "nostalgia", "transition"],
+ "seasons-celebrations-024": ["planning", "priorities", "celebration", "anticipation", "organization", "event"],
+ "seasons-celebrations-025": ["achievement", "friendship", "celebration", "support", "recognition", "congratulations"],
+ "seasons-celebrations-026": ["new season", "welcome", "ritual", "fresh start", "change", "renewal"],
+ "seasons-celebrations-027": ["plans going wrong", "adaptability", "celebration", "resilience", "disappointment", "party"],
+ "seasons-celebrations-028": ["tradition", "family", "holiday", "new tradition", "creativity", "togetherness"],
+ "seasons-celebrations-029": ["decoration", "holiday", "anticipation", "tradition", "home", "christmas"],
+ "seasons-celebrations-030": ["celebration", "holiday", "anticipation", "savoring", "joy", "festivity"],
+ "seasons-celebrations-031": ["milestone", "celebration", "personal achievement", "ritual", "recognition", "life event"],
+ "seasons-celebrations-032": ["preparation", "celebration", "home", "hosting", "party", "anticipation"],
+ "seasons-celebrations-033": ["clothing", "season", "fashion", "anticipation", "autumn", "winter"],
+ "seasons-celebrations-034": ["everyday joy", "gratitude", "ordinary day", "celebration", "mindfulness", "small pleasure"],
+ "seasons-celebrations-035": ["holiday meal", "family", "cooking", "tradition", "effort", "feast"],
+ "seasons-celebrations-036": ["celebration", "party", "knowing when to stop", "energy", "hosting", "limits"],
+ "seasons-celebrations-037": ["gift", "holiday", "giving", "generosity", "thoughtfulness", "present"],
+ "seasons-celebrations-038": ["tradition", "quiet", "family", "holiday", "simplicity", "ritual"],
+ "seasons-celebrations-039": ["light", "season", "nostalgia", "longing", "sunlight", "daylight"],
+ "seasons-celebrations-040": ["milestone", "loneliness", "self-recognition", "celebration", "solitude", "unnoticed achievement"],
+ "seasons-celebrations-041": ["weekend", "relaxation", "reward", "ritual", "celebration", "end of week"],
+ "seasons-celebrations-042": ["smell", "season", "celebration", "nostalgia", "senses", "holiday"],
+ "seasons-celebrations-043": ["tradition", "change", "family", "values", "letting go", "evolution"],
+ "seasons-celebrations-044": ["decoration", "favorite season", "anticipation", "tradition", "home", "ritual"],
+ "seasons-celebrations-045": ["celebration", "savoring", "afterglow", "joy", "tradition", "extending"],
+ "seasons-celebrations-046": ["smell", "new chapter", "season", "nostalgia", "change", "fresh start"],
+ "seasons-celebrations-047": ["spring", "winter", "smell", "renewal", "hope", "season change", "sensory memory"],
+ "seasons-celebrations-048": ["celebration", "holiday", "anticipation", "preparation", "planning", "countdown", "excitement"],
+ "seasons-celebrations-049": ["decoration", "holiday", "christmas tree", "letting go", "ending", "procrastination", "january"],
+ "seasons-celebrations-050": ["last minute", "party", "celebration", "improvisation", "resourcefulness", "spontaneity", "winging it"],
+ "seasons-celebrations-051": ["song", "music", "playlist", "holiday music", "season", "nostalgia", "ritual"],
+ "seasons-celebrations-052": ["small win", "achievement", "celebration", "pride", "reward", "recognition", "self-worth"],
+ "seasons-celebrations-053": ["autumn", "fall", "craving", "comfort food", "pumpkin spice", "comfort", "season change"],
+ "seasons-celebrations-054": ["forecast", "weather", "outdoor party", "barbecue", "picnic", "planning", "flexibility"],
+ "seasons-celebrations-055": ["holiday", "holiday blues", "hardship", "grief", "coping", "resilience", "acceptance"],
+ "seasons-celebrations-056": ["to-do list", "preparation", "planning", "priorities", "hosting", "party", "celebration"],
+ "seasons-celebrations-057": ["favorite season", "season", "season change", "arrival", "enthusiasm", "excitement", "joy"],
+ "seasons-celebrations-058": ["long distance", "tradition", "connection", "family", "friendship", "video call"],
+ "seasons-celebrations-059": ["holiday", "leftovers", "food", "anticipation", "comfort food", "tradition", "guilty pleasure"],
+ "seasons-celebrations-060": ["season change", "season", "autumn", "perception", "transition", "spring", "weather"],
+ "seasons-celebrations-061": ["new year", "planning", "resolution", "fresh start", "beginnings", "goal", "anticipation"],
+ "humor-001": ["embarrassment", "public", "funny story", "laughter", "awkward moment", "humor"],
+ "humor-002": ["habit", "quirk", "self-awareness", "strange", "funny", "alien"],
+ "humor-003": ["excuse", "honesty", "embarrassment", "regret", "humor", "white lie"],
+ "humor-004": ["pet", "review", "self-awareness", "animal", "funny", "perspective"],
+ "humor-005": ["argument", "silly", "debate", "competition", "pettiness", "humor"],
+ "humor-006": ["superhero", "object", "imagination", "silly", "sidekick", "creativity"],
+ "humor-007": ["joke", "laughter", "story", "humor", "favorite", "comedy"],
+ "humor-008": ["singing", "music", "hypothetical", "silly", "communication", "musical"],
+ "humor-009": ["chore", "avoidance", "procrastination", "laziness", "funny", "home"],
+ "humor-010": ["fashion", "past", "embarrassment", "style", "nostalgia", "outfit"],
+ "humor-011": ["misunderstanding", "awkward moment", "embarrassment", "communication", "mix-up", "humor"],
+ "humor-012": ["autobiography", "title", "self-reflection", "life story", "creativity", "funny"],
+ "humor-013": ["sports", "slow motion", "imagination", "silly", "athletics", "comedy"],
+ "humor-014": ["stranger", "slip of the tongue", "embarrassment", "mistake", "awkward moment", "funny"],
+ "humor-015": ["appliance", "explanation", "history", "technology", "imagination", "time travel"],
+ "humor-016": ["food", "prank", "opinion", "dislike", "silly", "absurd"],
+ "humor-017": ["mundane task", "music", "drama", "everyday life", "soundtrack", "exaggeration"],
+ "humor-018": ["clumsiness", "embarrassment", "pride", "trying to impress", "funny story", "mishap"],
+ "humor-019": ["talent", "trophy", "self-deprecation", "award", "useless skill", "quirk"],
+ "humor-020": ["misheard lyric", "song", "mistake", "misunderstanding", "childhood", "music"],
+ "humor-021": ["animal", "roommate", "living together", "imagination", "silly", "pet"],
+ "humor-022": ["questions", "communication", "hypothetical", "speech", "silly", "conversation"],
+ "humor-023": ["compliment", "stranger", "strange", "funny story", "social moment", "kind words"],
+ "humor-024": ["nature documentary", "narration", "everyday task", "imagination", "comedy", "observation"],
+ "humor-025": ["bet", "competition", "ridiculous", "dare", "risk", "funny story"],
+ "humor-026": ["nickname", "friendship", "identity", "family", "funny", "teasing"],
+ "humor-027": ["sound", "laughter", "everyday life", "quirk", "annoyance", "amusement"],
+ "humor-028": ["child", "pet", "funny story", "family", "innocence", "laughter"],
+ "humor-029": ["household", "rules", "family", "humor", "tradition", "quirk"],
+ "humor-030": ["nickname", "object", "home", "silly", "personification", "quirk"],
+ "humor-031": ["overheard", "stranger", "eavesdropping", "funny story", "public", "observation"],
+ "humor-032": ["excuse", "creativity", "lying", "funny story", "story", "humor"],
+ "humor-033": ["startle", "household", "surprise", "object", "fright", "funny story"],
+ "humor-034": ["fear", "silly", "childhood", "phobia", "self-awareness", "growing up"],
+ "humor-035": ["costume", "dress-up", "party", "embarrassment", "halloween", "funny story"],
+ "humor-036": ["superstition", "belief", "luck", "silly", "quirk", "ritual"],
+ "humor-037": ["object", "bad luck", "household", "personification", "frustration", "funny"],
+ "humor-038": ["overreaction", "inconvenience", "drama", "frustration", "self-awareness", "exaggeration"],
+ "humor-039": ["competition", "chore", "household", "gamification", "motivation", "playfulness"],
+ "humor-040": ["compliment", "mistake", "laughter", "awkward moment", "social moment", "funny story"],
+ "humor-041": ["competition", "games", "rivalry", "winning", "playfulness", "board game"],
+ "humor-042": ["voice", "impression", "quirk", "playfulness", "everyday phrase", "silly"],
+ "humor-043": ["lateness", "excuse", "punctuality", "funny story", "embarrassment", "silly"],
+ "humor-044": ["small talk", "avoidance", "introvert", "planning", "social anxiety", "funny story"],
+ "humor-045": ["sound", "memory", "household", "laughter", "nostalgia", "home"],
+ "humor-046": ["practice", "speech", "solitude", "strange", "preparation", "quirk"],
+ "humor-047": ["house rule", "household", "family", "absurd", "quirk", "tradition", "silly"],
+ "humor-048": ["household", "appliance", "self-talk", "thinking aloud", "quirk", "habit", "personification"],
+ "humor-049": ["funny voice", "voice", "impression", "accent", "silly", "playfulness", "quirk"],
+ "humor-050": ["losing", "sore loser", "competition", "sportsmanship", "game night", "board game", "overreaction"],
+ "humor-051": ["sleep talking", "sleep", "half asleep", "waking up", "embarrassment", "absurd", "funny story"],
+ "humor-052": ["childhood", "lying", "fib", "mischief", "secret", "confession", "honesty"],
+ "humor-053": ["voicemail", "phone", "phone call", "pocket dial", "embarrassment", "awkward moment", "mishap"],
+ "humor-054": ["household", "appliance", "gadget", "malfunction", "betrayal", "frustration", "mishap"],
+ "humor-055": ["pet", "nickname", "dog", "cat", "affection", "personality", "animal"],
+ "humor-056": ["mirror", "rehearsal", "practice", "preparation", "confidence", "embarrassment", "self-image"],
+ "humor-057": ["household", "lost property", "keys", "remote control", "annoyance", "mystery", "forgetfulness"],
+ "humor-058": ["argument", "inner conflict", "self-talk", "indecision", "inner voice", "rationalization", "silly"],
+ "humor-059": ["stranger", "avoidance", "awkward moment", "embarrassment", "silly", "social anxiety", "funny story"],
+ "humor-060": ["errand", "competition", "chore", "humor", "quirk", "shopping", "everyday task"],
+ "humor-061": ["drama", "good news", "exaggeration", "celebration", "personality", "humor", "sharing"],
+ "dilemmas-001": ["honesty", "gift", "tact", "friendship", "politeness", "white lie"],
+ "dilemmas-002": ["honesty", "integrity", "money", "stranger", "ethics", "doing the right thing"],
+ "dilemmas-003": ["honesty", "friendship", "courage", "difficult conversation", "tact", "hard truth"],
+ "dilemmas-004": ["promise", "integrity", "ethics", "commitment", "trust", "keeping your word"],
+ "dilemmas-005": ["neighbor", "noise", "conflict", "diplomacy", "dog", "boundaries"],
+ "dilemmas-006": ["manners", "etiquette", "stranger", "respect", "public transit", "consideration"],
+ "dilemmas-007": ["honesty", "integrity", "money", "cashier", "ethics", "doing the right thing"],
+ "dilemmas-008": ["money", "friendship", "boundaries", "lending", "trust", "loan"],
+ "dilemmas-009": ["fairness", "money", "dining out", "friendship", "bill", "splitting costs"],
+ "dilemmas-010": ["workplace", "credit", "fairness", "assertiveness", "colleague", "conflict"],
+ "dilemmas-011": ["friendship", "honesty", "relationship", "tact", "courage", "partner"],
+ "dilemmas-012": ["white lie", "honesty", "kindness", "ethics", "tact", "truth"],
+ "dilemmas-013": ["fairness", "line", "conflict", "patience", "etiquette", "queue"],
+ "dilemmas-014": ["invitation", "priorities", "social life", "scheduling", "choice", "commitment"],
+ "dilemmas-015": ["honesty", "feedback", "cooking", "friendship", "tact", "criticism"],
+ "dilemmas-016": ["etiquette", "noise", "public place", "courtesy", "phone", "conflict"],
+ "dilemmas-017": ["secret", "trust", "friendship", "betrayal", "honesty", "hurt"],
+ "dilemmas-018": ["neighbor", "obligation", "favor", "community", "boundaries", "generosity"],
+ "dilemmas-019": ["correction", "public", "tact", "humility", "etiquette", "mistake"],
+ "dilemmas-020": ["priorities", "deadline", "quality", "perfectionism", "time management", "workplace"],
+ "dilemmas-021": ["hospitality", "accident", "friendship", "parenting", "grace", "manners"],
+ "dilemmas-022": ["priorities", "family", "friendship", "loyalty", "scheduling", "difficult choice"],
+ "dilemmas-023": ["lateness", "friendship", "boundaries", "respect", "punctuality", "patience"],
+ "dilemmas-024": ["disagreement", "teamwork", "conformity", "courage", "group decision", "dissent"],
+ "dilemmas-025": ["courage", "fairness", "bystander", "justice", "stranger", "speaking up"],
+ "dilemmas-026": ["secret", "loyalty", "ethics", "friendship", "trust", "conscience"],
+ "dilemmas-027": ["blame", "fairness", "defending yourself", "injustice", "responsibility", "accountability"],
+ "dilemmas-028": ["honesty", "integrity", "money", "wallet", "ethics", "lost property"],
+ "dilemmas-029": ["social media", "disagreement", "friendship", "tact", "online", "opinion"],
+ "dilemmas-030": ["restaurant", "wrong order", "politeness", "assertiveness", "dining out", "speaking up"],
+ "dilemmas-031": ["interrupting", "friendship", "assertiveness", "communication", "boundaries", "respect"],
+ "dilemmas-032": ["cancelling", "friendship", "boundaries", "reliability", "disappointment", "flaky friend"],
+ "dilemmas-033": ["honesty", "credit", "integrity", "humility", "workplace", "ethics"],
+ "dilemmas-034": ["honesty", "receipt", "integrity", "ethics", "money", "stranger"],
+ "dilemmas-035": ["correction", "pronunciation", "friendship", "tact", "language", "humility"],
+ "dilemmas-036": ["group chat", "boundaries", "saying no", "social pressure", "friendship", "plans"],
+ "dilemmas-037": ["child", "manners", "host", "parenting", "patience", "tact"],
+ "dilemmas-038": ["friendship", "control", "dining out", "assertiveness", "manners", "table"],
+ "dilemmas-039": ["shared playlist", "music", "compromise", "taste", "boundaries", "sharing"],
+ "dilemmas-040": ["houseguest", "hospitality", "boundaries", "tact", "home", "guest"],
+ "dilemmas-041": ["friendship", "one-upmanship", "conversation", "ego", "patience", "boasting"],
+ "dilemmas-042": ["chore", "household", "fairness", "roommate", "responsibility", "conflict"],
+ "dilemmas-043": ["correction", "tour guide", "travel", "tact", "humility", "etiquette"],
+ "dilemmas-044": ["embarrassment", "kindness", "stranger", "tact", "awkward moment", "helping"],
+ "dilemmas-045": ["honesty", "wrong order", "integrity", "restaurant", "ethics", "speaking up"],
+ "dilemmas-046": ["kindness", "news", "consideration", "sleep", "timing", "good news"],
+ "dilemmas-047": ["advice", "friendship", "honesty", "tact", "hard truth", "tough love", "listening"],
+ "dilemmas-048": ["gift", "shared gift", "giving", "selfishness", "thoughtfulness", "guilt", "compromise"],
+ "dilemmas-049": ["surprise party", "surprise", "secret", "eavesdropping", "spoiler", "pretending", "honesty"],
+ "dilemmas-050": ["boundaries", "privacy", "assertiveness", "saying no", "friendship", "uninvited guest", "invitation"],
+ "dilemmas-051": ["host", "dinner party", "food", "honesty", "tact", "etiquette", "hospitality"],
+ "dilemmas-052": ["cheating", "fairness", "fair play", "integrity", "loyalty", "friendship", "game night"],
+ "dilemmas-053": ["gift", "regifting", "gratitude", "graciousness", "etiquette", "thoughtfulness", "friendship"],
+ "dilemmas-054": ["restaurant", "bill", "billing error", "honesty", "integrity", "ethics", "money"],
+ "dilemmas-055": ["haircut", "appearance", "honesty", "tact", "white lie", "friendship", "kindness"],
+ "dilemmas-056": ["bad idea", "friendship", "honesty", "support", "encouragement", "tact", "reality check"],
+ "dilemmas-057": ["interrupting", "listening", "patience", "manners", "tact", "repeated story", "conversation"],
+ "dilemmas-058": ["taking sides", "loyalty", "neutrality", "diplomacy", "conflict", "feud", "friendship"],
+ "dilemmas-059": ["honesty", "tact", "friendship", "feedback", "hard truth", "encouragement", "judgment"],
+ "dilemmas-060": ["promise", "memory", "accountability", "keeping your word", "integrity", "responsibility", "forgetfulness"],
+ "dilemmas-061": ["friendship", "generosity", "bill", "forgetfulness", "money", "fairness", "etiquette"],
+ "learning-growth-001": ["adult learning", "self-improvement", "regret", "new skill", "late bloomer", "hobby"],
+ "learning-growth-002": ["mistake", "failure", "resilience", "lesson learned", "trial and error", "hindsight"],
+ "learning-growth-003": ["feedback", "criticism", "humility", "openness", "unsolicited advice", "constructive criticism"],
+ "learning-growth-004": ["changing your mind", "open-mindedness", "growth", "opinion", "flexibility", "new perspective"],
+ "learning-growth-005": ["mentor", "unintended teacher", "role model", "influence", "lesson", "inspiration"],
+ "learning-growth-006": ["self-improvement", "goal", "progress", "practice", "personal growth", "work in progress"],
+ "learning-growth-007": ["mastery", "understanding", "learning", "self-assessment", "knowledge", "competence"],
+ "learning-growth-008": ["youth", "beliefs", "growth", "changing views", "maturity", "twenties", "letting go"],
+ "learning-growth-009": ["school", "perseverance", "curiosity", "subject", "education", "changed attitude"],
+ "learning-growth-010": ["perseverance", "patience", "frustration", "motivation", "learning curve", "persistence"],
+ "learning-growth-011": ["younger generation", "reverse mentoring", "humility", "fresh perspective", "teacher", "youth"],
+ "learning-growth-012": ["failure", "opportunity", "resilience", "silver lining", "second chance", "setback"],
+ "learning-growth-013": ["education", "learning style", "student", "change", "technology", "study habit"],
+ "learning-growth-014": ["feedback", "advice", "improvement", "criticism", "compliment", "growth"],
+ "learning-growth-015": ["habit", "breaking habits", "willpower", "change", "discipline", "self-control"],
+ "learning-growth-016": ["time management", "lifelong learning", "busy life", "priorities", "balance", "self-study"],
+ "learning-growth-017": ["education", "school", "career change", "dream", "study", "curiosity"],
+ "learning-growth-018": ["beginner", "humility", "new start", "learning", "fresh start", "novice"],
+ "learning-growth-019": ["criticism", "discernment", "feedback", "judgment", "resilience", "self-confidence"],
+ "learning-growth-020": ["repeated lesson", "stubbornness", "growth", "mistake", "patience", "life lesson"],
+ "learning-growth-021": ["honest advice", "trust", "friendship", "mentor", "self-awareness", "confidant"],
+ "learning-growth-022": ["personal growth", "past self", "self-reflection", "change", "progress", "younger self"],
+ "learning-growth-023": ["unlearning", "happiness", "letting go", "freedom", "growth", "bad habit"],
+ "learning-growth-024": ["curiosity", "expertise", "lifelong learning", "passion", "fresh eyes", "mastery"],
+ "learning-growth-025": ["challenge", "mentor", "growth", "surprise", "comfort zone", "coach"],
+ "learning-growth-026": ["regret", "missed opportunity", "new skill", "giving up", "second chance", "hobby"],
+ "learning-growth-027": ["asking for help", "independence", "humility", "vulnerability", "teamwork", "struggle"],
+ "learning-growth-028": ["failure", "gratitude", "silver lining", "turning point", "hindsight", "lesson learned"],
+ "learning-growth-029": ["self-taught", "independence", "diy", "determination", "new skill", "autodidact"],
+ "learning-growth-030": ["quitting", "perseverance", "judgment", "decision", "giving up", "grit"],
+ "learning-growth-031": ["teacher", "patience", "mentor", "role model", "school", "kindness"],
+ "learning-growth-032": ["procrastination", "new skill", "goal", "someday", "intention", "bucket list"],
+ "learning-growth-033": ["beginner", "humility", "inexperience", "confidence", "new job", "learning from others"],
+ "learning-growth-034": ["advice", "wisdom", "hindsight", "understanding", "elder", "life lesson"],
+ "learning-growth-035": ["relearning", "rust", "practice", "comeback", "old skill", "muscle memory"],
+ "learning-growth-036": ["difficult conversation", "giving feedback", "honesty", "leadership", "tact", "criticism"],
+ "learning-growth-037": ["hobby", "life lesson", "metaphor", "growth", "play", "insight"],
+ "learning-growth-038": ["practice", "lifelong learning", "persistence", "craft", "dedication", "patience"],
+ "learning-growth-039": ["gentle correction", "mentor", "kindness", "teacher", "feedback", "learning"],
+ "learning-growth-040": ["advice", "discernment", "wisdom", "judgment", "trust", "guidance"],
+ "learning-growth-041": ["stubbornness", "determination", "self-taught", "spite", "grit", "new skill"],
+ "learning-growth-042": ["outgrowing", "mindset", "growth", "change", "old habit", "self-awareness"],
+ "learning-growth-043": ["compliment", "encouragement", "motivation", "improvement", "praise", "confidence"],
+ "learning-growth-044": ["fear", "asking questions", "courage", "curiosity", "vulnerability", "speaking up"],
+ "learning-growth-045": ["outgrowing", "mindset", "growth", "change", "maturity", "self-awareness"],
+ "learning-growth-046": ["mistake", "public speaking", "embarrassment", "humility", "resilience", "courage"],
+ "learning-growth-047": ["unlearning", "bad habit", "self-improvement", "humility", "growth", "open mind", "beginner's mind"],
+ "learning-growth-048": ["criticism", "feedback", "tough love", "brutal honesty", "hindsight", "gratitude", "mentor"],
+ "learning-growth-049": ["curiosity", "obsession", "passion", "rabbit hole", "hobby", "balance", "self-awareness"],
+ "learning-growth-050": ["mistake", "humility", "self-awareness", "aha moment", "wake-up call", "bad habit", "course correction"],
+ "learning-growth-051": ["independence", "self-reliance", "necessity", "resourcefulness", "tough love", "life skill", "growing up"],
+ "learning-growth-052": ["mentor", "teacher", "role model", "outgrowing", "moving on", "independence", "growth"],
+ "learning-growth-053": ["costly mistake", "life lesson", "money", "finance", "hindsight", "regret", "wisdom"],
+ "learning-growth-054": ["obsolescence", "outdated skill", "lost art", "technology", "adaptation", "progress", "nostalgia"],
+ "learning-growth-055": ["praise", "compliment", "credit", "humility", "impostor syndrome", "recognition", "honesty"],
+ "learning-growth-056": ["regret", "practice", "lost skills", "hobby", "instrument", "language", "second chance"],
+ "learning-growth-057": ["teaching", "mastery", "mentor", "readiness", "confidence", "learning", "giving back"],
+ "learning-growth-058": ["failure", "setback", "silver lining", "life lesson", "resilience", "success", "year-end"],
+ "learning-growth-059": ["new skill", "hobby", "curiosity", "play", "joy", "lifelong learning", "passion"],
+ "learning-growth-060": ["plateau", "mastery", "improvement", "self-awareness", "progress", "acceptance", "expertise"],
+ "learning-growth-061": ["lesson", "stranger", "perspective", "wisdom", "work", "life lesson", "insight"],
+ "nature-outdoors-001": ["animal", "kinship", "pet", "identity", "wildlife", "spirit animal"],
+ "nature-outdoors-002": ["scenic place", "nature", "beauty", "awe", "landscape", "travel"],
+ "nature-outdoors-003": ["outdoors", "mood", "wellbeing", "fresh air", "mental health", "nature"],
+ "nature-outdoors-004": ["weather", "plans gone wrong", "serendipity", "memorable day", "rain", "storm"],
+ "nature-outdoors-005": ["plant", "flower", "tree", "meaning", "symbolism", "garden"],
+ "nature-outdoors-006": ["bucket list", "adventure", "aging", "outdoor activity", "hiking", "sport"],
+ "nature-outdoors-007": ["camping", "adventure", "outdoors", "comfort zone", "tent", "wilderness"],
+ "nature-outdoors-008": ["wild animal", "wildlife", "fear", "adventure", "encounter", "nature"],
+ "nature-outdoors-009": ["thinking place", "solitude", "reflection", "outdoors", "park", "retreat"],
+ "nature-outdoors-010": ["childhood", "nature", "change", "growing up", "playing outside", "nostalgia"],
+ "nature-outdoors-011": ["nature sound", "calm", "peace", "relaxation", "birdsong", "water"],
+ "nature-outdoors-012": ["season", "outdoors", "weather", "climate", "hometown", "favorite time"],
+ "nature-outdoors-013": ["animal", "observation", "lesson", "wildlife", "nature", "pet"],
+ "nature-outdoors-014": ["rain", "weather", "attitude", "optimism", "mood", "storm"],
+ "nature-outdoors-015": ["garden", "green space", "nature", "memory", "sanctuary", "park"],
+ "nature-outdoors-016": ["awe", "humility", "perspective", "nature", "wonder", "mountain"],
+ "nature-outdoors-017": ["digital detox", "phone", "outdoors", "disconnect", "solitude", "nature"],
+ "nature-outdoors-018": ["hiking", "beach", "vacation", "relaxation", "preference", "adventure"],
+ "nature-outdoors-019": ["sunrise", "sunset", "beauty", "memory", "sky", "travel"],
+ "nature-outdoors-020": ["houseplant", "nature", "home", "daily life", "greenery", "balance"],
+ "nature-outdoors-021": ["awe", "storm", "stargazing", "speechless", "wonder", "night sky"],
+ "nature-outdoors-022": ["nature", "appreciation", "indoors", "loss", "outdoors", "gratitude"],
+ "nature-outdoors-023": ["discovery", "surprise", "outdoors", "adventure", "found object", "nature"],
+ "nature-outdoors-024": ["insect", "bug", "nature", "annoyance", "outdoors", "tolerance"],
+ "nature-outdoors-025": ["good weather", "summer", "outdoor memory", "sunshine", "nostalgia", "perfect day"],
+ "nature-outdoors-026": ["weather", "storm", "extreme weather", "snow", "surprise", "climate"],
+ "nature-outdoors-027": ["water", "lake", "ocean", "river", "meaning", "nostalgia"],
+ "nature-outdoors-028": ["wildlife", "surprise", "animal", "wonder", "city nature", "encounter"],
+ "nature-outdoors-029": ["beauty", "morning", "evening", "golden hour", "nature", "time of day"],
+ "nature-outdoors-030": ["city life", "trees", "nature", "isolation", "deprivation", "green space"],
+ "nature-outdoors-031": ["sound", "city life", "nature", "loss", "homesickness", "quiet"],
+ "nature-outdoors-032": ["smell", "weather", "senses", "rain", "season", "nature"],
+ "nature-outdoors-033": ["coast", "forest", "trail", "travel", "dream destination", "nostalgia"],
+ "nature-outdoors-034": ["gardening", "therapy", "chore", "hobby", "relaxation", "plants"],
+ "nature-outdoors-035": ["small creature", "bird", "insect", "pause", "mindfulness", "wildlife"],
+ "nature-outdoors-036": ["campfire", "camping", "evening", "friends", "storytelling", "outdoors"],
+ "nature-outdoors-037": ["hiking", "solitude", "company", "friends", "preference", "trail"],
+ "nature-outdoors-038": ["plant", "perseverance", "survival", "houseplant", "care", "gardening"],
+ "nature-outdoors-039": ["silence", "solitude", "quiet", "peace", "wilderness", "nature"],
+ "nature-outdoors-040": ["trail", "strangers", "hiking", "etiquette", "community", "outdoors"],
+ "nature-outdoors-041": ["happy place", "view", "comfort", "mental escape", "resilience", "scenery"],
+ "nature-outdoors-042": ["season change", "observation", "nature", "spring", "autumn", "attentiveness"],
+ "nature-outdoors-043": ["silence", "nature", "solitude", "peace", "wilderness", "stillness"],
+ "nature-outdoors-044": ["bird", "animal sound", "childhood", "nature", "learning", "birdsong"],
+ "nature-outdoors-045": ["outdoor chore", "reward", "yard work", "satisfaction", "gardening", "work"],
+ "nature-outdoors-046": ["seating", "outdoors", "choice", "habit", "picnic", "people watching"],
+ "nature-outdoors-047": ["wildflower", "plant", "flower", "botany", "nature", "curiosity", "childhood"],
+ "nature-outdoors-048": ["forecast", "weather", "storm", "rain", "stubbornness", "risk", "consequence"],
+ "nature-outdoors-049": ["first frost", "frost", "cold", "winter", "autumn", "season change", "transition"],
+ "nature-outdoors-050": ["gardening", "green thumb", "harvest", "homegrown", "surprise", "patience", "pride"],
+ "nature-outdoors-051": ["outdoor chore", "chore", "yard work", "lawn mowing", "raking leaves", "growing up", "perspective"],
+ "nature-outdoors-052": ["cold", "winter", "outdoors", "freezing", "endurance", "limits", "toughness"],
+ "nature-outdoors-053": ["wild animal", "animal", "wildlife", "getting lost", "navigation", "trust", "instinct"],
+ "nature-outdoors-054": ["lake", "river", "ocean", "water", "peace", "calm", "serenity"],
+ "nature-outdoors-055": ["foraging", "wild food", "mushroom", "berry picking", "self-reliance", "survival", "risk"],
+ "nature-outdoors-056": ["sound", "childhood", "nostalgia", "innocence", "sensory memory", "birdsong", "summer"],
+ "nature-outdoors-057": ["redevelopment", "urban sprawl", "green space", "happy place", "loss", "nostalgia", "conservation"],
+ "nature-outdoors-058": ["sunrise", "morning", "sleeping in", "early bird", "rest", "priorities", "wonder"],
+ "nature-outdoors-059": ["plant", "admiration", "weed", "nature", "garden", "resilience", "appreciation"],
+ "nature-outdoors-060": ["swimming", "water", "lake", "ocean", "comfort", "fear", "preference"],
+ "nature-outdoors-061": ["morning", "sound", "birdsong", "nature", "outdoors", "mindfulness", "ritual"],
+ "habits-routines-001": ["morning routine", "habit", "mornings", "beginnings", "daily ritual", "early riser"],
+ "habits-routines-002": ["evening ritual", "routine", "wind down", "closure", "comfort", "night"],
+ "habits-routines-003": ["motivation", "procrastination", "morning", "discipline", "getting started", "momentum"],
+ "habits-routines-004": ["habit", "consistency", "pride", "discipline", "long-term commitment", "achievement"],
+ "habits-routines-005": ["routine", "change", "letting go", "new habit", "replacement", "transition"],
+ "habits-routines-006": ["weekend", "routine", "work-life balance", "weekday", "rest", "schedule"],
+ "habits-routines-007": ["secret", "daily habit", "private life", "quirk", "ritual", "personal"],
+ "habits-routines-008": ["small change", "routine", "impact", "improvement", "tiny habit", "compound effect"],
+ "habits-routines-009": ["sleep", "bedtime", "wind down", "evening routine", "relaxation", "rest"],
+ "habits-routines-010": ["parent", "inheritance", "family", "habit", "childhood", "upbringing"],
+ "habits-routines-011": ["chores", "automation", "daily task", "dislike", "housework", "efficiency"],
+ "habits-routines-012": ["running late", "morning", "stress", "adaptability", "time pressure", "improvisation"],
+ "habits-routines-013": ["to-do list", "organization", "productivity", "planning", "lists", "procrastination"],
+ "habits-routines-014": ["new habit", "goal", "self-improvement", "resolution", "planning", "change"],
+ "habits-routines-015": ["travel", "routine", "disruption", "adaptability", "vacation", "habit"],
+ "habits-routines-016": ["ordinary day", "ritual", "joy", "small pleasure", "self-care", "treat"],
+ "habits-routines-017": ["productivity", "morning person", "night owl", "thinking", "peak time", "focus"],
+ "habits-routines-018": ["morning", "time management", "getting ready", "leaving home", "punctuality", "lateness"],
+ "habits-routines-019": ["shared routine", "relationship", "tradition", "partner", "habit", "friendship"],
+ "habits-routines-020": ["bad habit", "guilty pleasure", "defense", "quirk", "vice", "indulgence"],
+ "habits-routines-021": ["reset", "routine", "recovery", "fresh start", "setback", "restart"],
+ "habits-routines-022": ["stress", "habit", "coping", "pressure", "routine", "anxiety"],
+ "habits-routines-023": ["new habit", "success", "sticking with it", "consistency", "habit formation", "achievement"],
+ "habits-routines-024": ["morning routine", "priorities", "editing", "simplify", "decision", "routine design"],
+ "habits-routines-025": ["workplace", "inheritance", "habit", "career", "office culture", "routine"],
+ "habits-routines-026": ["failed habit", "giving up", "resolution", "setback", "self-improvement", "regret"],
+ "habits-routines-027": ["vacation", "routine", "holiday", "discipline", "travel", "consistency"],
+ "habits-routines-028": ["ritual", "preparation", "big day", "nerves", "superstition", "pre-event routine"],
+ "habits-routines-029": ["busy schedule", "first to go", "priorities", "self-care", "stress", "habit"],
+ "habits-routines-030": ["housemate", "partner", "boundaries", "routine disruption", "compromise", "patience"],
+ "habits-routines-031": ["time of day", "routine", "schedule", "body clock", "structure", "habit"],
+ "habits-routines-032": ["leaving home", "checklist", "keys", "forgetfulness", "routine", "morning"],
+ "habits-routines-033": ["habit", "motivation", "consistency", "boredom", "perseverance", "discipline"],
+ "habits-routines-034": ["small routine", "busy day", "self-care", "priority", "protection", "ritual"],
+ "habits-routines-035": ["working from home", "quirk", "remote work", "oddity", "pandemic", "habit"],
+ "habits-routines-036": ["seasons", "routine", "change", "schedule", "winter", "holiday"],
+ "habits-routines-037": ["unlearning", "bad habit", "breaking habits", "difficulty", "change", "willpower"],
+ "habits-routines-038": ["bedtime", "night", "end of day", "routine", "lights out", "wind down"],
+ "habits-routines-039": ["accountability", "observation", "habit", "audience", "honesty", "social pressure"],
+ "habits-routines-040": ["travel", "return", "routine", "rebuild", "jet lag", "reset"],
+ "habits-routines-041": ["non-negotiable", "holiday", "habit", "discipline", "consistency", "vacation"],
+ "habits-routines-042": ["illness", "injury", "recovery", "routine", "reset", "patience"],
+ "habits-routines-043": ["end of day", "saving for last", "task", "routine", "procrastination", "reward"],
+ "habits-routines-044": ["unconscious habit", "autopilot", "accidental habit", "routine", "surprise", "change"],
+ "habits-routines-045": ["boundaries", "routine", "protection", "self-care", "other people", "priorities"],
+ "habits-routines-046": ["habit", "permanence", "consistency", "self-awareness", "long-term", "success"],
+ "habits-routines-047": ["habit", "routine", "small habit", "little things", "consistency", "self-care", "productivity"],
+ "habits-routines-048": ["secret", "routine", "ritual", "quirk", "embarrassment", "vulnerability", "guilty pleasure"],
+ "habits-routines-049": ["bedtime", "sleep", "night before", "big day", "preparation", "nerves", "anticipation"],
+ "habits-routines-050": ["habit", "new habit", "discipline", "motivation", "initiative", "independence", "self-improvement"],
+ "habits-routines-051": ["habit", "quirk", "superstition", "ritual", "comfort", "instinct"],
+ "habits-routines-052": ["habit", "motivation", "discipline", "procrastination", "self-talk", "exercise", "getting started"],
+ "habits-routines-053": ["habit", "necessity", "resourcefulness", "adaptation", "self-teaching", "independence", "living alone"],
+ "habits-routines-054": ["morning routine", "getting ready", "morning", "grooming", "efficiency", "simplicity", "priorities"],
+ "habits-routines-055": ["routine", "holiday", "vacation", "post-holiday", "transition", "reset", "fresh start"],
+ "habits-routines-056": ["habit", "integrity", "character", "authenticity", "intrinsic motivation", "values", "self-respect"],
+ "habits-routines-057": ["routine disruption", "bad day", "chaos", "stress", "priorities", "self-care", "coping"],
+ "habits-routines-058": ["morning", "waking up", "snooze button", "motivation", "self-talk", "perseverance", "discipline"],
+ "habits-routines-059": ["weekday", "weekend", "routine", "small habit", "work-life balance", "schedule", "boundaries"],
+ "habits-routines-060": ["pet", "plant", "routine", "responsibility", "habit", "daily ritual", "household"],
+ "habits-routines-061": ["roommate", "partner", "influence", "habit", "example", "relationship", "autopilot"],
+ "creativity-arts-001": ["music", "song", "mood", "emotion", "favorite song", "playlist"],
+ "creativity-arts-002": ["handmade", "craft", "diy", "making", "hands-on", "project"],
+ "creativity-arts-003": ["creativity", "role model", "inspiration", "innovation", "originality", "admiration"],
+ "creativity-arts-004": ["book", "reading", "literature", "emotion", "favorite book", "satisfaction"],
+ "creativity-arts-005": ["art", "music", "writing", "lasting impact", "inspiration", "memory"],
+ "creativity-arts-006": ["ideas", "inspiration", "brainstorming", "creativity", "shower thoughts", "insight"],
+ "creativity-arts-007": ["free time", "dream project", "fearlessness", "creative project", "vulnerability", "self-expression"],
+ "creativity-arts-008": ["teenage years", "nostalgia", "music", "memory", "youth", "emotion"],
+ "creativity-arts-009": ["film", "story", "movie", "nostalgia", "first time", "favorite film"],
+ "creativity-arts-010": ["creative skill", "hobby", "giving up", "comeback", "regret", "art"],
+ "creativity-arts-011": ["inspiration", "creative block", "stuck", "problem solving", "motivation", "resourcefulness"],
+ "creativity-arts-012": ["childhood", "drawing", "singing", "play", "imagination", "art"],
+ "creativity-arts-013": ["art", "understanding", "curiosity", "modern art", "appreciation", "learning"],
+ "creativity-arts-014": ["book", "perspective", "worldview", "literature", "reading", "change"],
+ "creativity-arts-015": ["talent", "creativity", "skill", "practice", "innovation", "originality"],
+ "creativity-arts-016": ["collaboration", "teamwork", "group project", "creativity", "togetherness", "community"],
+ "creativity-arts-017": ["instrument", "music", "mastery", "dream", "learning", "piano"],
+ "creativity-arts-018": ["novel", "storytelling", "writing", "imagination", "plot", "author"],
+ "creativity-arts-019": ["entertainment", "choice", "reading", "movies", "music", "discovery"],
+ "creativity-arts-020": ["creative habit", "admiration", "discipline", "routine", "inspiration", "role model"],
+ "creativity-arts-021": ["inspiration", "place", "creativity", "environment", "studio", "muse"],
+ "creativity-arts-022": ["sharing", "vulnerability", "creativity", "feedback", "courage", "self-expression"],
+ "creativity-arts-023": ["unfinished project", "procrastination", "creativity", "perfectionism", "abandoned", "hobby"],
+ "creativity-arts-024": ["silence", "creative process", "quiet", "solitude", "focus", "inspiration"],
+ "creativity-arts-025": ["color", "sound", "texture", "inspiration", "senses", "aesthetic"],
+ "creativity-arts-026": ["childhood", "storytelling", "imagination", "first story", "fiction", "memory"],
+ "creativity-arts-027": ["unfinished work", "clutter", "creativity", "perfectionism", "procrastination", "hobby"],
+ "creativity-arts-028": ["artist", "creator", "inspiration", "hero", "admiration", "role model"],
+ "creativity-arts-029": ["singing", "song", "sing-along", "joy", "music", "karaoke"],
+ "creativity-arts-030": ["creative risk", "courage", "fear", "risk-taking", "bravery", "self-expression"],
+ "creativity-arts-031": ["finishing", "perfectionism", "creative project", "completion", "judgment", "letting go"],
+ "creativity-arts-032": ["music", "nostalgia", "memory", "time travel", "song", "emotion"],
+ "creativity-arts-033": ["storytelling", "retelling", "anecdote", "story", "memory", "sharing"],
+ "creativity-arts-034": ["craft", "hobby", "admiration", "knitting", "woodworking", "curiosity"],
+ "creativity-arts-035": ["creative medium", "bucket list", "painting", "pottery", "art", "new hobby"],
+ "creativity-arts-036": ["lyric", "song", "music", "meaning", "connection", "poetry"],
+ "creativity-arts-037": ["music", "concentration", "focus", "work", "playlist", "study"],
+ "creativity-arts-038": ["color", "creativity", "starting something new", "preference", "aesthetic", "personality"],
+ "creativity-arts-039": ["craft", "gift", "handmade", "love", "generosity", "learning"],
+ "creativity-arts-040": ["songwriting", "poetry", "storytelling", "inspiration", "creativity", "lyrics"],
+ "creativity-arts-041": ["music", "first choice", "independence", "teenage", "nostalgia", "taste"],
+ "creativity-arts-042": ["creative habit", "private", "hobby", "journaling", "privacy", "self-expression"],
+ "creativity-arts-043": ["writing", "sharing", "readiness", "perfectionism", "editing", "vulnerability"],
+ "creativity-arts-044": ["finishing", "sharing", "perfectionism", "readiness", "creative project", "vulnerability"],
+ "creativity-arts-045": ["unfinished project", "idea", "revisiting", "creativity", "regret", "dream"],
+ "creativity-arts-046": ["writing", "creative writing", "poetry", "pride", "vulnerability", "self-expression", "confidence"],
+ "creativity-arts-047": ["instrument", "music", "sound", "piano", "violin", "awe", "beauty"],
+ "creativity-arts-048": ["creative project", "dream project", "creativity", "fear", "failure", "courage", "judgment"],
+ "creativity-arts-049": ["art", "artwork", "audience", "emotion", "impact", "self-expression", "connection"],
+ "creativity-arts-050": ["creative tool", "sketchbook", "notebook", "creative process", "intuition", "spontaneity", "doodling"],
+ "creativity-arts-051": ["rough draft", "idea", "feedback", "vulnerability", "perfectionism", "trust", "collaboration"],
+ "creativity-arts-052": ["movie", "soundtrack", "film score", "theme song", "music", "earworm", "nostalgia"],
+ "creativity-arts-053": ["craft supply", "craft", "hobby", "good intentions", "procrastination", "clutter", "impulse buy"],
+ "creativity-arts-054": ["unfinished project", "painting", "songwriting", "writing", "letting go", "perseverance", "sunk cost"],
+ "creativity-arts-055": ["anxiety", "coping", "creative outlet", "stress relief", "art therapy", "journaling", "self-care"],
+ "creativity-arts-056": ["music", "song", "songwriting", "masterpiece", "admiration", "inspiration", "envy"],
+ "creativity-arts-057": ["idea", "side project", "follow-through", "judgment", "initiative", "innovation", "ambition"],
+ "creativity-arts-058": ["handwriting", "art", "beauty", "writing", "craftsmanship", "personality", "appreciation"],
+ "creativity-arts-059": ["blank page", "creative process", "getting started", "fear", "creativity", "writing", "beginnings"],
+ "creativity-arts-060": ["craft", "self-taught", "self-teaching", "diy", "handmade", "technology", "hobby"],
+ "contest-style-001": ["courage", "bravery", "everyday life", "fear", "resilience", "character"],
+ "contest-style-002": ["priorities", "time", "values", "decision", "time management", "worth"],
+ "contest-style-003": ["productivity", "busyness", "priorities", "time management", "effectiveness", "focus"],
+ "contest-style-004": ["change", "silver lining", "gratitude", "blessing in disguise", "fear", "growth"],
+ "contest-style-005": ["good life", "meaning", "values", "philosophy", "purpose", "happiness"],
+ "contest-style-006": ["success", "definition", "ambition", "fulfillment", "values", "life stage"],
+ "contest-style-007": ["values", "integrity", "principles", "ethics", "character", "compromise"],
+ "contest-style-008": ["life lesson", "wisdom", "experience", "reflection", "growth", "insight"],
+ "contest-style-009": ["legacy", "remembrance", "relationships", "reputation", "character", "impact"],
+ "contest-style-010": ["patience", "timing", "wisdom", "decision", "restraint", "waiting"],
+ "contest-style-011": ["freedom", "independence", "everyday life", "choice", "autonomy", "liberty"],
+ "contest-style-012": ["hope", "resilience", "optimism", "adversity", "perseverance", "faith"],
+ "contest-style-013": ["comfort", "meaning", "purpose", "trade-off", "values", "fulfillment"],
+ "contest-style-014": ["growing up", "maturity", "turning point", "adulthood", "coming of age", "responsibility"],
+ "contest-style-015": ["ambition", "contentment", "balance", "satisfaction", "drive", "gratitude"],
+ "contest-style-016": ["listening", "empathy", "attention", "communication", "relationships", "presence"],
+ "contest-style-017": ["kindness", "courage", "confrontation", "compassion", "bravery", "conflict"],
+ "contest-style-018": ["legacy", "remembrance", "impact", "small acts", "meaning", "contribution"],
+ "contest-style-019": ["uncertainty", "future", "anxiety", "planning", "resilience", "coping"],
+ "contest-style-020": ["failure", "risk", "worthwhile struggle", "courage", "growth", "ambition"],
+ "contest-style-021": ["last day", "priorities", "work", "legacy", "finishing", "regret"],
+ "contest-style-022": ["gratitude", "perspective", "hard day", "attitude", "thankfulness", "positivity"],
+ "contest-style-023": ["resilience", "admiration", "strength", "role model", "adversity", "perseverance"],
+ "contest-style-024": ["good life", "fulfillment", "meaning", "happiness", "values", "purpose"],
+ "contest-style-025": ["self-acceptance", "truth", "identity", "self-awareness", "honesty", "humility"],
+ "contest-style-026": ["integrity", "honesty", "ethics", "character", "principles", "private conduct"],
+ "contest-style-027": ["productivity", "time management", "satisfaction", "good day", "fulfillment", "priorities"],
+ "contest-style-028": ["bravery", "restraint", "choice", "wisdom", "courage", "decision"],
+ "contest-style-029": ["patience", "daily life", "self-control", "waiting", "calm", "perseverance"],
+ "contest-style-030": ["speaking up", "silence", "judgment", "courage", "tact", "communication"],
+ "contest-style-031": ["kindness", "faith in humanity", "generosity", "small acts", "hope", "trust"],
+ "contest-style-032": ["showing up", "commitment", "presence", "support", "relationships", "reliability"],
+ "contest-style-033": ["risk", "decision", "judgment", "courage", "caution", "opportunity"],
+ "contest-style-034": ["playing it safe", "comfort zone", "regret", "risk", "missed opportunity", "courage"],
+ "contest-style-035": ["forgiveness", "apology", "letting go", "closure", "grudge", "healing"],
+ "contest-style-036": ["remembering", "memory", "meaning", "values", "nostalgia", "priorities"],
+ "contest-style-037": ["hope", "optimism", "realism", "expectation", "faith", "wishful thinking"],
+ "contest-style-038": ["promise", "integrity", "honesty", "commitment", "trust", "conscience"],
+ "contest-style-039": ["contentment", "enough", "satisfaction", "greed", "minimalism", "gratitude"],
+ "contest-style-040": ["discipline", "achievement", "hard work", "persistence", "habit", "success"],
+ "contest-style-041": ["forgiveness", "self-compassion", "regret", "mistake", "letting go", "healing"],
+ "contest-style-042": ["privacy", "speaking up", "sharing", "discretion", "honesty", "boundaries"],
+ "contest-style-043": ["approval", "people-pleasing", "validation", "authenticity", "self-worth", "peer pressure"],
+ "contest-style-044": ["integrity", "doing right", "ethics", "character", "honesty", "conscience"],
+ "contest-style-045": ["attention", "focus", "priorities", "mindfulness", "time", "presence"],
+ "contest-style-046": ["confidence", "certainty", "humility", "self-belief", "doubt", "leadership"],
+ "contest-style-047": ["kindness", "compassion", "integrity", "character", "peer pressure", "courage", "sacrifice"],
+ "contest-style-048": ["second chance", "forgiveness", "redemption", "trust", "judgment", "boundaries", "mercy"],
+ "contest-style-049": ["honesty", "courage", "integrity", "truth", "sacrifice", "confession", "speaking up", "hard truth"],
+ "contest-style-050": ["curiosity", "lifelong learning", "humility", "open mind", "complacency", "expertise", "beginner's mind"],
+ "contest-style-051": ["letting go", "giving up", "quitting", "acceptance", "moving on", "perseverance", "peace"],
+ "contest-style-052": ["silence", "speaking up", "silent treatment", "reconciliation", "reaching out", "communication", "courage"],
+ "contest-style-053": ["courage", "bravery", "comfort", "comfort zone", "small steps", "growth", "fear"],
+ "contest-style-054": ["goal", "sacrifice", "ambition", "priorities", "letting go", "burnout", "values"],
+ "contest-style-055": ["hardship", "silver lining", "perspective", "gratitude", "resilience", "self-reflection", "year-end", "new year"],
+ "contest-style-056": ["humility", "success", "ego", "pride", "staying grounded", "achievement", "gratitude"],
+ "contest-style-057": ["past", "memory lane", "looking back", "nostalgia", "self-reflection", "closure", "letting go"],
+ "contest-style-058": ["belonging", "love", "self-worth", "relationship", "obligation", "feeling valued", "acceptance"],
+ "contest-style-059": ["generosity", "time", "money", "giving", "values", "priorities", "presence"],
+ "contest-style-060": ["sacrifice", "regret", "decision", "hindsight", "values", "commitment", "trade-off"],
+ "contest-style-061": ["ambition", "restlessness", "contentment", "motivation", "purpose", "self-awareness", "satisfaction"]
+}
diff --git a/apps/table-topics/scripts/build.mjs b/apps/table-topics/scripts/build.mjs
index b8d2a8f7..d6331a25 100644
--- a/apps/table-topics/scripts/build.mjs
+++ b/apps/table-topics/scripts/build.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-// Render the whole site from content/questions.json into ./dist.
+// Render the whole site from content/questions.json (and the theme tags in
+// content/tags.json) into ./dist.
//
// node scripts/build.mjs # uses content/questions.json
// SITE_ORIGIN=https://www.timer-dev.toastmusters.com/tabletopics node scripts/build.mjs
@@ -8,14 +9,14 @@
// asset and root-relative link is prefixed, so www.toastmusters.com can serve
// it at /tabletopics through the timer Worker.
//
-// Env (all optional): SITE_ORIGIN, BUILD_DATE (YYYY-MM-DD), QUESTIONS_FILE,
+// Env (all optional): SITE_ORIGIN, BUILD_DATE (YYYY-MM-DD), QUESTIONS_FILE, TAGS_FILE,
// VITE_PUBLIC_POSTHOG_KEY, VITE_PUBLIC_POSTHOG_HOST (fall back to the repo-root .env).
import { readFileSync, writeFileSync, mkdirSync, rmSync, cpSync, existsSync, readdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, resolve, join, extname, basename } from 'node:path';
import { fileURLToPath } from 'node:url';
import { TOOLS, TIMER_APP_URL } from '@toastmaster-timer/shared/appLinks';
-import { validateBank } from '../src/lib/validate.js';
+import { validateBank, validateTags } from '../src/lib/validate.js';
import { flattenQuestions, drawSet, todaySet, utcDateString } from '../src/lib/picker.js';
import { SET_SIZE } from '../src/templates/widget.mjs';
import { indexPage } from '../src/templates/index.mjs';
@@ -61,14 +62,14 @@ export function buildAssets({ posthogKey, posthogHost, timerAppUrl, basePath = '
const read = (p) => readFileSync(p, 'utf8');
const strip = (code) =>
code
- .replace(/^import\s[^\n]*\n/gm, '')
+ .replace(/^import\s[\s\S]*?\sfrom\s+['"][^'"]+['"];?[ \t]*\n/gm, '')
.replace(/^export\s+(function|const|let|class)\s/gm, '$1 ')
.replace(/^export\s*\{[^}]*\};?\s*$/gm, '');
- const libs = ['rng.js', 'picker.js', 'links.js'].map((f) => strip(read(join(APP_ROOT, 'src/lib', f))));
+ const libs = ['rng.js', 'picker.js', 'links.js', 'themeMatch.js'].map((f) => strip(read(join(APP_ROOT, 'src/lib', f))));
const gen = strip(read(join(APP_ROOT, 'src/generator.js')))
.replace('__TIMER_APP_URL__', timerAppUrl)
.replace('__BASE_PATH__', basePath);
- const generator = `// Built from src/lib/{rng,picker,links}.js + src/generator.js\n${libs.join('\n')}\n${gen}`;
+ const generator = `// Built from src/lib/{rng,picker,links,themeMatch}.js + src/generator.js\n${libs.join('\n')}\n${gen}`;
const analytics = read(join(APP_ROOT, 'src/analytics.js')).replace('__POSTHOG_KEY__', posthogKey || '').replace('__POSTHOG_HOST__', posthogHost || '');
return {
'generator.js': generator,
@@ -100,8 +101,8 @@ export function applyBasePath(out, basePath) {
return moved;
}
-/** Pure: bank + config -> Map of output path -> file contents. */
-export function renderSite(bank, config) {
+/** Pure: bank + config (+ theme tags by id) -> Map of output path -> file contents. */
+export function renderSite(bank, config, tags = {}) {
const out = new Map();
const pool = flattenQuestions(bank.categories);
const seed = `home:${config.buildDate}`;
@@ -117,6 +118,10 @@ export function renderSite(bank, config) {
// Machine-readable copies.
out.set('/questions.json', JSON.stringify(bank));
+ // Theme tags for the offline theme match, fetched only when someone searches
+ // a theme. Only this bank's ids: tags.json may already hold questions that
+ // are on master but not on this branch.
+ out.set('/tags.json', JSON.stringify(Object.fromEntries(pool.filter((q) => Array.isArray(tags[q.id])).map((q) => [q.id, tags[q.id]]))));
const urls = [
{ loc: '/', priority: '1.0', changefreq: 'weekly', lastmod: config.buildDate },
@@ -173,7 +178,7 @@ export function loadConfig(env = process.env) {
};
}
-export function build({ questionsFile, distDir, env = process.env } = {}) {
+export function build({ questionsFile, tagsFile, distDir, env = process.env } = {}) {
const config = loadConfig(env);
const file = questionsFile || env.QUESTIONS_FILE || join(APP_ROOT, 'content/questions.json');
const dist = distDir || join(APP_ROOT, 'dist');
@@ -182,6 +187,13 @@ export function build({ questionsFile, distDir, env = process.env } = {}) {
if (problems.length) {
throw new Error(`questions.json has ${problems.length} problem(s):\n - ${problems.join('\n - ')}`);
}
+ // Untagged questions are fine (they match on text); malformed tags are not.
+ const tagPath = tagsFile || env.TAGS_FILE || join(APP_ROOT, 'content/tags.json');
+ const tags = existsSync(tagPath) ? JSON.parse(readFileSync(tagPath, 'utf8')) : {};
+ const tagProblems = validateTags(tags, bank).problems;
+ if (tagProblems.length) {
+ throw new Error(`tags.json has ${tagProblems.length} problem(s):\n - ${tagProblems.join('\n - ')}`);
+ }
const assets = buildAssets(config);
for (const [name, content] of Object.entries(assets)) config.assets[name] = hashedName(name, content);
@@ -192,7 +204,7 @@ export function build({ questionsFile, distDir, env = process.env } = {}) {
mkdirSync(join(dist, config.basePath, 'assets'), { recursive: true });
for (const [name, content] of Object.entries(assets)) writeFileSync(join(dist, config.basePath, config.assets[name]), content);
- const pages = renderSite(bank, config);
+ const pages = renderSite(bank, config, tags);
for (const [path, content] of pages) {
const target = join(dist, path);
mkdirSync(dirname(target), { recursive: true });
diff --git a/apps/table-topics/scripts/validate-questions.mjs b/apps/table-topics/scripts/validate-questions.mjs
index 26154b9d..67bed081 100644
--- a/apps/table-topics/scripts/validate-questions.mjs
+++ b/apps/table-topics/scripts/validate-questions.mjs
@@ -1,13 +1,18 @@
#!/usr/bin/env node
-// Validate content/questions.json. Exit 1 on any finding so CI, the build and
-// the weekly content routine all stop on a bad bank.
-import { readFileSync } from 'node:fs';
+// Validate content/questions.json and content/tags.json. Exit 1 on any
+// problem so CI, the build and the weekly content routine all stop on a bad
+// bank. Questions without theme tags are a warning: they still match on their
+// text and through the LLM, only the offline quick match misses them.
+//
+// node scripts/validate-questions.mjs [questions.json] [tags.json]
+import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
-import { validateBank } from '../src/lib/validate.js';
+import { validateBank, validateTags } from '../src/lib/validate.js';
const here = dirname(fileURLToPath(import.meta.url));
const file = process.argv[2] ? resolve(process.argv[2]) : resolve(here, '../content/questions.json');
+const tagsFile = process.argv[3] ? resolve(process.argv[3]) : resolve(dirname(file), 'tags.json');
let bank;
try {
@@ -18,10 +23,28 @@ try {
}
const problems = validateBank(bank);
+let tags = {};
+if (existsSync(tagsFile)) {
+ try {
+ tags = JSON.parse(readFileSync(tagsFile, 'utf8'));
+ } catch (err) {
+ problems.push(`cannot read ${tagsFile}: ${err.message}`);
+ }
+} else {
+ console.warn(`⚠ ${tagsFile} not found: every question is untagged`);
+}
+const tagCheck = validateTags(tags, bank);
+problems.push(...tagCheck.problems.map((p) => `tags: ${p}`));
+
const total = bank.categories?.reduce((n, c) => n + (c.questions?.length || 0), 0) ?? 0;
if (problems.length) {
console.error(`✗ ${problems.length} problem(s) in ${file}:`);
for (const p of problems) console.error(` - ${p}`);
process.exit(1);
}
-console.log(`✓ ${file}: ${bank.categories.length} categories, ${total} questions, no problems`);
+if (tagCheck.untagged.length) {
+ console.warn(`⚠ ${tagCheck.untagged.length} question(s) have no theme tags in ${tagsFile} (see content/GENERATION_PROMPT.md, "Theme tags"):`);
+ console.warn(` ${tagCheck.untagged.join(', ')}`);
+}
+if (tagCheck.unknown.length) console.log(`ℹ ${tagCheck.unknown.length} tagged id(s) are not in this bank (questions on another branch?); the build ignores them`);
+console.log(`✓ ${file}: ${bank.categories.length} categories, ${total} questions, ${total - tagCheck.untagged.length} tagged, no problems`);
diff --git a/apps/table-topics/src/generator.js b/apps/table-topics/src/generator.js
index 863d2e52..fcedb087 100644
--- a/apps/table-topics/src/generator.js
+++ b/apps/table-topics/src/generator.js
@@ -1,8 +1,18 @@
// Browser behaviour for the generator card and the Today page. The build
-// inlines ./lib/rng.js, ./lib/picker.js and ./lib/links.js above this code
-// (imports are stripped), so this file must only use their exported names.
+// inlines ./lib/rng.js, ./lib/picker.js, ./lib/links.js and ./lib/themeMatch.js
+// above this code (imports are stripped), so this file must only use their
+// exported names.
import { drawSet, flattenQuestions, todaySet, utcDateString } from './lib/picker.js';
import { timerDeepLink, shareLink } from './lib/links.js';
+import {
+ SHORTLIST_SIZE,
+ THEME_MIN_LENGTH,
+ buildThemeQueue,
+ cleanThemeInput,
+ moreThemeMatches,
+ replaceThemeQuestion,
+ themeMatchCount,
+} from './lib/themeMatch.js';
const TIMER_APP_URL = '__TIMER_APP_URL__';
// The path the site is served under ('' at a host root, '/tabletopics' on
@@ -50,6 +60,22 @@ function loadBank() {
return bankPromise;
}
+// Theme tags (question id -> tags) for the offline quick match. Fetched on the
+// first theme search only; without them the quick match uses question text.
+let tagsPromise = null;
+function loadTags() {
+ if (!tagsPromise) {
+ tagsPromise = fetch(`${BASE_PATH}/tags.json`, { cache: 'force-cache' })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`tags.json ${r.status}`))))
+ .catch((err) => {
+ console.warn('Table Topics: could not load theme tags', err);
+ tagsPromise = null; // try again on the next search
+ return {};
+ });
+ }
+ return tagsPromise;
+}
+
function randomSeed() {
const buf = new Uint32Array(1);
(window.crypto || window.msCrypto).getRandomValues(buf);
@@ -86,10 +112,66 @@ function renderItem(q, index) {
`;
}
+// One shortlist entry in theme mode: the reason it matched, and Pick / Replace.
+function renderThemeItem(q, index, picked) {
+ const isPicked = picked.has(q.id);
+ return `
+ ${index + 1}
+
+
${escapeHtml(q.text)}
+
+ ${escapeHtml(q.why || 'General pick')}
+ ·
+ ${escapeHtml(q.categoryName)}
+ ·
+ Time this
+
+
+
+ ${isPicked ? 'Picked ✓' : 'Pick'}
+ Replace
+
+ `;
+}
+
+const MATCH_TIMEOUT_MS = 30000;
+
+// Ask the Worker to rank the bank. Never throws: every failure comes back as
+// { picks: [], status } and the caller falls back to the offline quick match.
+async function fetchThemePicks(theme) {
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null;
+ const timer = ctrl ? setTimeout(() => ctrl.abort(), MATCH_TIMEOUT_MS) : null;
+ try {
+ const res = await fetch(`${BASE_PATH}/api/match`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ theme }),
+ signal: ctrl ? ctrl.signal : undefined,
+ });
+ if (!res.ok) return { picks: [], status: String(res.status) };
+ const body = await res.json();
+ const picks = Array.isArray(body.picks) ? body.picks.filter((p) => p && typeof p.id === 'string') : [];
+ return { picks, status: body.cached ? 'cached' : 'ok', model: body.model || null };
+ } catch (err) {
+ return { picks: [], status: err && err.name === 'AbortError' ? 'timeout' : 'error' };
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
function initGenerator(root) {
const setEl = root.querySelector('[data-tt-set]');
const statusEl = root.querySelector('[data-tt-status]');
+ const kickerEl = root.querySelector('[data-tt-kicker]');
+ const newBtn = root.querySelector('[data-tt-new]');
const chips = Array.from(root.querySelectorAll('[data-tt-chip]'));
+ const themeFormEl = root.querySelector('[data-tt-theme-form]');
+ const themeInput = root.querySelector('[data-tt-theme-input]');
+ const themeSubmit = root.querySelector('[data-tt-theme-submit]');
+ const themeClear = root.querySelector('[data-tt-theme-clear]');
+ const themeNote = root.querySelector('[data-tt-theme-note]');
+ const kickerText = kickerEl ? kickerEl.textContent : '';
+ const newText = newBtn.textContent;
const fixedCategory = root.dataset.ttCategory || '';
let category = fixedCategory;
// What is on screen. Before the bank loads we only know ids and texts from the HTML.
@@ -104,16 +186,29 @@ function initGenerator(root) {
for (const q of current) seen.add(q.id);
saveSeen(seen);
- function setStatus(msg) {
+ // Theme mode: the shortlist on screen, the ranked queue it draws from, and
+ // what has been picked or already shown.
+ const themed = { on: false, theme: '', queue: [], picked: new Set(), used: new Set(), search: 0 };
+
+ function setStatus(msg, sticky) {
statusEl.textContent = msg;
clearTimeout(statusTimer);
- if (msg) statusTimer = setTimeout(() => (statusEl.textContent = ''), 2600);
+ if (msg && !sticky) statusTimer = setTimeout(() => (statusEl.textContent = ''), 2600);
}
function ids() {
return current.map((q) => q.id);
}
+ function setUrl(params) {
+ const url = new URL(window.location.href);
+ for (const [k, v] of Object.entries(params)) {
+ if (v) url.searchParams.set(k, v);
+ else url.searchParams.delete(k);
+ }
+ history.replaceState(null, '', url);
+ }
+
function render(questions, source) {
current = questions;
for (const q of questions) seen.add(q.id);
@@ -121,9 +216,7 @@ function initGenerator(root) {
setEl.classList.add('is-changing');
setEl.innerHTML = questions.map(renderItem).join('');
setTimeout(() => setEl.classList.remove('is-changing'), 120);
- const url = new URL(window.location.href);
- url.searchParams.set('q', ids().join(','));
- history.replaceState(null, '', url);
+ setUrl({ q: ids().join(','), theme: '' });
track('tt_set_shown', { question_ids: ids(), category: category || 'all', source, count: questions.length });
questions.forEach((q, i) => track('tt_question_shown', { question_id: q.id, category: q.category, source, position: i + 1 }));
}
@@ -142,23 +235,161 @@ function initGenerator(root) {
pool = category ? all.filter((q) => q.category === category) : all;
}
- root.querySelector('[data-tt-new]').addEventListener('click', () => {
+ // ── Theme of the day ────────────────────────────────────────────────────
+ function pickedInOrder() {
+ return current.filter((q) => themed.picked.has(q.id));
+ }
+
+ function renderTheme() {
+ setEl.innerHTML = current.map((q, i) => renderThemeItem(q, i, themed.picked)).join('');
+ for (const q of current) themed.used.add(q.id);
+ const shareIds = (themed.picked.size ? pickedInOrder() : current).map((q) => q.id);
+ setUrl({ theme: themed.theme, q: shareIds.join(',') });
+ }
+
+ function showThemeNote(text) {
+ if (!themeNote) return;
+ themeNote.textContent = text;
+ themeNote.hidden = !text;
+ }
+
+ function enterThemeUi() {
+ themed.on = true;
+ if (kickerEl) kickerEl.textContent = `Best matches for “${themed.theme}”`;
+ newBtn.textContent = 'More matches';
+ if (themeClear) themeClear.hidden = false;
+ chips.forEach((c) => {
+ c.classList.remove('is-active');
+ c.setAttribute('aria-pressed', 'false');
+ });
+ }
+
+ function exitTheme() {
+ if (!themed.on) return;
+ themed.on = false;
+ themed.theme = '';
+ themed.queue = [];
+ themed.picked = new Set();
+ themed.used = new Set();
+ themed.search++;
+ if (kickerEl) kickerEl.textContent = kickerText;
+ newBtn.textContent = newText;
+ if (themeClear) themeClear.hidden = true;
+ if (themeInput) themeInput.value = '';
+ showThemeNote('');
+ chips.forEach((c) => {
+ const active = c.dataset.ttChip === category;
+ c.classList.toggle('is-active', active);
+ c.setAttribute('aria-pressed', active ? 'true' : 'false');
+ });
+ }
+
+ async function searchTheme(raw, via, sharedIds) {
+ const theme = cleanThemeInput(raw);
+ if (theme.length < THEME_MIN_LENGTH) {
+ setStatus(`Type a theme of at least ${THEME_MIN_LENGTH} letters`);
+ return;
+ }
+ const search = ++themed.search;
+ const started = Date.now();
+ if (themeSubmit) themeSubmit.disabled = true;
+ setEl.classList.add('is-changing');
+ setStatus(`Finding questions for “${theme}”…`, true);
+ const [bank, ai, tags] = await Promise.all([loadBank(), fetchThemePicks(theme), loadTags()]);
+ if (search !== themed.search) return; // a newer search or Clear won
+ if (themeSubmit) themeSubmit.disabled = false;
+ setEl.classList.remove('is-changing');
+ if (!bank) {
+ setStatus('Questions could not be loaded — try again');
+ return;
+ }
+ if (!all.length) {
+ all = flattenQuestions(bank.categories);
+ rebuildPool();
+ }
+ category = '';
+ root.dataset.ttCategory = '';
+ rebuildPool();
+
+ themed.theme = theme;
+ themed.queue = buildThemeQueue(all, theme, ai.picks, randomSeed(), tags);
+ themed.picked = new Set();
+ themed.used = new Set();
+ const byId = new Map(themed.queue.map((q) => [q.id, q]));
+ const lead = (sharedIds || []).map((id) => byId.get(id)).filter(Boolean);
+ const leadIds = new Set(lead.map((q) => q.id));
+ current = [...lead, ...themed.queue.filter((q) => !leadIds.has(q.id))].slice(0, SHORTLIST_SIZE);
+ enterThemeUi();
+ renderTheme();
+
+ const matched = themeMatchCount(themed.queue);
+ const aiCount = themed.queue.filter((q) => q.source === 'ai').length;
+ if (!matched) showThemeNote(`No close matches for “${theme}”. Here are versatile questions you can tie to the theme.`);
+ else if (matched < SHORTLIST_SIZE) showThemeNote(`Only ${matched} question${matched === 1 ? '' : 's'} match “${theme}” closely; the rest are general picks.`);
+ else if (!aiCount) showThemeNote('Quick match: smart matching is not available right now.');
+ else showThemeNote('');
+ setStatus('');
+ themeInput && (themeInput.value = theme);
+ track('tt_theme_searched', {
+ theme: theme.toLowerCase(),
+ via,
+ ai_status: ai.status,
+ ai_model: ai.model || null,
+ ai_count: aiCount,
+ tag_count: themed.queue.filter((q) => q.source === 'tag').length,
+ matched,
+ fallback: matched === 0,
+ ms: Date.now() - started,
+ });
+ current.forEach((q, i) => track('tt_question_shown', { question_id: q.id, category: q.category, source: `theme_${q.source}`, position: i + 1 }));
+ }
+
+ if (themeFormEl) {
+ themeFormEl.addEventListener('submit', (e) => {
+ e.preventDefault();
+ searchTheme(themeInput ? themeInput.value : '', 'typed');
+ });
+ }
+ if (themeClear) {
+ themeClear.addEventListener('click', () => {
+ exitTheme();
+ track('tt_theme_cleared', {});
+ if (pool.length) render(draw(), 'random');
+ else setUrl({ theme: '', q: '' });
+ if (themeInput) themeInput.focus();
+ });
+ }
+
+ newBtn.addEventListener('click', () => {
+ if (themed.on) {
+ const { shown, cycled } = moreThemeMatches(themed.queue, current, themed.picked, themed.used);
+ current = shown;
+ setEl.classList.add('is-changing');
+ renderTheme();
+ setTimeout(() => setEl.classList.remove('is-changing'), 120);
+ if (cycled) setStatus('That was every match — starting over');
+ track('tt_theme_more', { theme: themed.theme, picked: themed.picked.size });
+ return;
+ }
if (!pool.length) return setStatus('Questions are still loading…');
render(draw(), 'random');
});
root.querySelector('[data-tt-copy]').addEventListener('click', async () => {
- const text = current.map((q, i) => `${i + 1}. ${q.text}`).join('\n');
+ const list = themed.on && themed.picked.size ? pickedInOrder() : current;
+ const text = list.map((q, i) => `${i + 1}. ${q.text}`).join('\n');
const ok = await copyText(text);
- setStatus(ok ? `${current.length} questions copied` : 'Copy failed — select the text instead');
- track('tt_question_copied', { question_ids: ids(), ok });
+ setStatus(ok ? `${list.length} question${list.length === 1 ? '' : 's'} copied` : 'Copy failed — select the text instead');
+ track('tt_question_copied', { question_ids: list.map((q) => q.id), ok, theme: themed.on ? themed.theme : null });
});
root.querySelector('[data-tt-share]').addEventListener('click', async () => {
- const link = shareLink(window.location.origin, window.location.pathname, ids().join(','));
+ const list = themed.on && themed.picked.size ? pickedInOrder() : current;
+ let link = shareLink(window.location.origin, window.location.pathname, list.map((q) => q.id).join(','));
+ if (themed.on) link += `&theme=${encodeURIComponent(themed.theme)}`;
const ok = await copyText(link);
setStatus(ok ? 'Link copied' : link);
- track('tt_share_copied', { question_ids: ids(), ok });
+ track('tt_share_copied', { question_ids: list.map((q) => q.id), ok, theme: themed.on ? themed.theme : null });
});
root.querySelector('[data-tt-print]').addEventListener('click', () => {
@@ -167,14 +398,38 @@ function initGenerator(root) {
});
setEl.addEventListener('click', (e) => {
- const a = e.target.closest('[data-tt-time]');
- if (!a) return;
- const li = a.closest('[data-tt-item]');
- track('tt_timer_deeplink_clicked', { question_id: li?.dataset.ttId || null, category: category || 'all', source: 'set' });
+ const li = e.target.closest('[data-tt-item]');
+ if (!li) return;
+ if (e.target.closest('[data-tt-time]')) {
+ track('tt_timer_deeplink_clicked', { question_id: li.dataset.ttId || null, category: category || 'all', source: themed.on ? 'theme' : 'set' });
+ return;
+ }
+ if (!themed.on) return;
+ const index = current.findIndex((q) => q.id === li.dataset.ttId);
+ if (index < 0) return;
+ const q = current[index];
+ if (e.target.closest('[data-tt-pick]')) {
+ if (themed.picked.has(q.id)) themed.picked.delete(q.id);
+ else themed.picked.add(q.id);
+ renderTheme();
+ const n = themed.picked.size;
+ setStatus(n ? `${n} picked — Copy all and Copy link use your picks` : 'Nothing picked');
+ track('tt_theme_question_picked', { question_id: q.id, position: index + 1, source: q.source, picked: themed.picked.has(q.id), theme: themed.theme });
+ const again = setEl.querySelector(`[data-tt-id="${CSS.escape(q.id)}"] [data-tt-pick]`);
+ if (again) again.focus();
+ } else if (e.target.closest('[data-tt-replace]')) {
+ themed.picked.delete(q.id);
+ current = replaceThemeQuestion(themed.queue, current, index, themed.used);
+ renderTheme();
+ track('tt_theme_question_replaced', { question_id: q.id, position: index + 1, source: q.source, theme: themed.theme });
+ const again = setEl.querySelectorAll('[data-tt-replace]')[index];
+ if (again) again.focus();
+ }
});
chips.forEach((chip) => {
chip.addEventListener('click', () => {
+ exitTheme();
category = chip.dataset.ttChip;
chips.forEach((c) => {
const active = c === chip;
@@ -188,15 +443,21 @@ function initGenerator(root) {
});
});
+ const params = new URLSearchParams(window.location.search);
+ const linkedTheme = themeFormEl ? cleanThemeInput(params.get('theme') || '') : '';
+ const linkedIds = (params.get('q') || '').split(',').map((id) => id.trim()).filter(Boolean);
+ if (linkedTheme) {
+ if (themeInput) themeInput.value = linkedTheme;
+ searchTheme(linkedTheme, 'link', linkedIds);
+ }
+
loadBank().then((bank) => {
if (!bank) return;
- all = flattenQuestions(bank.categories);
+ if (!all.length) all = flattenQuestions(bank.categories);
rebuildPool();
+ if (linkedTheme) return; // searchTheme owns the list
const byId = new Map(all.map((q) => [q.id, q]));
- const shared = (new URLSearchParams(window.location.search).get('q') || '')
- .split(',')
- .map((id) => byId.get(id.trim()))
- .filter((q) => q && (!fixedCategory || q.category === fixedCategory));
+ const shared = linkedIds.map((id) => byId.get(id)).filter((q) => q && (!fixedCategory || q.category === fixedCategory));
const sharedIds = shared.map((q) => q.id).join(',');
if (shared.length && sharedIds !== ids().join(',')) {
render(shared, 'share');
diff --git a/apps/table-topics/src/lib/themeMatch.js b/apps/table-topics/src/lib/themeMatch.js
new file mode 100644
index 00000000..3af6c99e
--- /dev/null
+++ b/apps/table-topics/src/lib/themeMatch.js
@@ -0,0 +1,256 @@
+/**
+ * Theme of the day (#166): the offline half.
+ *
+ * The page asks the Worker (POST /tabletopics/api/match) to rank the bank
+ * against a theme with a free LLM. Everything here runs in the browser without
+ * it: a quick match on each question's theme tags (content/tags.json) and text
+ * for when the Worker cannot answer, and the queue that "Replace" and "More
+ * matches" draw from, which ends in general questions so the shortlist is
+ * never empty while the bank has questions.
+ *
+ * The build inlines this file into generator.js with imports and `export`
+ * stripped, next to rng.js, picker.js and links.js, so every top-level name
+ * here must be unique across those files.
+ */
+import { mulberry32, hashSeed, shuffle } from './rng.js';
+
+export const THEME_MIN_LENGTH = 2;
+export const THEME_MAX_LENGTH = 60;
+export const SHORTLIST_SIZE = 8;
+
+// Categories whose questions suit almost any theme: the last resort.
+export const GENERAL_CATEGORIES = ['contest-style', 'icebreakers', 'storytelling'];
+
+const THEME_STOPWORDS = new Set(
+ ('a an and are as at be been but by can could did do does for from had has have how i if in into is it its me my of on or our so ' +
+ 'than that the their them then there these they this to up was we were what when where which who whom why will with would you ' +
+ 'your yours about after all also am any because before being both each few more most other over same should some such too under ' +
+ 'until very just own off out again further once here only while during against between through above below now ever never one ' +
+ 'day theme themes topic topics meeting')
+ .split(' ')
+);
+
+// A theme word also matches its group, at a lower weight.
+const THEME_SYNONYMS = [
+ ['disaster', 'mishap', 'wrong', 'fiasco', 'mistake', 'fail', 'failure'],
+ ['ocean', 'sea', 'beach', 'coast', 'wave', 'island', 'shore'],
+ ['job', 'work', 'career', 'boss', 'colleague', 'office'],
+ ['friend', 'friendship', 'companion'],
+ ['travel', 'trip', 'journey', 'vacation', 'holiday'],
+ ['gratitude', 'thank', 'thankful', 'grateful', 'appreciate', 'appreciation'],
+ ['family', 'parent', 'mother', 'father', 'sibling', 'grandparent'],
+ ['child', 'childhood', 'kid', 'young', 'grow'],
+ ['fear', 'afraid', 'scared', 'brave', 'courage', 'nervous'],
+ ['change', 'new', 'begin', 'beginning', 'start', 'fresh'],
+ ['food', 'meal', 'cook', 'dish', 'eat', 'kitchen', 'recipe'],
+ ['music', 'song', 'sing'],
+ ['book', 'read', 'story'],
+ ['animal', 'pet', 'dog', 'cat'],
+ ['money', 'spend', 'save', 'buy'],
+ ['teacher', 'mentor', 'teach', 'taught', 'coach'],
+ ['home', 'house'],
+];
+
+/** Light stemmer: joins plurals, -ing/-ed forms and a few derivations. */
+export function themeStem(word) {
+ const special = { children: 'child', people: 'person', taught: 'teach', grateful: 'gratitude', thankful: 'thank', thanks: 'thank', disasters: 'disaster', disastrous: 'disaster' };
+ if (special[word]) return special[word];
+ if (word.length <= 3) return word;
+ for (const [suffix, repl] of [['ship', ''], ['ies', 'y'], ['sses', 'ss'], ['ness', ''], ['ing', ''], ['ed', ''], ['ly', ''], ['es', ''], ['s', '']]) {
+ if (word.endsWith(suffix) && word.length - suffix.length >= 3) return word.slice(0, -suffix.length) + repl;
+ }
+ return word;
+}
+
+export function themeTokens(text) {
+ return String(text || '')
+ .toLowerCase()
+ .replace(/[^a-z\s'-]/g, ' ')
+ .split(/[\s'-]+/)
+ .filter((t) => t && !THEME_STOPWORDS.has(t))
+ .map(themeStem);
+}
+
+const THEME_SYNONYM_MAP = new Map();
+for (const group of THEME_SYNONYMS) {
+ const stems = [...new Set(group.map(themeStem))];
+ for (const s of stems) THEME_SYNONYM_MAP.set(s, [...(THEME_SYNONYM_MAP.get(s) || []), ...stems.filter((o) => o !== s)]);
+}
+
+/** What the user typed, tidied: whitespace collapsed, trimmed, at most THEME_MAX_LENGTH characters. */
+export function cleanThemeInput(raw) {
+ return String(raw || '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, THEME_MAX_LENGTH);
+}
+
+// Quick-match weights. A tag hit counts more than a word in the text: tags name
+// what the question is about, the text only what it happens to say.
+const TAG_WEIGHT = 1.3;
+const SYNONYM_WEIGHT = 0.7;
+const CATEGORY_WEIGHT = 0.8;
+const PHRASE_BONUS = 2; // a tag that is exactly the typed theme
+// At most this many quick matches per category before the others get a turn,
+// so a shortlist mixes categories.
+const MATCHES_PER_CATEGORY = 3;
+
+function bm25Term(tf, len, avgLen, idf) {
+ return (idf * (tf * 2.2)) / (tf + 1.2 * (0.5 + 0.5 * (len / avgLen)));
+}
+
+/**
+ * Quick match of `theme` against each question's theme tags, text and
+ * category name, with no network. `tags` maps question id -> tag list
+ * (content/tags.json); without it only the text and category count.
+ * Returns [{ q, score, words, tag }] best first, only questions that match:
+ * `words` are the theme words it matched, `tag` the tag that matched (or null).
+ */
+export function keywordThemeMatch(pool, theme, tags = {}) {
+ const base = [...new Set(themeTokens(theme))];
+ if (!base.length || !pool.length) return [];
+ const viaSynonym = new Map();
+ for (const t of base) for (const s of THEME_SYNONYM_MAP.get(t) || []) if (!base.includes(s) && !viaSynonym.has(s)) viaSynonym.set(s, t);
+ const terms = [...base, ...viaSynonym.keys()];
+ const phrase = base.join(' ');
+
+ const docs = pool.map((q) => {
+ const qTags = Array.isArray(tags && tags[q.id]) ? tags[q.id] : [];
+ const tagTokens = qTags.map((g) => themeTokens(g));
+ return { q, tokens: themeTokens(q.text), catTokens: themeTokens(q.categoryName || ''), qTags, tagTokens, tagFlat: tagTokens.flat() };
+ });
+ const df = new Map();
+ for (const d of docs) for (const t of new Set([...d.tokens, ...d.tagFlat])) df.set(t, (df.get(t) || 0) + 1);
+ const N = docs.length;
+ const avgLen = docs.reduce((n, d) => n + d.tokens.length, 0) / N || 1;
+ const avgTagLen = docs.reduce((n, d) => n + d.tagFlat.length, 0) / N || 1;
+
+ const scored = [];
+ for (const d of docs) {
+ let score = 0;
+ const words = new Set();
+ const tagHits = new Set();
+ for (const t of terms) {
+ const tf = d.tokens.filter((x) => x === t).length;
+ const tfTag = d.tagFlat.filter((x) => x === t).length;
+ const inCategory = d.catTokens.includes(t);
+ if (!tf && !tfTag && !inCategory) continue;
+ const weight = viaSynonym.has(t) ? SYNONYM_WEIGHT : 1;
+ const idf = Math.log(1 + (N - (df.get(t) || 0) + 0.5) / ((df.get(t) || 0) + 0.5));
+ if (tf) score += weight * bm25Term(tf, d.tokens.length, avgLen, idf);
+ if (tfTag) {
+ score += weight * TAG_WEIGHT * bm25Term(tfTag, d.tagFlat.length, avgTagLen, idf);
+ tagHits.add(t);
+ }
+ if (inCategory) score += weight * CATEGORY_WEIGHT;
+ words.add(viaSynonym.get(t) || t);
+ }
+ if (!score) continue;
+ if (base.length > 1) score *= words.size === base.length ? 1.5 : 0.5;
+ const exact = d.qTags.find((g, i) => d.tagTokens[i].join(' ') === phrase);
+ if (exact) score += PHRASE_BONUS;
+ // The tag to show as the reason: the exact one, else one with a theme word, else one with a synonym.
+ const tag =
+ exact ||
+ d.qTags.find((g, i) => d.tagTokens[i].some((t) => tagHits.has(t) && !viaSynonym.has(t))) ||
+ d.qTags.find((g, i) => d.tagTokens[i].some((t) => tagHits.has(t))) ||
+ null;
+ scored.push({ q: d.q, score, words: [...words], tag });
+ }
+ scored.sort((a, b) => b.score - a.score || (a.q.id < b.q.id ? -1 : 1));
+ // Drop the weak tail: a partial match far below the best one is noise.
+ const floor = scored.length ? scored[0].score * 0.25 : 0;
+ return spreadCategories(scored.filter((s) => s.score >= floor));
+}
+
+/** Keep the order, but let no category take more than MATCHES_PER_CATEGORY places before the others have had theirs. */
+function spreadCategories(matches) {
+ const first = [];
+ const later = [];
+ const perCategory = new Map();
+ for (const m of matches) {
+ const n = perCategory.get(m.q.category) || 0;
+ perCategory.set(m.q.category, n + 1);
+ (n < MATCHES_PER_CATEGORY ? first : later).push(m);
+ }
+ return [...first, ...later];
+}
+
+/**
+ * The ordered list the shortlist draws from: the LLM's picks, then quick
+ * matches (tags and text), then general questions (the category the best
+ * matches come from first, then GENERAL_CATEGORIES, then everything),
+ * shuffled with `seed`. Each entry is { ...question, why, source } with
+ * source 'ai' | 'tag' | 'keyword' | 'general'.
+ */
+export function buildThemeQueue(pool, theme, aiPicks = [], seed = 1, tags = {}) {
+ const byId = new Map(pool.map((q) => [q.id, q]));
+ const out = [];
+ const used = new Set();
+ const push = (q, why, source) => {
+ if (!q || used.has(q.id)) return;
+ used.add(q.id);
+ out.push({ ...q, why, source });
+ };
+ // Free models leave a reason out now and then; the card must not call such a pick "General pick".
+ for (const p of aiPicks) push(byId.get(p.id), p.why || 'Fits the theme', 'ai');
+ for (const m of keywordThemeMatch(pool, theme, tags)) {
+ if (m.tag) push(m.q, `about “${m.tag}”`, 'tag');
+ else push(m.q, `mentions “${m.words.join(', ')}”`, 'keyword');
+ }
+
+ const rng = mulberry32(typeof seed === 'number' ? seed : hashSeed(String(seed)));
+ const lead = out[0]?.category;
+ const order = [...new Set([lead, ...GENERAL_CATEGORIES].filter(Boolean))];
+ for (const slug of order) for (const q of shuffle(pool.filter((x) => x.category === slug), rng)) push(q, 'General pick', 'general');
+ for (const q of shuffle(pool, rng)) push(q, 'General pick', 'general');
+ return out;
+}
+
+/** How many entries at the head of the queue actually match the theme. */
+export function themeMatchCount(queue) {
+ return queue.filter((q) => q.source !== 'general').length;
+}
+
+/** First queue entry whose id is not in `excluded`, or null. */
+export function nextThemeQuestion(queue, excluded) {
+ return queue.find((q) => !excluded.has(q.id)) || null;
+}
+
+/**
+ * "More matches": keep the picked questions where they are and replace every
+ * other one with the next unused entries. When the queue runs dry it starts
+ * over (skipping what is on screen), so the list always stays full.
+ * Returns { shown, cycled }.
+ */
+export function moreThemeMatches(queue, shown, picked, used) {
+ const onScreen = new Set(shown.map((q) => q.id));
+ let cycled = false;
+ const next = shown.map((q) => {
+ if (picked.has(q.id)) return q;
+ let n = nextThemeQuestion(queue, new Set([...used, ...onScreen]));
+ if (!n) {
+ cycled = true;
+ used.clear();
+ n = nextThemeQuestion(queue, onScreen);
+ }
+ if (!n) return q;
+ used.add(n.id);
+ onScreen.add(n.id);
+ return n;
+ });
+ return { shown: next, cycled };
+}
+
+/** "Replace": swap the question at `index` for the next unused entry. Returns the new shown list. */
+export function replaceThemeQuestion(queue, shown, index, used) {
+ const onScreen = new Set(shown.map((q) => q.id));
+ let n = nextThemeQuestion(queue, new Set([...used, ...onScreen]));
+ if (!n) {
+ used.clear();
+ n = nextThemeQuestion(queue, onScreen);
+ }
+ if (!n) return shown;
+ used.add(n.id);
+ return shown.map((q, i) => (i === index ? n : q));
+}
diff --git a/apps/table-topics/src/lib/validate.js b/apps/table-topics/src/lib/validate.js
index 21dfcef7..f0c72971 100644
--- a/apps/table-topics/src/lib/validate.js
+++ b/apps/table-topics/src/lib/validate.js
@@ -81,6 +81,41 @@ export function validateBank(bank, rules = {}) {
return problems;
}
+export const TAG_RULES = { min: 5, max: 8, maxLen: 30 };
+const TAG_RE = /^[a-z][a-z '-]*[a-z]$/;
+
+/**
+ * Validate content/tags.json (question id -> theme tags) against the bank.
+ * Returns { problems, untagged, unknown }:
+ * - problems: malformed entries; the build and the validator stop on these;
+ * - untagged: bank ids with no tags (they still match on their text and through
+ * the LLM, so this is a warning, not a failure);
+ * - unknown: tagged ids that are not in this bank, e.g. questions that are on
+ * master but not yet on this branch (harmless; the build drops them).
+ * Pure: no I/O.
+ */
+export function validateTags(tags, bank) {
+ const problems = [];
+ if (!tags || typeof tags !== 'object' || Array.isArray(tags)) return { problems: ['tags must be an object of id -> tag list'], untagged: [], unknown: [] };
+ const bankIds = new Set((bank?.categories || []).flatMap((c) => (c.questions || []).map((q) => q.id)));
+ for (const [id, list] of Object.entries(tags)) {
+ if (!Array.isArray(list)) {
+ problems.push(`${id}: tags must be an array`);
+ continue;
+ }
+ if (list.length < TAG_RULES.min || list.length > TAG_RULES.max) problems.push(`${id}: ${list.length} tags, expected ${TAG_RULES.min}–${TAG_RULES.max}`);
+ const seen = new Set();
+ for (const tag of list) {
+ if (typeof tag !== 'string' || !TAG_RE.test(tag) || tag.length > TAG_RULES.maxLen || /\s{2,}/.test(tag)) problems.push(`${id}: bad tag ${JSON.stringify(tag)} (lowercase letters, spaces, hyphens; at most ${TAG_RULES.maxLen} chars)`);
+ else if (seen.has(tag)) problems.push(`${id}: duplicate tag "${tag}"`);
+ else seen.add(tag);
+ }
+ }
+ const untagged = [...bankIds].filter((id) => !Object.prototype.hasOwnProperty.call(tags, id));
+ const unknown = Object.keys(tags).filter((id) => !bankIds.has(id));
+ return { problems, untagged, unknown };
+}
+
/** Next free id for a category, e.g. 'travel-021'. */
export function nextId(category) {
let max = 0;
diff --git a/apps/table-topics/src/styles/tabletopics.css b/apps/table-topics/src/styles/tabletopics.css
index 0b819b91..2facdcd3 100644
--- a/apps/table-topics/src/styles/tabletopics.css
+++ b/apps/table-topics/src/styles/tabletopics.css
@@ -43,6 +43,34 @@
.tt-btn-ghost:hover { border-color: var(--muted); color: var(--ink); }
.tt-status { min-height: 1.4em; margin: 0.9rem 0 0; font-size: 0.85rem; color: var(--green); }
+/* Theme of the day (#166) */
+.tt-theme { max-width: 46rem; margin: 0 auto 1.4rem; text-align: left; }
+.tt-theme-label { display: block; font-weight: 600; color: var(--ink); margin: 0 0 0.45rem; font-size: 0.95rem; }
+.tt-theme-row { display: flex; flex-wrap: wrap; gap: 0.5rem; }
+.tt-theme-input {
+ flex: 1 1 15rem; min-width: 0; font: inherit; font-size: 1rem; color: var(--ink);
+ background: #fff; border: 1px solid var(--border); border-radius: 999px; padding: 0.6rem 1rem;
+}
+.tt-theme-input:focus { outline: 2px solid var(--ink); outline-offset: 1px; border-color: var(--ink); }
+.tt-theme-row .tt-btn[disabled] { opacity: 0.6; cursor: progress; }
+.tt-theme-note { margin: 0.6rem 0 0; font-size: 0.86rem; color: var(--body-text); }
+.tt-theme-item { align-items: flex-start; }
+.tt-theme-item.is-picked { background: var(--cream); box-shadow: inset 3px 0 0 var(--green); padding-left: 0.6rem; border-radius: 0 10px 10px 0; }
+.tt-theme-actions { flex: 0 0 auto; display: flex; flex-direction: column; gap: 0.35rem; margin-top: 0.15rem; }
+.tt-mini {
+ font: inherit; font-size: 0.8rem; font-weight: 500; white-space: nowrap; cursor: pointer;
+ background: transparent; color: var(--body-text); border: 1px solid var(--border); border-radius: 999px; padding: 0.3rem 0.75rem;
+}
+.tt-mini:hover { border-color: var(--muted); color: var(--ink); }
+.tt-mini.is-on { background: var(--green); border-color: var(--green); color: #fff; }
+.tt-why { color: var(--body-text); font-style: italic; }
+.tt-why-general { color: var(--muted); font-style: normal; }
+@media (max-width: 560px) {
+ .tt-theme-item { flex-wrap: wrap; }
+ .tt-theme-item .tt-set-body { flex: 1 1 0; }
+ .tt-theme-actions { flex-direction: row; flex-basis: 100%; padding-left: 2.9rem; margin-top: 0; }
+}
+
.tt-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 0.85rem; margin: 1.25rem 0; }
.tt-card {
display: flex; flex-direction: column; gap: 0.35rem; padding: 1rem 1.1rem; text-decoration: none; color: inherit;
@@ -72,7 +100,7 @@
.tt-related li span { color: var(--faint); font-size: 0.82rem; margin-left: 0.25rem; }
@media print {
- .static-header, .static-footer, .static-breadcrumb, .tt-actions, .tt-chips, .tt-status, .tt-list-actions, .tt-set-time, .tt-today-teaser, .tt-zoom-pitch, .tt-related { display: none !important; }
+ .static-header, .static-footer, .static-breadcrumb, .tt-actions, .tt-chips, .tt-theme, .tt-theme-actions, .tt-why, .tt-status, .tt-list-actions, .tt-set-time, .tt-today-teaser, .tt-zoom-pitch, .tt-related { display: none !important; }
.static-card { box-shadow: none; border: 0; page-break-inside: avoid; }
.tt-list li { border-bottom: 1px solid #ddd; }
body { background: #fff; }
diff --git a/apps/table-topics/src/templates/index.mjs b/apps/table-topics/src/templates/index.mjs
index 9093c4f2..2bf9b5dc 100644
--- a/apps/table-topics/src/templates/index.mjs
+++ b/apps/table-topics/src/templates/index.mjs
@@ -18,7 +18,7 @@ export function indexPage(config, bank, initial) {
const body = `
Table Topics Question Generator
- Random, open-ended Table Topics questions for your next Toastmasters meeting. Pick a category or take them all, hit New question , and time the answer with one click.
+ Random, open-ended Table Topics questions for your next Toastmasters meeting. Type the meeting’s theme for a matching shortlist, or pick a category and hit New set , then time each answer with one click.
A Table Topics question is an impromptu speaking prompt answered in 1 to 2 minutes . This generator draws from ${total} curated questions in ${bank.categories.length} categories. Every question is open-ended, free of politics and trivia, and answerable by anyone in the room.
@@ -43,7 +43,7 @@ ${widget(config, { categories: bank.categories, categorySlug: '', initial, showC
How to run a great Table Topics session
- Prepare a theme, not a script. Pick one or two categories that fit the meeting theme and let the generator surprise you.
+ Prepare a theme, not a script. Type the meeting’s theme in the box above to get the best-matching questions, or pick one or two categories that fit it and let the generator surprise you.
Ask, then name. Read the question to the whole room first, then call on a speaker. Everyone gets a moment to think, and nobody tunes out.
Time every answer. Tap Time this to open the timer with the 1–2 minute Table Topics preset. Green at 1:00, yellow at 1:30, red at 2:00.
Favor guests and quiet members. Table Topics is the easiest way for a guest to speak for the first time. Keep an icebreaker question ready for them.
diff --git a/apps/table-topics/src/templates/widget.mjs b/apps/table-topics/src/templates/widget.mjs
index 0e29d50e..c712b848 100644
--- a/apps/table-topics/src/templates/widget.mjs
+++ b/apps/table-topics/src/templates/widget.mjs
@@ -1,5 +1,6 @@
import { esc, attr } from './layout.mjs';
import { timerDeepLink } from '../lib/links.js';
+import { THEME_MIN_LENGTH, THEME_MAX_LENGTH } from '../lib/themeMatch.js';
/**
* The interactive generator card. Rendered with a real question so the page
@@ -27,10 +28,13 @@ export function widget(config, { categories, categorySlug, initial, showChips })
.join('\n ')}
`
: '';
+ // Theme of the day (#166): only where the whole bank is in play, i.e. with the chips.
+ const theme = showChips ? themeForm() : '';
return `
+ ${theme}
${chips}
- Your ${initial.length === 1 ? 'question' : `set of ${initial.length}`}
+ Your ${initial.length === 1 ? 'question' : `set of ${initial.length}`}
${initial.map((q, i) => setItem(config, q, i)).join('\n ')}
@@ -45,6 +49,22 @@ export function widget(config, { categories, categorySlug, initial, showChips })
`;
}
+/**
+ * The theme box. Without JavaScript it submits ?theme= to the same page, which
+ * does nothing; with it, src/generator.js asks the Worker for the best matches.
+ */
+export function themeForm() {
+ return ` `;
+}
+
/** One question inside the set. Mirrored in src/generator.js renderItem(). */
export function setItem(config, q, index) {
return `
diff --git a/apps/table-topics/test/build.test.js b/apps/table-topics/test/build.test.js
index 94e1bf93..c3c886f4 100644
--- a/apps/table-topics/test/build.test.js
+++ b/apps/table-topics/test/build.test.js
@@ -21,7 +21,7 @@ describe('renderSite', () => {
it('emits every expected path', () => {
expect([...site.keys()].sort()).toEqual(
- ['/404.html', '/index.html', '/llms.txt', '/questions.json', '/robots.txt', '/sitemap.xml', '/today/index.html', '/topics/icebreakers/index.html', '/topics/index.html', '/topics/leadership/index.html', '/topics/travel-places/index.html'].sort()
+ ['/404.html', '/index.html', '/llms.txt', '/questions.json', '/robots.txt', '/sitemap.xml', '/tags.json', '/today/index.html', '/topics/icebreakers/index.html', '/topics/index.html', '/topics/leadership/index.html', '/topics/travel-places/index.html'].sort()
);
});
@@ -39,6 +39,21 @@ describe('renderSite', () => {
expect(doc).not.toContain(' {
+ const tags = { 'icebreakers-001': ['gratitude', 'joy', 'smile', 'happiness', 'this week'], 'humor-999': ['laughter', 'joke', 'fun', 'comedy', 'smile'] };
+ expect(JSON.parse(renderSite(bank, fixtureConfig, tags).get('/tags.json'))).toEqual({ 'icebreakers-001': tags['icebreakers-001'] });
+ expect(JSON.parse(html('/tags.json'))).toEqual({});
+ });
+
+ it('home: a theme-of-the-day box above the chips; category pages have none', () => {
+ const home = html('/index.html');
+ expect(home).toContain('data-tt-theme-form');
+ expect(home).toMatch(/ ]*maxlength="60"[^>]*data-tt-theme-input/);
+ expect(home.indexOf('data-tt-theme-form')).toBeLessThan(home.indexOf('data-tt-chip='));
+ expect(home).toMatch(/data-tt-theme-clear hidden/);
+ expect(html('/topics/icebreakers/index.html')).not.toContain('data-tt-theme-form');
+ });
+
it('category: Article + BreadcrumbList + ItemList, full list, escaped text, deep links', () => {
const doc = html('/topics/icebreakers/index.html');
expect(doc).toContain(' ');
@@ -127,10 +142,18 @@ describe('assets', () => {
expect(js).toContain('function drawQuestion');
expect(js).toContain('function todaySet');
expect(js).toContain('function timerDeepLink');
+ expect(js).toContain('function buildThemeQueue');
+ expect(js).toContain('function fetchThemePicks');
expect(js).toContain("'https://www.timer.toastmusters.com/app'");
expect(js).not.toContain('__TIMER_APP_URL__');
});
+ it('calls the theme matcher under the base path', () => {
+ const js = buildAssets({ posthogKey: '', posthogHost: '', timerAppUrl: 'https://t/app', basePath: '/tabletopics' })['generator.js'];
+ expect(js).toContain("const BASE_PATH = '/tabletopics'");
+ expect(js).toContain('`${BASE_PATH}/api/match`');
+ });
+
it('substitutes PostHog placeholders', () => {
expect(assets['analytics.js']).toContain("'phc_test'");
expect(assets['analytics.js']).not.toContain('__POSTHOG_');
@@ -153,7 +176,7 @@ describe('build (end to end into a temp dir)', () => {
writeFileSync(q, JSON.stringify(bank));
const dist = join(dir, 'dist');
const r = build({ questionsFile: q, distDir: dist, env: { BUILD_DATE: '2026-09-02', VITE_PUBLIC_POSTHOG_KEY: '', SITE_ORIGIN: 'https://www.tabletopics-dev.toastmusters.com' } });
- expect(r.pages).toBe(11);
+ expect(r.pages).toBe(12);
expect(existsSync(join(dist, 'topics/humor'))).toBe(false);
expect(existsSync(join(dist, 'topics/travel-places/index.html'))).toBe(true);
const assetFiles = readdirSync(join(dist, 'assets'));
@@ -166,6 +189,20 @@ describe('build (end to end into a temp dir)', () => {
writeFileSync(q, JSON.stringify(bad));
expect(() => build({ questionsFile: q, distDir: dist, env: {} })).toThrow(/problem/);
});
+
+ it('serves the theme tags it is given, and rejects malformed ones', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tt-build-tags-'));
+ const q = join(dir, 'q.json');
+ const t = join(dir, 'tags.json');
+ writeFileSync(q, JSON.stringify(bank));
+ const id = bank.categories[0].questions[0].id;
+ writeFileSync(t, JSON.stringify({ [id]: ['gratitude', 'joy', 'smile', 'happiness', 'this week'] }));
+ const dist = join(dir, 'dist');
+ build({ questionsFile: q, tagsFile: t, distDir: dist, env: { BUILD_DATE: '2026-09-02', VITE_PUBLIC_POSTHOG_KEY: '', SITE_ORIGIN: 'https://www.tabletopics-dev.toastmusters.com' } });
+ expect(JSON.parse(readFileSync(join(dist, 'tags.json'), 'utf8'))).toEqual({ [id]: ['gratitude', 'joy', 'smile', 'happiness', 'this week'] });
+ writeFileSync(t, JSON.stringify({ [id]: ['Gratitude'] }));
+ expect(() => build({ questionsFile: q, tagsFile: t, distDir: dist, env: {} })).toThrow(/tags\.json has 2 problem/);
+ });
});
describe('serving under a base path (www.toastmusters.com/tabletopics)', () => {
diff --git a/apps/table-topics/test/themeMatch.test.js b/apps/table-topics/test/themeMatch.test.js
new file mode 100644
index 00000000..bc5a2b8f
--- /dev/null
+++ b/apps/table-topics/test/themeMatch.test.js
@@ -0,0 +1,212 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { flattenQuestions } from '../src/lib/picker.js';
+import {
+ SHORTLIST_SIZE,
+ THEME_MAX_LENGTH,
+ themeStem,
+ themeTokens,
+ cleanThemeInput,
+ keywordThemeMatch,
+ buildThemeQueue,
+ themeMatchCount,
+ nextThemeQuestion,
+ moreThemeMatches,
+ replaceThemeQuestion,
+} from '../src/lib/themeMatch.js';
+import { fixtureBank } from './fixtures.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const realBank = JSON.parse(readFileSync(join(here, '../content/questions.json'), 'utf8'));
+const realTags = JSON.parse(readFileSync(join(here, '../content/tags.json'), 'utf8'));
+const real = flattenQuestions(realBank.categories);
+const fixture = flattenQuestions(fixtureBank().categories);
+
+describe('tokens', () => {
+ it('stems plurals, verb forms and a few derivations', () => {
+ expect(themeStem('jobs')).toBe('job');
+ expect(themeStem('stories')).toBe('story');
+ expect(themeStem('friendship')).toBe('friend');
+ expect(themeStem('grateful')).toBe('gratitude');
+ expect(themeStem('traveling')).toBe('travel');
+ });
+ it('drops stop words, including "theme" itself', () => {
+ expect(themeTokens('The theme of the day: first Jobs!')).toEqual(['first', 'job']);
+ });
+ it('cleanThemeInput collapses whitespace and caps the length', () => {
+ expect(cleanThemeInput(' travel \n disasters ')).toBe('travel disasters');
+ expect(cleanThemeInput('x'.repeat(100))).toHaveLength(THEME_MAX_LENGTH);
+ expect(cleanThemeInput(null)).toBe('');
+ });
+});
+
+describe('keywordThemeMatch on the real bank', () => {
+ const top = (theme, n = 3) => keywordThemeMatch(real, theme).slice(0, n).map((m) => m.q.text);
+
+ it('finds the obvious first-job question first', () => {
+ expect(top('first jobs', 1)[0]).toMatch(/first job/i);
+ });
+ it('reaches synonyms: an ocean theme finds the sea, but not any mention of water', () => {
+ const texts = keywordThemeMatch(real, 'the ocean').map((m) => m.q.text);
+ expect(texts.some((t) => /\bsea\b/i.test(t))).toBe(true);
+ expect(texts.some((t) => /hot water/i.test(t))).toBe(false);
+ });
+ it('matches gratitude through "thanked" and "grateful"', () => {
+ const texts = keywordThemeMatch(real, 'gratitude').map((m) => m.q.text);
+ expect(texts.some((t) => /grateful/i.test(t))).toBe(true);
+ expect(texts.some((t) => /thanked/i.test(t))).toBe(true);
+ });
+ it('explains each match with the theme word it hit', () => {
+ const [first] = keywordThemeMatch(real, 'first jobs');
+ expect(first.words).toEqual(expect.arrayContaining(['first', 'job']));
+ });
+ it('returns nothing for a theme the bank never mentions', () => {
+ expect(keywordThemeMatch(real, 'zombies')).toEqual([]);
+ expect(keywordThemeMatch(real, 'the of and')).toEqual([]);
+ });
+});
+
+describe('quick match with theme tags', () => {
+ const shortlist = (theme, tags = realTags) => buildThemeQueue(real, theme, [], 1, tags).slice(0, SHORTLIST_SIZE);
+
+ it('finds abstract themes the text rarely names: a full list for gratitude and second chances', () => {
+ expect(shortlist('gratitude', {}).filter((q) => q.source !== 'general').length).toBeLessThan(SHORTLIST_SIZE);
+ expect(shortlist('gratitude').every((q) => q.source === 'tag')).toBe(true);
+ // The wording may name "second chance" in a question or two, but never enough to fill a list.
+ const byText = shortlist('second chances', {}).filter((q) => q.source !== 'general');
+ expect(byText.length).toBeLessThan(SHORTLIST_SIZE);
+ expect(shortlist('second chances').filter((q) => q.source === 'tag').length).toBeGreaterThan(byText.length);
+ expect(shortlist('second chances').filter((q) => q.source === 'tag').length).toBeGreaterThanOrEqual(5);
+ });
+
+ it('says which tag matched', () => {
+ const [first] = shortlist('courage');
+ expect(first.source).toBe('tag');
+ expect(first.why).toBe('about “courage”');
+ expect(realTags[first.id]).toContain('courage');
+ });
+
+ it('ranks a tag that is exactly the typed phrase first', () => {
+ const [m] = keywordThemeMatch(real, 'first job', realTags);
+ expect(m.tag).toBe('first job');
+ });
+
+ it('mixes categories: no more than 3 from one category while others match', () => {
+ const counts = {};
+ for (const q of shortlist('friendship')) counts[q.category] = (counts[q.category] || 0) + 1;
+ expect(Math.max(...Object.values(counts))).toBeLessThanOrEqual(3);
+ });
+
+ it('a theme the tags never mention still falls back to general questions', () => {
+ expect(shortlist('zombies').every((q) => q.source === 'general')).toBe(true);
+ });
+
+ it('ignores tags for ids that are not in the pool, and a missing tag list', () => {
+ expect(() => buildThemeQueue(real, 'gratitude', [], 1, { 'nope-001': ['gratitude'], [real[0].id]: null })).not.toThrow();
+ });
+});
+
+describe('buildThemeQueue', () => {
+ it('puts the AI picks first, in order, with their reasons, and skips unknown ids', () => {
+ const picks = [
+ { id: real[5].id, why: 'reason five' },
+ { id: 'no-such-question-999', why: 'ghost' },
+ { id: real[2].id, why: 'reason two' },
+ ];
+ const queue = buildThemeQueue(real, 'gratitude', picks, 7);
+ expect(queue.slice(0, 2).map((q) => [q.id, q.why, q.source])).toEqual([
+ [real[5].id, 'reason five', 'ai'],
+ [real[2].id, 'reason two', 'ai'],
+ ]);
+ expect(queue.some((q) => q.id === 'no-such-question-999')).toBe(false);
+ });
+
+ it('gives an AI pick without a reason a neutral one, never "General pick"', () => {
+ const [first] = buildThemeQueue(real, 'gratitude', [{ id: real[5].id, why: '' }], 7);
+ expect([first.id, first.why, first.source]).toEqual([real[5].id, 'Fits the theme', 'ai']);
+ });
+
+ it('follows with keyword matches, then general picks, and holds every question exactly once', () => {
+ const queue = buildThemeQueue(real, 'first jobs', [], 7);
+ expect(queue[0].source).toBe('keyword');
+ expect(queue[0].why).toMatch(/^mentions “/);
+ const sources = queue.map((q) => q.source);
+ expect(sources.indexOf('general')).toBeGreaterThan(sources.lastIndexOf('keyword'));
+ expect(new Set(queue.map((q) => q.id)).size).toBe(real.length);
+ expect(queue).toHaveLength(real.length);
+ });
+
+ it('never leaves the shortlist empty: a theme with no match falls back to general questions', () => {
+ const queue = buildThemeQueue(real, 'zombies', [], 3);
+ expect(themeMatchCount(queue)).toBe(0);
+ expect(queue.slice(0, SHORTLIST_SIZE)).toHaveLength(SHORTLIST_SIZE);
+ expect(queue.slice(0, SHORTLIST_SIZE).every((q) => q.source === 'general' && q.why === 'General pick')).toBe(true);
+ // Broad categories come first.
+ expect(['contest-style', 'icebreakers', 'storytelling']).toContain(queue[0].category);
+ });
+
+ it('starts the general picks with the category the matches came from', () => {
+ const queue = buildThemeQueue(real, 'first jobs', [], 9);
+ const firstGeneral = queue.find((q) => q.source === 'general');
+ expect(firstGeneral.category).toBe(queue[0].category);
+ });
+
+ it('is deterministic for a seed and varies across seeds', () => {
+ const a = buildThemeQueue(real, 'zombies', [], 1).slice(0, 8).map((q) => q.id);
+ expect(buildThemeQueue(real, 'zombies', [], 1).slice(0, 8).map((q) => q.id)).toEqual(a);
+ expect(buildThemeQueue(real, 'zombies', [], 2).slice(0, 8).map((q) => q.id)).not.toEqual(a);
+ });
+
+ it('works on an empty bank without throwing', () => {
+ expect(buildThemeQueue([], 'gratitude', [{ id: 'x', why: 'y' }])).toEqual([]);
+ });
+});
+
+describe('replace and more', () => {
+ const queue = buildThemeQueue(fixture, 'habit', [], 4);
+ const first = () => queue.slice(0, 4);
+
+ it('nextThemeQuestion skips excluded ids', () => {
+ expect(nextThemeQuestion(queue, new Set([queue[0].id])).id).toBe(queue[1].id);
+ expect(nextThemeQuestion([], new Set())).toBeNull();
+ });
+
+ it('replace swaps one entry for the next unused one', () => {
+ const shown = first();
+ const used = new Set(shown.map((q) => q.id));
+ const next = replaceThemeQuestion(queue, shown, 1, used);
+ expect(next[0]).toBe(shown[0]);
+ expect(next[1].id).toBe(queue[4].id);
+ expect(next[2]).toBe(shown[2]);
+ expect(used.has(queue[4].id)).toBe(true);
+ });
+
+ it('more keeps picked entries in place and refreshes the rest', () => {
+ const shown = first();
+ const used = new Set(shown.map((q) => q.id));
+ const picked = new Set([shown[2].id]);
+ const { shown: next, cycled } = moreThemeMatches(queue, shown, picked, used);
+ expect(cycled).toBe(false);
+ expect(next[2]).toBe(shown[2]);
+ expect(next.map((q) => q.id)).toEqual([queue[4].id, queue[5].id, shown[2].id, queue[6].id]);
+ });
+
+ it('more starts over when the queue runs dry, without repeating what is on screen', () => {
+ const small = queue.slice(0, 5);
+ const shown = small.slice(0, 4);
+ const used = new Set(shown.map((q) => q.id));
+ const { shown: next, cycled } = moreThemeMatches(small, shown, new Set(), used);
+ expect(cycled).toBe(true);
+ expect(next).toHaveLength(4);
+ expect(new Set(next.map((q) => q.id)).size).toBe(4);
+ });
+
+ it('a list as long as the queue cannot be refreshed and stays as it is', () => {
+ const tiny = queue.slice(0, 2);
+ const { shown: next } = moreThemeMatches(tiny, tiny, new Set(), new Set(tiny.map((q) => q.id)));
+ expect(next.map((q) => q.id)).toEqual(tiny.map((q) => q.id));
+ expect(replaceThemeQuestion(tiny, tiny, 0, new Set())).toEqual(tiny);
+ });
+});
diff --git a/apps/table-topics/test/validate.test.js b/apps/table-topics/test/validate.test.js
index e6155340..8dc9b491 100644
--- a/apps/table-topics/test/validate.test.js
+++ b/apps/table-topics/test/validate.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { validateBank, nextId } from '../src/lib/validate.js';
+import { validateBank, validateTags, nextId } from '../src/lib/validate.js';
import { normalizeText, tokenJaccard } from '../src/lib/normalize.js';
function q(slug, n, text, added = '2026-09-02') {
@@ -67,3 +67,50 @@ describe('normalize', () => {
expect(tokenJaccard('apple pear', 'car train')).toBe(0);
});
});
+
+describe('validateTags', () => {
+ const ok = ['gratitude', 'first job', 'self-care', 'role model', 'joy'];
+ const ids = good.categories.flatMap((c) => c.questions.map((x) => x.id));
+
+ it('accepts well-formed tags and lists untagged and unknown ids', () => {
+ const r = validateTags({ [ids[0]]: ok, 'gamma-001': ok }, good);
+ expect(r.problems).toEqual([]);
+ expect(r.untagged).toEqual(ids.slice(1));
+ expect(r.unknown).toEqual(['gamma-001']);
+ });
+
+ it('every real question is tagged, and the real tags are well formed', async () => {
+ const { readFileSync } = await import('node:fs');
+ const real = JSON.parse(readFileSync(new URL('../content/questions.json', import.meta.url), 'utf8'));
+ const tags = JSON.parse(readFileSync(new URL('../content/tags.json', import.meta.url), 'utf8'));
+ const r = validateTags(tags, real);
+ expect(r.problems).toEqual([]);
+ expect(r.untagged).toEqual([]);
+ });
+
+ it('flags the wrong count, bad characters, long and duplicate tags', () => {
+ const r = validateTags(
+ {
+ [ids[0]]: ['one', 'two'],
+ [ids[1]]: ['Gratitude', 'joy!', 'ok tag', 'x'.repeat(31), 'a b'],
+ [ids[2]]: ['joy', 'joy', 'fun', 'smile', 'play'],
+ [ids[3]]: 'gratitude',
+ },
+ good
+ ).problems;
+ expect(r).toEqual([
+ `${ids[0]}: 2 tags, expected 5–8`,
+ `${ids[1]}: bad tag "Gratitude" (lowercase letters, spaces, hyphens; at most 30 chars)`,
+ `${ids[1]}: bad tag "joy!" (lowercase letters, spaces, hyphens; at most 30 chars)`,
+ `${ids[1]}: bad tag "${'x'.repeat(31)}" (lowercase letters, spaces, hyphens; at most 30 chars)`,
+ `${ids[1]}: bad tag "a b" (lowercase letters, spaces, hyphens; at most 30 chars)`,
+ `${ids[2]}: duplicate tag "joy"`,
+ `${ids[3]}: tags must be an array`,
+ ]);
+ });
+
+ it('rejects a file that is not an object of lists', () => {
+ expect(validateTags([], good).problems).toEqual(['tags must be an object of id -> tag list']);
+ expect(validateTags(null, good).problems).toEqual(['tags must be an object of id -> tag list']);
+ });
+});
diff --git a/apps/web/public/404.html b/apps/web/public/404.html
index 1dffc956..b2ad435a 100644
--- a/apps/web/public/404.html
+++ b/apps/web/public/404.html
@@ -96,6 +96,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/best-toastmasters-timer-apps.html b/apps/web/public/best-toastmasters-timer-apps.html
index 3de0f78e..e4bddbe5 100644
--- a/apps/web/public/best-toastmasters-timer-apps.html
+++ b/apps/web/public/best-toastmasters-timer-apps.html
@@ -399,6 +399,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/how-to-use-zoom-for-toastmasters.html b/apps/web/public/how-to-use-zoom-for-toastmasters.html
index cf424a77..749308b7 100644
--- a/apps/web/public/how-to-use-zoom-for-toastmasters.html
+++ b/apps/web/public/how-to-use-zoom-for-toastmasters.html
@@ -363,6 +363,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/table-topics-timer.html b/apps/web/public/table-topics-timer.html
index 12947bf9..3586934c 100644
--- a/apps/web/public/table-topics-timer.html
+++ b/apps/web/public/table-topics-timer.html
@@ -342,6 +342,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-speech-contest-timing-rules.html b/apps/web/public/toastmasters-speech-contest-timing-rules.html
index c686e219..c1065509 100644
--- a/apps/web/public/toastmasters-speech-contest-timing-rules.html
+++ b/apps/web/public/toastmasters-speech-contest-timing-rules.html
@@ -424,6 +424,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-speech-types-and-timing.html b/apps/web/public/toastmasters-speech-types-and-timing.html
index 19a44d9c..7db3f10d 100644
--- a/apps/web/public/toastmasters-speech-types-and-timing.html
+++ b/apps/web/public/toastmasters-speech-types-and-timing.html
@@ -568,6 +568,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-timer-demo.html b/apps/web/public/toastmasters-timer-demo.html
index fe45c02e..a04f1074 100644
--- a/apps/web/public/toastmasters-timer-demo.html
+++ b/apps/web/public/toastmasters-timer-demo.html
@@ -115,7 +115,7 @@ What You'll See in This Demo
Timing rules that load themselves — pick the speaker and their role, and the rules load automatically. Every rule can be changed, and you can add your own roles.
Next speaker, one click — press Finish and the next speaker is ready.
Bigger signals — put the color behind you, replace your video with it, or go full screen and share it.
- Agenda import — paste your agenda straight from EasySpeak. Speakers and roles are picked up for you, and you can drag to reorder.
+ Agenda import — paste your agenda straight from EasySpeak. Speakers are picked up for you, each with its role when that role is in your role list, and you can drag to reorder.
Automatic report — when the meeting ends, your timing report is already written.
Club card artwork (Pro) — use your club's own card artwork.
@@ -137,8 +137,8 @@ Video Transcript
Want a bigger signal? Put the colour behind you, replace your video, or go full screen and share
- it. Paste your agenda straight from EasySpeak. Speakers and roles are picked up for you. Drag to
- reorder. And when the meeting ends, your Timer's report is already written.
+ it. Paste your agenda straight from EasySpeak. Speakers are picked up for you, each with its role
+ when that role is in your role list. Drag to reorder. And when the meeting ends, your Timer's report is already written.
Every timing rule is yours to change. Add your own roles. And with Pro, use your club's own card
@@ -203,6 +203,7 @@
Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-timer-role-guide.html b/apps/web/public/toastmasters-timer-role-guide.html
index 5bb3e108..f4871e78 100644
--- a/apps/web/public/toastmasters-timer-role-guide.html
+++ b/apps/web/public/toastmasters-timer-role-guide.html
@@ -298,6 +298,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-timer-script.html b/apps/web/public/toastmasters-timer-script.html
index 4fb30b24..c8b8e657 100644
--- a/apps/web/public/toastmasters-timer-script.html
+++ b/apps/web/public/toastmasters-timer-script.html
@@ -337,6 +337,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-timer-zoom-demo.html b/apps/web/public/toastmasters-timer-zoom-demo.html
index 41fca9fa..7d7b52cc 100644
--- a/apps/web/public/toastmasters-timer-zoom-demo.html
+++ b/apps/web/public/toastmasters-timer-zoom-demo.html
@@ -172,6 +172,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-timing-chart.html b/apps/web/public/toastmasters-timing-chart.html
index 5f9e3ef4..3f585e44 100644
--- a/apps/web/public/toastmasters-timing-chart.html
+++ b/apps/web/public/toastmasters-timing-chart.html
@@ -533,6 +533,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/toastmasters-zoom-timer-backgrounds.html b/apps/web/public/toastmasters-zoom-timer-backgrounds.html
index 7053259d..40321ce7 100644
--- a/apps/web/public/toastmasters-zoom-timer-backgrounds.html
+++ b/apps/web/public/toastmasters-zoom-timer-backgrounds.html
@@ -360,6 +360,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/public/tutorials.html b/apps/web/public/tutorials.html
index 8d8b0017..05aa45cb 100644
--- a/apps/web/public/tutorials.html
+++ b/apps/web/public/tutorials.html
@@ -87,7 +87,7 @@
"item": {
"@type": "VideoObject",
"name": "Load your agenda in 30 seconds",
- "description": "Import a meeting agenda from EasySpeak into the Toastmasters Timer: roles and time limits load for every speaker.",
+ "description": "Import a meeting agenda from EasySpeak into the Toastmasters Timer: every speaker is listed, with the time limits of a role that is in your role list.",
"thumbnailUrl": "https://www.toastmusters.com/video/tutorials/agenda-poster.jpg",
"uploadDate": "2026-10-15",
"duration": "PT30S",
@@ -264,6 +264,7 @@ Load your agenda in 30 seconds
Transcript
Typing every speaker, role and time limit takes minutes. Skip it. Open the Agenda tab, tap Import Text, and paste your meeting roles. Or the whole EasySpeak page. Every speaker comes in with the right role, and the right time limits. Drag them into running order. Back on the Live tab, tap the name field. Everyone on your agenda is right there. Pick one, and their time limits load. Toastmasters Timer. Free in the Zoom App Marketplace.
+ Since this video: a speaker comes in with a role, and its time limits, when the agenda names a role that is in your role list, however it is spelt. You pick the role for any other speaker on the Agenda tab.
@@ -397,6 +398,7 @@ Get Started
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/src/components/AgendaTab.jsx b/apps/web/src/components/AgendaTab.jsx
index bb6c7e44..1052a2ae 100644
--- a/apps/web/src/components/AgendaTab.jsx
+++ b/apps/web/src/components/AgendaTab.jsx
@@ -1,4 +1,4 @@
-import { useState, memo } from 'react';
+import { useState, useCallback, memo } from 'react';
import { useTimer } from '../context/TimerContext';
import { useToast } from '../context/ToastContext';
import { Plus, Upload, X, Edit2, Trash2, GripVertical, Check, AlertTriangle } from 'lucide-react';
@@ -19,8 +19,10 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
-import { DEFAULT_ROLE_RULES, DEFAULT_CUSTOM_RULES, loadTimeInputMode, saveTimeInputMode, agendaItemNeedsRole } from '@toastmaster-timer/shared';
+import { AGENDA_FILE_ACCEPT, DEFAULT_ROLE_RULES, DEFAULT_CUSTOM_RULES, loadTimeInputMode, saveTimeInputMode, agendaItemNeedsRole, agendaReadRoles, agendaReadRoleTimes, readAgendaText, readAgendaForImport } from '@toastmaster-timer/shared';
+import AgendaImportPanel, { useAgendaImport } from '@toastmaster-timer/ui/AgendaImport';
import TimeInput, { TimeInputModeToggle } from './TimeInput';
+import { useAgendaAiAccess } from '../hooks/useAgendaAi';
import { trackEvent } from '../utils/posthog';
@@ -58,7 +60,7 @@ function SortableItem({ item, isActive, isCompleted, needsRole, roleOptions, onP
}
export default memo(function AgendaTab({ onSwitchToLive }) {
- const { agenda, activeSpeakerId, addToAgenda, removeFromAgenda, reorderAgenda, updateAgendaItem, loadSpeakerFromAgenda, importBulkSpeakers, importEasySpeakSpeakers, clearAllAgenda, roleRules, roleOptions } = useTimer();
+ const { agenda, activeSpeakerId, addToAgenda, removeFromAgenda, reorderAgenda, updateAgendaItem, loadSpeakerFromAgenda, importBulkSpeakers, importAgendaText, importAgendaItems, clearAllAgenda, roleRules, roleOptions } = useTimer();
const { showToast } = useToast();
// Standard Speech unless it was removed in Edit Rules; then the first listed
// role, so the picker never shows one role while saving another.
@@ -67,9 +69,6 @@ export default memo(function AgendaTab({ onSwitchToLive }) {
const needsRoleCount = agenda.filter(needsRole).length;
const [showImportModal, setShowImportModal] = useState(false);
const [showAddModal, setShowAddModal] = useState(false);
- const [importTab, setImportTab] = useState('easyspeak');
- const [importText, setImportText] = useState('');
- const [easySpeakText, setEasySpeakText] = useState('');
const [editItem, setEditItem] = useState(null);
const [newSpeakerName, setNewSpeakerName] = useState('');
const [newSpeakerRole, setNewSpeakerRole] = useState(defaultRole);
@@ -91,23 +90,37 @@ export default memo(function AgendaTab({ onSwitchToLive }) {
trackEvent('agenda_reordered', { items_count: newOrder.length });
};
- const handleSimpleImport = () => {
- if (importText.trim()) {
- const { count, needsRole: unmatched } = importBulkSpeakers(importText);
- if (unmatched > 0) showToast(`Imported ${count} speaker(s). ${unmatched} need${unmatched === 1 ? 's' : ''} a role`, 'warning');
- else showToast(`Imported ${count} speaker(s)`, 'success');
- setImportText('');
- setShowImportModal(false);
- }
- };
- const handleEasySpeakImport = () => {
- if (easySpeakText.trim()) {
- const count = importEasySpeakSpeakers(easySpeakText);
- showToast(`Imported ${count} speaker(s)`, 'success');
- setEasySpeakText('');
- setShowImportModal(false);
- }
- };
+ // The import dialog (#111): one paste box, one reader and, for Pro, an
+ // AI read or an upload. The web session is a cookie, so the read needs no token.
+ const aiAccess = useAgendaAiAccess();
+ const matchImport = useCallback((text) => {
+ const { ok, items, leftOut, unused } = readAgendaText(text, roleOptions);
+ // Counted the way importAgendaText will store the rows: the role the agenda names, else the role as written.
+ const needs = (item) => agendaItemNeedsRole({ role: item.role ?? item.roleText ?? '' }, roleOptions);
+ return { recognised: ok, count: items.length, needsRole: items.filter(needs).length, leftOut, unused };
+ }, [roleOptions]);
+ // A row the Worker read has a role only when it names one of this user's roles.
+ const readRowNeedsRole = useCallback((item) => !roleOptions.includes(item.role), [roleOptions]);
+ const readImport = useCallback(
+ (input) => readAgendaForImport({ ...input, roles: agendaReadRoles(roleOptions), roleTimes: agendaReadRoleTimes(roleOptions, roleRules) }),
+ [roleOptions, roleRules]
+ );
+ const importFlow = useAgendaImport({
+ match: matchImport,
+ importText: importAgendaText,
+ importLines: importBulkSpeakers,
+ importItems: importAgendaItems,
+ read: readImport,
+ itemNeedsRole: readRowNeedsRole,
+ ai: aiAccess,
+ notify: showToast,
+ // In a new tab: the account page is another route, and going there in this
+ // one would unmount the timer, a running speech and the pasted agenda with it.
+ onUpgrade: () => { trackEvent('agenda_ai_upgrade_opened', {}); window.open('/account', '_blank', 'noopener'); },
+ onDone: () => setShowImportModal(false),
+ });
+ const openImport = () => { importFlow.reset(); setShowImportModal(true); };
+ const closeImport = () => { importFlow.reset(); setShowImportModal(false); };
const handleAdd = () => {
if (newSpeakerName.trim()) {
@@ -183,7 +196,7 @@ export default memo(function AgendaTab({ onSwitchToLive }) {
return (
-
{ setImportTab('easyspeak'); setImportText(''); setEasySpeakText(''); setShowImportModal(true); }} className="flex-1 bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg flex items-center justify-center gap-2">
+
Import Text
{ setEditItem(null); setNewSpeakerName(''); setNewSpeakerRole(defaultRole); setCustomRules({ ...DEFAULT_CUSTOM_RULES }); setShowAddModal(true); }} className="flex-1 bg-green-500 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded-lg flex items-center justify-center gap-2">
@@ -218,34 +231,12 @@ export default memo(function AgendaTab({ onSwitchToLive }) {
{showImportModal && (
-
+
Import Speakers
- { setShowImportModal(false); setImportText(''); setEasySpeakText(''); setImportTab('easyspeak'); }} className="text-gray-400 hover:text-gray-600">
-
-
- setImportTab('easyspeak')} className={`px-4 py-2 font-medium text-sm ${importTab === 'easyspeak' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'}`}>EasySpeak Format
- setImportTab('simple')} className={`px-4 py-2 font-medium text-sm ${importTab === 'simple' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'}`}>Simple Format
+
- {importTab === 'easyspeak' ? (
-
-
Paste meeting details from EasySpeak website.
-
- ) : (
-
-
One speaker per line with the role in parentheses, spelled as in your role list. Example: John Doe (Ice Breaker). A row whose role isn't in the list is highlighted so you can pick one.
-
- )}
+
)}
diff --git a/apps/web/src/components/AgendaTab.test.jsx b/apps/web/src/components/AgendaTab.test.jsx
index 7712b576..88cdb3c2 100644
--- a/apps/web/src/components/AgendaTab.test.jsx
+++ b/apps/web/src/components/AgendaTab.test.jsx
@@ -1,8 +1,38 @@
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { resetEntitlementForTests, resetFlagsForTests, setEntitlement, setFlags } from '@toastmaster-timer/shared';
import AgendaTab from './AgendaTab';
import { renderWithProviders } from '../test/helpers';
+/** Agenda tab -> Import Text, paste into the one box, press Import. */
+const openImport = (user) => user.click(screen.getByRole('button', { name: /import text/i }));
+const pasteAgenda = async (user, text) => {
+ await openImport(user);
+ await user.click(screen.getByRole('textbox', { name: 'Agenda text' }));
+ await user.paste(text);
+};
+const importPaste = async (user, text) => {
+ await pasteAgenda(user, text);
+ await user.click(screen.getByRole('button', { name: /^import$/i }));
+};
+const savedAgenda = () => JSON.parse(localStorage.getItem('toastmaster_agenda'));
+
+// A schedule in no format the app reads: clock times and free wording.
+const UNKNOWN_FORMAT = [
+ '6:30 PM Call to order, Sergeant at Arms: Mike',
+ '6:40 PM Speech 1: "My Journey" by John Smith, 5 to 7 minutes',
+ '6:50 PM Evaluation of speech 1 by Mary Jones',
+].join('\n');
+
+beforeEach(() => {
+ resetFlagsForTests();
+ resetEntitlementForTests();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
describe('AgendaTab', () => {
describe('empty state', () => {
it('shows "No speakers in agenda" message', () => {
@@ -154,15 +184,8 @@ describe('AgendaTab', () => {
});
describe('roles that need picking (#91)', () => {
- const importSimple = async (user, text) => {
- await user.click(screen.getByRole('button', { name: /import text/i }));
- await user.click(screen.getByRole('button', { name: 'Simple Format' }));
- await user.click(screen.getByRole('textbox'));
- await user.paste(text);
- await user.click(screen.getByRole('button', { name: /^import$/i }));
- };
+ const importSimple = importPaste;
const row = (name) => screen.getByText(name, { selector: '.font-medium' }).closest('[data-needs-role], div.flex');
- const savedAgenda = () => JSON.parse(localStorage.getItem('toastmaster_agenda'));
const banner = () => screen.queryByText(/a role\. Nothing was guessed/);
it('highlights lines whose role is not one of yours, and says how many', async () => {
@@ -275,6 +298,149 @@ describe('AgendaTab', () => {
});
});
+ describe('one paste box, one reader (#111)', () => {
+ it('has one text box and no format tabs', async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
);
+ await openImport(user);
+
+ const dialog = screen.getByRole('dialog', { name: 'Import Speakers' });
+ expect(within(dialog).getAllByRole('textbox')).toHaveLength(1);
+ expect(within(dialog).queryByRole('button', { name: 'EasySpeak Format' })).not.toBeInTheDocument();
+ expect(within(dialog).queryByRole('button', { name: 'Simple Format' })).not.toBeInTheDocument();
+ });
+
+ it('reads a table of roles and names, and says what it left out', async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
);
+
+ await pasteAgenda(user, 'Timer\tRachel Adams\n1st Speaker\tSarah Chen\nIce Breaker\tEmily Brown');
+ // A role is matched by its own name: "Ice Breaker" is one of the default roles, "1st Speaker" is not.
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Found 2 speakers. 1 needs a role: you pick it after import. 1 left out: the timer does not time that role.'
+ );
+ await user.click(screen.getByRole('button', { name: /^import$/i }));
+
+ expect(await screen.findByText('Imported 2 speaker(s). 1 needs a role')).toBeInTheDocument();
+ expect(savedAgenda().map((item) => [item.name, item.role, Boolean(item.rules)])).toEqual([
+ ['Sarah Chen', '1st Speaker', false],
+ ['Emily Brown', 'Ice Breaker', true],
+ ]);
+ });
+
+ it('reads a role set off by a dash or a colon, and a role in any spelling', async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
);
+
+ await pasteAgenda(user, 'Ana - Ice Breaker\nSTANDARDSPEECH: Ben\nCy | speech-evaluation');
+ expect(screen.getByRole('status')).toHaveTextContent('Found 3 speakers.');
+ await user.click(screen.getByRole('button', { name: /^import$/i }));
+
+ expect(await screen.findByText('Imported 3 speaker(s)')).toBeInTheDocument();
+ expect(savedAgenda().map((item) => [item.name, item.role])).toEqual([
+ ['Ana', 'Ice Breaker'],
+ ['Ben', 'Standard Speech'],
+ ['Cy', 'Speech Evaluation'],
+ ]);
+ });
+
+ it("puts the rows of a table on the user's own roles of those names, and asks for the rest", async () => {
+ // A club that removed every built-in role and made its own.
+ const oneMinute = { green: 30, yellow: 45, red: 60, graceAfterRed: 15 };
+ localStorage.setItem(
+ 'toastmaster_hidden_builtin_roles',
+ JSON.stringify(['Short Roles', 'Table Topics Speech', 'Table Topics Evaluation', 'Standard Speech', 'Ice Breaker', 'Speech Evaluation', 'General Evaluation', 'Custom'])
+ );
+ localStorage.setItem('toastmaster_role_rules', JSON.stringify({ Grammarian: { green: 15, yellow: 30, red: 45, graceAfterRed: 10 }, '1min Role': oneMinute }));
+ localStorage.setItem('toastmaster_role_order', JSON.stringify(['Grammarian', '1min Role']));
+ const user = userEvent.setup();
+ renderWithProviders(
);
+
+ await pasteAgenda(user, '1st Speaker\tSarah Chen\nGrammarian\tPriya Sharma\nAh Counter\tJordan Blake');
+ expect(screen.getByRole('status')).toHaveTextContent('Found 3 speakers. 2 need a role: you pick it after import.');
+ await user.click(screen.getByRole('button', { name: /^import$/i }));
+
+ expect(await screen.findByText('Imported 3 speaker(s). 2 need a role')).toBeInTheDocument();
+ // The Grammarian landed on the club's own Grammarian; the other two say what the agenda called them.
+ expect(screen.getByText('(1st Speaker) is not one of your roles')).toBeInTheDocument();
+ expect(screen.getByText('(Ah Counter) is not one of your roles')).toBeInTheDocument();
+ expect(screen.queryByRole('combobox', { name: 'Pick a role for Priya Sharma' })).not.toBeInTheDocument();
+ expect(savedAgenda().map((item) => [item.name, item.role, Boolean(item.rules)])).toEqual([
+ ['Sarah Chen', '1st Speaker', false],
+ ['Priya Sharma', 'Grammarian', true],
+ ['Jordan Blake', 'Ah Counter', false],
+ ]);
+
+ // Picked by hand, a row times with that role's own rules.
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Pick a role for Jordan Blake' }), '1min Role');
+ await waitFor(() => expect(savedAgenda()[2]).toMatchObject({ name: 'Jordan Blake', role: '1min Role', rules: oneMinute }));
+ });
+
+ it('adds nothing from a text it cannot tell the rows of, and offers each line as a speaker', async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
);
+
+ await pasteAgenda(user, UNKNOWN_FORMAT);
+
+ expect(screen.getByRole('status')).toHaveTextContent("We don't recognise this format.");
+ expect(screen.getByRole('button', { name: /^import$/i })).toBeDisabled();
+ expect(screen.queryByRole('button', { name: /upload a photo or file/i })).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: 'Add each line as a speaker' }));
+ expect(await screen.findByText('Imported 3 speaker(s). 3 need a role')).toBeInTheDocument();
+ });
+ });
+
+ describe('AI import (#111)', () => {
+ const AI_ITEMS = [
+ { name: 'John Smith', role: 'Standard Speech', roleText: 'Speech 1' },
+ { name: 'Raj Patel', role: null, roleText: 'Word of the day' },
+ ];
+ const answer = (body, status = 200) => vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+ it('reads a text no format matched with the cookie session, and adds it on confirm', async () => {
+ setFlags({ pro: true, agenda_ai: true });
+ setEntitlement({ plan: 'pro', entitled: true, source: 'subscription' });
+ const fetchMock = answer({ items: AI_ITEMS, via: 'ai', provider: 'openrouter' });
+ vi.stubGlobal('fetch', fetchMock);
+ const user = userEvent.setup();
+ renderWithProviders(
);
+
+ await pasteAgenda(user, UNKNOWN_FORMAT);
+ await user.click(screen.getByRole('button', { name: 'Read with AI' }));
+ expect(await screen.findByRole('list', { name: 'Speakers found' })).toBeInTheDocument();
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/agenda/import');
+ // No bearer on the web: the session is the cookie.
+ expect(init.headers.Authorization).toBeUndefined();
+ expect(init.credentials).toBe('same-origin');
+
+ await user.click(screen.getByRole('button', { name: 'Add 2 speakers' }));
+ expect(await screen.findByText('Imported 2 speaker(s). 1 needs a role')).toBeInTheDocument();
+ expect(savedAgenda()).toMatchObject([
+ { name: 'John Smith', role: 'Standard Speech' },
+ { name: 'Raj Patel', role: 'Word of the day' },
+ ]);
+ });
+
+ it('opens the account page beside the timer for a free plan, and keeps the pasted text', async () => {
+ setFlags({ pro: true, agenda_ai: true });
+ setEntitlement({ plan: 'free', entitled: false });
+ const opened = vi.fn();
+ vi.stubGlobal('open', opened);
+ const user = userEvent.setup();
+ renderWithProviders(
);
+ await pasteAgenda(user, UNKNOWN_FORMAT);
+
+ await user.click(screen.getByRole('button', { name: 'Upload a photo or file (Pro)' }));
+
+ // A new tab: going to /account in this one would unmount the timer.
+ expect(opened).toHaveBeenCalledWith('/account', '_blank', 'noopener');
+ expect(screen.getByRole('textbox', { name: 'Agenda text' })).toHaveValue(UNKNOWN_FORMAT);
+ });
+ });
+
describe('switching to live tab', () => {
it('calls onSwitchToLive when a speaker item is clicked', async () => {
const user = userEvent.setup();
diff --git a/apps/web/src/components/ClubCodeSection.jsx b/apps/web/src/components/ClubCodeSection.jsx
index d39bada5..ce6225ff 100644
--- a/apps/web/src/components/ClubCodeSection.jsx
+++ b/apps/web/src/components/ClubCodeSection.jsx
@@ -1,26 +1,53 @@
import React, { useState, useSyncExternalStore } from 'react'
import { Users, Check } from 'lucide-react'
import { loadClub, activateClub, leaveClub, subscribeClub } from '@toastmaster-timer/shared'
-import { useEntitlement } from '../hooks/useEntitlement'
+import { useEntitlement, useWebIdentity } from '../hooks/useEntitlement'
import { useFlag } from '../hooks/useFlag'
+import { resolveWebIdentity, signInUrl } from '../utils/webIdentity'
import { trackEvent } from '../utils/posthog'
/**
- * Joining a club, and seeing the one this browser already joined.
+ * Joining a club, and seeing the one this account is in.
*
* Shared by /account and /pro/
, which are the same transaction reached
* two ways: the officer's link carries the code, and the account page is where
- * a timer types it. Both end on the same confirmation, so a person who followed
- * a link and a person who typed see the product say the same thing.
+ * a timer types it. Club Pro belongs to a Zoom account (#167), so both need a
+ * Zoom sign-in, and a signed-out browser is sent through one that comes back
+ * to /pro/.
*/
-/** Every rejection looks the same on the server, so there is one line to show. */
+/**
+ * A wrong code, a lapsed club and a blocked account all look the same on the
+ * server, so they share one line; the refusals a person can act on name what
+ * to do.
+ */
const CLUB_ERRORS = {
network: 'Could not reach the server. Check your connection and try again.',
too_many_attempts: 'Too many tries. Wait a minute, then try again.',
}
const CLUB_ERROR_FALLBACK = "That code isn't active. Check with your club officer."
+/** The line to show for a refused code. */
+export function clubErrorFor(result) {
+ if (result.error === 'full') {
+ return `This club's Pro is full (${result.placesUsed ?? 3} of ${result.placesTotal ?? 3}). Ask the person who shared the code to free a place.`
+ }
+ if (result.error === 'already_in_club') {
+ return `You're already in ${result.clubName || 'another club'}. Leave it to join another club.`
+ }
+ return CLUB_ERRORS[result.error] || CLUB_ERROR_FALLBACK
+}
+
+const leaveCopy = (name) => `Leave ${name}? You'll lose its Pro on every computer where you're signed in.`
+
+/** Why leaving was refused. The owner never sees Leave, but the server says so too. */
+const LEAVE_ERRORS = {
+ last_admin: 'A club needs at least one admin. Promote somebody else first.',
+ owner: 'The club’s owner can’t leave it. To end it, cancel the subscription.',
+ network: 'Could not reach the server. Check your connection and try again.',
+}
+const LEAVE_ERROR_FALLBACK = 'Could not leave the club. Please try again.'
+
export function useClub() {
return useSyncExternalStore(subscribeClub, loadClub, () => null)
}
@@ -38,20 +65,40 @@ export default function ClubCodeSection({ source = 'web_account', identified = f
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
+ // Set when a code was entered without a Zoom sign-in behind it.
+ const [needsSignIn, setNeedsSignIn] = useState(false)
+ // The page's own answer on who this is; the prop is false until it lands.
+ const identity = useWebIdentity()
+ const signedOut = !identified && identity !== null && !identity.identified
+ // Signed out, the code goes to the sign-in rather than the server, and the
+ // sign-in comes back to /pro/, which joins.
+ const typed = code.trim()
+ const signInHref = signInUrl(typed ? `/pro/${encodeURIComponent(typed)}` : '/account')
const handleActivate = async (event) => {
event?.preventDefault?.()
- if (busy || !code.trim()) return
- setBusy(true)
+ if (busy || !typed) return
setError(null)
- // No bearer on the web: the session, if there is one, travels as a cookie.
- const result = await activateClub(code)
+ // Asked again rather than trusted from the prop, which is false until the
+ // page's own identity call has answered.
+ const who = identified ? null : await resolveWebIdentity()
+ if (!identified && !who?.identified) {
+ setNeedsSignIn(true)
+ trackEvent('club_code_rejected', { surface: 'web', source, reason: 'sign_in_required' })
+ return
+ }
+
+ setBusy(true)
+ setNeedsSignIn(false)
+ // No bearer on the web: the session travels as a cookie.
+ const result = await activateClub(typed, who?.uid ? { uid: who.uid } : {})
setBusy(false)
if (!result.ok) {
- setError(CLUB_ERRORS[result.error] || CLUB_ERROR_FALLBACK)
trackEvent('club_code_rejected', { surface: 'web', source, reason: result.error })
+ if (result.error === 'sign_in_required') setNeedsSignIn(true)
+ else setError(clubErrorFor(result))
return
}
@@ -60,15 +107,21 @@ export default function ClubCodeSection({ source = 'web_account', identified = f
surface: 'web',
source,
club_id: result.club.club?.id ?? null,
- is_guest: !identified,
+ places_used: result.placesUsed,
via: 'typed',
})
onActivated?.(result.club)
}
- const handleLeave = () => {
+ // By account, on every computer it is signed in on, so it asks first.
+ const handleLeave = async () => {
const clubId = club?.club?.id ?? null
- leaveClub()
+ if (!window.confirm(leaveCopy(club?.club?.name || 'your club'))) return
+ const result = await leaveClub()
+ if (!result.ok) {
+ setError(LEAVE_ERRORS[result.error] || LEAVE_ERROR_FALLBACK)
+ return
+ }
setError(null)
trackEvent('club_left', { surface: 'web', source, club_id: clubId })
}
@@ -80,7 +133,7 @@ export default function ClubCodeSection({ source = 'web_account', identified = f
{club.club?.name || 'Your club'}
- This browser is on Pro through your club.
+ You're on Pro through {club.club?.name || 'your club'}.
Your club's shared timing presets
Your club's branding on cards and reports
@@ -90,18 +143,22 @@ export default function ClubCodeSection({ source = 'web_account', identified = f
{entitlement.source === 'club' && (
- Timing in Zoom too? Open the timer there, tap Upgrade and
- enter the same code.
+ Timing in Zoom too? Open the timer there with this same Zoom account: your club's Pro is
+ already there.
)}
- {/* A deletion, not a restore: this browser's own presets and artwork
- were never written over, so leaving cannot take them away. */}
-
- Leave this club on this device
-
+ {error && {error}
}
+ {/* The owner pays for the club and ends it by cancelling, so they are
+ never offered Leave. Nobody's own presets and artwork were written
+ over, so leaving cannot take them away. */}
+ {!club.isOwner && (
+
+ Leave {club.club?.name || 'this club'}
+
+ )}
>
)
}
@@ -114,7 +171,7 @@ export default function ClubCodeSection({ source = 'web_account', identified = f
Already on Pro through your club?
- Enter the code your club officer shared. No sign-in needed.
+ Enter the code your club officer shared. It joins the Zoom account you're signed in with.
{error && {error}
}
+ {(needsSignIn || signedOut) && (
+
+ Sign in with Zoom to join
+
+ )}
)
}
diff --git a/apps/web/src/components/ClubCodeSection.test.jsx b/apps/web/src/components/ClubCodeSection.test.jsx
new file mode 100644
index 00000000..9b6f29f0
--- /dev/null
+++ b/apps/web/src/components/ClubCodeSection.test.jsx
@@ -0,0 +1,268 @@
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+import { resetClubForTests, resetEntitlementForTests, resetFlagsForTests, setFlags } from '@toastmaster-timer/shared';
+import { resetWebIdentityForTests, signInUrl } from '../utils/webIdentity';
+import { trackEvent } from '../utils/posthog';
+import ClubCodeSection from './ClubCodeSection';
+
+/**
+ * The code field on /account (#167). Joining needs a Zoom sign-in, the joined
+ * state belongs to the account, Leave asks first, and the owner cannot leave.
+ */
+
+const CODE = 'DTSP-7K2QM9';
+
+const STATE = {
+ ver: 1,
+ club: { id: 'club-1', name: 'Downtown Speakers' },
+ kit: null,
+ presets: null,
+ badge: { x: 0.8, y: 0.12, scale: 0.12 },
+ cards: null,
+ timezone: null,
+ role: 'member',
+ isOwner: false,
+ code: null,
+ shareUrl: null,
+ plan: 'pro',
+ entitled: true,
+ status: 'active',
+ currentPeriodEnd: null,
+ cancelAtPeriodEnd: false,
+ source: 'club',
+ placesUsed: 2,
+};
+
+const copy = (text) =>
+ new RegExp(text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/'/g, "['\u2019]"));
+const sameText = (a, b) => a.replace(/\u2019/g, "'") === b.replace(/\u2019/g, "'");
+
+/** A fetch stub keyed by path, recording every call. */
+function stubApi({ me, activate = { status: 200, body: STATE }, leave = { status: 200, body: { left: true } } }) {
+ const calls = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url, init = {}) => {
+ const path = String(url).split('?')[0];
+ calls.push({ path, method: init.method || 'GET', body: init.body, headers: init.headers ?? {} });
+ const answer =
+ path === '/api/me'
+ ? me
+ : path === '/api/club/activate'
+ ? activate
+ : path === '/api/club/leave'
+ ? leave
+ : { status: 404, body: {} };
+ return {
+ ok: answer.status >= 200 && answer.status < 300,
+ status: answer.status,
+ json: async () => answer.body ?? {},
+ };
+ })
+ );
+ return calls;
+}
+
+const SIGNED_OUT = { status: 401, body: { error: 'Unauthorized' } };
+const SIGNED_IN = { status: 200, body: { uid: 'timer-uid', entitlement: { plan: 'free', entitled: false } } };
+
+const renderSection = ({ identified }) =>
+ render(
+
+
+
+ );
+
+const codeField = () => screen.queryByLabelText(/already on pro through your club/i) ?? screen.queryByRole('textbox');
+const callsTo = (calls, path) => calls.filter((call) => call.path === path);
+const headerNames = (call) => Object.keys(call.headers ?? {}).map((name) => name.toLowerCase());
+
+/** Type the code and submit it, the way a person on /account does. */
+async function enterCode(user, code = CODE) {
+ const field = await waitFor(() => {
+ const found = codeField();
+ expect(found).toBeTruthy();
+ return found;
+ });
+ await user.type(field, code);
+ await user.keyboard('{Enter}');
+}
+
+/**
+ * Answer the confirm, whichever way the page asks: window.confirm, or an in-app
+ * dialog with the same words.
+ */
+async function answerConfirm(user, message, { accept }) {
+ if (window.confirm.mock.calls.length) {
+ expect(sameText(window.confirm.mock.calls.at(-1)[0], message)).toBe(true);
+ return;
+ }
+ const dialog = screen.queryByRole('alertdialog') ?? (await screen.findByRole('dialog'));
+ expect(dialog).toHaveTextContent(copy(message));
+ const buttons = within(dialog).getAllByRole('button');
+ const choice = accept
+ ? buttons.find((button) => /leave/i.test(button.textContent))
+ : buttons.find((button) => /cancel|stay|keep/i.test(button.textContent));
+ await user.click(choice);
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ resetClubForTests();
+ resetWebIdentityForTests();
+ resetEntitlementForTests();
+ resetFlagsForTests();
+ setFlags({ pro: true });
+ trackEvent.mockClear();
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('ClubCodeSection: signed out (AC-1d)', () => {
+ it('sends nothing and offers a Zoom sign-in that returns to /pro/', async () => {
+ const user = userEvent.setup();
+ const calls = stubApi({ me: SIGNED_OUT });
+ renderSection({ identified: false });
+
+ await enterCode(user);
+
+ const link = await screen.findByRole('link', { name: /sign in with zoom to join/i });
+ expect(link).toHaveAttribute('href', signInUrl(`/pro/${CODE}`));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(callsTo(calls, '/api/club/activate')).toEqual([]);
+ await waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith(
+ 'club_code_rejected',
+ expect.objectContaining({ reason: 'sign_in_required' })
+ )
+ );
+ });
+
+ it('no longer says no sign-in is needed (AC-7)', async () => {
+ stubApi({ me: SIGNED_OUT });
+ renderSection({ identified: false });
+
+ await waitFor(() => expect(codeField() ?? screen.queryByRole('link', { name: /sign in with zoom/i })).toBeTruthy());
+ expect(document.body.textContent).not.toMatch(/No sign-in needed/i);
+ });
+});
+
+describe('ClubCodeSection: signed in', () => {
+ it('joins and shows the account wording (AC-1d, AC-7)', async () => {
+ const user = userEvent.setup();
+ const calls = stubApi({ me: SIGNED_IN });
+ renderSection({ identified: true });
+
+ await enterCode(user);
+
+ expect(await screen.findByText(copy("You're on Pro through Downtown Speakers"))).toBeInTheDocument();
+ expect(document.body.textContent).not.toMatch(/This browser is on Pro/i);
+ expect(document.body.textContent).not.toMatch(/This device is on Pro/i);
+ expect(screen.queryByRole('button', { name: /on this device/i })).toBeNull();
+
+ const [activate] = callsTo(calls, '/api/club/activate');
+ expect(JSON.parse(activate.body).deviceId).toBeUndefined();
+ expect(headerNames(activate)).not.toContain('x-club');
+ });
+
+ it('reports places_used and no is_guest on club_code_activated (AC-10)', async () => {
+ const user = userEvent.setup();
+ stubApi({ me: SIGNED_IN });
+ renderSection({ identified: true });
+
+ await enterCode(user);
+
+ await waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('club_code_activated', expect.objectContaining({ places_used: 2 }))
+ );
+ const [, props] = trackEvent.mock.calls.find(([event]) => event === 'club_code_activated');
+ expect(props).not.toHaveProperty('is_guest');
+ });
+
+ it('shows the full message (AC-3, AC-10)', async () => {
+ const user = userEvent.setup();
+ stubApi({ me: SIGNED_IN, activate: { status: 409, body: { error: 'full', placesUsed: 3, placesTotal: 3 } } });
+ renderSection({ identified: true });
+
+ await enterCode(user);
+
+ expect(
+ await screen.findByText(
+ copy("This club's Pro is full (3 of 3). Ask the person who shared the code to free a place.")
+ )
+ ).toBeInTheDocument();
+ expect(trackEvent).toHaveBeenCalledWith('club_code_rejected', expect.objectContaining({ reason: 'full' }));
+ });
+
+ it('names the club the account is already in (AC-5, AC-10)', async () => {
+ const user = userEvent.setup();
+ stubApi({
+ me: SIGNED_IN,
+ activate: { status: 409, body: { error: 'already_in_club', clubName: 'Riverside Toastmasters' } },
+ });
+ renderSection({ identified: true });
+
+ await enterCode(user);
+
+ expect(
+ await screen.findByText(copy("You're already in Riverside Toastmasters. Leave it to join another club."))
+ ).toBeInTheDocument();
+ expect(trackEvent).toHaveBeenCalledWith(
+ 'club_code_rejected',
+ expect.objectContaining({ reason: 'already_in_club' })
+ );
+ });
+});
+
+describe('ClubCodeSection: leaving (AC-4, AC-12)', () => {
+ const LEAVE_MESSAGE =
+ "Leave Downtown Speakers? You'll lose its Pro on every computer where you're signed in.";
+
+ async function joined(user, state = STATE) {
+ const calls = stubApi({ me: SIGNED_IN, activate: { status: 200, body: state } });
+ renderSection({ identified: true });
+ await enterCode(user);
+ await screen.findByText(copy("You're on Pro through Downtown Speakers"));
+ return calls;
+ }
+
+ it('asks first, then leaves with the session and no X-Club', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(true);
+ const calls = await joined(user);
+
+ await user.click(screen.getByRole('button', { name: /^leave/i }));
+ await answerConfirm(user, LEAVE_MESSAGE, { accept: true });
+
+ await waitFor(() => expect(callsTo(calls, '/api/club/leave')).toHaveLength(1));
+ const [leave] = callsTo(calls, '/api/club/leave');
+ expect(leave.method).toBe('POST');
+ expect(headerNames(leave)).not.toContain('x-club');
+ await waitFor(() => expect(screen.queryByText(copy("You're on Pro through Downtown Speakers"))).toBeNull());
+ });
+
+ it('stays in the club when the confirm is cancelled', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(false);
+ const calls = await joined(user);
+
+ await user.click(screen.getByRole('button', { name: /^leave/i }));
+ await answerConfirm(user, LEAVE_MESSAGE, { accept: false });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(callsTo(calls, '/api/club/leave')).toEqual([]);
+ expect(screen.getByText(copy("You're on Pro through Downtown Speakers"))).toBeInTheDocument();
+ });
+
+ it('offers the owner no Leave at all', async () => {
+ const user = userEvent.setup();
+ await joined(user, { ...STATE, role: 'admin', isOwner: true, code: CODE });
+
+ expect(screen.queryByRole('button', { name: /leave/i })).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/ClubStatusBanner.test.jsx b/apps/web/src/components/ClubStatusBanner.test.jsx
index 157b3e41..7f89ce17 100644
--- a/apps/web/src/components/ClubStatusBanner.test.jsx
+++ b/apps/web/src/components/ClubStatusBanner.test.jsx
@@ -16,7 +16,7 @@ const DAY = 24 * 60 * 60 * 1000;
const cache = (over = {}) =>
JSON.stringify({
- clubToken: 'tok.sig',
+ uid: 'u-1',
lastRefreshAt: Date.now(),
ver: 1,
club: { id: 'club-1', name: 'Downtown Speakers' },
diff --git a/apps/web/src/components/FlagGate.test.jsx b/apps/web/src/components/FlagGate.test.jsx
index aec90158..96265b90 100644
--- a/apps/web/src/components/FlagGate.test.jsx
+++ b/apps/web/src/components/FlagGate.test.jsx
@@ -13,7 +13,7 @@ import FlagGate from './FlagGate';
*/
const CLUB = {
- clubToken: 'tok.sig',
+ uid: 'u-1',
ver: 1,
club: { id: 'club-1', name: 'Downtown Speakers' },
kit: null,
@@ -29,11 +29,12 @@ const CLUB = {
source: 'club',
};
-/** The identity call answers "signed out"; activation answers with the club. */
+/** The identity call answers "signed in"; activation answers with the club. */
function stubApi() {
const fetchMock = vi.fn(async (url) => {
const path = String(url).split('?')[0];
if (path === '/api/club/activate') return { ok: true, status: 200, json: async () => CLUB };
+ if (path === '/api/me') return { ok: true, status: 200, json: async () => ({ uid: 'u-1', entitlement: null }) };
return { ok: false, status: 401, json: async () => ({ error: 'Unauthorized' }) };
});
vi.stubGlobal('fetch', fetchMock);
@@ -67,9 +68,9 @@ describe('FlagGate', () => {
const activations = stubApi();
renderAt('/pro/DTSP-7K2QM9');
- expect(await screen.findByText(/You're on Pro in this browser/)).toBeInTheDocument();
+ expect(await screen.findByText(/You're on Pro through Downtown Speakers/)).toBeInTheDocument();
expect(activations()).toHaveLength(1);
- expect(JSON.parse(activations()[0][1].body)).toEqual({ code: 'DTSP-7K2QM9', deviceId: expect.any(String) });
+ expect(JSON.parse(activations()[0][1].body)).toEqual({ code: 'DTSP-7K2QM9' });
});
it('shows the fallback and activates nothing while the flags are still unknown, then activates once they land', async () => {
@@ -81,7 +82,7 @@ describe('FlagGate', () => {
expect(activations()).toHaveLength(0);
act(() => { setFlags({ pro: true }); });
- expect(await screen.findByText(/You're on Pro in this browser/)).toBeInTheDocument();
+ expect(await screen.findByText(/You're on Pro through Downtown Speakers/)).toBeInTheDocument();
expect(activations()).toHaveLength(1);
});
diff --git a/apps/web/src/components/Footer.jsx b/apps/web/src/components/Footer.jsx
index f8e68b10..4f44a5b1 100644
--- a/apps/web/src/components/Footer.jsx
+++ b/apps/web/src/components/Footer.jsx
@@ -1,7 +1,8 @@
import { useState, lazy, Suspense, memo } from 'react';
-import { ExternalLink, MessageSquare, Star } from 'lucide-react';
+import { Coffee, ExternalLink, MessageSquare, Star } from 'lucide-react';
import {
FEEDBACK_SURVEY_ID,
+ PATRON_URL,
REVIEW_PROMPT,
REVIEW_SURVEY_ID,
ZOOM_MARKETPLACE_LISTING_URL,
@@ -39,7 +40,10 @@ export default memo(function Footer() {
return (
<>
-
+
+ {/* Under the field, what it would do and where the speaker stands: the
+ status, the actions that say what a tap does, and the add panel. */}
+ {labels && (
+
+
+
+
+
+ )}
)
});
diff --git a/apps/web/src/context/TimerContext.jsx b/apps/web/src/context/TimerContext.jsx
index 233f7590..691e182c 100644
--- a/apps/web/src/context/TimerContext.jsx
+++ b/apps/web/src/context/TimerContext.jsx
@@ -1,8 +1,8 @@
import { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
-import { DEFAULT_ROLE_RULES, getDefaultGraceAfterRed, BREAK_ROLE, parseSimpleFormatText, agendaItemNeedsRole } from '@toastmaster-timer/shared';
+import { DEFAULT_ROLE_RULES, getDefaultGraceAfterRed, BREAK_ROLE, agendaItemNeedsRole, readAgendaText, readAgendaLines } from '@toastmaster-timer/shared';
import { calculateStatus, formatTime } from '@toastmaster-timer/shared';
import { saveAgenda, loadAgenda, saveReports, loadReports, saveRoleRules, saveRoleOrder, saveHiddenBuiltinRoles, clearAgenda, clearReports } from '@toastmaster-timer/shared';
-import { parseEasySpeakText } from '@toastmaster-timer/shared';
+import { insertAfter } from '@toastmaster-timer/shared';
import { recordSpeechFinished } from '@toastmaster-timer/shared';
import { recordSpeech } from '@toastmaster-timer/shared';
import { resolveActiveRules, resolveActiveHiddenBuiltins, resolveActiveRoleOrder } from '@toastmaster-timer/shared';
@@ -50,6 +50,24 @@ export function TimerProvider({ children }) {
// --- stable state ---
const [currentSpeaker, setCurrentSpeaker] = useState(null);
const [activeSpeakerId, setActiveSpeakerId] = useState(null);
+ // Two things the Live tab's speaker controls keep here rather than in the
+ // tab, which unmounts on every tab switch (#168, as in the Zoom app): the row
+ // let go of for a quick timing ("Back to agenda", and where a speaker added
+ // meanwhile goes), and an edit of the loaded row not yet saved with Update. A
+ // ref for the draft: it is read once when the tab mounts, so a keystroke need
+ // not re-render everything that reads the timer.
+ const [releasedRowId, setReleasedRowId] = useState(null);
+ // Speakers added without going on the timer (a speech was in progress): they
+ // wait on the agenda in the order added, so the next one goes behind them
+ // (afterQueue), not in front.
+ const [waitingSpeakerIds, setWaitingSpeakerIds] = useState([]);
+ const speakerDraftRef = useRef(null);
+ const rememberSpeakerDraft = useCallback((draft) => { speakerDraftRef.current = draft; }, []);
+ const recallSpeakerDraft = useCallback(() => speakerDraftRef.current, []);
+ // Back on the agenda, so there is nothing to go back to.
+ useEffect(() => {
+ if (activeSpeakerId) setReleasedRowId(null);
+ }, [activeSpeakerId]);
// --- lazy localStorage initializers (1f) ---
const [agenda, setAgenda] = useState(() => {
@@ -198,13 +216,26 @@ export function TimerProvider({ children }) {
resetTimer();
}, [roleRules, resetTimer]);
- const addToAgenda = useCallback((speaker) => {
+ /**
+ * @param {Object} speaker
+ * @param {{activate?: boolean, insertAfter?: string|null}} [options] - activate
+ * makes the new item the speaker the timer is on; insertAfter puts it right
+ * after that agenda id (#168: a speaker picked on the spot speaks next).
+ * Without insertAfter the item is appended, which is what the Agenda tab's
+ * form and the imports rely on. Same calls as the Zoom app's context.
+ */
+ const addToAgenda = useCallback((speaker, { activate = false, insertAfter: afterId = null } = {}) => {
const id = Date.now().toString();
const rules = speaker.rules || roleRules[speaker.role] || DEFAULT_ROLE_RULES['Standard Speech'];
- setAgenda(prev => [...prev, { id, name: speaker.name, role: speaker.role, rules, completed: false }]);
+ setAgenda(prev => insertAfter(prev, afterId, { id, name: speaker.name, role: speaker.role, rules, completed: false }));
+ if (!activate && afterId) setWaitingSpeakerIds(prev => [...prev, id]);
+ if (activate) {
+ setCurrentSpeakerAction({ name: speaker.name, role: speaker.role, rules });
+ setActiveSpeakerId(id);
+ }
trackEvent('speaker_added', { speaker_name: speaker.name || 'Unnamed', role: speaker.role });
return id;
- }, [roleRules]);
+ }, [roleRules, setCurrentSpeakerAction]);
const removeFromAgenda = useCallback((id) => {
const itemToRemove = agenda.find(item => item.id === id);
@@ -215,6 +246,18 @@ export function TimerProvider({ children }) {
const reorderAgenda = useCallback((newOrder) => setAgenda(newOrder), []);
+ /**
+ * Rename an agenda speaker in place, keeping their position and role. The
+ * current speaker follows along when it is the one being renamed, as in the
+ * Zoom app's context.
+ * @param {string} id - Agenda item id
+ * @param {string} name - Corrected name
+ */
+ const renameAgendaSpeaker = useCallback((id, name) => {
+ setAgenda(prev => prev.map(item => (item.id === id ? { ...item, name } : item)));
+ setCurrentSpeaker(prev => (prev && activeSpeakerId === id ? { ...prev, name } : prev));
+ }, [activeSpeakerId]);
+
// Edit a speaker in place so their position in the agenda is preserved
const updateAgendaItem = useCallback((id, speaker) => {
const rules = speaker.rules || roleRules[speaker.role] || DEFAULT_ROLE_RULES['Standard Speech'];
@@ -248,13 +291,14 @@ export function TimerProvider({ children }) {
}
}, [agenda, setCurrentSpeakerAction]);
- // Simple Format import. A line gets a role only when its bracket names one
- // the dropdown offers. Any other line keeps the text as written, with no
- // rules, and the Agenda tab asks for its role: a guess times the speaker
- // with the wrong colours and nobody notices until the card changes (#91).
- const importBulkSpeakers = useCallback((text) => {
+ // Rows read out of an agenda's text, written to the agenda. A row gets a
+ // role only when the agenda names one the dropdown offers, by that role's
+ // own name. Any other row keeps the role as written, with no rules, and the
+ // Agenda tab asks for its role: a guess times the speaker with the wrong
+ // colours and nobody notices until the card changes (#91).
+ const addReadRows = useCallback((rows, extra = {}) => {
const stamp = Date.now();
- const newItems = parseSimpleFormatText(text, roleOptions).map(({ name, role, roleText }, index) => ({
+ const newItems = rows.map(({ name, role, roleText }, index) => ({
id: `${stamp}-${index}`,
name,
role: role ?? roleText,
@@ -268,21 +312,61 @@ export function TimerProvider({ children }) {
items_count: newItems.length,
custom_role_count: newItems.filter((item) => customRoleNames.includes(item.role)).length,
needs_role_count: needsRole,
+ ...extra,
});
return { count: newItems.length, needsRole };
}, [roleRules, roleOptions, customRoleNames]);
- const importEasySpeakSpeakers = useCallback((text) => {
- const parsedItems = parseEasySpeakText(text);
- const newItems = parsedItems.map((item, index) => {
- const role = item.role;
- const rules = roleRules[role] || DEFAULT_ROLE_RULES['Standard Speech'];
- return { id: `${Date.now()}-${index}`, name: item.name, role, originalShortRole: item.originalShortRole || null, rules, completed: false };
+ // Every line as a speaker: for a text the reader can tell no rows of, when
+ // the user asks for it added as it is.
+ const importBulkSpeakers = useCallback((text) => addReadRows(readAgendaLines(text, roleOptions)), [addReadRows, roleOptions]);
+
+ // One paste box, one reader (#111): whatever way the agenda is laid out, the
+ // rows the reader finds are the rows that are added, so the count under the
+ // box is the count in the toast. A text it cannot tell the rows of adds
+ // nothing; the dialog asks what to do with it.
+ const importAgendaText = useCallback((text) => {
+ const read = readAgendaText(text, roleOptions);
+ if (!read.ok || read.items.length === 0) return { count: 0, needsRole: 0, leftOut: read.leftOut };
+ return { ...addReadRows(read.items, { left_out_count: read.leftOut }), leftOut: read.leftOut };
+ }, [roleOptions, addReadRows]);
+
+ // Rows the Worker read (#111): an AI read of a text the reader could not tell
+ // the rows of, or an uploaded photo or document. As for a paste, a row gets a role only
+ // when it is one the dropdown offers; any other keeps the role as written,
+ // with no rules, and the Agenda tab asks for one (#91).
+ const importAgendaItems = useCallback((items, { via = 'ai', source = 'paste', provider = null } = {}) => {
+ const stamp = Date.now();
+ const newItems = (items ?? []).map(({ name, role, roleText, originalShortRole }, index) => {
+ const listed = roleOptions.includes(role) ? role : null;
+ const shortRole = originalShortRole || (listed === 'Short Roles' && roleText && roleText !== listed ? roleText : null);
+ // With no role, the row shows the slot as the agenda worded it. Not when
+ // that wording happens to be one of the user's roles ("Ice Breaker",
+ // "Custom"): the reader was asked and did not give it, and the row would
+ // pass for that role with no rules behind it.
+ const written = roleText || role || '';
+ return {
+ id: `${stamp}-${index}`,
+ name,
+ role: listed ?? (roleOptions.includes(written) ? '' : written),
+ ...(listed && roleRules[listed] && { rules: roleRules[listed] }),
+ ...(listed && shortRole && { originalShortRole: shortRole }),
+ completed: false,
+ };
});
+ const needsRole = newItems.filter((item) => agendaItemNeedsRole(item, roleOptions)).length;
setAgenda(prev => [...prev, ...newItems]);
- trackEvent('agenda_imported', { import_type: 'easyspeak', items_count: newItems.length });
- return newItems.length;
- }, [roleRules]);
+ trackEvent('agenda_imported', {
+ import_type: via === 'ai' ? 'ai' : 'file',
+ source,
+ format: via,
+ provider,
+ items_count: newItems.length,
+ custom_role_count: newItems.filter((item) => customRoleNames.includes(item.role)).length,
+ needs_role_count: needsRole,
+ });
+ return { count: newItems.length, needsRole };
+ }, [roleRules, roleOptions, customRoleNames]);
const formatPassedRedComment = useCallback((elapsedSeconds, redThreshold) => {
if (elapsedSeconds <= redThreshold) return '';
@@ -443,6 +527,11 @@ export function TimerProvider({ children }) {
currentSpeaker,
agenda,
activeSpeakerId,
+ releasedRowId,
+ waitingSpeakerIds,
+ setReleasedRowId,
+ rememberSpeakerDraft,
+ recallSpeakerDraft,
reports,
roleRules,
roleOptions,
@@ -455,11 +544,13 @@ export function TimerProvider({ children }) {
addToAgenda,
removeFromAgenda,
reorderAgenda,
+ renameAgendaSpeaker,
updateAgendaItem,
markCompleted,
loadSpeakerFromAgenda,
importBulkSpeakers,
- importEasySpeakSpeakers,
+ importAgendaText,
+ importAgendaItems,
clearAllAgenda,
addReport,
finishCurrentSpeech,
@@ -473,6 +564,10 @@ export function TimerProvider({ children }) {
currentSpeaker,
agenda,
activeSpeakerId,
+ releasedRowId,
+ waitingSpeakerIds,
+ rememberSpeakerDraft,
+ recallSpeakerDraft,
reports,
roleRules,
roleOptions,
@@ -485,11 +580,13 @@ export function TimerProvider({ children }) {
addToAgenda,
removeFromAgenda,
reorderAgenda,
+ renameAgendaSpeaker,
updateAgendaItem,
markCompleted,
loadSpeakerFromAgenda,
importBulkSpeakers,
- importEasySpeakSpeakers,
+ importAgendaText,
+ importAgendaItems,
clearAllAgenda,
addReport,
finishCurrentSpeech,
diff --git a/apps/web/src/context/TimerContext.test.jsx b/apps/web/src/context/TimerContext.test.jsx
index bfa294cc..4524af53 100644
--- a/apps/web/src/context/TimerContext.test.jsx
+++ b/apps/web/src/context/TimerContext.test.jsx
@@ -3,6 +3,7 @@ import { ToastProvider } from './ToastContext';
import { TimerProvider, useTimer, useTimerTick } from './TimerContext';
import { setPageBackgroundFromStatus } from '../utils/pageBackground';
import { trackEvent } from '../utils/posthog';
+import { DEFAULT_ROLE_RULES } from '@toastmaster-timer/shared';
// Convenience hook for tests: merges both contexts into one object so all
// existing test assertions continue to work without modification.
@@ -519,6 +520,152 @@ describe('TimerContext', () => {
});
});
+ // ---------------------------------------------------------------------------
+ // importAgendaText
+ // ---------------------------------------------------------------------------
+ describe('importAgendaText: a table of roles and the roles the user has', () => {
+ // The Toastmaster is a role the timer does not time. No default role is
+ // named as this agenda names its roles.
+ const AGENDA = [
+ 'Toastmaster\tRachel Adams',
+ 'Grammarian\tPriya Sharma',
+ '1st Speaker\tSarah Chen',
+ '1st Evaluator\tEmily Brown',
+ 'General Evaluator\tMichael Lee',
+ 'Ah Counter\tJordan Blake',
+ 'Joke Master\tSam Lee',
+ ].join('\n');
+
+ it('reads every row and maps none onto a default role: a role is matched by its own name', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ let summary;
+
+ act(() => {
+ summary = result.current.importAgendaText(AGENDA);
+ });
+
+ // Six rows that each ask for a role, and the Toastmaster's left out.
+ expect(summary).toEqual({ count: 6, needsRole: 6, leftOut: 1 });
+ expect(result.current.agenda.map((item) => [item.name, item.role, item.rules])).toEqual([
+ ['Priya Sharma', 'Grammarian', undefined],
+ ['Sarah Chen', '1st Speaker', undefined],
+ ['Emily Brown', '1st Evaluator', undefined],
+ ['Michael Lee', 'General Evaluator', undefined],
+ ['Jordan Blake', 'Ah Counter', undefined],
+ ['Sam Lee', 'Joke Master', undefined],
+ ]);
+ expect(trackEvent).toHaveBeenCalledWith('agenda_imported', {
+ import_type: 'bulk',
+ items_count: 6,
+ custom_role_count: 0,
+ needs_role_count: 6,
+ left_out_count: 1,
+ });
+ });
+
+ it("puts a row on the user's role of that name, with its rules, however either is spelt", () => {
+ const grammarian = { green: 15, yellow: 30, red: 45, graceAfterRed: 10 };
+ const jokeMaster = { green: 60, yellow: 90, red: 120, graceAfterRed: 15 };
+ const toastmaster = { green: 120, yellow: 150, red: 180, graceAfterRed: 30 };
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+
+ act(() => {
+ result.current.addRoleRules('GRAMMARIAN', grammarian);
+ });
+ act(() => {
+ result.current.addRoleRules('joke-master', jokeMaster);
+ });
+ act(() => {
+ result.current.addRoleRules('Toastmaster', toastmaster);
+ });
+ let summary;
+ act(() => {
+ summary = result.current.importAgendaText(AGENDA);
+ });
+
+ // With a role of that name, the Toastmaster is timed like anyone else.
+ expect(summary).toEqual({ count: 7, needsRole: 4, leftOut: 0 });
+ const row = Object.fromEntries(result.current.agenda.map((item) => [item.name, item]));
+ expect(row['Rachel Adams']).toMatchObject({ role: 'Toastmaster', rules: toastmaster });
+ expect(row['Priya Sharma']).toMatchObject({ role: 'GRAMMARIAN', rules: grammarian });
+ expect(row['Sam Lee']).toMatchObject({ role: 'joke-master', rules: jokeMaster });
+ // No role of theirs is called "Ah Counter" or "1st Speaker": those rows ask.
+ expect([row['Jordan Blake'].role, row['Jordan Blake'].rules]).toEqual(['Ah Counter', undefined]);
+ expect([row['Sarah Chen'].role, row['Sarah Chen'].rules]).toEqual(['1st Speaker', undefined]);
+ expect(trackEvent).toHaveBeenCalledWith('agenda_imported', {
+ import_type: 'bulk',
+ items_count: 7,
+ custom_role_count: 3,
+ needs_role_count: 4,
+ left_out_count: 0,
+ });
+ });
+
+ it("keeps a row in the agenda's words, with no rules, when the user has no role for it", () => {
+ // Every built-in removed in Edit Rules, and two roles of the club's own.
+ const grammarian = { green: 15, yellow: 30, red: 45, graceAfterRed: 10 };
+ localStorage.setItem('toastmaster_hidden_builtin_roles', JSON.stringify(Object.keys(DEFAULT_ROLE_RULES)));
+ localStorage.setItem(
+ 'toastmaster_role_rules',
+ JSON.stringify({ Grammarian: grammarian, '1min Role': { green: 30, yellow: 45, red: 60, graceAfterRed: 15 } })
+ );
+ localStorage.setItem('toastmaster_role_order', JSON.stringify(['Grammarian', '1min Role']));
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ let summary;
+
+ act(() => {
+ summary = result.current.importAgendaText(AGENDA);
+ });
+
+ expect(summary).toEqual({ count: 6, needsRole: 5, leftOut: 1 });
+ // A row with no role has no rules, and the Agenda tab asks (#91).
+ expect(result.current.agenda.map((item) => [item.name, item.role, item.rules])).toEqual([
+ ['Priya Sharma', 'Grammarian', grammarian],
+ ['Sarah Chen', '1st Speaker', undefined],
+ ['Emily Brown', '1st Evaluator', undefined],
+ ['Michael Lee', 'General Evaluator', undefined],
+ ['Jordan Blake', 'Ah Counter', undefined],
+ ['Sam Lee', 'Joke Master', undefined],
+ ]);
+ expect(trackEvent).toHaveBeenCalledWith('agenda_imported', {
+ import_type: 'bulk',
+ items_count: 6,
+ custom_role_count: 1,
+ needs_role_count: 5,
+ left_out_count: 1,
+ });
+ });
+
+ it('reads the roles the same way whatever sets them apart from the names', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ let summary;
+
+ act(() => {
+ summary = result.current.importAgendaText('Priya Sharma (ICEBREAKER)\nSarah Chen - Standard Speech\nspeech-evaluation: Emily Brown\nRachel Adams (Toastmaster)');
+ });
+
+ expect(summary).toEqual({ count: 3, needsRole: 0, leftOut: 1 });
+ expect(result.current.agenda.map((item) => [item.name, item.role, item.rules])).toEqual([
+ ['Priya Sharma', 'Ice Breaker', DEFAULT_ROLE_RULES['Ice Breaker']],
+ ['Sarah Chen', 'Standard Speech', DEFAULT_ROLE_RULES['Standard Speech']],
+ ['Emily Brown', 'Speech Evaluation', DEFAULT_ROLE_RULES['Speech Evaluation']],
+ ]);
+ });
+
+ it('adds nothing for a text it cannot tell the rows of', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ let summary;
+
+ act(() => {
+ summary = result.current.importAgendaText('6:30 PM Call to order\n6:40 PM Speech 1: "My Journey" by John Smith');
+ });
+
+ expect(summary).toEqual({ count: 0, needsRole: 0, leftOut: 0 });
+ expect(result.current.agenda).toEqual([]);
+ expect(trackEvent).not.toHaveBeenCalledWith('agenda_imported', expect.anything());
+ });
+ });
+
// ---------------------------------------------------------------------------
// finishCurrentSpeech / reports
// ---------------------------------------------------------------------------
@@ -714,3 +861,82 @@ describe('TimerContext', () => {
});
});
});
+
+// #168 (AC-12): the web Live tab follows the Zoom app, so its context grows the
+// same agenda calls: addToAgenda(speaker, { activate, insertAfter }) and
+// renameAgendaSpeaker(id, name). Without insertAfter, an add still appends (the
+// Agenda tab's form and the imports build the running order that way).
+describe('agenda calls for on-the-spot speakers (#168)', () => {
+ const SEED = [
+ { id: 'a', name: 'Ana', role: 'Standard Speech', rules: { green: 300, yellow: 360, red: 420, graceAfterRed: 30 }, completed: false },
+ { id: 'b', name: 'Jordan', role: 'Ice Breaker', rules: { green: 240, yellow: 300, red: 360, graceAfterRed: 30 }, completed: false },
+ { id: 'c', name: 'Cole', role: 'Standard Speech', rules: { green: 300, yellow: 360, red: 420, graceAfterRed: 30 }, completed: false },
+ ];
+ const TABLE_TOPICS = { green: 60, yellow: 90, red: 120, graceAfterRed: 30 };
+ const names = (agenda) => agenda.map((item) => item.name);
+
+ beforeEach(() => {
+ localStorage.setItem('toastmaster_agenda', JSON.stringify(SEED));
+ });
+
+ it('AC-1: addToAgenda inserts right after the given row; without it, appends', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+
+ act(() => {
+ result.current.addToAgenda({ name: 'Dana', role: 'Table Topics Speech' }, { insertAfter: 'b' });
+ });
+ expect(names(result.current.agenda)).toEqual(['Ana', 'Jordan', 'Dana', 'Cole']);
+ expect(result.current.agenda[2]).toMatchObject({ name: 'Dana', role: 'Table Topics Speech', rules: TABLE_TOPICS });
+
+ act(() => {
+ result.current.addToAgenda({ name: 'Eve', role: 'Standard Speech' });
+ });
+ expect(names(result.current.agenda)).toEqual(['Ana', 'Jordan', 'Dana', 'Cole', 'Eve']);
+ });
+
+ it('AC-1: with activate, the new speaker is loaded under their own rules', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ act(() => {
+ result.current.loadSpeakerFromAgenda('b');
+ });
+
+ let id;
+ act(() => {
+ id = result.current.addToAgenda({ name: 'Dana', role: 'Table Topics Speech' }, { insertAfter: 'b', activate: true });
+ });
+
+ expect(names(result.current.agenda)).toEqual(['Ana', 'Jordan', 'Dana', 'Cole']);
+ expect(result.current.activeSpeakerId).toBe(id);
+ expect(result.current.currentSpeaker).toMatchObject({ name: 'Dana', role: 'Table Topics Speech', rules: TABLE_TOPICS });
+ });
+
+ it('AC-13: without activate, the loaded speaker stays', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ act(() => {
+ result.current.loadSpeakerFromAgenda('b');
+ });
+ act(() => {
+ result.current.addToAgenda({ name: 'Dana', role: 'Table Topics Speech' }, { insertAfter: 'b' });
+ });
+
+ expect(names(result.current.agenda)).toEqual(['Ana', 'Jordan', 'Dana', 'Cole']);
+ expect(result.current.activeSpeakerId).toBe('b');
+ expect(result.current.currentSpeaker).toMatchObject({ name: 'Jordan', role: 'Ice Breaker' });
+ });
+
+ it('renameAgendaSpeaker renames in place, and the loaded speaker follows', () => {
+ const { result } = renderHook(() => useAllTimer(), { wrapper });
+ expect(typeof result.current.renameAgendaSpeaker, 'the web context offers renameAgendaSpeaker()').toBe('function');
+ act(() => {
+ result.current.loadSpeakerFromAgenda('b');
+ });
+
+ act(() => {
+ result.current.renameAgendaSpeaker('b', 'Dana');
+ });
+
+ expect(names(result.current.agenda)).toEqual(['Ana', 'Dana', 'Cole']);
+ expect(result.current.agenda[1]).toMatchObject({ id: 'b', role: 'Ice Breaker' });
+ expect(result.current.currentSpeaker).toMatchObject({ name: 'Dana', role: 'Ice Breaker' });
+ });
+});
diff --git a/apps/web/src/context/ToastContext.jsx b/apps/web/src/context/ToastContext.jsx
index 1ebbe25c..30820bfe 100644
--- a/apps/web/src/context/ToastContext.jsx
+++ b/apps/web/src/context/ToastContext.jsx
@@ -1,4 +1,4 @@
-import { createContext, useContext, useState, useCallback } from 'react';
+import { createContext, useContext, useState, useCallback, useEffect, useRef } from 'react';
import Toast from '../components/Toast';
const ToastContext = createContext(null);
@@ -13,17 +13,35 @@ export function useToast() {
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([]);
+ // Auto-remove timers still waiting. They are cleared when the provider goes
+ // away: one left behind would set state on a page that is no longer there.
+ const timers = useRef(new Set());
+ const gone = useRef(false);
+ useEffect(() => {
+ gone.current = false;
+ const pending = timers.current;
+ return () => {
+ gone.current = true;
+ pending.forEach(clearTimeout);
+ pending.clear();
+ };
+ }, []);
const showToast = useCallback((message, type = 'info', duration = 3000) => {
const id = Date.now().toString() + Math.random().toString(36).substr(2, 9);
const newToast = { id, message, type, duration };
+ // A call that arrives after the provider has gone (a late answer to
+ // something the page asked for) has nothing to show and starts no timer.
+ if (gone.current) return id;
setToasts(prev => [...prev, newToast]);
if (duration > 0) {
- setTimeout(() => {
+ const timer = setTimeout(() => {
+ timers.current.delete(timer);
setToasts(prev => prev.filter(toast => toast.id !== id));
}, duration);
+ timers.current.add(timer);
}
return id;
diff --git a/apps/web/src/context/ToastContext.test.jsx b/apps/web/src/context/ToastContext.test.jsx
index 11261c56..29c495f0 100644
--- a/apps/web/src/context/ToastContext.test.jsx
+++ b/apps/web/src/context/ToastContext.test.jsx
@@ -77,6 +77,38 @@ describe('ToastContext', () => {
});
});
+ describe('when the provider goes away', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('leaves no auto-remove timer behind', () => {
+ vi.useFakeTimers();
+ const { result, unmount } = renderHook(() => useToast(), { wrapper });
+
+ act(() => {
+ result.current.showToast('Still on screen', 'info', 3000);
+ result.current.showToast('And this one', 'warning', 6000);
+ });
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('starts no timer for a toast asked for afterwards', () => {
+ vi.useFakeTimers();
+ const { result, unmount } = renderHook(() => useToast(), { wrapper });
+ const { showToast } = result.current;
+
+ unmount();
+ const id = showToast('Too late', 'info', 3000);
+
+ expect(typeof id).toBe('string');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ });
+
describe('removeToast', () => {
it('removes a toast immediately by id', () => {
const { result } = renderHook(() => useToast(), { wrapper });
diff --git a/apps/web/src/hooks/useAgendaAi.js b/apps/web/src/hooks/useAgendaAi.js
new file mode 100644
index 00000000..fabf8352
--- /dev/null
+++ b/apps/web/src/hooks/useAgendaAi.js
@@ -0,0 +1,26 @@
+import { useEntitlement } from './useEntitlement';
+import { useFlag } from './useFlag';
+
+/**
+ * Whether this user gets the AI agenda reader (#111): "Read with AI" for a
+ * paste no format matches, and uploading a photo or a document.
+ *
+ * - 'usable': the `agenda_ai` flag is on and the plan is Pro.
+ * - 'locked': a free plan once `agenda_ai` and `pro` are both released. The
+ * controls show with a lock and open the upgrade.
+ * - 'hidden': everything else. While either flag is off nobody can get it, so
+ * nothing about it shows; and until both answers are in, a Pro user is not
+ * shown a lock that is about to go away.
+ *
+ * The Worker decides for real (worker/agenda-import.js); this is only what the
+ * dialog offers. Mirrors the Zoom app's hook of the same name.
+ *
+ * @returns {'usable'|'locked'|'hidden'}
+ */
+export function useAgendaAiAccess() {
+ const { enabled: released, known: flagsKnown } = useFlag('agenda_ai');
+ const { enabled: proReleased } = useFlag('pro');
+ const { isPro, known: planKnown } = useEntitlement();
+ if (!flagsKnown || !planKnown || !released || !proReleased) return 'hidden';
+ return isPro ? 'usable' : 'locked';
+}
diff --git a/apps/web/src/main.jsx b/apps/web/src/main.jsx
index 16ccd236..07378cde 100644
--- a/apps/web/src/main.jsx
+++ b/apps/web/src/main.jsx
@@ -7,15 +7,11 @@ import App from './App.jsx'
import './index.css'
import { initPostHog, trackEvent } from './utils/posthog.js'
import { startWebSession } from './utils/webIdentity.js'
-import { initClubFromCache, refreshClub, warmClubLogo, drainOutbox, setArchiveReporter, startClubCardSync } from '@toastmaster-timer/shared'
+import { warmClubLogo, drainOutbox, setArchiveReporter, startClubCardSync } from '@toastmaster-timer/shared'
-// Before the first paint, and synchronous: a browser that joined a club is Pro,
-// and reading that out of localStorage now is what stops the plan flashing
-// "free" while /api/me is still in flight.
-initClubFromCache()
-// The club's logo, decoded once so the badge and the report header have it on
-// first paint. Never awaited; a failure leaves a name-only badge.
-warmClubLogo()
+// Club Pro belongs to a Zoom account (#167), so nothing club-shaped is applied
+// or fetched before /api/me says whose browser this is: startWebSession does
+// it then.
// Render first with uninitialized posthog (all trackEvent calls already check __loaded)
ReactDOM.createRoot(document.getElementById('root')).render(
@@ -33,26 +29,29 @@ const deferInit = window.requestIdleCallback || ((cb) => setTimeout(cb, 1))
deferInit(() => { initPostHog() })
// Then find out whether this browser is signed in (Sign in with Zoom) and, if
-// so, tie analytics to the person and start settings sync. Never awaited:
-// the timer renders and works regardless.
+// so, tie analytics to the person, bring the club in line with the account and
+// start settings sync. Never awaited: the timer renders and works regardless.
deferInit(() => {
- startWebSession().catch((error) => {
- console.warn('Failed to start web session:', error)
- })
- // Re-check the club, at most once a day. A failed refresh leaves the cache in
- // place, so a lapse can only land on a successful one.
- refreshClub().catch((error) => {
- console.warn('Failed to refresh the club:', error)
- })
- // The club's card set, fetched where this browser lacks it, now and whenever
- // the club changes.
- startClubCardSync()
+ startWebSession()
+ .catch((error) => {
+ console.warn('Failed to start web session:', error)
+ })
+ // The club's logo, decoded once for the badge and the report header, and
+ // its card set, fetched where this browser lacks it, now and whenever the
+ // club changes. Both for the club this account is in, never another
+ // account's copy. Never awaited; a failure leaves a name-only badge.
+ .then(() => {
+ warmClubLogo()
+ startClubCardSync()
+ })
+ // Speeches the last session could not hand over — a tab closed mid-meeting,
+ // a hall with no wifi. The queue is in localStorage precisely so this works,
+ // and it goes out once the club is known for this account.
+ .then(() => drainOutbox())
+ .catch((error) => {
+ console.warn('Failed to send queued speeches to the club:', error)
+ })
// An upload that does not go out is invisible from here — the device keeps
// its own copy and the timer sees nothing wrong — so it has to report itself.
setArchiveReporter(trackEvent)
- // Speeches the last session could not hand over — a tab closed mid-meeting,
- // a hall with no wifi. The queue is in localStorage precisely so this works.
- drainOutbox().catch((error) => {
- console.warn('Failed to send queued speeches to the club:', error)
- })
})
diff --git a/apps/web/src/pages/Account.test.jsx b/apps/web/src/pages/Account.test.jsx
index a546204a..707f1c60 100644
--- a/apps/web/src/pages/Account.test.jsx
+++ b/apps/web/src/pages/Account.test.jsx
@@ -332,7 +332,7 @@ describe('Account: setting up a club', () => {
ok: true,
status: 200,
json: async () => ({
- clubToken: 'tok.sig',
+ uid: 'u-1',
created: true,
code: 'DTSP-7K2QM9',
shareUrl: 'https://www.example.test/pro/DTSP-7K2QM9',
@@ -418,12 +418,12 @@ describe('Account: the pro flag, the ways into a club', () => {
expect(setupButton()).toBeNull();
});
- it('still shows a browser already in a club its club, and lets it leave', async () => {
+ it('still shows an account already in a club its club, and lets it leave', async () => {
const { CLUB_STORAGE_KEY, initClubFromCache } = await import('@toastmaster-timer/shared');
localStorage.setItem(
CLUB_STORAGE_KEY,
JSON.stringify({
- clubToken: 'tok.sig',
+ uid: 'u-1',
lastRefreshAt: Date.now(),
ver: 1,
club: { id: 'club-1', name: 'Downtown Speakers' },
@@ -447,8 +447,8 @@ describe('Account: the pro flag, the ways into a club', () => {
setFlags({ pro: false });
renderAccount();
- expect(await screen.findByText('This browser is on Pro through your club.')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /leave this club on this device/i })).toBeInTheDocument();
+ expect(await screen.findByText("You're on Pro through Downtown Speakers.")).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /^leave downtown speakers/i })).toBeInTheDocument();
// The code is a door for somebody else, and that door is shut.
expect(screen.queryByDisplayValue('DTSP-7K2QM9')).toBeNull();
});
diff --git a/apps/web/src/pages/ClubAdmin.jsx b/apps/web/src/pages/ClubAdmin.jsx
index 0c6ab148..02450019 100644
--- a/apps/web/src/pages/ClubAdmin.jsx
+++ b/apps/web/src/pages/ClubAdmin.jsx
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
-import { Users, ExternalLink, ShieldCheck, LogOut, Upload, Trash2, RotateCcw, Pencil } from 'lucide-react'
-import { clubHeaders, refreshClub } from '@toastmaster-timer/shared'
+import { Users, ExternalLink, ShieldCheck, LogOut, Upload, Trash2, Pencil, MoreHorizontal } from 'lucide-react'
+import { refreshClub } from '@toastmaster-timer/shared'
import { signInUrl } from '../utils/webIdentity'
import { trackEvent } from '../utils/posthog'
@@ -13,10 +13,15 @@ import { trackEvent } from '../utils/posthog'
* cannot open inside the Zoom sidebar at all, so nothing in the Zoom app needs
* to know this page exists.
*
- * Two doors land here. Signing in with Zoom is the everyday path and needs the
- * club token this browser already holds; the mailed link names its own club, so
- * it works in a browser that never typed a code. Both reach one permission
- * check in the Worker, and differ only in the actor they carry.
+ * Two doors land here. Signing in with Zoom is the everyday path: the club is
+ * the one that account is in. The mailed link names its own club, so it works
+ * for whoever holds the billing mailbox. Both reach one permission check in the
+ * Worker, and differ only in the actor they carry.
+ *
+ * The roster is people, not devices (#167): the owner, who pays and is fixed,
+ * then up to 3 accounts the code let in. Remove frees a place and lets the
+ * account rejoin with the code; Block, tucked in a row's "…" menu because it
+ * is rare, frees it and keeps the code from letting them back in.
*/
const ROLE_LABELS = { admin: 'Admin', editor: 'Editor', member: 'Member' }
@@ -25,16 +30,18 @@ const DATE_FORMAT = { day: 'numeric', month: 'short' }
const shortDate = (value) =>
typeof value === 'number' && value > 0 ? new Date(value).toLocaleDateString(undefined, DATE_FORMAT) : '—'
-/** Every console call carries whatever credentials this browser happens to hold. */
+const removeCopy = (name) =>
+ `Remove ${name}? They lose the club's Pro at their next open and the place is freed. They can rejoin with the code; to keep them out, use Block.`
+const blockCopy = (name) =>
+ `Block ${name}? They lose the club's Pro at their next open, the place is freed, and the code won't let them back in until you unblock them.`
+
+/** Every console call carries the cookie: the Zoom sign-in, or the billing link's. */
async function api(path, { method = 'GET', body, form } = {}) {
const response = await fetch(path, {
method,
credentials: 'same-origin',
cache: 'no-store',
- headers: {
- ...clubHeaders(),
- ...(body ? { 'Content-Type': 'application/json' } : {}),
- },
+ headers: body ? { 'Content-Type': 'application/json' } : {},
...(form ? { body: form } : body ? { body: JSON.stringify(body) } : {}),
})
const json = await response.json().catch(() => ({}))
@@ -66,7 +73,7 @@ function DoorsPanel({ reason }) {
Manage your club
{reason === 'forbidden'
- ? 'This account is on the club, but it is not an admin. Ask a club admin to promote you, or use the billing address below.'
+ ? 'This Zoom account is not an admin of a club. Ask a club admin to promote you, or use the billing address below.'
: 'Sign in with the Zoom account that runs your club, or ask for a link at the address that pays for it.'}
@@ -114,7 +121,7 @@ function DoorsPanel({ reason }) {
}
/**
- * One person, and the laptops they time from.
+ * One person in the club.
*
* The label is the one piece of this page that had nothing to show. Zoom's
* `screenName` is reachable through `getUserContext` and would fill the roster
@@ -122,11 +129,14 @@ function DoorsPanel({ reason }) {
* until that is a decision somebody has made, an officer looking at their own
* club sees "You", and anyone else is whatever an admin typed. A raw uid is the
* fallback, not the answer.
+ *
+ * The owner's row says "Owner" where the role select would be, with no "…":
+ * nobody can remove, block or demote the account that pays.
*/
-function MemberRow({ member, isYou, busy, onRole, onDevice, onName }) {
- const revoked = Boolean(member.revokedAt)
+function MemberRow({ member, isYou, busy, onRole, onBlock, onName }) {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState(member.displayName || '')
+ const [menuOpen, setMenuOpen] = useState(false)
const label = member.displayName || (isYou ? 'You' : member.uid)
const saveName = async (event) => {
@@ -161,7 +171,7 @@ function MemberRow({ member, isYou, busy, onRole, onDevice, onName }) {
<>
{label}
@@ -176,58 +186,54 @@ function MemberRow({ member, isYou, busy, onRole, onDevice, onName }) {
>
)}
-
- {revoked ? 'No access' : ROLE_LABELS[member.role] ?? member.role}
-
-
-
- Role for {label}
-
- onRole(member.uid, event.target.value)}
- className="rounded-md border border-white/20 bg-black/40 px-2 py-1 text-sm text-white disabled:opacity-50"
- >
- Admin
- Editor
- Member
- No access
-
-
-
-
-
- )
-}
-
-function DeviceRow({ device, busy, onRevoke }) {
- const revoked = Boolean(device.revokedAt)
- return (
-
- {device.label}
-
- first seen {shortDate(device.activatedAt)} · last seen {shortDate(device.lastSeenAt)}
-
- {onRevoke && (
- onRevoke(device.deviceId, !revoked)}
- className="ml-auto inline-flex items-center gap-1 text-xs text-gray-400 hover:text-gray-100 disabled:opacity-50"
- >
- {revoked ? : }
- {revoked ? 'Restore' : 'Revoke'}
-
- )}
+
)
}
@@ -276,8 +282,8 @@ function KitEditor({ kit, clubName, onSaved }) {
setSaved(true)
onSaved?.(result.body)
// The admin is usually looking at their own timer in the next tab, so pull
- // the new kit down here rather than making them wait for tomorrow.
- refreshClub({ force: true }).catch(() => {})
+ // the new kit down here rather than making them wait for the next open.
+ refreshClub().catch(() => {})
}
return (
@@ -394,10 +400,7 @@ function ClubCards({ cards, clubName, onRemoved }) {
Promise.all(
Object.entries(cards.images).map(async ([color, hash]) => {
try {
- const response = await fetch(`/api/club/cards/${hash}`, {
- credentials: 'same-origin',
- headers: { ...clubHeaders() },
- })
+ const response = await fetch(`/api/club/cards/${hash}`, { credentials: 'same-origin' })
if (!response.ok) return null
const url = URL.createObjectURL(await response.blob())
minted.push(url)
@@ -485,6 +488,7 @@ const KIT_ERRORS = {
const ROLE_ERRORS = {
last_admin: 'A club needs at least one admin. Promote somebody else first.',
+ owner: 'The club’s owner pays for it, so nobody can remove, block or demote them.',
forbidden: 'Only a club admin can change roles.',
}
@@ -532,10 +536,12 @@ export default function ClubAdmin() {
})
}, [load])
- const handleRole = async (uid, role) => {
+ const handleRole = async (member, label, role) => {
+ // Remove asks first; a role change is undone with the same select.
+ if (role === 'revoked' && !window.confirm(removeCopy(label))) return
setBusy(true)
setError(null)
- const result = await api(`/api/club/members/${encodeURIComponent(uid)}/role`, { method: 'POST', body: { role } })
+ const result = await api(`/api/club/members/${encodeURIComponent(member.uid)}/role`, { method: 'POST', body: { role } })
setBusy(false)
if (!result.ok) {
setError(ROLE_ERRORS[result.body?.error] || 'Could not change that role. Please try again.')
@@ -550,33 +556,33 @@ export default function ClubAdmin() {
await load()
}
- const handleName = async (uid, name) => {
+ /** Block asks first; Unblock loses nothing, so it doesn't. */
+ const handleBlock = async (uid, blocked, label) => {
+ if (blocked && !window.confirm(blockCopy(label))) return
setBusy(true)
setError(null)
- const result = await api(`/api/club/members/${encodeURIComponent(uid)}/name`, { method: 'POST', body: { name } })
+ const result = await api(`/api/club/members/${encodeURIComponent(uid)}/block`, { method: 'POST', body: { blocked } })
setBusy(false)
if (!result.ok) {
- setError('Could not save that name. Please try again.')
+ setError(ROLE_ERRORS[result.body?.error] || 'Could not change that. Please try again.')
return
}
+ trackEvent(blocked ? 'club_member_blocked' : 'club_member_unblocked', {
+ surface: 'web',
+ club_id: roster?.club?.id ?? null,
+ })
await load()
}
- const handleDevice = async (deviceId, revoked) => {
+ const handleName = async (uid, name) => {
setBusy(true)
setError(null)
- const result = await api(`/api/club/devices/${encodeURIComponent(deviceId)}/revoke`, {
- method: 'POST',
- body: { revoked },
- })
+ const result = await api(`/api/club/members/${encodeURIComponent(uid)}/name`, { method: 'POST', body: { name } })
setBusy(false)
if (!result.ok) {
- setError('Could not change that device. Please try again.')
+ setError('Could not save that name. Please try again.')
return
}
- if (revoked) {
- trackEvent('club_access_revoked', { surface: 'web', club_id: roster?.club?.id ?? null, scope: 'device' })
- }
await load()
}
@@ -627,8 +633,11 @@ export default function ClubAdmin() {
{roster.club?.name || 'Your club'}
- {roster.counts?.devices ?? 0} device{roster.counts?.devices === 1 ? '' : 's'} ·{' '}
- {roster.counts?.people ?? 0} {roster.counts?.people === 1 ? 'person' : 'people'}
+ {roster.counts?.people ?? 0} {roster.counts?.people === 1 ? 'person' : 'people'} ·{' '}
+ {/* Null when the place counter can't be reached: a dash, not a
+ "0" that reads as three free places. */}
+ {typeof roster.counts?.placesUsed === 'number' ? roster.counts.placesUsed : '—'} of{' '}
+ {roster.counts?.placesTotal ?? 3} places used
@@ -641,6 +650,10 @@ export default function ClubAdmin() {
Who is in the club
+
+ The code lets in up to {roster.counts?.placesTotal ?? 3} Zoom accounts besides the owner. Each has the
+ club's Pro wherever they sign in.
+
{roster.members.map((member) => (
handleBlock(person.uid, true, label)}
onName={handleName}
/>
))}
- {roster.guestDevices?.length > 0 && (
+ {roster.blocked?.length > 0 && (
-
Guest devices
- {/* A device that activated with no Zoom identity is the only
- handle an admin has on whoever is using their code. */}
+
Blocked
- These activated with the code and never signed in with Zoom. They can use the club and change
- nothing.
+ The code won't let these accounts in. Unblocking doesn't put them back; they can join
+ with the code again.
- {roster.guestDevices.map((device) => (
-
- ))}
+ {roster.blocked.map((person) => {
+ const label = person.displayName || person.uid
+ return (
+
+
+ {label}
+
+ handleBlock(person.uid, false, label)}
+ className="ml-auto text-xs text-gray-400 hover:text-gray-100 disabled:opacity-50"
+ >
+ Unblock
+
+
+ )
+ })}
)}
@@ -691,8 +720,8 @@ export default function ClubAdmin() {
clubName={roster.club?.name}
onRemoved={() => {
load()
- // This browser may be a club device too; let it drop the set now.
- refreshClub({ force: true }).catch(() => {})
+ // This browser's account is usually in the club too; let it drop the set now.
+ refreshClub().catch(() => {})
}}
/>
diff --git a/apps/web/src/pages/ClubAdmin.members.test.jsx b/apps/web/src/pages/ClubAdmin.members.test.jsx
new file mode 100644
index 00000000..40fd360c
--- /dev/null
+++ b/apps/web/src/pages/ClubAdmin.members.test.jsx
@@ -0,0 +1,360 @@
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+import { CLUB_STORAGE_KEY, resetClubForTests } from '@toastmaster-timer/shared';
+import { trackEvent } from '../utils/posthog';
+import ClubAdmin from './ClubAdmin';
+
+/**
+ * The console's people list after #167: accounts, not devices. The owner is
+ * fixed, the others can be removed (and rejoin) or blocked (and kept out until
+ * unblocked), and an admin sees how many of the 3 places are used.
+ */
+
+const ROSTER = {
+ club: {
+ id: 'club-1',
+ name: 'Downtown Speakers',
+ code: 'DTSP-7K2QM9',
+ billingEmail: 'treasurer@downtownspeakers.org',
+ },
+ kit: { name: 'Downtown Speakers', logoUrl: null, primaryColor: '#772432', showOnCards: true, showOnReports: true },
+ actor: { type: 'zoom', uid: 'sarah' },
+ role: 'admin',
+ plan: 'pro',
+ entitled: true,
+ counts: { people: 3, placesUsed: 2, placesTotal: 3 },
+ members: [
+ { uid: 'sarah', role: 'admin', displayName: 'Sarah Chen', addedAt: 1_700_000_000_000, isOwner: true },
+ { uid: 'james', role: 'editor', displayName: 'James Okoro', addedAt: 1_700_000_000_001, isOwner: false },
+ { uid: 'priya', role: 'member', displayName: 'Priya Patel', addedAt: 1_700_000_000_002, isOwner: false },
+ ],
+ blocked: [],
+};
+
+const withoutPriya = {
+ ...ROSTER,
+ counts: { people: 2, placesUsed: 1, placesTotal: 3 },
+ members: ROSTER.members.filter((member) => member.uid !== 'priya'),
+};
+
+const copy = (text) =>
+ new RegExp(text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/'/g, "['\u2019]"));
+const sameText = (a, b) => a.replace(/\u2019/g, "'") === b.replace(/\u2019/g, "'");
+
+/**
+ * A fetch stub keyed by path. A route may be a list of answers, one per call
+ * (the last repeats), so a roster can change after a write.
+ */
+function stubApi(routes) {
+ const calls = [];
+ const seen = new Map();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url, init = {}) => {
+ const path = String(url).split('?')[0];
+ calls.push({ path, method: init.method || 'GET', body: init.body, headers: init.headers ?? {} });
+ const n = seen.get(path) ?? 0;
+ seen.set(path, n + 1);
+ const route = routes[path] ?? { status: 404, body: {} };
+ const answer = Array.isArray(route) ? route[Math.min(n, route.length - 1)] : route;
+ return {
+ ok: answer.status >= 200 && answer.status < 300,
+ status: answer.status,
+ json: async () => answer.body ?? {},
+ };
+ })
+ );
+ return calls;
+}
+
+const renderConsole = () =>
+ render(
+
+
+
+ );
+
+const callsTo = (calls, path) => calls.filter((call) => call.path === path);
+
+/** Each row's "…" control, by its accessible name, label or title. */
+function moreOptionsIn(container) {
+ const scope = within(container);
+ return [
+ ...scope.queryAllByRole('button', { name: /more options/i }),
+ ...scope.queryAllByLabelText(/more options/i),
+ ...scope.queryAllByTitle(/more options/i),
+ ].filter((element, index, all) => all.indexOf(element) === index);
+}
+
+/** The smallest element holding this person's name and a control of their own. */
+function rowOf(name) {
+ let node = screen.getByText(name);
+ while (node && node !== document.body) {
+ const scope = within(node);
+ if (moreOptionsIn(node).length || scope.queryAllByRole('combobox').length || scope.queryAllByText(/^Owner$/).length) {
+ return node;
+ }
+ node = node.parentElement;
+ }
+ throw new Error(`No row for ${name}`);
+}
+
+async function chooseBlock(user, name) {
+ const row = rowOf(name);
+ const [more] = moreOptionsIn(row);
+ expect(more).toBeTruthy();
+ await user.click(more);
+ const block =
+ within(row).queryByRole('menuitem', { name: /^block$/i }) ??
+ within(row).queryByRole('button', { name: /^block$/i }) ??
+ within(row).queryByText(/^block$/i) ??
+ screen.queryByRole('menuitem', { name: /^block$/i }) ??
+ (await screen.findAllByText(/^block$/i)).at(-1);
+ await user.click(block);
+}
+
+/** window.confirm, or an in-app dialog with the same words. */
+async function answerConfirm(user, message, { accept, verb }) {
+ if (window.confirm.mock.calls.length) {
+ expect(sameText(window.confirm.mock.calls.at(-1)[0], message)).toBe(true);
+ return;
+ }
+ const dialog = screen.queryByRole('alertdialog') ?? (await screen.findByRole('dialog'));
+ expect(dialog).toHaveTextContent(copy(message));
+ const buttons = within(dialog).getAllByRole('button');
+ const choice = accept
+ ? buttons.find((button) => verb.test(button.textContent))
+ : buttons.find((button) => /cancel|keep/i.test(button.textContent));
+ await user.click(choice);
+}
+
+const REMOVE_MESSAGE =
+ "Remove Priya Patel? They lose the club's Pro at their next open and the place is freed. They can rejoin with the code; to keep them out, use Block.";
+const BLOCK_MESSAGE =
+ "Block Priya Patel? They lose the club's Pro at their next open, the place is freed, and the code won't let them back in until you unblock them.";
+
+beforeEach(() => {
+ localStorage.clear();
+ resetClubForTests();
+ trackEvent.mockClear();
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('ClubAdmin: people, not devices (AC-3, AC-7)', () => {
+ it('shows the places used and no device rows', async () => {
+ stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
+ renderConsole();
+
+ expect(await screen.findByText('Priya Patel')).toBeInTheDocument();
+ expect(screen.getByText(/2 of 3 places used/)).toBeInTheDocument();
+ expect(screen.getByText('James Okoro')).toBeInTheDocument();
+
+ expect(screen.queryByText('Guest devices')).toBeNull();
+ expect(document.body.textContent).not.toMatch(/\d+ devices?\b/);
+ expect(document.body.textContent).not.toMatch(/No device has activated/i);
+ expect(screen.queryByRole('button', { name: /revoke/i })).toBeNull();
+ });
+
+ // A browser left with an old device token must not send it to the console.
+ it('sends the cookie only, never X-Club', async () => {
+ localStorage.setItem(
+ CLUB_STORAGE_KEY,
+ JSON.stringify({
+ clubToken: 'old.token',
+ lastRefreshAt: Date.now(),
+ ver: 1,
+ club: { id: 'club-1', name: 'Downtown Speakers' },
+ role: 'admin',
+ plan: 'pro',
+ entitled: true,
+ source: 'club',
+ })
+ );
+ resetClubForTests();
+ const calls = stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
+ renderConsole();
+
+ await screen.findByText('Priya Patel');
+ for (const call of calls) {
+ const names = Object.keys(call.headers ?? {}).map((name) => name.toLowerCase());
+ expect(names).not.toContain('x-club');
+ }
+ });
+});
+
+describe('ClubAdmin: the owner row (AC-12)', () => {
+ it('says Owner, with no role select and no "…" menu', async () => {
+ stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
+ renderConsole();
+
+ await screen.findByText('Sarah Chen');
+ const owner = rowOf('Sarah Chen');
+ expect(within(owner).getByText(/^Owner$/)).toBeInTheDocument();
+ expect(screen.queryByLabelText('Role for Sarah Chen')).toBeNull();
+ expect(moreOptionsIn(owner)).toEqual([]);
+
+ // Everyone else keeps both.
+ expect(screen.getByLabelText('Role for James Okoro')).toBeInTheDocument();
+ expect(screen.getByLabelText('Role for Priya Patel')).toBeInTheDocument();
+ expect(moreOptionsIn(rowOf('James Okoro')).length).toBeGreaterThan(0);
+ expect(moreOptionsIn(rowOf('Priya Patel')).length).toBeGreaterThan(0);
+ });
+});
+
+describe('ClubAdmin: Remove (AC-4)', () => {
+ it('offers Remove instead of No access', async () => {
+ stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
+ renderConsole();
+
+ const select = await screen.findByLabelText('Role for Priya Patel');
+ const labels = within(select).getAllByRole('option').map((option) => option.textContent);
+ expect(labels).toContain('Remove');
+ expect(labels).not.toContain('No access');
+ });
+
+ it('asks first, then removes, and the person drops off the roster', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(true);
+ const calls = stubApi({
+ '/api/club/roster': [
+ { status: 200, body: ROSTER },
+ { status: 200, body: withoutPriya },
+ ],
+ '/api/club/members/priya/role': { status: 200, body: { uid: 'priya', removed: true } },
+ });
+ renderConsole();
+
+ const select = await screen.findByLabelText('Role for Priya Patel');
+ await user.selectOptions(select, 'revoked');
+ await answerConfirm(user, REMOVE_MESSAGE, { accept: true, verb: /remove/i });
+
+ await waitFor(() => {
+ const [call] = callsTo(calls, '/api/club/members/priya/role');
+ expect(call).toBeTruthy();
+ expect(JSON.parse(call.body)).toEqual({ role: 'revoked' });
+ });
+ await waitFor(() => expect(screen.queryByText('Priya Patel')).toBeNull());
+ expect(screen.queryByText(/^Removed$/)).toBeNull();
+ expect(trackEvent).toHaveBeenCalledWith('club_access_revoked', expect.objectContaining({ club_id: 'club-1' }));
+ });
+
+ it('sends nothing when the confirm is cancelled', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(false);
+ const calls = stubApi({
+ '/api/club/roster': { status: 200, body: ROSTER },
+ '/api/club/members/priya/role': { status: 200, body: {} },
+ });
+ renderConsole();
+
+ const select = await screen.findByLabelText('Role for Priya Patel');
+ await user.selectOptions(select, 'revoked');
+ await answerConfirm(user, REMOVE_MESSAGE, { accept: false, verb: /remove/i });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(callsTo(calls, '/api/club/members/priya/role')).toEqual([]);
+ expect(screen.getByText('Priya Patel')).toBeInTheDocument();
+ });
+});
+
+describe('ClubAdmin: Block and Unblock (AC-10, AC-11)', () => {
+ const blockedRoster = {
+ ...withoutPriya,
+ blocked: [{ uid: 'priya', displayName: 'Priya Patel', blockedAt: 1_700_000_100_000 }],
+ };
+
+ it('shows no Blocked section while nobody is blocked', async () => {
+ stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
+ renderConsole();
+
+ await screen.findByText('Priya Patel');
+ expect(screen.queryByText(/^Blocked$/)).toBeNull();
+ expect(screen.queryByRole('button', { name: /unblock/i })).toBeNull();
+ });
+
+ it('blocks from the row\'s "…" menu after a confirm, and lists the account under Blocked', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(true);
+ const calls = stubApi({
+ '/api/club/roster': [
+ { status: 200, body: ROSTER },
+ { status: 200, body: blockedRoster },
+ ],
+ '/api/club/members/priya/block': { status: 200, body: { uid: 'priya', blocked: true } },
+ });
+ renderConsole();
+
+ await screen.findByText('Priya Patel');
+ await chooseBlock(user, 'Priya Patel');
+ await answerConfirm(user, BLOCK_MESSAGE, { accept: true, verb: /block/i });
+
+ await waitFor(() => {
+ const [call] = callsTo(calls, '/api/club/members/priya/block');
+ expect(call).toBeTruthy();
+ expect(call.method).toBe('POST');
+ expect(JSON.parse(call.body)).toEqual({ blocked: true });
+ });
+
+ const heading = await screen.findByText(/^Blocked$/);
+ expect(heading).toBeInTheDocument();
+ expect(screen.getByText('Priya Patel')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /unblock/i })).toBeInTheDocument();
+ expect(trackEvent).toHaveBeenCalledWith(
+ 'club_member_blocked',
+ expect.objectContaining({ club_id: 'club-1', surface: 'web' })
+ );
+ });
+
+ it('sends nothing when the block confirm is cancelled', async () => {
+ const user = userEvent.setup();
+ window.confirm.mockReturnValue(false);
+ const calls = stubApi({
+ '/api/club/roster': { status: 200, body: ROSTER },
+ '/api/club/members/priya/block': { status: 200, body: {} },
+ });
+ renderConsole();
+
+ await screen.findByText('Priya Patel');
+ await chooseBlock(user, 'Priya Patel');
+ await answerConfirm(user, BLOCK_MESSAGE, { accept: false, verb: /block/i });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(callsTo(calls, '/api/club/members/priya/block')).toEqual([]);
+ });
+
+ it('unblocks with one click and no confirm', async () => {
+ const user = userEvent.setup();
+ const calls = stubApi({
+ '/api/club/roster': [
+ { status: 200, body: blockedRoster },
+ { status: 200, body: withoutPriya },
+ ],
+ '/api/club/members/priya/block': { status: 200, body: { uid: 'priya', blocked: false } },
+ });
+ renderConsole();
+
+ await screen.findByText(/^Blocked$/);
+ await user.click(screen.getByRole('button', { name: /unblock/i }));
+
+ await waitFor(() => {
+ const [call] = callsTo(calls, '/api/club/members/priya/block');
+ expect(call).toBeTruthy();
+ expect(JSON.parse(call.body)).toEqual({ blocked: false });
+ });
+ expect(window.confirm).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ // Not put back automatically: the account rejoins with the code.
+ await waitFor(() => expect(screen.queryByText(/^Blocked$/)).toBeNull());
+ expect(screen.queryByText('Priya Patel')).toBeNull();
+ expect(trackEvent).toHaveBeenCalledWith(
+ 'club_member_unblocked',
+ expect.objectContaining({ club_id: 'club-1', surface: 'web' })
+ );
+ });
+});
diff --git a/apps/web/src/pages/ClubAdmin.test.jsx b/apps/web/src/pages/ClubAdmin.test.jsx
index d001d619..b5c204ae 100644
--- a/apps/web/src/pages/ClubAdmin.test.jsx
+++ b/apps/web/src/pages/ClubAdmin.test.jsx
@@ -1,4 +1,4 @@
-import { render, screen, waitFor, within } from '@testing-library/react';
+import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { resetClubForTests } from '@toastmaster-timer/shared';
@@ -21,29 +21,14 @@ const ROSTER = {
role: 'admin',
plan: 'pro',
entitled: true,
- counts: { devices: 4, people: 2, guestDevices: 1 },
+ counts: { people: 2, placesUsed: 1, placesTotal: 3 },
+ // A club with no known owner (minted by hand), so the last-admin rule is
+ // what guards it; the owner's row is in ClubAdmin.members.test.jsx.
members: [
- {
- uid: 'sarah',
- role: 'admin',
- displayName: 'Sarah Chen',
- revokedAt: null,
- devices: [
- { deviceId: 'd1', label: 'Chrome · Windows', activatedAt: 1_700_000_000_000, lastSeenAt: 1_700_100_000_000, revokedAt: null },
- { deviceId: 'd2', label: 'Safari · iPad', activatedAt: 1_700_000_000_000, lastSeenAt: 1_700_050_000_000, revokedAt: null },
- ],
- },
- {
- uid: 'james',
- role: 'editor',
- displayName: 'James Okoro',
- revokedAt: null,
- devices: [{ deviceId: 'd3', label: 'Chrome · macOS', activatedAt: 1, lastSeenAt: 2, revokedAt: null }],
- },
- ],
- guestDevices: [
- { deviceId: 'd4', label: 'Firefox · Windows', activatedAt: 1, lastSeenAt: 2, revokedAt: null },
+ { uid: 'sarah', role: 'admin', displayName: 'Sarah Chen', addedAt: 1, isOwner: false },
+ { uid: 'james', role: 'editor', displayName: 'James Okoro', addedAt: 2, isOwner: false },
],
+ blocked: [],
};
/** A fetch stub keyed by path, recording every call. */
@@ -94,6 +79,8 @@ describe('ClubAdmin — the two doors', () => {
renderConsole();
expect(await screen.findByRole('alert')).toHaveTextContent('not an admin');
+ // True for a member and for an account in no club alike: both get a 403.
+ expect(screen.getByRole('alert')).not.toHaveTextContent('on the club');
expect(screen.getByTestId('sign-in-with-zoom')).toBeInTheDocument();
});
@@ -117,21 +104,26 @@ describe('ClubAdmin — the two doors', () => {
});
describe('ClubAdmin — the roster', () => {
- it('renders every device grouped under its person, with guests on their own', async () => {
+ it('renders the people in the club and the places they use', async () => {
stubApi({ '/api/club/roster': { status: 200, body: ROSTER } });
renderConsole();
expect(await screen.findByText('Downtown Speakers')).toBeInTheDocument();
expect(screen.getByText('DTSP-7K2QM9')).toBeInTheDocument();
- expect(screen.getByText(/4 devices · 2 people/)).toBeInTheDocument();
+ expect(screen.getByText(/2 people · 1 of 3 places used/)).toBeInTheDocument();
expect(screen.getByText('Sarah Chen')).toBeInTheDocument();
- expect(screen.getByText('Chrome · Windows')).toBeInTheDocument();
- expect(screen.getByText('Safari · iPad')).toBeInTheDocument();
expect(screen.getByText('James Okoro')).toBeInTheDocument();
+ });
+
+ // Null when the place counter could not be reached: "0 of 3" would read as
+ // three free places.
+ it('shows a dash, not a zero, when the place count is unknown', async () => {
+ stubApi({ '/api/club/roster': { status: 200, body: { ...ROSTER, counts: { ...ROSTER.counts, placesUsed: null } } } });
+ renderConsole();
- const guests = screen.getByText('Guest devices').closest('div');
- expect(within(guests).getByText('Firefox · Windows')).toBeInTheDocument();
+ expect(await screen.findByText(/2 people · — of 3 places used/)).toBeInTheDocument();
+ expect(screen.queryByText(/0 of 3 places used/)).not.toBeInTheDocument();
});
// The roster used to label anyone without a `displayName` — which was
@@ -200,23 +192,6 @@ describe('ClubAdmin — the roster', () => {
expect(await screen.findByRole('alert')).toHaveTextContent('at least one admin');
});
-
- it('revokes a guest device', async () => {
- const calls = stubApi({
- '/api/club/roster': { status: 200, body: ROSTER },
- '/api/club/devices/d4/revoke': { status: 200, body: { deviceId: 'd4' } },
- });
- renderConsole();
-
- await screen.findByText('Guest devices');
- const guests = screen.getByText('Guest devices').closest('div');
- await userEvent.click(within(guests).getByRole('button', { name: /Revoke/ }));
-
- await waitFor(() => {
- const call = calls.find((c) => c.path === '/api/club/devices/d4/revoke');
- expect(JSON.parse(call.body)).toEqual({ revoked: true });
- });
- });
});
describe('ClubAdmin — the kit', () => {
diff --git a/apps/web/src/pages/Landing.jsx b/apps/web/src/pages/Landing.jsx
index 67a1672e..ce8fd096 100644
--- a/apps/web/src/pages/Landing.jsx
+++ b/apps/web/src/pages/Landing.jsx
@@ -11,7 +11,7 @@ import {
Play,
} from 'lucide-react'
import { trackEvent } from '../utils/posthog'
-import { TOOLS, ZOOM_MARKETPLACE_LISTING_URL } from '@toastmaster-timer/shared'
+import { PATRON_URL, TOOLS, ZOOM_MARKETPLACE_LISTING_URL } from '@toastmaster-timer/shared'
import DemoDialog from '../components/DemoDialog'
import AccountMenu from '../components/AccountMenu'
@@ -120,7 +120,7 @@ const TUTORIAL_STEPS = [
},
{
title: 'Load your agenda',
- body: 'Paste your list of speakers, or paste the meeting page straight from EasySpeak. Every speaker comes in with the right role and time limits, and you can drag them into order.',
+ body: 'Paste your list of speakers, or paste the meeting page straight from EasySpeak. A speaker whose role is in your role list comes in with its time limits, you pick the role for the rest, and you can drag them into order.',
src: '/zoom/tutorial/02-agenda-import.jpg',
hint: 'Agenda tab with the import box and a filled agenda',
},
@@ -132,7 +132,7 @@ const TUTORIAL_STEPS = [
},
{
title: 'Name the speaker',
- body: 'Pick whoever is up next from your agenda, or straight from the people in the meeting. Someone who is not on the list? Type their name and press Enter to add them. Type over a name and press Enter to fix a spelling, and they keep their place in the running order.',
+ body: 'Pick whoever is up next from your agenda, or straight from the people in the meeting. Someone picked on the spot? Tap "Add a speaker" and they go right after the speaker on the timer. Type over a name, or change the role, then tap Update (or press Enter) to fix it, and they keep their place in the running order.',
src: '/zoom/tutorial/04-speaker-name.jpg',
hint: 'Speaker name field with the suggestion list open, showing agenda names and people in the meeting',
},
@@ -230,7 +230,7 @@ const FEATURES = [
icon: ClipboardPaste,
dot: 'bg-timer-red',
title: 'Quick import',
- body: 'Paste your meeting roles — or the whole EasySpeak page — and the agenda loads itself, roles and time limits included.',
+ body: 'Paste your meeting roles — or the whole EasySpeak page — and the agenda loads itself. A role that is in your role list brings its time limits; you pick the rest.',
},
{
icon: Monitor,
@@ -1016,6 +1016,7 @@ export default function Landing() {
Add to Zoom
Web timer
Zoom Marketplace
+ Buy me a coffee
diff --git a/apps/web/src/pages/Landing.test.jsx b/apps/web/src/pages/Landing.test.jsx
index ebb5dc0f..14a9d99f 100644
--- a/apps/web/src/pages/Landing.test.jsx
+++ b/apps/web/src/pages/Landing.test.jsx
@@ -286,3 +286,36 @@ describe('Landing footer tools', () => {
expect(screen.getByText(/Toastmusters Timer \(this site\)/)).toBeInTheDocument();
});
});
+
+// #160: a low-key thank-you link beside Pro. It unlocks nothing.
+describe('Landing footer "Buy me a coffee"', () => {
+ const PATRON_URL = 'https://buymeacoffee.com/shuhao';
+ const coffeeLink = () =>
+ screen.getAllByRole('link', { name: 'Buy me a coffee' }).find((a) => a.closest('footer'));
+
+ it('links to the Buy Me a Coffee page in a new tab', () => {
+ render(
+
+
+
+ );
+
+ const link = coffeeLink();
+ expect(link).toBeDefined();
+ expect(link).toHaveAttribute('href', PATRON_URL);
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');
+ });
+
+ it('records the click as a patron call to action from the footer', () => {
+ render(
+
+
+
+ );
+
+ fireEvent.click(coffeeLink());
+
+ expect(trackEvent).toHaveBeenCalledWith('cta_clicked', { cta: 'patron', location: 'footer', page: '/' });
+ });
+});
diff --git a/apps/web/src/pages/ProActivate.jsx b/apps/web/src/pages/ProActivate.jsx
index f9be4d93..905aa30a 100644
--- a/apps/web/src/pages/ProActivate.jsx
+++ b/apps/web/src/pages/ProActivate.jsx
@@ -3,44 +3,54 @@ import { Link, useParams } from 'react-router-dom'
import { Users, Check } from 'lucide-react'
import { activateClub } from '@toastmaster-timer/shared'
import { useWebIdentity } from '../hooks/useEntitlement'
-import { useClub } from '../components/ClubCodeSection'
+import { useClub, clubErrorFor } from '../components/ClubCodeSection'
+import { signInUrl } from '../utils/webIdentity'
import { trackEvent } from '../utils/posthog'
/**
* /pro/
— the officer's shareable link.
*
* It can only ever land in a browser: links open the system browser, never the
- * Zoom sidebar. So this page activates the club here and then tells a timer who
- * times in Zoom exactly where to type the same code, which is the other half of
- * the job — the link is the discoverability mechanism for a field that has no
- * banner and no first-launch prompt pointing at it.
+ * Zoom sidebar. Club Pro belongs to a Zoom account (#167), so this page joins
+ * the account signed in here — and a signed-out browser sends nothing and is
+ * asked to sign in with Zoom, which comes back to this same link and joins.
+ * Then it tells a timer who times in Zoom where to type the same code, which
+ * is the other half of the job: the link is the discoverability mechanism for
+ * a field that has no banner and no first-launch prompt pointing at it.
*/
-const CLUB_ERRORS = {
- network: 'Could not reach the server. Check your connection and try again.',
- too_many_attempts: 'Too many tries. Wait a minute, then reload this page.',
-}
-const CLUB_ERROR_FALLBACK = "That code isn't active. Check with your club officer."
+const RETRY_LATER = { too_many_attempts: 'Too many tries. Wait a minute, then reload this page.' }
export default function ProActivate() {
const { code } = useParams()
const identity = useWebIdentity()
const club = useClub()
- const [phase, setPhase] = useState('activating') // activating | done | error
+ const [phase, setPhase] = useState('activating') // activating | sign_in | done | error
const [error, setError] = useState(null)
- // Activation writes a device record, so it must happen once per visit and not
- // once per render — React 18's StrictMode double-invokes effects in dev.
+ // Joining takes a place in the club, so it must happen once per visit and
+ // not once per render — React 18's StrictMode double-invokes effects in dev.
const startedRef = useRef(false)
useEffect(() => {
- if (startedRef.current) return
+ // Nothing is sent until the Worker has said who this is.
+ if (!identity || startedRef.current) return
startedRef.current = true
- activateClub(code).then((result) => {
+ if (!identity.identified) {
+ setPhase('sign_in')
+ trackEvent('club_code_rejected', { surface: 'web', source: 'pro_link', reason: 'sign_in_required' })
+ return
+ }
+
+ activateClub(code, { uid: identity.uid }).then((result) => {
if (!result.ok) {
- setError(CLUB_ERRORS[result.error] || CLUB_ERROR_FALLBACK)
- setPhase('error')
trackEvent('club_code_rejected', { surface: 'web', source: 'pro_link', reason: result.error })
+ if (result.error === 'sign_in_required') {
+ setPhase('sign_in')
+ return
+ }
+ setError(RETRY_LATER[result.error] || clubErrorFor(result))
+ setPhase('error')
return
}
setPhase('done')
@@ -48,14 +58,11 @@ export default function ProActivate() {
surface: 'web',
source: 'pro_link',
club_id: result.club.club?.id ?? null,
- // Resolved after this fires in the common case; the link is explicitly
- // built for people who are not signed in, so the default is honest.
- is_guest: !identity?.identified,
+ places_used: result.placesUsed,
via: 'link',
})
})
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [code])
+ }, [identity, code])
return (
@@ -72,6 +79,23 @@ export default function ProActivate() {
{phase === 'activating' && Activating…
}
+ {phase === 'sign_in' && (
+ <>
+ Join your club's Pro
+
+ Your club's Pro follows your Zoom account, on every computer where you're
+ signed in. Sign in with Zoom and this link joins you.
+
+ {/* A server route, not an app route: a full page load. */}
+
+ Sign in with Zoom to join
+
+ >
+ )}
+
{phase === 'error' && (
<>
That code didn't work
@@ -91,21 +115,21 @@ export default function ProActivate() {
{club?.club?.name || 'Your club'}
- You're on Pro in this browser
+ You're on Pro through {club?.club?.name || 'your club'}
+ On every computer where you're signed in with this Zoom account.
Your club's shared timing presets
Your club's branding on cards and reports
{/* The other half of the link's job. A Zoom link cannot open the
- sidebar app, so the code has to be typed there instead. */}
+ sidebar app, but the club follows the account into it. */}
Time your meetings in Zoom?
- Open Toastmusters Timer in Zoom, tap Upgrade , and enter
- this code:
+ Open Toastmusters Timer in Zoom with this same Zoom account: your club's Pro is
+ already there, no code needed.
-
{code?.toUpperCase()}
(#167). Club Pro belongs to a Zoom account now, so the link joins
+ * the signed-in account and, for a signed-out browser, sends nothing and asks
+ * for a Zoom sign-in that comes back here.
+ */
+
+const CODE = 'DTSP-7K2QM9';
+
+/** The club state the Worker answers a join with: no clubToken, plus the place count. */
+const STATE = {
+ ver: 1,
+ club: { id: 'club-1', name: 'Downtown Speakers' },
+ kit: null,
+ presets: null,
+ badge: { x: 0.8, y: 0.12, scale: 0.12 },
+ cards: null,
+ timezone: null,
+ role: 'member',
+ isOwner: false,
+ code: null,
+ shareUrl: null,
+ plan: 'pro',
+ entitled: true,
+ status: 'active',
+ currentPeriodEnd: null,
+ cancelAtPeriodEnd: false,
+ source: 'club',
+ placesUsed: 2,
+};
+
+/** A straight or a curly apostrophe: the copy may use either. */
+const copy = (text) =>
+ new RegExp(text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/'/g, "['\u2019]"));
+
+/**
+ * A fetch stub keyed by path. `me` answers /api/me (signed in or out);
+ * `activate` answers POST /api/club/activate.
+ */
+function stubApi({ me, activate }) {
+ const calls = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url, init = {}) => {
+ const path = String(url).split('?')[0];
+ calls.push({ path, method: init.method || 'GET', body: init.body, headers: init.headers ?? {} });
+ const answer =
+ path === '/api/me' ? me : path === '/api/club/activate' ? activate : { status: 404, body: {} };
+ return {
+ ok: answer.status >= 200 && answer.status < 300,
+ status: answer.status,
+ json: async () => answer.body ?? {},
+ };
+ })
+ );
+ return calls;
+}
+
+const SIGNED_OUT = { status: 401, body: { error: 'Unauthorized' } };
+const SIGNED_IN = { status: 200, body: { uid: 'timer-uid', entitlement: { plan: 'free', entitled: false } } };
+
+const renderPage = () =>
+ render(
+
+
+ } />
+
+
+ );
+
+const activateCalls = (calls) => calls.filter((call) => call.path === '/api/club/activate');
+
+beforeEach(() => {
+ localStorage.clear();
+ resetClubForTests();
+ resetWebIdentityForTests();
+ resetEntitlementForTests();
+ resetFlagsForTests();
+ setFlags({ pro: true });
+ trackEvent.mockClear();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('ProActivate: a signed-out browser (AC-1d)', () => {
+ it('sends nothing and links to Zoom sign-in that comes back to this page', async () => {
+ const calls = stubApi({ me: SIGNED_OUT, activate: { status: 200, body: STATE } });
+ renderPage();
+
+ const link = await screen.findByRole('link', { name: /sign in with zoom to join/i });
+ expect(link).toHaveAttribute('href', signInUrl(`/pro/${CODE}`));
+ // The return trip is the whole point: /pro/ joins once signed in.
+ expect(decodeURIComponent(link.getAttribute('href'))).toBe(`/api/auth/zoom/start?returnTo=/pro/${CODE}`);
+
+ // Give a stray activation every chance to go out.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(activateCalls(calls)).toEqual([]);
+ });
+
+ it('never claims Pro for "this browser" or says no sign-in is needed (AC-7)', async () => {
+ stubApi({ me: SIGNED_OUT, activate: { status: 200, body: STATE } });
+ renderPage();
+
+ await screen.findByRole('link', { name: /sign in with zoom to join/i });
+ expect(document.body.textContent).not.toMatch(/on Pro in this browser/i);
+ expect(document.body.textContent).not.toMatch(/This device is on Pro/i);
+ expect(document.body.textContent).not.toMatch(/No sign-in needed/i);
+ });
+});
+
+describe('ProActivate: a signed-in browser', () => {
+ it('joins the account and says so in the account wording (AC-1d, AC-7)', async () => {
+ const calls = stubApi({ me: SIGNED_IN, activate: { status: 200, body: STATE } });
+ renderPage();
+
+ expect(await screen.findByText(copy("You're on Pro through Downtown Speakers"))).toBeInTheDocument();
+ expect(document.body.textContent).not.toMatch(/on Pro in this browser/i);
+ expect(document.body.textContent).not.toMatch(/This device is on Pro/i);
+
+ const [activate] = activateCalls(calls);
+ expect(activate.method).toBe('POST');
+ const body = JSON.parse(activate.body);
+ expect(body.code).toBeTruthy();
+ // Nothing per device any more.
+ expect(body.deviceId).toBeUndefined();
+ const headerNames = Object.keys(activate.headers).map((name) => name.toLowerCase());
+ expect(headerNames).not.toContain('x-club');
+ });
+
+ it('reports places_used and no is_guest on club_code_activated (AC-10)', async () => {
+ stubApi({ me: SIGNED_IN, activate: { status: 200, body: STATE } });
+ renderPage();
+
+ await waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('club_code_activated', expect.objectContaining({ places_used: 2 }))
+ );
+ const [, props] = trackEvent.mock.calls.find(([event]) => event === 'club_code_activated');
+ expect(props).not.toHaveProperty('is_guest');
+ });
+
+ it('shows the full message when every place is taken (AC-3)', async () => {
+ stubApi({ me: SIGNED_IN, activate: { status: 409, body: { error: 'full', placesUsed: 3, placesTotal: 3 } } });
+ renderPage();
+
+ expect(
+ await screen.findByText(
+ copy("This club's Pro is full (3 of 3). Ask the person who shared the code to free a place.")
+ )
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('club_code_rejected', expect.objectContaining({ reason: 'full' }))
+ );
+ });
+
+ it('names the club an account is already in (AC-5)', async () => {
+ stubApi({
+ me: SIGNED_IN,
+ activate: { status: 409, body: { error: 'already_in_club', clubName: 'Riverside Toastmasters' } },
+ });
+ renderPage();
+
+ expect(
+ await screen.findByText(copy("You're already in Riverside Toastmasters. Leave it to join another club."))
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith(
+ 'club_code_rejected',
+ expect.objectContaining({ reason: 'already_in_club' })
+ )
+ );
+ });
+});
diff --git a/apps/web/src/pages/Reconnect.jsx b/apps/web/src/pages/Reconnect.jsx
index 6ff613eb..154faced 100644
--- a/apps/web/src/pages/Reconnect.jsx
+++ b/apps/web/src/pages/Reconnect.jsx
@@ -12,7 +12,10 @@ import { trackEvent } from '../utils/posthog'
*
* The site cannot tell a lapsed user from a healthy one, so every line here has
* to be true for anyone who reads it. Visitors who did not need to reconnect
- * get quiet ways out: open the app, or go to the homepage.
+ * get easy ways out: open the app, or go to the homepage (the header logo, the
+ * header's "Homepage" link, or the link under the buttons). Leaving for the
+ * homepage sticks: the Worker stops sending this browser here until it
+ * approves the app in Zoom again.
*
* Reached two ways. A browser that has added the app from our site before is
* sent here by the Worker when it opens a bare / (worker/reconnect.js), which
@@ -26,9 +29,16 @@ import { trackEvent } from '../utils/posthog'
const BTN_PRIMARY = 'inline-flex items-center justify-center rounded-full bg-ink px-7 py-3 text-base font-semibold text-white hover:bg-stone-700 transition-colors'
const LINK = 'underline underline-offset-4 decoration-stone-300 hover:text-ink hover:decoration-ink transition-colors'
+// /?home, not /. The Worker sends a returning browser's bare / to this page
+// (#96). A full navigation, not a client-side , so the request reaches the
+// Worker: it remembers the choice, and the next bare / is the homepage
+// (worker/reconnect.js, reconnectDismissal).
+const HOME_URL = '/?home'
+
// The homepage's click event, with this page's path. `cta` is what the click
-// does: approve_in_zoom, web_timer, open_in_zoom or home.
-const trackCta = (cta) => () => trackEvent('cta_clicked', { cta, location: 'hero', page: '/reconnect' })
+// does: approve_in_zoom, web_timer, open_in_zoom or home. `location` tells the
+// three ways home apart: hero (under the buttons), header or logo.
+const trackCta = (cta, location = 'hero') => () => trackEvent('cta_clicked', { cta, location, page: '/reconnect' })
const REASSURANCES = [
{ title: 'Your agendas, roles and reports are safe.', body: 'Approving does not touch them.' },
@@ -45,13 +55,18 @@ export default function Reconnect() {
return (
-
-
-
Toastmusters Timer
+
@@ -94,17 +109,14 @@ export default function Reconnect() {
Use the browser timer instead
-
+
Already approved? Open in Zoom
{' · '}
- {/* /?home, not /. The design sends a returning browser's bare /
- to this page (#96); a query string always reaches the
- homepage, and keeps it there on a reload. */}
-
+
Go to the homepage
-
+
diff --git a/apps/web/src/pages/Reconnect.test.jsx b/apps/web/src/pages/Reconnect.test.jsx
index 0b20530c..d25f0766 100644
--- a/apps/web/src/pages/Reconnect.test.jsx
+++ b/apps/web/src/pages/Reconnect.test.jsx
@@ -106,17 +106,24 @@ describe('Reconnect', () => {
expect(screen.getByRole('link', { name: 'Use the browser timer instead' })).toHaveAttribute('href', '/timer/app');
});
- // A bare / is where a returning browser gets sent back here; any query string
- // reaches the homepage and keeps it there on a reload.
- it('"Go to the homepage" goes to /?home, not /', () => {
+ // A bare / is where a returning browser gets sent back here. Every way home
+ // goes to /?home with a full page load, not a client-side route, so the
+ // Worker sees the request and stops sending this browser back here.
+ it.each([
+ ['Go to the homepage'],
+ ['Homepage'],
+ [/^Toastmusters Timer app logo/],
+ ])('"%s" goes to /?home with a full page load', (name) => {
renderPage();
- const home = screen.getByRole('link', { name: 'Go to the homepage' });
+ const home = screen.getByRole('link', { name });
expect(home).toHaveAttribute('href', '/?home');
fireEvent.click(home);
- expect(screen.getByTestId('location')).toHaveTextContent('/?home');
+ // The router did not handle it: still on the reconnect page.
+ expect(screen.queryByTestId('location')).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Reconnect Toastmusters Timer to Zoom');
});
// The funnel's second step is cta_clicked { cta: 'approve_in_zoom' } on this
@@ -126,12 +133,14 @@ describe('Reconnect', () => {
['Use the browser timer instead', 'web_timer'],
['Already approved? Open in Zoom', 'open_in_zoom'],
['Go to the homepage', 'home'],
- ])('tracks a click on "%s" as cta_clicked %s', (name, cta) => {
+ ['Homepage', 'home', 'header'],
+ [/^Toastmusters Timer app logo/, 'home', 'logo'],
+ ])('tracks a click on "%s" as cta_clicked %s', (name, cta, location = 'hero') => {
renderPage();
fireEvent.click(screen.getByRole('link', { name }));
expect(trackEvent).toHaveBeenCalledTimes(1);
- expect(trackEvent).toHaveBeenCalledWith('cta_clicked', { cta, location: 'hero', page: '/reconnect' });
+ expect(trackEvent).toHaveBeenCalledWith('cta_clicked', { cta, location, page: '/reconnect' });
});
});
diff --git a/apps/web/src/pages/TimerApp.test.jsx b/apps/web/src/pages/TimerApp.test.jsx
index c871dc5b..53e77f54 100644
--- a/apps/web/src/pages/TimerApp.test.jsx
+++ b/apps/web/src/pages/TimerApp.test.jsx
@@ -13,7 +13,7 @@ import TimerApp from './TimerApp';
*/
const club = (over = {}) => ({
- clubToken: 'club.tok',
+ uid: 'u-1',
ver: 1,
club: { id: 'club-1', name: 'Claude Test Club' },
kit: {
diff --git a/apps/web/src/staticPages.patron.test.js b/apps/web/src/staticPages.patron.test.js
new file mode 100644
index 00000000..a66a388b
--- /dev/null
+++ b/apps/web/src/staticPages.patron.test.js
@@ -0,0 +1,38 @@
+// #160: the "Buy me a coffee" patron link on the hand-written HTML pages, which
+// React never renders: the 13 pages in public/ (in their footer) and /support
+// (apps/zoom-app/public/support.html, which has no footer). A thank-you only:
+// a plain link to the Buy Me a Coffee page, in a new tab.
+import { readFileSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+
+const PATRON_URL = 'https://buymeacoffee.com/shuhao';
+const PUBLIC_DIR = path.resolve(__dirname, '../public');
+const SUPPORT_PAGE = path.resolve(__dirname, '../../zoom-app/public/support.html');
+const pages = readdirSync(PUBLIC_DIR).filter((f) => f.endsWith('.html'));
+
+const parse = (file) => new DOMParser().parseFromString(readFileSync(file, 'utf8'), 'text/html');
+const coffeeLinks = (root) =>
+ [...root.querySelectorAll('a')].filter((a) => a.textContent.replace(/\s+/g, ' ').trim() === 'Buy me a coffee');
+
+function expectPatronLink(link) {
+ expect(link, 'a "Buy me a coffee" link').toBeDefined();
+ expect(link.getAttribute('href')).toBe(PATRON_URL);
+ expect(link.getAttribute('target')).toBe('_blank');
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
+}
+
+describe('"Buy me a coffee" on the static pages', () => {
+ it('finds all 13 pages', () => {
+ expect(pages).toHaveLength(13);
+ });
+
+ it.each(pages)('%s has it in its footer, opening in a new tab', (file) => {
+ const footer = parse(path.join(PUBLIC_DIR, file)).querySelector('footer');
+ expect(footer, 'a ').not.toBeNull();
+ expectPatronLink(coffeeLinks(footer)[0]);
+ });
+
+ it('/support has it, opening in a new tab', () => {
+ expectPatronLink(coffeeLinks(parse(SUPPORT_PAGE).body)[0]);
+ });
+});
diff --git a/apps/web/src/utils/webIdentity.js b/apps/web/src/utils/webIdentity.js
index 0408d9c3..b2066dfd 100644
--- a/apps/web/src/utils/webIdentity.js
+++ b/apps/web/src/utils/webIdentity.js
@@ -5,6 +5,8 @@ import {
subscribeEntitlement,
FREE_ENTITLEMENT,
setFlags,
+ syncClubWithIdentity,
+ forgetClub,
} from '@toastmaster-timer/shared'
import { identifyUser, setUserProperties } from './posthog'
@@ -22,8 +24,9 @@ import { identifyUser, setUserProperties } from './posthog'
// /api/me, which keeps flag resolution at one request per page load.
const ME_ENDPOINT = '/api/me?flags=1'
// `flags: null` for when the Worker could not be reached: the flag store reads
-// it as "answered, all off", so nothing gated waits forever.
-const ANONYMOUS = Object.freeze({ identified: false, uid: null, entitlement: null, flags: null })
+// it as "answered, all off", so nothing gated waits forever. `reachable` says
+// whether it answered at all, which is what the club copy is applied on.
+const ANONYMOUS = Object.freeze({ identified: false, uid: null, entitlement: null, flags: null, reachable: false })
let identityPromise = null
@@ -39,8 +42,11 @@ async function resolveOnce() {
// Read before the uid check: a signed-out visitor gets `{ uid: null, flags }`
// and still has to end the load knowing which features to show.
const flags = body?.flags ?? null
- if (!response.ok || !body?.uid) return { ...ANONYMOUS, flags }
- return { identified: true, uid: body.uid, entitlement: body.entitlement ?? null, flags }
+ // A 401 is an answer; a 5xx is a Worker (or the edge in front of it) that
+ // could not give one.
+ const reachable = response.status < 500
+ if (!response.ok || !body?.uid) return { ...ANONYMOUS, flags, reachable }
+ return { identified: true, uid: body.uid, entitlement: body.entitlement ?? null, flags, reachable }
} catch {
return { ...ANONYMOUS }
}
@@ -48,7 +54,7 @@ async function resolveOnce() {
/**
* @returns {Promise<{identified: boolean, uid: string|null, entitlement: Object|null,
- * flags: Object|null}>} never rejects
+ * flags: Object|null, reachable: boolean}>} never rejects
*/
export function resolveWebIdentity() {
if (!identityPromise) identityPromise = resolveOnce().catch(() => ({ ...ANONYMOUS }))
@@ -68,6 +74,8 @@ export async function signOut() {
// The cookie may survive, but the page reload below shows the truth.
}
identityPromise = null
+ // The club belongs to the account that just signed out, not to this browser.
+ forgetClub()
}
/**
@@ -77,13 +85,30 @@ export async function signOut() {
*/
export async function startWebSession() {
const identity = await resolveWebIdentity()
- setEntitlement(identity.entitlement ?? FREE_ENTITLEMENT)
+ // An /api/me that never answered says nothing about the plan, so a club
+ // member offline keeps the Pro their club copy gives them below.
+ if (identity.reachable) setEntitlement(identity.entitlement ?? FREE_ENTITLEMENT)
+ // The club, now that the account is known (#167): refreshed for this
+ // account, forgotten for any other or for a signed-out browser. Offline the
+ // browser can't tell whose its cookie is, so, like Zoom while it says
+ // authorized, it trusts its copy. The forgetting happens before the flags
+ // below can switch club features on.
+ const clubSynced = syncClubWithIdentity({
+ identified: identity.identified,
+ uid: identity.uid,
+ authStatus: identity.identified || !identity.reachable ? 'authorized' : 'unauthenticated',
+ reachable: identity.reachable,
+ entitlement: identity.entitlement,
+ }).catch(() => null)
// In the same breath as the entitlement, so a flag-gated control and an
// entitlement-gated one appear together. Held for the whole page; nothing
// re-asks.
setFlags(identity.flags)
setUserProperties({ surface: 'web', web_signed_in: identity.identified })
- if (!identity.identified) return identity
+ if (!identity.identified) {
+ await clubSynced
+ return identity
+ }
// Same namespace as the Zoom app, so one person is one person in PostHog.
identifyUser(`zoom:${identity.uid}`)
@@ -101,7 +126,7 @@ export async function startWebSession() {
wasPro = nowPro
})
- await startSync().catch(() => {})
+ await Promise.all([startSync().catch(() => {}), clubSynced])
return identity
}
diff --git a/apps/web/src/utils/webIdentity.test.js b/apps/web/src/utils/webIdentity.test.js
index 9fed5fb0..d1de50a9 100644
--- a/apps/web/src/utils/webIdentity.test.js
+++ b/apps/web/src/utils/webIdentity.test.js
@@ -3,6 +3,7 @@ import { resolveWebIdentity, signInUrl, signOut, startWebSession, resetWebIdenti
import { identifyUser } from './posthog';
import {
getEntitlement,
+ isEntitlementKnown,
resetEntitlementForTests,
getFlags,
areFlagsKnown,
@@ -23,11 +24,11 @@ afterEach(() => {
describe('resolveWebIdentity', () => {
it('is anonymous on 401, network failure, or a body without a uid', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json: async () => ({}) })));
- expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: null });
+ expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: null, reachable: true });
resetWebIdentityForTests();
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
- expect(await resolveWebIdentity()).toMatchObject({ identified: false });
+ expect(await resolveWebIdentity()).toMatchObject({ identified: false, reachable: false });
});
it('identifies from /api/me using the cookie, once per page load', async () => {
@@ -39,7 +40,7 @@ describe('resolveWebIdentity', () => {
vi.stubGlobal('fetch', fetchMock);
const [a, b] = await Promise.all([resolveWebIdentity(), resolveWebIdentity()]);
- expect(a).toEqual({ identified: true, uid: 'u1', entitlement: { plan: 'pro', entitled: true }, flags: { pro: true } });
+ expect(a).toEqual({ identified: true, uid: 'u1', entitlement: { plan: 'pro', entitled: true }, flags: { pro: true }, reachable: true });
expect(a).toBe(b);
expect(fetchMock).toHaveBeenCalledTimes(1);
// The identity call is the one that asks for flags; the entitlement polls
@@ -52,12 +53,12 @@ describe('resolveWebIdentity', () => {
// flags have to be read before the uid decides this is anonymous.
it('keeps the flags for a signed-out visitor', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ uid: null, flags: { pro: true } }) })));
- expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: { pro: true } });
+ expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: { pro: true }, reachable: true });
});
it('survives a body that is not JSON', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 502, json: async () => { throw new SyntaxError('not json'); } })));
- expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: null });
+ expect(await resolveWebIdentity()).toEqual({ identified: false, uid: null, entitlement: null, flags: null, reachable: false });
});
});
@@ -124,4 +125,11 @@ describe('startWebSession', () => {
expect(areFlagsKnown()).toBe(true);
expect(getFlags()).toEqual({});
});
+
+ // A club member offline keeps the Pro their club copy gives them (#167).
+ it('says nothing about the plan when the Worker cannot be reached', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
+ await startWebSession();
+ expect(isEntitlementKnown()).toBe(false);
+ });
});
diff --git a/apps/zoom-app/public/documentation.html b/apps/zoom-app/public/documentation.html
index 049c01fe..1e4f1499 100644
--- a/apps/zoom-app/public/documentation.html
+++ b/apps/zoom-app/public/documentation.html
@@ -267,8 +267,7 @@ Managing Multiple Speakers (Agenda Tab)
Add Speakers:
Click "Add Speaker" to add manually
- Or use "Import from Text" to paste a list of names
- Or use "Import from Easy-Speak" if you use Easy-Speak for meeting management
+ Or use "Import Text" and paste your agenda: a table of roles and names (an EasySpeak meeting page, for one), or a list with one speaker per line and the role in brackets or after a dash. A speaker gets a role when the agenda names one that is in your role list, however it is spelt; you pick the role for the rest
Reorder Speakers: Drag and drop speakers to reorder them
diff --git a/apps/zoom-app/public/privacy.html b/apps/zoom-app/public/privacy.html
index a1407c7a..8b2445a5 100644
--- a/apps/zoom-app/public/privacy.html
+++ b/apps/zoom-app/public/privacy.html
@@ -74,7 +74,7 @@
Privacy Policy
-
Last Updated: October 4, 2026
+
Last Updated: December 1, 2026
1. Introduction
@@ -93,6 +93,7 @@
2. Information We Collect
Billing Email Address: If you subscribe to the Pro plan, we store the email address you entered on Stripe's checkout page, against your Stripe customer identifier. It is stored for one purpose: a Pro subscription covers a whole club, and the club's officers change, so the club's settings page can be reached by a sign-in link sent to the address that pays. We do not use it for marketing and we do not share it. It is kept separately from your Zoom account email, described above.
Club Information (Pro): A Pro subscription creates a club record holding the club's name, an optional logo you upload, a colour, the club's shared timing presets, and a list of the devices and Zoom user IDs that have joined the club with its code. A club member's role (admin, editor or member) is stored against their Zoom user ID.
Timing Reports (Pro clubs only): On a device that has joined a Pro club, each finished speech is saved to that club's archive on our servers: the speaker name as the timer typed it, the role, the duration, and any comment the timer added. Speaker names on the timing report are typed by the timer, so please enter only what your club is comfortable recording. On a free device, reports stay on the device and are never sent to us. If a club shares a report as a link, that report becomes readable by anyone holding the link.
+
AI Agenda Import (Pro, optional): An agenda the app can read by itself (a table of roles and names such as an EasySpeak page, or one speaker per line) is read on your device and is not sent anywhere. If you ask the app to read an agenda with AI, or you upload a photo or a file of one, that text or file is sent to our servers and on to an AI model, which lists the speakers and roles it finds. The names of your timing roles, and the times you set for them, are sent with it so the model can choose a role for each speaker. It is used to answer that one request and nothing else: we do not store it and we do not log it. An agenda names the people speaking, so please import only what your club is comfortable sharing in this way.
Sign-in on the web (optional): On our website you can sign in with your Zoom account. Zoom then tells us your Zoom user ID and your Zoom account email and name, as described above, so your settings and plan are the same on the web and in Zoom. We do not receive your password, and we do not keep the access token Zoom issues.
Usage Data: We collect anonymous product analytics — which features are used, how many speeches are timed, and approximate country — to understand how the app is used and what to improve. We do not sell this data or use it for advertising.
@@ -158,17 +159,28 @@
6. Third-Party Services
Zoom's Privacy Policy .
- We use three service providers and no others: PostHog
+ We use four service providers and no others: PostHog
for the product analytics described above,
Cloudflare to host
- the app and store synced settings, contact details and subscription status, and
+ the app, store synced settings, contact details and subscription status, and run the
+ AI model behind AI Agenda Import,
Stripe to process payments for
- the Pro plan. When you subscribe, Stripe collects your payment details and email address
+ the Pro plan, and OpenRouter
+ as the backup for AI Agenda Import. When you subscribe, Stripe collects your payment details and email address
for receipts under its own privacy policy; we receive your plan status, opaque Stripe
identifiers, and the email address you entered, which we store for the club sign-in link
described above. Sign-in emails are sent through Cloudflare. We do not sell your
information or share it with advertisers.
+
+ AI Agenda Import is processed by Cloudflare's Workers AI, which does not keep what it is
+ sent and does not use it to train AI models. Only when that service cannot answer, the
+ same request is sent through OpenRouter to one of the AI model providers it routes to.
+ Those providers handle it under their own policies, which may include keeping the request
+ or using it to improve their models. If your club would rather not have an agenda
+ processed this way, paste it in a format the app reads by itself, or add the speakers by
+ hand: neither sends anything to an AI model.
+
7. Data Security
diff --git a/apps/zoom-app/public/support.html b/apps/zoom-app/public/support.html
index 1c3a476c..936aad61 100644
--- a/apps/zoom-app/public/support.html
+++ b/apps/zoom-app/public/support.html
@@ -329,6 +329,10 @@
Reporting Bugs
Found a bug? Please report it to
shuhao@starwatchlabs.com
with the subject line "Bug Report" and include as much detail as possible about the issue.
+
+
+ Buy me a coffee
+