Commit Graph

379 Commits

Author SHA1 Message Date
Arnas Donauskas
ddf15184c8
fix(migration-014): drop subquery from buttons CHECK (Postgres disallows it)
Postgres rejects CHECK constraints that contain subqueries with
SQLSTATE 0A000 — `NOT EXISTS (SELECT 1 FROM jsonb_array_elements(...))`
inside CHECK is illegal even though it parses.

Move per-element validation entirely to the API layer (the upcoming
template-validators in PR 3). The DB CHECK keeps the cheap shape
guard: NULL or an array of length <= 10. Per-element validation
needs specific error messages anyway ("button #3 has no `text` field")
which API-layer validators do much better than a CHECK violation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 12:21:14 +02:00
Arnas Donauskas
aa4f34c94c
feat(templates): store raw Meta status enum + lay schema groundwork for submission
Switches message_templates.status from the local TitleCase set
(Draft|Pending|Approved|Rejected) to Meta's raw enum (DRAFT|PENDING|
APPROVED|REJECTED|PAUSED|DISABLED|IN_APPEAL|PENDING_DELETION) and
adds the columns the upcoming submit / edit / resubmit / webhook
flows need. No new user-facing behavior — this is groundwork.

Migration 014 also adds:

  * sample_values JSONB        Meta requires these for variable templates
  * meta_template_id TEXT      hsm_id for scoped edit/delete (avoids
                               nuking sibling-language variants)
  * rejection_reason TEXT      surfaced from webhook on REJECTED
  * quality_score TEXT         GREEN | YELLOW | RED, from webhook
  * header_handle TEXT         from Resumable Upload (media headers)
  * header_media_url TEXT      URL fallback for media headers (v1 path)
  * submission_error TEXT      last 4xx from Meta, for retry surface
  * last_submitted_at          rate-limit awareness (100 creates/hour)
  * buttons JSONB shape CHECK  permissive array-of-typed-objects guard
                               (strict per-type validation lives in API)
  * UNIQUE (user_id, name, language)
                               so sync upsert is atomic and prevents
                               duplicate language variants
  * idx on meta_template_id    fast webhook lookup

Sync route now:
  * persists Meta's status verbatim (PAUSED no longer collapses to
    REJECTED — these are different states with different recoverability)
  * parses BUTTONS components into the new discriminated-union shape
  * extracts sample_values from body.example.body_text + header.example
  * persists meta_template_id, quality_score, header_handle

Shared template-status.ts gives the manager / inbox picker / broadcast
picker one source of truth for labels + dark-theme badge classes.

Part of the Issue #147 overhaul plan (PR 2 of 6 in the sequence).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 12:12:01 +02:00
Arnas Donauskas
3b0d841533
Merge pull request #148 from ArnasDon/fix/template-header-none-sentinel
fix(templates): map "None" header sentinel to null before save
2026-05-29 11:48:25 +02:00
Arnas Donauskas
266e487ac8
fix(templates): map "None" header sentinel to null before save
The header type Select uses value="none" as a sentinel (Radix disallows
value=""), but the Save handler passed it through verbatim to Supabase.
The DB CHECK constraint on message_templates.header_type only allows
text|image|video|document, so picking "None" raised a constraint
violation and the template never saved.

Normalize "none" (and any falsy value) to '' at the input boundary so
form.header_type is always either '' (→ null on save) or a valid type.

Closes #147 (the header-dropdown half — Meta submission is tracked separately).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 11:45:59 +02:00
Arnas Donauskas
e828372fe3
Merge pull request #142 from ArnasDon/dependabot/npm_and_yarn/lucide-react-1.16.0
chore(deps): bump lucide-react from 1.8.0 to 1.16.0
2026-05-26 15:27:58 +02:00
dependabot[bot]
56345ca986
chore(deps): bump lucide-react from 1.8.0 to 1.16.0
Bumps [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) from 1.8.0 to 1.16.0.
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.16.0/packages/lucide-react)

---
updated-dependencies:
- dependency-name: lucide-react
  dependency-version: 1.16.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-26 13:27:34 +00:00
Arnas Donauskas
ddfc1b601f
Merge pull request #141 from ArnasDon/dependabot/npm_and_yarn/base-ui/react-1.5.0
chore(deps): bump @base-ui/react from 1.4.1 to 1.5.0
2026-05-26 15:26:23 +02:00
Arnas Donauskas
08b6b2154d
Merge pull request #140 from ArnasDon/dependabot/npm_and_yarn/date-fns-4.3.0
chore(deps): bump date-fns from 4.1.0 to 4.3.0
2026-05-26 15:25:14 +02:00
dependabot[bot]
857595a81f
chore(deps): bump date-fns from 4.1.0 to 4.3.0
Bumps [date-fns](https://github.com/date-fns/date-fns) from 4.1.0 to 4.3.0.
- [Release notes](https://github.com/date-fns/date-fns/releases)
- [Commits](https://github.com/date-fns/date-fns/compare/v4.1.0...v4.3.0)

---
updated-dependencies:
- dependency-name: date-fns
  dependency-version: 4.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-26 13:23:44 +00:00
dependabot[bot]
c3c17dbfac
chore(deps): bump @base-ui/react from 1.4.1 to 1.5.0
Bumps [@base-ui/react](https://github.com/mui/base-ui/tree/HEAD/packages/react) from 1.4.1 to 1.5.0.
- [Release notes](https://github.com/mui/base-ui/releases)
- [Changelog](https://github.com/mui/base-ui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/base-ui/commits/v1.5.0/packages/react)

---
updated-dependencies:
- dependency-name: "@base-ui/react"
  dependency-version: 1.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-26 13:23:41 +00:00
Arnas Donauskas
af8f17973f
Merge pull request #139 from ArnasDon/dependabot/npm_and_yarn/dev-dependencies-3c17d0768b
chore(deps-dev): bump the dev-dependencies group with 2 updates
2026-05-26 15:22:41 +02:00
Arnas Donauskas
79bddda164
Merge pull request #138 from ArnasDon/dependabot/npm_and_yarn/supabase-cb5af0f2dc
chore(deps): bump @supabase/supabase-js from 2.106.0 to 2.106.2 in the supabase group
2026-05-26 15:21:17 +02:00
Arnas Donauskas
5af535ccd6
Merge pull request #144 from ArnasDon/docs/changelog-0.2.1
docs: changelog for 0.2.1 (whatsapp_config single-tenant fix)
2026-05-26 15:15:21 +02:00
Arnas Donauskas
ec91cc3382
docs: changelog for 0.2.1 (whatsapp_config single-tenant fix)
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.
2026-05-26 11:26:17 +02:00
Arnas Donauskas
352e1db985
Merge pull request #143 from ArnasDon/fix/whatsapp-config-phone-number-collision
fix(whatsapp): prevent silent inbound-message drop on duplicate phone_number_id
2026-05-26 10:46:03 +02:00
Arnas Donauskas
71ae95f441
fix(whatsapp): prevent silent inbound-message drop when two users share a phone_number_id
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.
2026-05-26 10:35:59 +02:00
dependabot[bot]
f91ded06b1
chore(deps-dev): bump the dev-dependencies group with 2 updates
Bumps the dev-dependencies group with 2 updates: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) and [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest).


Updates `@types/node` from 25.9.0 to 25.9.1
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `vitest` from 4.1.6 to 4.1.7
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.7/packages/vitest)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.9.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-dependencies
- dependency-name: vitest
  dependency-version: 4.1.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-25 16:21:54 +00:00
dependabot[bot]
23efcdc4b4
chore(deps): bump @supabase/supabase-js in the supabase group
Bumps the supabase group with 1 update: [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js).


Updates `@supabase/supabase-js` from 2.106.0 to 2.106.2
- [Release notes](https://github.com/supabase/supabase-js/releases)
- [Changelog](https://github.com/supabase/supabase-js/blob/master/packages/core/supabase-js/CHANGELOG.md)
- [Commits](https://github.com/supabase/supabase-js/commits/v2.106.2/packages/core/supabase-js)

---
updated-dependencies:
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.106.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: supabase
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-25 16:21:27 +00:00
Arnas Donauskas
423995533c
Merge pull request #135 from ArnasDon/docs/changelog
docs: changelog for 0.2.0 (Flows + color themes + soft-GA)
2026-05-22 17:24:52 +03:00
Arnas Donauskas
f40c6becde
docs: changelog for 0.2.0 (Flows + color themes + soft-GA)
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>
2026-05-22 17:23:09 +03:00
Arnas Donauskas
515cf6427f
Merge pull request #134 from ArnasDon/feat/flows-open-to-all
feat(flows): soft-GA — open to all users + Beta label
2026-05-22 17:19:24 +03:00
Arnas Donauskas
4e89b2b902
feat(flows): soft-GA — open to all users + Beta label
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>
2026-05-22 17:16:58 +03:00
Arnas Donauskas
f3ccb002a3
Merge pull request #133 from ArnasDon/feat/color-themes-full-sweep
feat(theme): sweep remaining violet-* → primary across all surfaces
2026-05-22 17:02:37 +03:00
Arnas Donauskas
32022c13fe
feat(theme): sweep remaining violet-* → primary across all surfaces
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>
2026-05-22 17:00:32 +03:00
Arnas Donauskas
dc3eac34e3
Merge pull request #132 from ArnasDon/feat/color-themes
feat(settings): color theme picker (5 themes)
2026-05-22 16:50:37 +03:00
Arnas Donauskas
54a969c56d
feat(settings): color theme picker (5 themes)
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>
2026-05-22 16:48:40 +03:00
Arnas Donauskas
39b03f1299
Merge pull request #131 from ArnasDon/fix/flows-dialog-actually-wider
fix(flows): create-flow dialog was still clamped to 384px — override sm: variant
2026-05-22 16:27:10 +03:00
Arnas Donauskas
df6c8e34ac
fix(flows): create-flow dialog was still clamped to 384px — override sm: variant
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>
2026-05-22 16:25:22 +03:00
Arnas Donauskas
6522b9b485
Merge pull request #130 from ArnasDon/fix/flows-sticky-validation
fix(flows): pin validation panel to viewport bottom while editing
2026-05-22 16:21:26 +03:00
Arnas Donauskas
47836d2c08
fix(flows): pin validation panel to viewport bottom while editing
"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>
2026-05-22 16:19:19 +03:00
Arnas Donauskas
87560e5768
Merge pull request #129 from ArnasDon/fix/flows-template-dialog-readability
fix(flows): widen create-flow dialog so template cards are readable
2026-05-22 16:18:47 +03:00
Arnas Donauskas
a6cc847636
fix(flows): widen create-flow dialog so template cards are readable
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>
2026-05-22 16:15:39 +03:00
Arnas Donauskas
9febfae9b2
Merge pull request #128 from ArnasDon/fix/flows-spurious-redirect
fix(flows): bounce-to-dashboard race when navigating into /flows
2026-05-22 16:07:25 +03:00
Arnas Donauskas
6fcf77de8c
fix(flows): bounce-to-dashboard race when navigating into /flows
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>
2026-05-22 16:05:59 +03:00
Arnas Donauskas
1a6419b815
Merge pull request #127 from ArnasDon/feat/flows-cron-timing-safe
fix(flows): constant-time compare for cron secret
2026-05-22 15:58:38 +03:00
Arnas Donauskas
ce9c7925a1
Merge pull request #126 from ArnasDon/feat/flows-drop-reread-and-limit
perf(flows): drop wasted re-read after reprompt reset + defensive limit(1)
2026-05-22 15:57:27 +03:00
Arnas Donauskas
dcaba6e612
Merge remote-tracking branch 'origin/main' into feat/flows-drop-reread-and-limit
# Conflicts:
#	src/lib/flows/engine.ts
2026-05-22 15:56:39 +03:00
Arnas Donauskas
fe4e0117da
fix(flows): constant-time compare for cron secret
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>
2026-05-22 15:51:34 +03:00
Arnas Donauskas
56ec96d50d
perf(flows): drop wasted re-read after reprompt reset + defensive limit(1)
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>
2026-05-22 15:48:09 +03:00
Arnas Donauskas
8ffb043303
Merge pull request #125 from ArnasDon/feat/flows-preload-nodes
perf(flows): preload all flow_nodes once per dispatch
2026-05-22 15:46:38 +03:00
Arnas Donauskas
dc58f71925
perf(flows): preload all flow_nodes once per dispatch
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>
2026-05-22 15:44:40 +03:00
Arnas Donauskas
4b368139f3
Merge pull request #124 from ArnasDon/feat/flows-atomic-execution-count
fix(flows): atomic execution_count increment via SECURITY DEFINER RPC
2026-05-22 15:42:38 +03:00
Arnas Donauskas
e83538678a
fix(flows): atomic execution_count increment via SECURITY DEFINER RPC
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>
2026-05-22 15:39:00 +03:00
Arnas Donauskas
551a857a32
Merge pull request #123 from ArnasDon/feat/flows-redact-reply-text
fix(flows): redact customer text from reply_received event payload
2026-05-22 15:38:02 +03:00
Arnas Donauskas
8ac764e3b8
fix(flows): redact customer text from reply_received event payload
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>
2026-05-22 15:35:42 +03:00
Arnas Donauskas
9ff4a8d1ba
Merge pull request #122 from ArnasDon/feat/flows-unsaved-changes-guard
feat(flows): unsaved-changes indicator + reload guard
2026-05-22 15:17:11 +03:00
Arnas Donauskas
31bd967861
Merge remote-tracking branch 'origin/main' into feat/flows-unsaved-changes-guard
# Conflicts:
#	src/components/flows/flow-builder.tsx
2026-05-22 15:16:35 +03:00
Arnas Donauskas
323e0f06cb
Merge pull request #121 from ArnasDon/feat/flows-clickable-validation-issues
feat(flows): clickable validation issues jump to node
2026-05-22 15:10:30 +03:00
Arnas Donauskas
ad91d205fb
feat(flows): unsaved-changes indicator + reload guard
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>
2026-05-22 15:10:06 +03:00
Arnas Donauskas
b95ce8b372
Merge pull request #120 from ArnasDon/feat/flows-node-card-previews
feat(flows): show content preview in collapsed node cards
2026-05-22 15:06:38 +03:00