PATCH bump for the bug fix in #143 (closes#136). Surfaces the
required migration (013_whatsapp_config_phone_number_id_unique.sql)
and the diagnostic SQL self-hosters should run before applying it,
plus a note that wacrm is single-tenant per WhatsApp number by
design.
The webhook routes inbound messages by phone_number_id and uses
`.single()` to find the owning config. If two users save the same
phone_number_id, `.single()` errors PGRST116 ("multiple rows") and every
inbound message is silently dropped while the log misleadingly reports
"No config found".
Three layers of fix:
- POST /api/whatsapp/config now rejects with 409 when another user has
already claimed the phone_number_id. The check uses a service-role
client because RLS hides the conflicting row from the saving user.
- Webhook lookup no longer uses `.single()`. It distinguishes 0 rows
(true "no config") from ≥2 rows (duplicate claim) so logs name the
real cause and list conflicting user_ids.
- Migration 013 adds UNIQUE(phone_number_id) to whatsapp_config so the
same can't happen via direct DB writes or a race. Fails loudly with a
copy-pasteable resolution hint if duplicates already exist, rather
than auto-deduping (which would destroy tokens).
Closes#136.
Versions the prior `## Unreleased` chat-actions block as 0.1.1 (it
shipped with migration 009 a few days back) and adds 0.2.0 covering
the Flows feature, color themes, and the various engine + UX work
that landed alongside.
Also bumps package.json: 0.1.0 → 0.2.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Flows feature was previously gated on a per-account
`profiles.beta_features` opt-in: the sidebar entry was invisible
to non-beta accounts, every /api/flows route 404'd, the webhook
dispatcher was a no-op, and the agent-handoff pause was skipped.
This PR opens the surface to every authenticated user. A small
"Beta" chip in the sidebar nav + on the /flows page H1 keeps the
"young feature" signal without holding anyone out.
Removed:
- `src/lib/flows/feature-flag.ts` + its tests (-11 tests).
- The `requireFlowsBeta` / `requireFlowsBetaAndOwnership` helpers
in the API routes — collapsed to plain `requireUser` / RLS
ownership.
- The `isProfileFlowsEnabled` helper + branch in the webhook
dispatcher — the runner takes the cheap "no_match" exit on
accounts with no active flows (single indexed SELECT).
- The agent-handoff pause gate in /api/whatsapp/send — the UPDATE
matches zero rows when no active run exists, also cheap.
- Client-side beta gates in the 3 flows pages (and the redundant
`useAuth` + `profileLoading` plumbing they needed).
- The defensive message-bubble gate that would have rendered
interactive replies as plain text for non-beta accounts.
- The `betaKey` field on the sidebar NavItem schema, replaced by a
simpler boolean `beta` that purely drives the visual chip.
Kept:
- `profiles.beta_features` column. Generic mechanism for future
beta gates; no current feature reads it. Comments in
`src/types/index.ts` + `use-auth.tsx` updated to say so.
- The chip can be removed in a one-liner once the team's satisfied
Flows has bedded in.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PR #132 (color themes) only tokenized the high-visibility chrome.
Inbox / contacts / pipelines / broadcasts / automations / auth /
settings sub-forms still had ~150 hard-coded `violet-*` classes
across ~32 files, so picking a non-violet theme felt half-broken —
sidebar and header changed colour, but message bubbles, deal cards,
and the broadcast wizard all stayed violet.
This is the mechanical follow-up: replace every `violet-N(/N)?`
with `primary(/N)?` so the theme picker themes the whole app.
Two non-trivial swaps inside the pass:
- `text-white` on a `bg-primary` button → `text-primary-foreground`.
Emerald and Amber define a *dark* `--primary-foreground` because
their primaries are bright; `text-white` over those would tank
contrast.
- `bg-primary hover:bg-primary` (hover identical to base — original
code had this latent bug from `hover:bg-violet-500`) → adds `/90`
on hover so the lift is visible.
Test update:
- `broadcast-status.test.ts` asserted shade numbers (`bg-X-N/10`).
Relaxed the regex to also accept token form (`bg-X/10`) since
brand-accent status badges now ride the active theme.
Files touched: 49. Lint clean (existing warnings only), 173/173
tests, typecheck + build green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a new "Appearance" tab in Settings with 5 dark color themes
(Violet, Emerald, Cobalt, Amber, Rose). Pick a theme → applied
immediately and persisted to localStorage. Boot script in the root
layout replays the pick before first paint so there's no
flash-of-default on subsequent loads.
Implementation, ordered the way it's read:
1. `globals.css` — 5 `html[data-theme="..."]` blocks extracted
verbatim from the design handoff at project/Color Themes.html.
`:root` mirrors Violet so SSR / first-paint renders correctly
even before the boot script runs. Three new tokens
(`--primary-hover`, `--primary-soft`, `--primary-soft-2`) added
to all themes — used by tinted-primary surfaces.
2. `src/lib/themes.ts` — single source of truth for the catalog
(id, name, tagline, swatch). Adding a theme = append a CSS
block + append an entry here.
3. `src/hooks/use-theme.tsx` — ThemeProvider client component. Reads
what the boot script already applied, syncs across tabs via the
`storage` event, persists to localStorage. Falls back to a no-op
setter when used outside the provider.
4. `src/app/layout.tsx` — inline `beforeInteractive` script that
reads localStorage and sets `documentElement.dataset.theme`
before React hydrates. Knowledge of valid theme IDs comes from
the THEME_IDS constant so adding a theme doesn't silently break
the boot path. Wraps the tree in ThemeProvider.
5. `src/components/settings/appearance-panel.tsx` — picker UI. 5
cards, swatch + name + tagline + a 4-tone preview strip. Active
card carries a primary-tinted ring + "Active" chip.
6. `src/app/(dashboard)/settings/page.tsx` — new "appearance" tab
alongside profile/whatsapp/templates/tags.
7. Key-surface tokenization — replaced hard-coded `violet-*` with
`primary` tokens on the high-visibility surfaces so the theme
switch feels real: sidebar logo + active nav + unread dot +
avatar fallback, header avatar, dashboard-shell loading
spinner, Flows header icon + entry-node picker icon + entry
badge + flash ring, Flows list page (template card hover,
FlowCard icon), Flows editor + runs "back" links, Settings tabs
active state.
NOT touched (intentional follow-ups):
- Per-node-type colors in flow-builder.tsx NODE_META — those are a
deliberate per-type rainbow, not a brand accent.
- The inbox/contacts/pipelines surfaces — many `violet-*` usages
there. Sweep is a contained follow-up; the user explicitly
scoped this PR to "tokens + tab + key surfaces".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PR #129 added `max-w-3xl` to the create-flow DialogContent thinking
it would widen the modal. It was a no-op. shadcn's DialogContent has
`sm:max-w-sm` baked into its default classes, and Tailwind-merge
treats `max-w-*` (base) and `sm:max-w-*` (sm-prefixed) as different
variants — both survive, and at every real desktop breakpoint the
sm-scoped 384px wins.
So the modal stayed at 384px regardless. Template cards continued to
look squished because the dialog never actually grew.
Override at the sm: variant directly. Use 4xl (896px) — gives each of
the three template cards roughly 270px of breathing room, enough for
the description to wrap to 4-5 lines instead of 10+.
Left a comment at the call site so the next person doesn't repeat
the same mistake.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
"No issues. Ready to activate." (and the equivalent error count)
sat at the very bottom of the editor. With even a handful of nodes
the panel was below the fold — the user had to scroll past every
node card to see whether they could activate.
Wrap the panel in a sticky-bottom container so the activate-readiness
status follows the user as they scroll. Shadow-xl gives it the lift
to read as "pinned" against the node list behind it.
Side fix while I was in there: the success-state panel used
bg-emerald-500/10 (10% emerald on whatever's behind). Fine when
nothing's behind, but sticky-positioned over a slate-900 node card
the green tint bled through ugly. Switched both states to a
bg-slate-950 base with the severity expressed in the border + text
color only — readable on any backdrop.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The dialog was max-w-2xl with sm:grid-cols-3, leaving each template
card ~150px wide. With p-3 padding and line-clamp-3 the descriptions
truncated to four-word fragments — the gallery looked squished even
on desktop.
- Dialog: max-w-2xl → max-w-3xl
- Grid: stack on mobile, 2-col on sm, 3-col on lg (matches the
flow-card list grid elsewhere in the page).
- Card: p-3 → p-4, gap-2 → gap-2.5, h-4 icon → h-5.
- Drop the line-clamp on the description — at the new width it fits.
- Move the "X nodes" footer above a top-border so it reads as
metadata, not part of the description.
- Add a divider above the "Or start blank" section so the two
paths feel like distinct choices.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
use-auth's `loading` flips false as soon as the session settles —
the profile fetch is fire-and-forget so the page renders quickly
with just the user object. The flows pages, though, gate access on
`isFlowsEnabled(profile.beta_features)`. During the gap between
session-ready and profile-ready they saw `{ loading: false,
profile: null }` and read it as "not opted in", redirecting a
legitimate beta user back to /dashboard.
Expose a separate `profileLoading` boolean from the auth context
that stays true until fetchProfile settles (success, missing row,
or error). Pages that branch on `profile.*` gate on it; chrome
that only needs the user object keeps using `loading` as before.
Three call sites updated: /flows, /flows/[id], /flows/[id]/runs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The `/api/flows/cron` route gated on `supplied !== expected`, which
compares strings byte-by-byte with early exit on first mismatch.
An attacker who can hit the endpoint could in principle recover the
secret one byte at a time by measuring response-time deltas. With
a high-entropy 64-char secret this is mostly theoretical, but the
upgrade is a one-liner.
Switch to crypto.timingSafeEqual with a length pre-check (the
function throws on mismatched lengths; the length itself isn't
sensitive when the expected value is set by the operator).
Not touching the equivalent line in /api/automations/cron in this
PR — one fix per branch keeps the diff easy to review and revert.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two small things noticed in review:
1. handleReplyForActiveRun did UPDATE reprompt_count=0 → SELECT *
the whole row → use it. The re-read existed because the
collect_input capture branch wrote `vars` to the DB without
mirroring the change to the local `run` object — so the next
advance step would interpolate stale vars otherwise.
Mirror the UPDATE in-memory instead. Also skip the reset UPDATE
when reprompt_count is already 0 (the common case after a
successful collect_input — that branch already zeroed it).
2. loadActiveRunForContact used .maybeSingle() which throws on >1
row. The partial unique index makes that impossible by design,
but a migration glitch or manual SQL could produce one and would
crash dispatch for that contact's webhook forever. Switch to
.order().limit(1) so the runner picks the newest and lets the
cron sweep clean up duplicates if any ever appear.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The advance loop called loadNode() on every iteration — one DB
round trip per node visited. A flow with 5 chained auto-advance
nodes (send_message → condition → set_tag → send_message → end)
cost 5 sequential round trips synchronous in the webhook hot path.
At ~50ms each that's 250ms before the customer sees anything.
Switch to a single upfront SELECT into a Map<node_key, FlowNodeRow>
keyed on the flow_id, passed through advanceFromNodeKey and
handleReplyForActiveRun. The advance loop is now in-memory and the
hot path costs one round trip regardless of chain length.
node_not_found semantics are preserved: missing keys still end the
run with that reason, same as the old per-node lookup.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
startNewRun read flows.execution_count from a cached row and wrote
`cached + 1`. Two concurrent webhooks starting runs on the same flow
for different contacts both read N and both write N+1 — one count
permanently lost.
Mirrors the automations engine's solution (migration 007): a tiny
SECURITY DEFINER function that does the increment server-side, locked
to the service role. The engine's call becomes a single RPC.
The counter is best-effort: if the RPC fails we log + continue rather
than failing the run for a stat error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The `reply_received` event was persisting `text: message.text` verbatim
into flow_run_events.payload. A customer prompted "what's your card
number?" by a collect_input node would leave the PAN sitting in the
events table forever, surfaced via the runs viewer to anyone with
access.
Switch to `text_length` only. The `node_entered` event already records
`captured_length` for the same reason after a successful capture; this
makes the asymmetry symmetric.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Editing 5 node configs and then refreshing the tab silently wiped them.
Activate also silently invoked Save first — useful, but invisible: users
had no way to know if pending edits had landed.
Adds:
- A `dirty` boolean flipped true on any user edit, false on a successful
PUT. Internal `state.status` changes from the activate API path use
raw setState and don't dirty the form.
- An "● Edited" amber chip next to the StatusBadge while dirty.
- A `beforeunload` listener that prompts the native confirm on
reload / tab-close / external-link click when dirty.
SPA navigation (sidebar, back button) isn't covered — Next 16's App
Router doesn't fire beforeunload on client-side routes. Worth a
follow-up but the accidental-refresh case is the noisier one.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The validation panel sits at the bottom of the editor. When it surfaced
an error ("node X is missing next_node_key") the user had to scroll up,
find that node, expand it, find the broken field. Long feedback loop.
Each node-scoped IssueLine becomes a button: click it and the editor
expands the offending node, scrolls it into view, and briefly rings
its border so the eye lands on the right card. Trigger-scoped issues
stay non-interactive (the trigger panel is already at the top of the
page).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
A flow with 8 send_message nodes used to show 8 identical-looking pills
in the editor — the only way to tell them apart was to expand each
one. Adds a one-line summary below the meta label when the card is
collapsed:
- send_message → first 80 chars of text
- send_buttons → text + button titles
- send_list → text + option count
- collect_input → prompt + target var
- condition → "var.email == 'support@…'"
- set_tag → "Add tag 1f8c…"
- handoff → first 80 chars of note
Empty nodes (just added, no fields set) keep the old compact look so
you can tell at a glance what still needs configuration.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The data model and the runner already supported multiple sections in a
WhatsApp interactive list, but the builder UI exposed no way to add one
— it only let you add rows within the single default section. So users
couldn't build a categorized menu (Billing / Support / Sales) without
editing the DB directly.
Adds an "Add section" button below the sections list (capped at the
WhatsApp spec's 10) and a per-section remove button (shown when more
than one section exists).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Node key and per-button/row reply IDs are auto-generated and consumed
only by the runner — exposing them in the main form read as developer
leakage. Move them behind a per-node "Show advanced" toggle so the
default UI shows only customer-facing fields. Power users who need
stable IDs for analytics can still get them.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>