Compare commits

...
11 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 4015b24857 feat(audio-search): title-matched best pick; Spotify track match is Recommended, not 'Limited sources' (v0.264.0) (#1122)
## Summary
Live kjbox night 2026-10-01: a singer's make-it for **Braxton Keith -
The Chair** got 10 Spotify results (3 were the right track) and no
torrents. Because Spotify counts as "not lossless", the search was
**tier 3 "Limited sources found"** with a wrong-track best pick ("I Own
This Bar"), so the singer pasted a YouTube link. That then hit the
YouTube bot-check.

- `getBestResult(results, searchTitle)`: when any torrent/Spotify result
is a **confirmed** track-name match, only those compete. YouTube is
never promoted this way. Ties go to seeders, then popularity
(`view_count`). If nothing in the pool ranks, the fallback stays within
the matches.
- `isConfirmedTitleMatch`: the track filename must actually be compared
and equal to the title, ignoring only trailing version suffixes (`(feat.
…)`, `[…]`, ` - 2013 Remaster`). "The Chairman" ≠ "The Chair"; "7
Rings", "Mr. Brightside" and "(I Can't Get No) Satisfaction" work.
- `checkFilenameMismatch` now strips only real audio extensions. Before,
"Mr. Brightside" lost ". Brightside" as an "extension".
- `getSearchConfidence`: a title-matched Spotify best pick is **tier 2**
(Recommended), with no "No lossless sources" warning and a "Spotify
audio" reason.

kjbox ports this 1:1 in `static-sing/audio_rank.js` (separate PR).

## Test plan
- [x] `audio-search-utils.test.ts`: 10 new tests from the real Braxton
Keith results plus edge cases (86 total)
- [x] Full frontend jest: 1617 passed
- [x] Local CodeRabbit: 3 cycles, all findings fixed

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:08:12 -04:00
github-actions[bot] 7ea86a8dda test(e2e): self-heal Stripe Checkout (fillPostalCode) (#1119)
## 🩹 Stripe Checkout self-heal

Stripe changed its hosted checkout page. In [run
#197](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37140934446)
every deterministic variant of **fillPostalCode** failed; the Gemini
fallback completed the step(s), and the purchase was then **verified
server-side** (credit granted).

This PR only adds the recipe(s) to `learned-variants.json`, so future
runs replay them deterministically (no LLM). It auto-merges once CI
passes.

### Learned recipes
```json
[
  {
    "stepId": "fillPostalCode",
    "model": "gemini-3.5-flash-lite",
    "llmCalls": 1,
    "actions": [
      {
        "type": "fill",
        "target": {
          "by": "css",
          "css": "#billingPostalCode",
          "frameUrlIncludes": "checkout.stripe.com/c/pay"
        },
        "value": "{{POSTAL_CODE}}"
      }
    ]
  }
]
```

@coderabbitai ignore

🤖 Generated by the E2E Daily self-healing workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-03 18:07:21 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 c8461e56d0 fix(e2e): self-heal CI approval — correct pending detection, re-approve open PRs (#1121)
## Summary
This fixes the approval step from #1118, found by the live test on run
37140934446. That run reported `approved=true`, but bot PR #1119's CI
run was still `action_required`: the old check treated *any* existing
`pull_request` run as already running.

- `approve_ci` now succeeds only once a `pull_request` CI run exists
that is past `action_required`. It approves pending runs as it finds
them.
- When a self-heal PR is already open, the job now runs `approve_ci` for
that PR instead of exiting. So a stuck bot PR gets unstuck on the next
run.
- Polling is tolerant of transient `gh`/`jq` failures (from the local
CodeRabbit review). An empty branch name fails fast.

## Testing
- `actionlint` is clean for the changed lines; local CodeRabbit review:
2 findings, both fixed.
- After merge: a forced-LLM run on `main` will hit the "PR already open"
path for #1119. That approves its CI with the workflow's own token and
should let it auto-merge with no manual input.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:50:38 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 1c9104a79d fix(e2e): self-heal job approves its PR's CI run (no manual step) (#1118)
## Summary
This follows #1116. The live test of the self-heal loop (bot PR #1117)
merged, but only after one manual step: approving its CI run.

- **Approve the bot PR's CI run.** A bot-authored PR's `pull_request` CI
run is created as **action_required** (waiting for approval), and until
it runs it outranks the passing CI Gate from the dispatched run. The
`self-heal-pr` job now approves that run via `POST
/actions/runs/{id}/approve`. If approval fails, it dispatches `ci.yml`
and the Discord alert says the PR needs a one-click approval, with a
link.
- **Ruleset dependency, now documented.**
`require_extra_approval_for_unattributed_changes` is now set to `false`
on the `protect main` ruleset (11423976). It's a newer GitHub setting
that defaults to true and blocks bot-authored PRs until a human
approves. This is recorded in `docs/TESTING.md` and
`docs/LESSONS-LEARNED.md`.

## Testing
- `actionlint` is clean for the changed lines.
- After merge: a forced-LLM run on `main` on a step with no learned
recipe yet (`fillPostalCode`) will open a fresh bot PR and exercise
approval → CI → auto-merge without manual input.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:30:35 +00:00
github-actions[bot] 84f709ea0e test(e2e): self-heal Stripe Checkout (selectCard) (#1117)
## 🩹 Stripe Checkout self-heal

Stripe changed its hosted checkout page. In [run
#196](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37139075045)
every deterministic variant of **selectCard** failed; the Gemini
fallback completed the step(s), and the purchase was then **verified
server-side** (credit granted).

This PR only adds the recipe(s) to `learned-variants.json`, so future
runs replay them deterministically (no LLM). It auto-merges once CI
passes.

### Learned recipes
```json
[
  {
    "stepId": "selectCard",
    "model": "gemini-3.1-flash-lite",
    "llmCalls": 3,
    "actions": [
      {
        "type": "click",
        "target": {
          "by": "css",
          "css": "[data-testid='card-accordion-item']",
          "frameUrlIncludes": "checkout.stripe.com/c/pay"
        }
      }
    ]
  }
]
```

@coderabbitai ignore

🤖 Generated by the E2E Daily self-healing workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-03 17:29:06 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 4768164a94 feat(e2e): self-healing Stripe Checkout (LLM fallback + auto-merging fix PRs) (#1116)
## Summary
Stripe's hosted checkout page has broken the daily E2E **5 times since
April** (#916, #919, #945, #1115…). Each fix added another selector, and
each new Stripe change still needed a human. This PR makes the Stripe
stage repair itself, with no manual steps.

**How it works.** `stripe-checkout.ts` now runs the checkout as verified
steps (`selectCard`, `fillCardNumber`, `fillCardExpiry`, `fillCardCvc`,
`fillCardholderName`, `fillPostalCode`, `uncheckSaveInfo`,
`submitPayment`). Each step tries, in order:
1. **learned variants** (`learned-variants.json`, newest first),
2. the existing hand-written **built-in** selectors,
3. a **Gemini fallback** that drives the page one action at a time until
the step's check passes. Model list: `gemini-3.5-flash-lite` →
`gemini-3.1-flash-lite` → `gemini-3.8-flash`; IDs that aren't available
are skipped.

A step only counts as done when its **check** passes, never just because
a click didn't throw (the root cause of run #192's misleading failure).

**Fully self-healing loop.** When the LLM repairs a step *and* the
purchase is confirmed server-side (credit granted), the new
`self-heal-pr` job (on `main` only):
- opens a **data-only** PR that changes only `learned-variants.json`
(label `e2e-self-heal`, `@coderabbitai ignore`),
- enables auto-merge,
- dispatches `ci.yml` on the branch, because PRs opened with the
workflow token don't trigger CI.

The next run replays the recipe without the LLM. Discord and the daily
email report 🩹 when this happens, and only one self-heal PR is open at a
time.

**Safety**
- Card data never reaches the LLM. It may only use per-step
`{{CARD_NUMBER}}`-style placeholders, which are substituted locally.
Field values and card-number-like digit runs are redacted from what it
sees, and inputs are masked in screenshots. Tests assert no secret
appears in the prompt.
- Guardrails refuse clicks on Link/Klarna/Cash App/Bank/"Back to…", and
on the final Pay button outside `submitPayment`. They check the
**resolved element** (text, aria-label, test ID, submit type), not just
the model's label.
- The Pay step's check is "redirected to the success page OR credit
granted server-side" (throttled), so the fallback never submits twice.
The cancel URL doesn't count as success.

**Gemini key:** the AI Studio `gemini-api-key`, billed outside the
nomadkaraoke project. A `GEMINI_API_KEY` repo secret is used if set;
otherwise it's read from Secret Manager via keyless login, and the
credential file is deleted before the tests run. With no key, the test
runs deterministic-only, as before.

Also passes the existing `E2E_STRIPE_ZIP` secret, which was never wired
up.

## Testing
- **Offline:** `playwright.selfheal.config.ts`, 21 tests with fixture
Stripe pages served on fake checkout.stripe.com/js.stripe.com and a stub
LLM. Covers: known layout uses no LLM; unknown layout → LLM repairs it →
recipe learned → replayed without the LLM; no secrets reach the LLM;
guardrails, including CSS targets; deterministic-only failure mode; unit
tests for redaction, merging and frame keys. Added to CI's smoke job.
- **Live (real Stripe, real Gemini) on this branch,** with
`self_heal_force_llm=selectCard`:
- [run
37137960148](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37137960148):
`gemini-3.5-flash-lite` completed "choose Card" in one call, credit
granted 1→2. This exposed the session ID in Stripe's URL path, now
fixed.
- [run
37138459027](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37138459027):
repeated after the review fixes. Recipe
`[data-testid="card-accordion-item"]` @ `checkout.stripe.com/c/pay`,
credit granted.
  - The PR-opening job is skipped on branches by design.
- After merge, I'll dispatch once on `main` with
`self_heal_force_llm=selectCard` to exercise the PR → CI → auto-merge
path.
- Local CodeRabbit review: 2 findings, both fixed.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:02:12 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 2b68cca183 fix(e2e): expand Stripe Checkout card accordion (daily E2E run #192) (#1115)
## Summary
Daily E2E Stage 1 failed (run #192): `Could not find card field:
cardNumber in any frame`.

**Root cause:** Stripe changed its Checkout payment-method accordion.
The Card row is now a plain `Card` text label with a visually-hidden
`button "Pay with card"`. There is no longer a radio/button named
`Card`, so the helper never expanded the accordion. This only affects
the test. Customers can still pay.

(Runs #190/#191 on Oct 1-2 failed for a different, already-fixed reason:
the Postmark 403 outage, so the magic-link email was never sent.)

## Changes
- `frontend/e2e/helpers/stripe-checkout.ts`: the chooser now matches
`Card` / `Pay with card` (radio, button, or exact label text). If the
fields still don't appear, it dispatches a click on the hidden `Pay with
card` button. On failure it writes
`test-results/stripe-checkout-dom.html` so the next markup change can be
diagnosed from the artifacts.

## Testing
- Type-checks; `playwright --list` loads the spec.
- Not run end to end yet: that needs a live Stripe charge ($0.50).
Verify with a `workflow_dispatch` of *E2E Daily Test* on this branch, or
the next scheduled run.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Tests**
* Automated checkout checks now recognize additional card-selection
options, including card choices presented as buttons or radio options,
and retry when card fields are slow to appear. If the fields remain
unavailable, the checks save diagnostic details from the checkout frames
to help investigate the issue. These updates affect the checkout test
process; no changes to the customer-facing payment flow are described.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:31:02 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 d6972f10aa infra(monitoring): alert when Postmark SMTP-fallback sends fail + document static-IP options (#1114)
## Summary
This is a follow-up to #1112/#1113 and decide#147. Postmark confirmed
(ticket #11562402) that the nginx 403s are an IP-reputation block on
shared Google us-central1 egress IPs, and they won't lift it. The SMTP
fallback is working in prod: on 2026-10-02 between 19:10 and 20:17 UTC,
12 of 12 blocked sends were delivered with 0 failures. To save money,
we're **deferring** a static egress IP and adding a free tripwire
instead.

## Changes
- `infrastructure/modules/monitoring.py`:
`create_email_delivery_observability()` adds:
- A log-based metric `email/postmark_smtp_fallback_failures`, plus an
alert policy ("Email - Postmark SMTP fallback failing (emails being
lost)") that fires on any failed fallback send in karaoke-backend **or**
karaoke-decide.
- The filter matches **both** `jsonPayload.message` (gen logs structured
JSON) and `textPayload` (decide logs plain text).
- `docs/archive/2026-10-02-postmark-ip-block-options.md`: full write-up
covering the evidence, Postmark's answer, how the fallback works, the
alert, and the static-IP options. It includes **measured costs**:
reusing the existing `github-runners-nat` with a reserved IP is
~$4–7/mo. It also has Pulumi steps, NAT sizing, and how to verify the
reserved IP is used.
- `docs/TROUBLESHOOTING.md` and `infrastructure/monitoring/README.md`
link to it.

## Testing / rollout
- Filter validated against real logs:
  - 0 failures, which is correct.
- Positive control on the gen JSON branch: 12/12 real fallback sends
matched.
  - Positive control on the decide text branch: 5/5 real lines matched.
- `pulumi preview` showed: +2 to create, 274 unchanged.
- **Already applied locally with `pulumi up`** (repo rule). The first
apply hit the log-metric propagation race, and re-running succeeded;
that gotcha is now documented in the code. The alert is live, enabled,
and has the email channel attached.
- Cost: $0 now. Alert policies cost $0.35/mo from 2027-09-01.

Local CodeRabbit review: 2 findings (Cloud NAT sizing, reserved-IP
verification in the options doc), both addressed.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 18:42:29 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 5181e42b46 fix(email): failed SMTP QUIT after an accepted send doesn't fail the send (v0.263.2) (#1113)
## Summary
This is a follow-up to #1112. CodeRabbit found the issue while reviewing
the same fix in karaoke-decide. If Postmark accepts the message but the
SMTP `QUIT` fails during the `with` block's exit, `_send_via_smtp`
reported a failure, and a caller retry could then send the email twice.
Cleanup errors are now swallowed, falling back to `close()`, and only
errors from the send itself fail the send.

## Testing
- Added `test_quit_failure_after_send_still_reports_success`. Email
tests: 72 passed.

The same change was reviewed by local CodeRabbit in karaoke-decide#147.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:38:42 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 eb1c914e4a fix(email): fall back to Postmark SMTP when the API edge returns HTML 403 (v0.263.1) (#1112)
## Summary
Since 2026-10-02 11:25 UTC **every** backend email has failed: magic
links, made-for-you order confirmations and admin alerts (e.g. job
`18bee12c`). Postmark's API edge answers our us-central1 Cloud Run
egress IPs with a bare nginx HTML 403. The retries added in v0.261.1
never get past it, because a block lasts hours.

- Postmark IP Allowlisting is **off** (checked in the UI at account and
server level). karaoke-decide (us-central1) gets the same 403s, but
us-east4 jobs and residential IPs don't. That points to a network-level
block on Postmark's side. Support ticket **#11562402** is filed.
- Postmark SMTP is served by separate infrastructure and is already
enabled on the server.

## Changes
- `PostmarkEmailProvider`: on an HTML 403 (edge block), go straight to
SMTP (`smtp.postmarkapp.com:587`, STARTTLS, server token as username and
password, `X-PM-Message-Stream: outbound`). The API retry was dropped
for this case; it only added about 4s of latency.
- Also fall back to SMTP when every API attempt hits a connect timeout
(the message never reached Postmark, so no duplicate risk).
- Unchanged: 429/5xx are still retried on the API. JSON Postmark errors
and read timeouts never fall back.
- SMTP sends return no MessageID and clear `last_message_id`.
Header-injection `ValueError`s are caught.
- `docs/TROUBLESHOOTING.md` runbook updated. Version bumped to 0.263.1.

## Testing
- 71 email unit tests, plus `make test-backend` (unit + emulator)
passing.
- **A real send through `_send_via_smtp` from a local machine** to
andrew@nomadkaraoke.com shows as `Sent` on the outbound stream in
Postmark's message API, and the Unicode subject came through intact.
- After deploy: trigger a magic-link email and confirm `via Postmark
SMTP fallback` in the backend logs.

Local CodeRabbit review: 1 finding (header-injection ValueError), fixed.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 13:50:33 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 b90ad82d90 docs: record Vertex and Gemini API shutdown in nomadkaraoke (#1111)
Records the manual (non-Pulumi) infra changes from the Gemini migration
(#1108): Vertex IAM removal, the cross-project Aquarius grant removal,
disabling aiplatform + generativelanguage in nomadkaraoke, deleting the
unused restricted API key, and how to rotate `gemini-api-key`. Docs
only, so no version bump.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Updated deployment guidance to record recent API access and credential
changes, including disabled services and removal of an unused restricted
key. The guidance also describes the associated project and billing
setup, with steps for re-enabling services or rotating credentials. No
end-user product behavior changes are included.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 22:51:39 -04:00
29 changed files with 3180 additions and 278 deletions

No files matched your search

+6
View File
@@ -181,6 +181,12 @@ jobs:
working-directory: frontend
run: npx playwright test smoke.spec.ts --project=chromium --reporter=line
# Offline (fixture pages + stub LLM) tests for the self-healing Stripe
# Checkout runner used by the daily production E2E.
- name: Run self-healing Stripe runner tests
working-directory: frontend
run: npx playwright test --config=playwright.selfheal.config.ts --reporter=line
- name: Upload Playwright report
if: failure()
uses: actions/upload-artifact@v4
+247 -1
View File
@@ -33,6 +33,11 @@ on:
required: false
default: 'false'
type: boolean
self_heal_force_llm:
description: 'Self-healing test: comma-separated Stripe step ids to force through the LLM fallback (e.g. selectCard). Learned recipes still open an auto-merge PR.'
required: false
default: ''
type: string
permissions:
contents: read
@@ -46,10 +51,16 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
permissions:
contents: read
id-token: write # keyless GCP auth, only to read the Gemini key for self-healing
outputs:
session_token: ${{ steps.extract_token.outputs.token }}
result: ${{ steps.test_result.outputs.result }}
healed: ${{ steps.self_heal.outputs.healed }}
env:
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
steps:
- name: Checkout code
@@ -74,6 +85,48 @@ jobs:
working-directory: frontend
run: mkdir -p test-results
# ── Self-healing Stripe Checkout: LLM fallback key ───────────────────
# The Stripe step runner (frontend/e2e/helpers/self-healing) falls back
# to Gemini when every deterministic variant of a step fails. The key is
# the AI Studio key (billed outside the nomadkaraoke project). Prefer a
# GEMINI_API_KEY repo secret; otherwise read it from Secret Manager via
# keyless auth. All of this is best-effort: without a key the test runs
# deterministic-only, exactly as before.
- name: Authenticate to Google Cloud (Gemini key)
id: gcp_auth
if: ${{ env.HAS_GEMINI_SECRET != 'true' }}
continue-on-error: true
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Set up Cloud SDK
if: steps.gcp_auth.outcome == 'success'
continue-on-error: true
uses: google-github-actions/setup-gcloud@v2
- name: Load Gemini key for self-healing fallback
continue-on-error: true
env:
GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY }}
GCP_AUTHED: ${{ steps.gcp_auth.outcome == 'success' }}
run: |
KEY="$GEMINI_SECRET"
if [ -z "$KEY" ] && [ "$GCP_AUTHED" = "true" ]; then
KEY=$(gcloud secrets versions access latest --secret=gemini-api-key --project=nomadkaraoke 2>/dev/null || true)
fi
# Drop the deployer credentials before any test code runs.
if [ -n "${GOOGLE_GHA_CREDS_PATH:-}" ]; then rm -f "$GOOGLE_GHA_CREDS_PATH"; fi
if [ -n "${CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE:-}" ]; then rm -f "$CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE"; fi
if [ -n "$KEY" ]; then
echo "::add-mask::$KEY"
echo "GEMINI_API_KEY=$KEY" >> "$GITHUB_ENV"
echo "Self-healing LLM fallback: enabled"
else
echo "::warning::Self-healing LLM fallback disabled (no Gemini key) — Stripe steps run deterministic-only"
fi
- name: Ensure testmail.app domain is allowlisted
run: |
curl -sf -X POST \
@@ -93,6 +146,8 @@ jobs:
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
E2E_STRIPE_ZIP: ${{ secrets.E2E_STRIPE_ZIP }}
E2E_SELF_HEAL_FORCE_LLM: ${{ inputs.self_heal_force_llm || '' }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
@@ -117,6 +172,37 @@ jobs:
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Detect self-healed Stripe steps
id: self_heal
if: always()
working-directory: frontend
run: |
REPORT=test-results/self-heal/self-heal-report.json
LEARNED=test-results/self-heal/learned-variants.json
if [ -f "$REPORT" ]; then
{
echo "### Stripe Checkout self-healing"
echo '```json'
jq '{flowVerified, llmCalls, learnedWritten, added, outcomes: [.outcomes[] | {stepId, status, via, variant, model, reason}]}' "$REPORT"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
# Only promote recipes from a run whose purchase was verified server-side.
if [ "${{ steps.test_result.outputs.result }}" = "success" ] && [ -f "$LEARNED" ]; then
echo "healed=true" >> "$GITHUB_OUTPUT"
echo "::warning::Stripe Checkout changed — LLM fallback healed it; an auto-merge PR will record the new variant"
else
echo "healed=false" >> "$GITHUB_OUTPUT"
fi
- name: Upload self-heal learned variants
if: steps.self_heal.outputs.healed == 'true'
uses: actions/upload-artifact@v4
with:
name: self-heal-learned-${{ github.run_number }}
path: frontend/test-results/self-heal/
retention-days: 30
- name: Extract session token
id: extract_token
if: steps.test_result.outputs.result == 'success'
@@ -153,6 +239,165 @@ jobs:
if: steps.test_result.outputs.result == 'failure'
run: exit 1
# =========================================================================
# Self-heal: record LLM-discovered Stripe variants via an auto-merging PR
# =========================================================================
# One Stripe layout change → one LLM-healed run → one data-only PR (only
# learned-variants.json) that auto-merges, so the next run replays the
# recipe deterministically. No human in the loop.
#
# Merge gates for a bot PR (all verified live with #1117, 2026-10-03):
# - its `pull_request` CI run is created "action_required" and, until run,
# supersedes other CI Gate results → we approve it via the API;
# - the `protect main` ruleset's require_extra_approval_for_unattributed_changes
# (GitHub default true since ~Aug 2026) would demand a human review for
# bot-authored changes → set to false on ruleset 11423976;
# - review threads must be resolved → `@coderabbitai ignore` in the body.
self-heal-pr:
name: "Self-heal: auto-merge PR"
runs-on: ubuntu-latest
timeout-minutes: 10
needs: e2e-credit-purchase
# Only learn from main — branch runs (e.g. testing self_heal_force_llm on a
# feature branch) must not open PRs against main.
if: always() && needs.e2e-credit-purchase.outputs.healed == 'true' && github.ref == 'refs/heads/main'
permissions:
contents: write
pull-requests: write
actions: write
outputs:
pr_url: ${{ steps.pr.outputs.pr_url }}
unchanged: ${{ steps.pr.outputs.unchanged }}
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
ref: main
- name: Download learned variants
uses: actions/download-artifact@v4
with:
name: self-heal-learned-${{ github.run_number }}
path: /tmp/self-heal
- name: Open auto-merge PR
id: pr
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TARGET=frontend/e2e/helpers/self-healing/learned-variants.json
# A bot-authored PR's `pull_request` CI run is created as
# "action_required" (awaiting approval) and, until it runs, supersedes
# any other CI Gate result for the ruleset. Approve it; succeed once a
# pull_request run exists that is past approval.
approve_ci() {
local branch=$1 runs pending active
for _ in $(seq 1 18); do
runs=$(gh run list --workflow ci.yml --branch "$branch" --event pull_request --json databaseId,status,conclusion) || { sleep 10; continue; }
pending=$(jq -r '.[] | select(.conclusion == "action_required" or .status == "waiting" or .status == "action_required") | .databaseId' <<<"$runs") || pending=""
active=$(jq '[.[] | select(.conclusion != "action_required" and .status != "waiting" and .status != "action_required")] | length' <<<"$runs") || active=0
for id in $pending; do
if gh api -X POST "repos/${{ github.repository }}/actions/runs/$id/approve" >/dev/null; then
echo "Approved CI run $id"
else
echo "::warning::Could not approve CI run $id with GITHUB_TOKEN"
fi
done
if [ -z "$pending" ] && [ "$active" -gt 0 ]; then
echo "CI is running for $branch"
return 0
fi
sleep 10
done
return 1
}
REPORT=/tmp/self-heal/self-heal-report.json
OPEN=$(gh pr list --label e2e-self-heal --state open --json url --jq '.[0].url // ""')
if [ -n "$OPEN" ]; then
echo "A self-heal PR is already open ($OPEN) — not opening another; making sure its CI can run"
echo "pr_url=$OPEN" >> "$GITHUB_OUTPUT"
OPEN_BRANCH=$(gh pr view "$OPEN" --json headRefName --jq .headRefName || true)
if [ -z "$OPEN_BRANCH" ] || ! approve_ci "$OPEN_BRANCH"; then
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
fi
exit 0
fi
cp /tmp/self-heal/learned-variants.json "$TARGET"
if git diff --quiet -- "$TARGET"; then
echo "learned-variants.json unchanged vs main — nothing to do"
echo "unchanged=true" >> "$GITHUB_OUTPUT"
exit 0
fi
STEPS=$(jq -r '[.outcomes[] | select(.status == "healed") | .stepId] | unique | join(", ")' "$REPORT")
BRANCH="self-heal/stripe-checkout-${{ github.run_id }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -b "$BRANCH"
git add "$TARGET"
git commit -m "test(e2e): self-heal Stripe Checkout steps: $STEPS" -m "Learned by the LLM fallback in $RUN_URL (purchase verified server-side)."
git push origin "$BRANCH"
gh label create e2e-self-heal --color FBCA04 --description "Auto-generated by the self-healing Stripe E2E" 2>/dev/null || true
{
echo "## 🩹 Stripe Checkout self-heal"
echo
echo "Stripe changed its hosted checkout page. In [run #${{ github.run_number }}]($RUN_URL) every deterministic variant of **$STEPS** failed; the Gemini fallback completed the step(s), and the purchase was then **verified server-side** (credit granted)."
echo
echo "This PR only adds the recipe(s) to \`learned-variants.json\`, so future runs replay them deterministically (no LLM). It auto-merges once CI passes."
echo
echo "### Learned recipes"
echo '```json'
jq '[.outcomes[] | select(.status == "healed") | {stepId, model, llmCalls, actions}]' "$REPORT"
echo '```'
echo
echo "@coderabbitai ignore"
echo
echo "🤖 Generated by the E2E Daily self-healing workflow"
} > /tmp/pr-body.md
PR_URL=$(gh pr create --base main --head "$BRANCH" --label e2e-self-heal \
--title "test(e2e): self-heal Stripe Checkout ($STEPS)" --body-file /tmp/pr-body.md)
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
gh pr merge "$PR_URL" --auto --squash
if approve_ci "$BRANCH"; then
echo "Opened $PR_URL (auto-merge enabled, CI approved)"
else
# Fallback: dispatched CI (allowed from GITHUB_TOKEN) puts a CI Gate
# check on the head SHA if no pull_request run ever appears.
gh workflow run ci.yml --ref "$BRANCH"
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
echo "::warning::CI for $PR_URL may need a one-click approval (PR → Checks → Approve and run)"
fi
- name: Discord notification (self-heal)
# Recipe already on main (e.g. merged between checkout and now) → nothing to report.
if: always() && steps.pr.outputs.unchanged != 'true'
run: |
PR="${{ steps.pr.outputs.pr_url }}"
if [ -n "$PR" ] && [ "${{ steps.pr.outputs.ci_needs_approval }}" = "true" ]; then
TITLE="🩹 E2E self-healed Stripe — PR needs a CI approval click"
DESC="LLM fallback healed a Stripe Checkout change. The auto-merge PR's CI run awaits approval (open the PR → Checks → Approve and run): $PR"
COLOR=16776960
elif [ -n "$PR" ]; then
TITLE="🩹 E2E self-healed a Stripe Checkout change"
DESC="Stripe changed its checkout page; the LLM fallback got through and the purchase was verified. Auto-merge PR: $PR"
COLOR=16776960
else
TITLE="⚠️ E2E self-heal PR could not be opened"
DESC="The LLM fallback healed a Stripe step but opening the PR failed — see the run."
COLOR=15105570
fi
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"$TITLE\", \"description\": \"$DESC\n\n**Run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": $COLOR}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
# =========================================================================
# Stage 2: Happy Path (uses credit from Stage 1)
# =========================================================================
@@ -309,7 +554,7 @@ jobs:
notify:
name: "Notify"
runs-on: ubuntu-latest
needs: [e2e-credit-purchase, e2e-happy-path]
needs: [e2e-credit-purchase, e2e-happy-path, self-heal-pr]
if: always()
steps:
@@ -338,6 +583,7 @@ jobs:
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
Stripe self-heal: ${{ needs.e2e-credit-purchase.outputs.healed == 'true' && format('Stripe changed its checkout; LLM fallback healed it. Auto-merge PR: {0}', needs.self-heal-pr.outputs.pr_url || (needs.self-heal-pr.outputs.unchanged == 'true' && '(already on main)' || '(failed to open — see run)')) || 'not needed' }}
Run: #${{ github.run_number }}
Trigger: ${{ github.event_name }}
+96 -16
View File
@@ -11,9 +11,13 @@ import html
import logging
import os
import re
import smtplib
import ssl
import sys
import time
from abc import ABC, abstractmethod
from email.message import EmailMessage
from email.utils import formataddr
from datetime import datetime, timedelta, timezone
from typing import NamedTuple, Optional, List
from zoneinfo import ZoneInfo
@@ -175,29 +179,40 @@ class PostmarkEmailProvider(EmailProvider):
API_URL = "https://api.postmarkapp.com/email"
# Seconds to sleep before each retry of a transient failure. Postmark's edge
# intermittently answers some us-central1 Cloud Run egress IPs with a bare
# nginx HTML 403 (not its JSON error format) — a fresh connection a moment
# later often succeeds. Kept short: magic-link sends block the request.
# SMTP fallback for when Postmark's API edge blocks us. Since 2026-09-30 the
# edge has answered us-central1 Cloud Run egress IPs with a bare nginx HTML
# 403 for hours at a time, so retrying the API doesn't help; SMTP is served
# by separate infrastructure. Auth = server token as username and password.
SMTP_HOST = "smtp.postmarkapp.com"
SMTP_PORT = 587
SMTP_TIMEOUT = 15
MESSAGE_STREAM = "outbound"
# Seconds to sleep before each retry of a transient failure (429 / 5xx /
# connect timeout). Kept short: magic-link sends block the request.
RETRY_DELAYS = (1.0, 3.0)
@staticmethod
def _is_transient_failure(response: requests.Response) -> bool:
"""True for failures worth retrying: 429, 5xx, or a non-JSON 403.
"""True for failures worth retrying against the API: 429 or 5xx."""
status = response.status_code
return status == 429 or status >= 500
@staticmethod
def _is_edge_block(response: requests.Response) -> bool:
"""True for a 403 without a JSON body: an IP-level block at Postmark's edge.
Postmark's own API errors (bad token, invalid payload, suppressed
recipient) come back as JSON and are deterministic, so retrying them
would just repeat the same answer. A 403 without a JSON body is an
edge/IP-level block, not a verdict on the request itself.
recipient) come back as JSON and are verdicts on the request itself; a
bare HTML 403 never reached the API, so the message was not accepted and
it's safe to resend it over SMTP.
"""
status = response.status_code
if status == 429 or status >= 500:
if response.status_code != 403:
return False
try:
response.json()
except ValueError:
return True
if status == 403:
try:
response.json()
except ValueError:
return True
return False
def _post_with_retry(self, payload: dict) -> requests.Response:
@@ -295,7 +310,20 @@ class PostmarkEmailProvider(EmailProvider):
if bcc_emails:
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
response = self._post_with_retry(payload)
try:
response = self._post_with_retry(payload)
except requests.ConnectTimeout:
# Never connected, so Postmark didn't accept it: safe to resend.
logger.warning("Postmark API connect timed out on every attempt; falling back to SMTP")
return self._send_via_smtp(to_email, subject, html_content, text_content,
cc_emails, bcc_emails, sender_email)
if self._is_edge_block(response):
logger.warning(
f"Postmark API edge returned HTML 403 for {to_email}; falling back to SMTP"
)
return self._send_via_smtp(to_email, subject, html_content, text_content,
cc_emails, bcc_emails, sender_email)
if 200 <= response.status_code < 300:
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
@@ -338,6 +366,58 @@ class PostmarkEmailProvider(EmailProvider):
logger.exception("Failed to send email via Postmark")
return SendResult(success=False, message_id=None)
def _send_via_smtp(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str],
cc_emails: Optional[List[str]],
bcc_emails: Optional[List[str]],
sender_email: str,
) -> SendResult:
"""Send through Postmark's SMTP endpoint (used when the API is unreachable).
SMTP returns no Postmark MessageID and can't report suppressed
recipients synchronously (Postmark logs those as bounces instead).
"""
cc = _dedupe_emails(cc_emails) if cc_emails else []
bcc = _dedupe_emails(bcc_emails) if bcc_emails else []
try:
msg = EmailMessage()
msg["From"] = formataddr((self.from_name, sender_email))
msg["To"] = to_email
msg["Subject"] = subject
msg["X-PM-Message-Stream"] = self.MESSAGE_STREAM
if cc:
msg["Cc"] = ", ".join(cc)
if text_content:
msg.set_content(text_content)
msg.add_alternative(html_content, subtype="html")
else:
msg.set_content(html_content, subtype="html")
smtp = smtplib.SMTP(self.SMTP_HOST, self.SMTP_PORT, timeout=self.SMTP_TIMEOUT)
try:
smtp.starttls(context=ssl.create_default_context())
smtp.login(self.server_token, self.server_token)
smtp.send_message(msg, to_addrs=[to_email, *cc, *bcc])
finally:
# A failed QUIT after an accepted send must not fail the send
# (a caller retry would then duplicate the email).
try:
smtp.quit()
except (smtplib.SMTPException, OSError):
smtp.close()
except (smtplib.SMTPException, OSError, ValueError):
# ValueError: EmailMessage rejects CR/LF in header values.
logger.exception(f"Failed to send email to {to_email} via Postmark SMTP fallback")
return SendResult(success=False, message_id=None)
logger.info(f"Email sent to {to_email} via Postmark SMTP fallback")
self.last_message_id = None
return SendResult(success=True, message_id=None)
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
# lyrics/instrumental review access, referral codes). We persist a redacted copy
+88 -11
View File
@@ -285,25 +285,101 @@ class TestPostmarkRetry:
def provider(self):
return PostmarkEmailProvider(server_token="t", from_email="f@e.com")
def test_html_403_then_success_is_retried(self, provider):
"""The prod failure mode: nginx HTML 403 from Postmark's edge, then OK."""
@pytest.fixture
def mock_smtp(self):
with patch("backend.services.email_service.smtplib.SMTP") as smtp_cls:
self.smtp = smtp_cls.return_value
yield smtp_cls
def test_html_403_falls_back_to_smtp_without_api_retries(self, provider, mock_smtp):
"""The prod failure mode: nginx HTML 403 from Postmark's edge lasts hours."""
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = [self._response(403, json_body=False), self._response(200)]
mock_post.return_value = self._response(403, json_body=False)
result = self._send(provider)
assert result.success is True
assert result.message_id == "abc"
assert mock_post.call_count == 2
self.mock_sleep.assert_called_once_with(1.0)
assert result.message_id is None
assert mock_post.call_count == 1
self.mock_sleep.assert_not_called()
mock_smtp.assert_called_once_with("smtp.postmarkapp.com", 587, timeout=15)
self.smtp.starttls.assert_called_once()
self.smtp.login.assert_called_once_with("t", "t")
msg = self.smtp.send_message.call_args.args[0]
assert msg["To"] == "user@example.com"
assert msg["From"] == "Nomad Karaoke <f@e.com>"
assert msg["X-PM-Message-Stream"] == "outbound"
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == ["user@example.com"]
def test_html_403_gives_up_after_all_attempts(self, provider):
def test_smtp_fallback_builds_multipart_with_cc_bcc(self, provider, mock_smtp):
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = provider.send_email_detailed(
to_email="user@example.com",
subject="Ünïcode subject",
html_content="<p>hi</p>",
text_content="hi",
cc_emails=["cc@example.com", "CC@example.com"],
bcc_emails=["bcc@example.com"],
from_email_override="tenant@example.com",
)
assert result.success is True
msg = self.smtp.send_message.call_args.args[0]
assert msg["Cc"] == "cc@example.com"
assert msg["Bcc"] is None # BCC never appears in headers
assert msg["Subject"] == "Ünïcode subject"
assert msg["From"] == "Nomad Karaoke <tenant@example.com>"
assert msg.get_body(("plain",)).get_content().strip() == "hi"
assert msg.get_body(("html",)).get_content().strip() == "<p>hi</p>"
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == [
"user@example.com", "cc@example.com", "bcc@example.com"
]
def test_smtp_fallback_failure_reports_failure(self, provider, mock_smtp):
import smtplib as _smtplib
self.smtp.login.side_effect = _smtplib.SMTPAuthenticationError(535, b"bad")
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = self._send(provider)
assert result.success is False
assert mock_post.call_count == 3
assert [c.args[0] for c in self.mock_sleep.call_args_list] == [1.0, 3.0]
def test_smtp_fallback_connection_error_reports_failure(self, provider, mock_smtp):
mock_smtp.side_effect = OSError("unreachable")
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = self._send(provider)
assert result.success is False
def test_smtp_fallback_rejects_header_injection_without_raising(self, provider, mock_smtp):
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = provider.send_email_detailed(
to_email="user@example.com", subject="Song\nBcc: evil@example.com", html_content="<p>x</p>"
)
assert result.success is False
self.smtp.send_message.assert_not_called()
def test_quit_failure_after_send_still_reports_success(self, provider, mock_smtp):
"""Postmark already accepted the message; a failed QUIT must not trigger a resend."""
import smtplib as _smtplib
self.smtp.quit.side_effect = _smtplib.SMTPServerDisconnected("gone")
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = self._send(provider)
assert result.success is True
self.smtp.close.assert_called_once()
def test_smtp_success_clears_stale_message_id(self, provider, mock_smtp):
provider.last_message_id = "old"
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
self._send(provider)
assert provider.last_message_id is None
@pytest.mark.parametrize("status", [429, 500, 503])
def test_rate_limit_and_server_errors_are_retried(self, provider, status):
@@ -340,14 +416,15 @@ class TestPostmarkRetry:
assert result.success is True
assert mock_post.call_count == 2
def test_connect_timeout_on_every_attempt_fails_cleanly(self, provider):
def test_connect_timeout_on_every_attempt_falls_back_to_smtp(self, provider, mock_smtp):
import requests as _requests
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = _requests.ConnectTimeout("slow")
result = self._send(provider)
assert result.success is False
assert result.success is True
assert mock_post.call_count == 3
self.smtp.send_message.assert_called_once()
def test_read_timeout_not_retried_to_avoid_duplicate_send(self, provider):
"""Postmark may have accepted the message; it has no idempotency key."""
+37
View File
@@ -1415,6 +1415,20 @@ quota/billing/key errors (not per-minute 429s) skip retries, degrade, and Discor
at most once per 6h. (Supersedes the old "Vertex AI Auth" / "global location" notes —
the Developer API has no project/location.)
**Manual (non-Pulumi) changes made 2026-10-02 (admin@nomadkaraoke.com), after v0.262.0
deployed and Vertex `request_count` stayed at zero:**
- 02:46Z `roles/aiplatform.user` binding for `karaoke-backend` deleted (Pulumi, targeted).
- 02:47Z removed cross-project `roles/aiplatform.user` for
`aquarius-backend@aquarius-fundraising-mvp.iam.gserviceaccount.com` (zero traffic).
- 02:48Z `gcloud services disable aiplatform.googleapis.com generativelanguage.googleapis.com`
(no `--force` needed). Re-enable with `gcloud services enable ...` if ever required.
- 02:49Z deleted unused restricted API key `98073667-…` ("Generative Language API Key";
0 valid requests in 30 days; undelete possible for 30 days via `gcloud services api-keys undelete`).
- `gemini-api-key` belongs to AI Studio project `gen-lang-client-0983596166` (number
810524901596), billed to "Aquarius Billing". To swap keys: `printf '%s' "$KEY" | gcloud
secrets versions add gemini-api-key --project=nomadkaraoke --data-file=-`, then roll the
service (any new revision) — jobs pick it up on their next execution.
### LangChain: REST over gRPC
Use `langchain-google-genai` (REST) instead of `langchain-google-vertexai` (gRPC) to avoid silent hangs.
@@ -2207,3 +2221,26 @@ got it right. What we learned (verified on prod's static ffmpeg 7.0.2 and libass
fallback. Verify rendering in Linux (`scripts/run-render-tests-linux.sh`).
- **Dropped sub-0.1s word gaps made the highlight run early** (up to 0.22s by line end on
this job). Karaoke tags now come from one absolute centisecond timeline.
## Stripe Checkout E2E: self-heal instead of chasing selectors (2026-10-03)
Stripe's hosted checkout broke the daily E2E five times in six months (radio→button chooser,
card-only layout, nested iframe, relabelled name/ZIP, hidden "Pay with card" overlay). Each fix
added another selector variant — and each next change still needed a human. Lessons:
- **Verify sub-goals, don't trust actions.** Run #192 "selected Card" (it found nothing to
click), carried on, and failed later on a symptom. Every step now has a `verify`
postcondition; a variant only counts if the postcondition holds.
- **Self-heal into data, not code.** The LLM fallback's output is a serializable recipe
(semantic role/name/text targets, never snapshot refs), promoted to `learned-variants.json`
by an auto-merging, data-only PR — safe to merge unattended and replayed without the LLM.
- **Bot PRs hit three invisible merge gates** (found live on #1117): (1) their
`pull_request` CI run is created "action_required" and, unrun, supersedes a passing
dispatched CI Gate — approve it via `POST /actions/runs/{id}/approve`; (2) GitHub's new
ruleset default `require_extra_approval_for_unattributed_changes: true` demands a human
approval for bot-authored changes even with 0 required reviews — set false explicitly;
(3) review threads must be resolved → `@coderabbitai ignore` in bot PR bodies.
- **Never send card data to an LLM.** Placeholders substituted locally + redacted snapshots +
masked screenshots; tests assert the prompt contains no secrets.
See `docs/TESTING.md` § Self-Healing Stripe Checkout.
+50
View File
@@ -480,6 +480,56 @@ The production tests cover:
- Final encoding and download
- Admin dashboard functionality
## Self-Healing Stripe Checkout (daily E2E Stage 1)
Stripe changes its hosted checkout page without notice (5 breaking changes Apr–Oct 2026),
so `frontend/e2e/helpers/stripe-checkout.ts` runs the checkout as **verified sub-goals**
(`selectCard`, `fillCardNumber`, `fillCardExpiry`, `fillCardCvc`, `fillCardholderName`,
`fillPostalCode`, `uncheckSaveInfo`, `submitPayment`) via `e2e/helpers/self-healing/`:
1. **Learned variants** (`self-healing/learned-variants.json`, newest first) — recipes the
LLM discovered on earlier live runs.
2. **Builtin variants** — the hand-written selectors in `stripe-checkout.ts`.
3. **LLM fallback** — Gemini (`E2E_SELF_HEAL_MODELS`, default
`gemini-3.5-flash-lite,gemini-3.1-flash-lite,gemini-3.8-flash`; unavailable ids are skipped,
failures escalate down the list) is shown a redacted ARIA snapshot + input-masked screenshot
and drives the page one action at a time until the step's `verify` postcondition passes.
Each attempt is judged only by the step's `verify` (e.g. "card-number input visible",
"filled field holds the expected value and looks like a card-number field", "redirected to
our success page or credit granted server-side") — never by "the click didn't throw".
**Card data never reaches the LLM:** it may only use `{{CARD_NUMBER}}`-style placeholders
(per-step allowlist) that are substituted locally; textbox values and PAN-like digit runs are
redacted from observations; inputs are masked in screenshots. Guardrails refuse clicks on
Link/Klarna/Cash App/Bank/"Back to…" and on the final Pay button outside `submitPayment`.
**Fully automatic loop.** When the LLM heals a step and the purchase is verified server-side,
the spec writes `test-results/self-heal/learned-variants.json`; the workflow's
`self-heal-pr` job opens a data-only PR (label `e2e-self-heal`, `@coderabbitai ignore`),
enables auto-merge, and approves the PR's `pull_request` CI run (bot PRs' runs start as
"action_required" and block the CI Gate until run; falls back to dispatching `ci.yml`).
Next run replays the recipe without the LLM.
**Repo setting this depends on (changed 2026-10-03, not in code):** the `protect main`
ruleset (id 11423976) has `require_extra_approval_for_unattributed_changes: false`. GitHub
defaults it to `true` (server-side, ~Aug 2026), which silently blocks bot-authored PRs
(`mergeStateStatus: BLOCKED` with all checks green) until a human approves. If a ruleset
update ever omits the key, GitHub resets it to `true` — set it explicitly. Discord + the daily email
report 🩹 when this happens. Only one open self-heal PR at a time.
The Gemini key is the AI Studio `gemini-api-key` (billed outside the nomadkaraoke project):
a `GEMINI_API_KEY` repo secret if set, else read from Secret Manager via keyless auth (the
credential file is deleted before tests run). No key → deterministic-only, as before.
```bash
cd frontend
# Offline tests (fixture checkout pages + stub LLM) — also run in CI's smoke job
npx playwright test --config=playwright.selfheal.config.ts
# Exercise the live LLM path end-to-end: Actions → E2E Daily → Run workflow →
# self_heal_force_llm = selectCard (forces that step through Gemini; opens a PR)
```
## Concurrent-Load Regression Test (review pages)
`scripts/load-test-review.py` replays the 2026-09-18 "10 tabs melt the backend"
+24 -9
View File
@@ -68,25 +68,40 @@ defense-in-depth beneath the signing-free review path.
`Failed to send magic link email to …`.
**Cause:** a bare nginx HTML 403 (not Postmark's JSON error format) is an edge/IP-level
block at `api.postmarkapp.com`, not a token or payload problem. Seen intermittently
from `karaoke-backend` (us-central1, shared Cloud Run egress IPs) since 2026-09-30;
us-east4 Cloud Run Jobs were unaffected. A JSON 403 (`ErrorCode=10`) is a real bad-token error instead.
block at `api.postmarkapp.com`, not a token or payload problem. Seen from
`karaoke-backend` and karaoke-decide (us-central1, shared Cloud Run egress IPs) since
2026-09-30, in blocks lasting hours (all sends failed 2026-10-02 11:25 UTC onward);
us-east4 Cloud Run Jobs were unaffected. IP Allowlisting is OFF in Postmark (checked
2026-10-02), so this is Postmark's network firewall — ticket #11562402, where Postmark
confirmed an IP-reputation block on the shared Google IP that they won't lift. A JSON 403
(`ErrorCode=10`) is a real bad-token error instead.
**Mitigation in code:** `PostmarkEmailProvider` retries 429 / 5xx / non-JSON 403 /
connect timeouts (backoff 1s, 3s). JSON Postmark errors and read timeouts are not
retried (deterministic, or risk of a duplicate send).
**Mitigation in code:** on an HTML 403, `PostmarkEmailProvider` immediately re-sends via
Postmark SMTP (`smtp.postmarkapp.com:587`, STARTTLS, server token as user+password,
`X-PM-Message-Stream: outbound`) — API retries never got past a block. Also falls back
when every API attempt hits a connect timeout. 429 / 5xx / connect timeouts are still
retried on the API (backoff 1s, 3s). JSON Postmark errors and read timeouts never fall
back (deterministic, or risk of a duplicate send). SMTP sends log
`Email sent to … via Postmark SMTP fallback` and have no Postmark MessageID; SMTP access
must stay enabled on the Postmark server (Server → Settings).
**Diagnosis:**
```bash
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send")' \
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send" OR textPayload:"SMTP")' \
--project nomadkaraoke --freshness 2d --limit 50 --format='value(timestamp,textPayload)'
```
The E2E `waitForEmail` helper now checks `GET /api/admin/users/{email}/emails` on
timeout and reports whether the backend sent anything ("backend has NO record…" =
server-side send failure; "backend sent N email(s)…" = delivery/testmail problem).
**If it persists after retries:** contact Postmark support with failure timestamps, or
give the backend a static egress IP (Direct VPC egress + Cloud NAT).
**Alert:** "Email - Postmark SMTP fallback failing (emails being lost)" (log-based metric
`email/postmark_smtp_fallback_failures`, `infrastructure/modules/monitoring.py`) fires if a
fallback send fails in karaoke-backend or karaoke-decide.
**If SMTP fallback also fails / the alert fires:** Postmark is likely blocking SMTP from our
IPs too → give the services a static egress IP. Options, measured costs (~$4–7/mo for the
recommended reuse-the-existing-NAT route) and Pulumi steps:
[`docs/archive/2026-10-02-postmark-ip-block-options.md`](archive/2026-10-02-postmark-ip-block-options.md).
## Fast rollback (bad backend deploy)
@@ -0,0 +1,101 @@
# Postmark IP block: current mitigation, and options if we need more
**Date:** 2026-10-02 · **Status:** mitigated (SMTP fallback, $0). Static egress IP **deferred** to save money; revisit only if the alert below fires.
**Applies to:** `karaoke-backend` (this repo) and `karaoke-decide` (both Cloud Run, us-central1).
## TL;DR
- Postmark's network firewall blocks some of Google Cloud's **shared us-central1 egress IPs** for API sends. They return a bare **nginx HTML 403**, not Postmark JSON. Postmark support confirmed the cause on ticket #11562402: the IP "has previously been associated with malicious activity, and has been blocked. We do not lift these blocks ourselves."
- **Current mitigation (free):** on that HTML 403, both services resend the email through **Postmark SMTP** (`smtp.postmarkapp.com:587`). This is proven in prod: on 2026-10-02 between 19:10 and 20:17 UTC, 12 of 12 blocked sends were delivered via SMTP, each ~0.5s slower, with 0 failures.
- **Tripwire (free until 2027-09-01, then $0.35/mo):** a Cloud Monitoring alert, **"Email - Postmark SMTP fallback failing (emails being lost)"**, emails andrew@beveridge.uk if an SMTP-fallback send ever fails.
- **If that alert fires**, Postmark is probably blocking SMTP from our IPs too. Implement **Option A** below (reuse the existing Cloud NAT with a reserved static IP). Estimated cost: **~$4–7/month**.
## Background & evidence
- Onset: 2026-09-30 05:26 UTC. Every gen backend send failed from 2026-10-02 11:25 UTC until the fallback shipped. Lost emails included magic-link logins, made-for-you order confirmations, and admin alerts. Impacted users got an apology plus 1 credit (see the workspace session record `docs/sessions/2026-Q4/2026-10-02-postmark-403-smtp-fallback.md`).
- The block is per egress IP. On 2026-10-02 at 03:33 UTC decide was blocked while gen succeeded in the same minute. us-east4 Cloud Run Jobs were never blocked. From a residential IP, all 3 `api.postmarkapp.com` IPs answer normally.
- Postmark **IP Allowlisting** (UI-only, released 2026-08-27) is **OFF** at both account and server level (checked 2026-10-02). It also returns JSON `ErrorCode 1480` when it blocks, which is a different signature from this.
- Retrying the API is useless: each Cloud Run instance keeps the same egress IP, so the block lasts hours. v0.261.1's retries never got through. Postmark's own advice: retry only helps if the IP changes; otherwise use a dedicated static egress.
## How the current mitigation works
| | karaoke-backend | karaoke-decide |
|---|---|---|
| Code | `backend/services/email_service.py` → `PostmarkEmailProvider._send_via_smtp` | `backend/services/email_service.py` → `EmailService._send_via_smtp` |
| Version / PR | v0.263.1 (#1112), v0.263.2 (#1113) | v0.9.3 (decide #147) |
| Log field | `jsonPayload.message` (structured) | `textPayload` (plain) |
- **Falls back to SMTP on:** an HTML (non-JSON) 403, or the API being unreachable (connect errors).
- **Never falls back on:** Postmark JSON errors (bad token, invalid payload, suppressed recipient) or read timeouts (Postmark may already have accepted the message, so a resend could duplicate).
- **SMTP auth:** the server token is both username and password. The header `X-PM-Message-Stream: outbound` selects the stream.
- **Trade-offs while on SMTP:** no Postmark `MessageID` is returned (the email_log entry is not linked to Postmark), and suppressed or invalid recipients only show up later as bounces in Postmark, not as an immediate error.
- **Requirement:** SMTP must stay **enabled** on the Postmark server "Nomad Karaoke Gen" (ID 19037711) under Server → Settings.
- **Log lines to grep:** `falling back to SMTP` (block hit), `via Postmark SMTP fallback` (sent), `Failed to send email to … via Postmark SMTP fallback` (lost; this is what the alert counts).
## The alert (tripwire)
- Code: `infrastructure/modules/monitoring.py` → `create_email_delivery_observability()`.
- **Log-based metric:** `logging.googleapis.com/user/email/postmark_smtp_fallback_failures`.
- **Filter:** `SMTP_FALLBACK_FAILURE_LOG_FILTER`. It must match **both** `jsonPayload.message` (gen) and `textPayload` (decide).
- Validated 2026-10-02: 0 matches, which is correct. A positive control on the gen JSON branch matched 12/12 real fallback sends; one on the decide text branch matched 5/5 real decide 403 lines.
- **Fires on:** any failure within a 10-minute window. Notifies the `alerts-email` channel.
- **Cost:** counter metric points are within the free allotment. Alert policies are free until **2027-09-01**, then **$0.35/month** per metric reference (Google Cloud Observability pricing, checked 2026-10-02).
## Options if we need more
Prices are from Google's Cloud NAT pricing page, checked 2026-10-02:
- **Gateway:** $0.0014/hr per instance using it, capped at $0.044/hr above 32 instances.
- **Static IP:** $0.005/hr each.
- **Data processing:** $0.045/GiB, counting both directions of connections *initiated* by the workload. Responses to inbound user requests do **not** go through the NAT.
Measured usage (2026-10-02):
- Average instances (7-day, hourly max): karaoke-backend ~2.2, karaoke-decide ~0.9 (it scales to zero ~half the time).
- The existing `github-runners-nat` cost **~$4.53/30 days** (IP $2.90 + gateway uptime $1.63).
### Option A (recommended if needed): reuse the existing Cloud NAT with a reserved static IP. ~$4–7/month extra
`infrastructure/compute/github_runners.py` already creates `github-runners-router` and `github-runners-nat` on the `default` network in us-central1, with `AUTO_ONLY` IPs and `ALL_SUBNETWORKS_ALL_IP_RANGES`.
Steps:
1. Reserve a static external IP: `compute.Address("email-egress-ip", region="us-central1")`.
2. Switch `github-runners-nat` to `nat_ip_allocate_option="MANUAL_ONLY"` with `nat_ips=[address.self_link]`. Its traffic is all ours (CI runners plus our services), so the IP's reputation is our own. You could also keep the runners on AUTO by giving the NAT subnetwork-specific config and putting Cloud Run on its own subnet; that's more config for no saving.
3. Put **karaoke-backend** and **karaoke-decide** on **Direct VPC egress**: `--network=default --subnet=default --vpc-egress=all-traffic`, set in each service's deploy config (gen: the CI deploy step or `modules/cloud_run.py`; decide: its own `infrastructure/`). `all-traffic` is required, because `private-ranges-only` keeps internet traffic on Google's shared IPs.
4. Make sure **Private Google Access** is on for that subnet, so Firestore/GCS/Secret Manager/Gemini traffic goes direct and isn't billed as NAT data processing.
5. **Size the NAT for Cloud Run.** Port exhaustion makes outbound connections time out, which would break email again and every other outbound call too. Settings on the `RouterNat`:
- `endpoint_types=["ENDPOINT_TYPE_VM"]`. This is the default, and Direct VPC egress instances count as VM endpoints.
- `enable_dynamic_port_allocation=True` with `min_ports_per_vm=128` and `max_ports_per_vm=4096`. Google's guidance is a minimum of at least ~2× the ports each Cloud Run instance needs. A backend instance makes many concurrent outbound calls (Stripe, Postmark, flacfetch, AudioShake), so 64 static ports could run out.
- Capacity check: 1 NAT IP = 64,512 ports, about 504 endpoints at 128 min ports each. Peak demand is 20 backend + 10 decide max instances, plus CI runners, which is well under that. If NAT logs ever show `OUT_OF_RESOURCES` / dropped packets, add a second reserved IP to `nat_ips`.
- Turn on NAT logging (`log_config.filter="ALL"` temporarily, then back to `ERRORS_ONLY`) for the first week, to watch for drops and to measure the data-processing volume.
6. Apply locally with `pulumi up` **before** merging (repo rule).
7. **Verify the reserved IP is actually used.** A successful Postmark send alone doesn't prove it, since the old dynamic IP might just not be blocked at that moment.
- From inside the deployed service's network path, call an IP-echo endpoint, e.g. `curl -s https://checkip.amazonaws.com`. Do this from a one-off Cloud Run job using the same `--network/--subnet/--vpc-egress=all-traffic` settings, or a temporary admin-only debug endpoint. The result must equal the reserved `email-egress-ip` address.
- With NAT logging on `ALL`, confirm that translations from the Cloud Run subnet show the reserved IP.
- Then trigger a magic link and confirm `Email sent to … via Postmark` (the API path, not the SMTP fallback) in the logs.
- Optionally tell Postmark the new IP on ticket #11562402.
Cost estimate:
- **IP:** switching AUTO → 1 reserved IP: $3.65/mo vs the ~$2.90 auto-IP spend today, so **+~$0.75**.
- **Gateway:** +(2.2 + 0.9) × $0.0014 × 730h = **+~$3.20**.
- **Data processing:** **+~$0.50–3**, unmeasured. It covers the outbound calls we make (Stripe, Postmark, flacfetch, AudioShake, Dropbox, YouTube, etc.). It could be more if the backend downloads large media from non-Google hosts, so measure it for a week via NAT logs after enabling.
- **Total: ~$4–7/month.**
### Option B: dedicated new NAT just for the Cloud Run services. ~$7–10/month extra
Same as A but with a new router + NAT + reserved IP scoped to one subnet. Cleaner separation from the CI runners, but you pay a second IP and gateway. Only worth it if CI-runner traffic ever risks our email IP's reputation.
### Option C: route only email through a fixed IP. ~$0 extra, more moving parts
Send Postmark traffic through something that already has a static IP, e.g. a tiny relay or proxy. The candidates are poor:
- The **encoding-worker VMs** have reserved IPs (34.57.78.246, 34.10.189.118, 34.16.73.140), but they're Spot and stop when idle, so they're unsuitable as an always-on relay.
- `divebar-sync` is TERMINATED.
- Home servers are out (reliability, and residential IPs have their own deliverability problems).
Not recommended unless we get an always-on box with a static IP for another reason.
### Option D: switch or add an email provider
As a last resort, send via a second provider (e.g. SES/Resend) when both Postmark paths fail. That means another account and another set of DNS/DKIM. Only consider it if Postmark keeps blocking us even from a static IP.
## Decision log
- **2026-10-02:** shipped the SMTP fallback (gen + decide) and the tripwire alert. **Deferred Option A to save money** (Andrew: "we're trying to save money everywhere right now"). Revisit if the alert fires, if SMTP-path bounces show something odd, or if we need Postmark `MessageID`s during blocks.
@@ -0,0 +1,158 @@
// frontend/e2e/helpers/self-healing/actions.ts
import type { Frame, Locator, Page } from '@playwright/test';
import type { Action, Secrets, TargetSpec } from './types';
const PLACEHOLDER_RE = /\{\{([A-Z_]+)\}\}/g;
/** Substitute `{{NAME}}` placeholders. Throws on unknown placeholders so a typo can't type literal braces into a payment form. */
export function substitutePlaceholders(value: string, secrets: Secrets): string {
return value.replace(PLACEHOLDER_RE, (_, key: string) => {
if (!(key in secrets)) throw new Error(`Unknown placeholder {{${key}}}`);
return secrets[key];
});
}
/** Path segments that identify a session/object rather than a page (e.g. `cs_live_a1j04…`). */
function isDynamicSegment(seg: string): boolean {
// Stripe object ids, or long opaque tokens (no '.'/'-' like real page names).
return (
/^[a-z]{2,5}_(live|test)_/i.test(seg) ||
(seg.length >= 16 && /^[A-Za-z0-9_]+$/.test(seg) && /\d/.test(seg) && /[a-z]/i.test(seg))
);
}
/**
* Stable frame key: host + path up to the first session-specific segment, no
* query/hash. Stripe puts the checkout session id in the PATH
* (`checkout.stripe.com/c/pay/cs_live_…`), so stripping the query isn't enough —
* a learned recipe must never pin (or leak) one run's session id.
*/
export function frameUrlKey(url: string): string {
try {
const u = new URL(url);
const kept: string[] = [];
for (const seg of u.pathname.split('/').filter(Boolean)) {
if (isDynamicSegment(seg)) break;
kept.push(seg);
}
return kept.length ? `${u.host}/${kept.join('/')}` : u.host;
} catch {
return url;
}
}
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function nameMatcher(name: string, exact?: boolean): string | RegExp {
return exact ? name : new RegExp(escapeRegex(name), 'i');
}
/** Build a frame-scoped locator for a TargetSpec. */
export function targetLocator(frame: Frame, t: TargetSpec): Locator {
switch (t.by) {
case 'role':
if (!t.role) throw new Error('TargetSpec by=role requires role');
return frame.getByRole(t.role as Parameters<Frame['getByRole']>[0], {
...(t.name ? { name: nameMatcher(t.name, t.exact), exact: t.exact } : {}),
includeHidden: t.includeHidden,
});
case 'text':
if (!t.text) throw new Error('TargetSpec by=text requires text');
return frame.getByText(nameMatcher(t.text, t.exact));
case 'placeholder':
if (!t.text) throw new Error('TargetSpec by=placeholder requires text');
return frame.getByPlaceholder(nameMatcher(t.text, t.exact));
case 'label':
if (!t.text) throw new Error('TargetSpec by=label requires text');
return frame.getByLabel(nameMatcher(t.text, t.exact));
case 'css':
if (!t.css) throw new Error('TargetSpec by=css requires css');
return frame.locator(t.css);
default:
throw new Error(`Unknown TargetSpec.by: ${(t as TargetSpec).by}`);
}
}
function orderedFrames(page: Page, t: TargetSpec): Frame[] {
const frames = page.frames().filter((f) => !f.isDetached());
if (!t.frameUrlIncludes) return frames;
const preferred = frames.filter((f) => frameUrlKey(f.url()).includes(t.frameUrlIncludes!));
return [...preferred, ...frames.filter((f) => !preferred.includes(f))];
}
/**
* Find the element for a TargetSpec in any frame (preferred frame first),
* polling until `timeoutMs`. Visible matches win; with `includeHidden`, an
* attached-but-hidden match is accepted as a last resort.
*/
export async function resolveTarget(
page: Page,
t: TargetSpec,
timeoutMs = 5_000
): Promise<{ locator: Locator; visible: boolean } | null> {
const deadline = Date.now() + timeoutMs;
do {
let hidden: Locator | null = null;
for (const frame of orderedFrames(page, t)) {
let loc: Locator;
try {
loc = targetLocator(frame, t).first();
} catch {
return null; // malformed spec — retrying won't help
}
if (await loc.isVisible().catch(() => false)) return { locator: loc, visible: true };
if (t.includeHidden && !hidden && (await loc.count().catch(() => 0)) > 0) hidden = loc;
}
if (hidden) return { locator: hidden, visible: false };
await page.waitForTimeout(250);
} while (Date.now() < deadline);
return null;
}
/** Execute one Action. Throws if the target can't be found or the action fails. */
export async function executeAction(
page: Page,
action: Action,
secrets: Secrets,
timeoutMs = 5_000
): Promise<Locator> {
const found = await resolveTarget(page, action.target, timeoutMs);
if (!found) throw new Error(`Target not found: ${JSON.stringify(action.target)}`);
const { locator, visible } = found;
const value = action.value !== undefined ? substitutePlaceholders(action.value, secrets) : undefined;
switch (action.type) {
case 'click':
if (visible) await locator.click({ force: true, timeout: timeoutMs });
else await locator.dispatchEvent('click');
break;
case 'fill':
if (value === undefined) throw new Error('fill requires value');
await locator.click({ timeout: timeoutMs });
await locator.fill('', { timeout: timeoutMs }).catch(() => {});
// Stripe's card inputs reformat as you type; typing (not fill) keeps their
// input handlers and validation in sync.
await locator.pressSequentially(value, { delay: 40, timeout: timeoutMs * 4 });
break;
case 'select':
if (value === undefined) throw new Error('select requires value');
await locator.selectOption({ label: value }, { timeout: timeoutMs }).catch(() =>
locator.selectOption(value, { timeout: timeoutMs })
);
break;
case 'check':
await locator.check({ force: true, timeout: timeoutMs });
break;
case 'uncheck':
await locator.uncheck({ force: true, timeout: timeoutMs });
break;
case 'press':
await locator.press(value || 'Enter', { timeout: timeoutMs });
break;
default:
throw new Error(`Unknown action type: ${(action as Action).type}`);
}
return locator;
}
@@ -0,0 +1,72 @@
// frontend/e2e/helpers/self-healing/learned-store.ts
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import type { Action, LearnedVariant, LearnedVariantsFile } from './types';
/**
* learned-variants.json holds step recipes the LLM fallback discovered on live
* runs. The daily E2E workflow opens an auto-merging PR whenever a run adds one,
* so the next run replays it deterministically (no LLM) — "1 Stripe change =
* 1 auto-merged data PR".
*/
export const LEARNED_VARIANTS_PATH = path.join(__dirname, 'learned-variants.json');
/** Keep only the newest N per step: Stripe A/B-tests layouts, so a few recent ones are useful; ancient ones are noise. */
export const MAX_LEARNED_PER_STEP = 5;
export function emptyFile(): LearnedVariantsFile {
return { version: 1, steps: {} };
}
export function loadLearned(file = LEARNED_VARIANTS_PATH): LearnedVariantsFile {
try {
const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as LearnedVariantsFile;
if (parsed?.version === 1 && parsed.steps && typeof parsed.steps === 'object') return parsed;
console.warn(` ⚠️ ${file} has unexpected shape — ignoring learned variants`);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn(` ⚠️ Could not read ${file}: ${(e as Error).message} — ignoring learned variants`);
}
}
return emptyFile();
}
/** Stable id from the actions only (not timestamps), so re-learning the same recipe dedupes. */
export function variantId(actions: Action[]): string {
return crypto.createHash('sha256').update(JSON.stringify(actions)).digest('hex').slice(0, 12);
}
/**
* Merge newly-healed recipes into the file (pure — returns a new object).
* Returns `changed: false` when every recipe was already known.
*/
export function mergeLearned(
current: LearnedVariantsFile,
healed: Array<{ stepId: string; actions: Action[]; model?: string }>,
meta: { runUrl?: string; now?: string } = {}
): { file: LearnedVariantsFile; changed: boolean; added: Array<{ stepId: string; variant: LearnedVariant }> } {
const file: LearnedVariantsFile = JSON.parse(JSON.stringify(current));
const added: Array<{ stepId: string; variant: LearnedVariant }> = [];
for (const h of healed) {
if (!h.actions.length) continue;
const id = variantId(h.actions);
const list = file.steps[h.stepId] || [];
if (list.some((v) => v.id === id)) continue;
const variant: LearnedVariant = {
id,
learnedAt: meta.now || new Date().toISOString(),
...(meta.runUrl ? { runUrl: meta.runUrl } : {}),
...(h.model ? { model: h.model } : {}),
actions: h.actions,
};
// Newest first — the most recent layout is the likeliest to be live.
file.steps[h.stepId] = [variant, ...list].slice(0, MAX_LEARNED_PER_STEP);
added.push({ stepId: h.stepId, variant });
}
return { file, changed: added.length > 0, added };
}
export function serialize(file: LearnedVariantsFile): string {
return JSON.stringify(file, null, 2) + '\n';
}
@@ -0,0 +1,42 @@
{
"version": 1,
"steps": {
"selectCard": [
{
"id": "19fdebfcbbb1",
"learnedAt": "2026-10-03T17:05:03.246Z",
"runUrl": "https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37139075045",
"model": "gemini-3.1-flash-lite",
"actions": [
{
"type": "click",
"target": {
"by": "css",
"css": "[data-testid='card-accordion-item']",
"frameUrlIncludes": "checkout.stripe.com/c/pay"
}
}
]
}
],
"fillPostalCode": [
{
"id": "92cb503db41b",
"learnedAt": "2026-10-03T17:35:16.436Z",
"runUrl": "https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37140934446",
"model": "gemini-3.5-flash-lite",
"actions": [
{
"type": "fill",
"target": {
"by": "css",
"css": "#billingPostalCode",
"frameUrlIncludes": "checkout.stripe.com/c/pay"
},
"value": "{{POSTAL_CODE}}"
}
]
}
]
}
}
@@ -0,0 +1,363 @@
// frontend/e2e/helpers/self-healing/llm-agent.ts
import { executeAction, resolveTarget } from './actions';
import { observe, type Observation } from './observe';
import type { Action, ActionType, CheckoutStep, StepContext, TargetSpec } from './types';
/**
* LLM fallback for one checkout step: observe → ask the model for ONE action →
* execute → verify, up to MAX_ITERATIONS. The model only ever picks elements by
* semantic description and uses `{{PLACEHOLDER}}` tokens for secrets; we
* substitute real values locally.
*/
export interface LlmTarget extends Omit<TargetSpec, 'frameUrlIncludes'> {
frameIndex?: number;
}
export interface LlmDecision {
thought: string;
status: 'act' | 'done' | 'give_up';
action?: { type: ActionType; target: LlmTarget; value?: string };
}
export interface PlannerInput {
stepId: string;
goal: string;
allowSubmit: boolean;
placeholders: string[];
history: string[];
observation: Observation;
/** 0 = cheapest model; incremented after failures to escalate. */
escalation: number;
}
export interface Planner {
decide(input: PlannerInput): Promise<{ decision: LlmDecision; model: string }>;
}
export interface HealResult {
success: boolean;
actions: Action[];
model: string;
llmCalls: number;
reason?: string;
}
const MAX_ITERATIONS = 6;
const MAX_ESCALATIONS = 2;
/** Express/alternative payment methods and the cancel/back link — the agent must never pick these. */
const FORBIDDEN_CLICK_RE = /\b(back to|cancel|link|klarna|cash ?app|bank|affirm|afterpay|google pay|apple pay|amazon pay|paypal)\b/i;
/** The final submit button ("Pay", "Pay $0.50", "Subscribe"…) — only allowed in the submit step. */
const SUBMIT_RE = /^\s*(pay|subscribe|buy|purchase|place order|complete (order|purchase)|confirm( payment)?)\s*(\$?[\d.,]+)?\s*$/i;
/** Returns a rejection reason, or null if the action is acceptable. */
export function checkGuards(
action: NonNullable<LlmDecision['action']>,
step: Pick<CheckoutStep, 'allowSubmit' | 'placeholders'>
): string | null {
const label = action.target.name || action.target.text || '';
if (action.type === 'click' && FORBIDDEN_CLICK_RE.test(label)) {
return `Refused: "${label}" looks like an alternative/express payment method. Use the card form only.`;
}
if (action.type === 'click' && !step.allowSubmit && SUBMIT_RE.test(label)) {
return `Refused: clicking the final "${label}" button is not allowed in this step.`;
}
if (action.value !== undefined) {
const allowed = new Set(step.placeholders || []);
for (const m of action.value.matchAll(/\{\{([A-Z_]+)\}\}/g)) {
if (!allowed.has(m[1])) return `Refused: placeholder {{${m[1]}}} is not available in this step.`;
}
// A model must never invent card-like numbers — secrets come only via placeholders.
if (/\d{4,}/.test(action.value.replace(/\{\{[A-Z_]+\}\}/g, '').replace(/\s/g, ''))) {
return 'Refused: literal digits in value. Use a {{PLACEHOLDER}} for secret values.';
}
}
if (action.target.by === 'css' && !action.target.css) return 'Refused: by=css requires css.';
if (action.target.by === 'role' && !action.target.role) return 'Refused: by=role requires role.';
if (['text', 'placeholder', 'label'].includes(action.target.by) && !action.target.text) {
return `Refused: by=${action.target.by} requires text.`;
}
return null;
}
/** What a click target actually is on the page (not what the model called it). */
export interface ResolvedElementInfo {
text?: string;
ariaLabel?: string;
value?: string;
title?: string;
testid?: string;
type?: string;
}
/**
* Guard the RESOLVED element of a click, so css/unnamed targets can't bypass
* the label-based checks (e.g. `[data-testid="hosted-payment-submit-button"]`).
*/
export function checkResolvedClick(
info: ResolvedElementInfo,
step: Pick<CheckoutStep, 'allowSubmit'>
): string | null {
const labels = [info.text, info.ariaLabel, info.value, info.title].filter(Boolean) as string[];
for (const label of labels) {
if (FORBIDDEN_CLICK_RE.test(label)) {
return `Refused: the target element ("${label.slice(0, 60)}") is an alternative/express payment method or cancel link.`;
}
}
if (info.testid && /\b(link|klarna|cashapp|cash-app|bank|express|back|cancel)\b/i.test(info.testid.replace(/[-_]/g, ' '))) {
return `Refused: the target element (data-testid="${info.testid}") is an alternative/express payment method or cancel link.`;
}
if (!step.allowSubmit) {
const isSubmit =
info.type === 'submit' ||
(info.testid !== undefined && /submit/i.test(info.testid)) ||
labels.some((l) => SUBMIT_RE.test(l));
if (isSubmit) return 'Refused: the target element is the final Pay/submit button, which is not allowed in this step.';
}
return null;
}
async function describeResolved(ctx: StepContext, action: Action): Promise<ResolvedElementInfo | null> {
const found = await resolveTarget(ctx.page, action.target, 3_000);
if (!found) return null;
return found.locator
.evaluate((n) => {
const el = n as HTMLInputElement;
const clean = (v: string | null | undefined) => (v || '').replace(/\s+/g, ' ').trim() || undefined;
return {
text: clean(el.innerText || el.textContent),
ariaLabel: clean(el.getAttribute('aria-label')),
value: el.tagName === 'INPUT' || el.tagName === 'BUTTON' ? clean(el.getAttribute('value')) : undefined,
title: clean(el.getAttribute('title')),
testid: clean(el.getAttribute('data-testid')),
type: clean(el.getAttribute('type')),
};
})
.catch(() => null);
}
export function toTargetSpec(t: LlmTarget, frameKeys: string[]): TargetSpec {
const { frameIndex, ...rest } = t;
const spec: TargetSpec = { ...rest };
if (frameIndex !== undefined && frameKeys[frameIndex]) spec.frameUrlIncludes = frameKeys[frameIndex];
// Drop empty optional fields the model sometimes emits.
for (const k of Object.keys(spec) as (keyof TargetSpec)[]) {
if (spec[k] === '' || spec[k] === null) delete spec[k];
}
return spec;
}
export async function pollVerify(step: CheckoutStep, ctx: StepContext, timeoutMs: number): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
do {
if (await step.verify(ctx).catch(() => false)) return true;
await ctx.page.waitForTimeout(500);
} while (Date.now() < deadline);
return false;
}
export async function healStep(step: CheckoutStep, ctx: StepContext, planner: Planner): Promise<HealResult> {
const history: string[] = [];
const executed: Action[] = [];
let escalation = 0;
let llmCalls = 0;
let model = '';
for (let i = 0; i < MAX_ITERATIONS; i++) {
const observation = await observe(ctx.page, ctx.secrets);
let decision: LlmDecision;
try {
const res = await planner.decide({
stepId: step.id,
goal: step.goal,
allowSubmit: !!step.allowSubmit,
placeholders: step.placeholders || [],
history,
observation,
escalation,
});
llmCalls++;
decision = res.decision;
model = res.model;
} catch (e) {
return { success: false, actions: executed, model, llmCalls, reason: `planner error: ${(e as Error).message}` };
}
console.log(` 🤖 [${model}] ${decision.status}: ${decision.thought}`);
if (decision.status === 'give_up') {
history.push(`You gave up: ${decision.thought}`);
if (++escalation > MAX_ESCALATIONS) break;
continue;
}
if (decision.status === 'done' || !decision.action) {
if (await pollVerify(step, ctx, 3_000)) return { success: true, actions: executed, model, llmCalls };
history.push('You said the goal is done, but the automated check says it is NOT. Look again.');
escalation = Math.min(escalation + 1, MAX_ESCALATIONS);
continue;
}
const refusal = checkGuards(decision.action, step);
if (refusal) {
history.push(refusal);
continue;
}
const action: Action = {
type: decision.action.type,
target: toTargetSpec(decision.action.target, observation.frameKeys),
...(decision.action.value !== undefined ? { value: decision.action.value } : {}),
};
if (action.type === 'click') {
const info = await describeResolved(ctx, action);
const resolvedRefusal = info && checkResolvedClick(info, step);
if (resolvedRefusal) {
history.push(resolvedRefusal);
continue;
}
}
try {
const loc = await executeAction(ctx.page, action, ctx.secrets);
if (action.type === 'fill') ctx.lastFilled = loc;
executed.push(action);
history.push(`OK: ${JSON.stringify(action)}`);
} catch (e) {
history.push(`FAILED: ${JSON.stringify(action)} — ${(e as Error).message.split('\n')[0]}`);
escalation = Math.min(escalation + 1, MAX_ESCALATIONS);
continue;
}
// Clicks can trigger slow transitions (accordion, redirect); after a fill,
// a short check suffices — the model will usually need more actions.
const verifyMs = action.type === 'click' ? step.verifyTimeoutMs ?? 5_000 : 2_000;
if (await pollVerify(step, ctx, verifyMs)) {
return { success: true, actions: executed, model, llmCalls };
}
}
return { success: false, actions: executed, model, llmCalls, reason: 'goal not verified after LLM attempts' };
}
// ---------------------------------------------------------------------------
// Gemini planner
// ---------------------------------------------------------------------------
/** Cheapest first; escalation walks down the list. Unavailable model ids are skipped. */
export const DEFAULT_MODELS = ['gemini-3.5-flash-lite', 'gemini-3.1-flash-lite', 'gemini-3.8-flash'];
const SYSTEM_PROMPT = `You are a careful browser-automation assistant completing ONE sub-goal on a Stripe hosted checkout page during an automated end-to-end test of our own product.
You receive: the sub-goal, a history of your previous actions and their results, and an observation of every frame (ARIA snapshot + interactive element attributes + a screenshot where input contents are masked).
Respond with exactly ONE next action (status "act"), or status "done" if the sub-goal is already achieved, or "give_up" if it is impossible.
Rules:
- Pay ONLY with the card form. Never click Link, Klarna, Cash App, Bank, Affirm, Google/Apple Pay or any other alternative/express method.
- Never type real data. Use ONLY the {{PLACEHOLDER}} tokens listed for this step as values (e.g. "{{CARD_NUMBER}}"). Non-secret literals (e.g. a country name for a select) are allowed.
- Do not click the final Pay/submit button unless the step explicitly allows it.
- Identify targets by STABLE semantics so the same description works on future runs:
prefer by="role" with role + accessible name; else by="label"/"placeholder"/"text"; use by="css" only with stable attributes (id, name, autocomplete, data-testid), never generated class names or nth-child.
- Set frameIndex to the frame[N] that contains the element.
- If the right element exists but is hidden behind an overlay or visually hidden, set includeHidden=true.
- Do not repeat an action that already FAILED with the same target; try a different description.`;
const RESPONSE_SCHEMA = {
type: 'object',
properties: {
thought: { type: 'string', description: 'One short sentence of reasoning.' },
status: { type: 'string', enum: ['act', 'done', 'give_up'] },
action: {
type: 'object',
properties: {
type: { type: 'string', enum: ['click', 'fill', 'select', 'check', 'uncheck', 'press'] },
target: {
type: 'object',
properties: {
frameIndex: { type: 'integer' },
by: { type: 'string', enum: ['role', 'text', 'css', 'placeholder', 'label'] },
role: { type: 'string' },
name: { type: 'string' },
exact: { type: 'boolean' },
text: { type: 'string' },
css: { type: 'string' },
includeHidden: { type: 'boolean' },
},
required: ['by'],
},
value: { type: 'string' },
},
required: ['type', 'target'],
},
},
required: ['thought', 'status'],
};
function isModelUnavailable(e: unknown): boolean {
const msg = String((e as Error)?.message || e);
return /\b404\b|not found|NOT_FOUND|is not supported|unsupported model|invalid model/i.test(msg);
}
export function buildPrompt(input: PlannerInput): string {
return [
`## Sub-goal (step "${input.stepId}")\n${input.goal}`,
`## Allowed placeholders\n${input.placeholders.length ? input.placeholders.map((p) => `{{${p}}}`).join(', ') : '(none)'}`,
`## Final Pay/submit button allowed in this step: ${input.allowSubmit ? 'YES' : 'NO'}`,
`## History\n${input.history.length ? input.history.map((h, i) => `${i + 1}. ${h}`).join('\n') : '(no actions yet)'}`,
`## Observation (page ${input.observation.url})\n${input.observation.text}`,
].join('\n\n');
}
export class GeminiPlanner implements Planner {
private readonly unavailable = new Set<string>();
constructor(
private readonly apiKey: string,
private readonly models: string[] = DEFAULT_MODELS
) {}
static fromEnv(): GeminiPlanner | null {
const key = process.env.GEMINI_API_KEY;
if (!key) return null;
const models = (process.env.E2E_SELF_HEAL_MODELS || '').split(',').map((m) => m.trim()).filter(Boolean);
return new GeminiPlanner(key, models.length ? models : DEFAULT_MODELS);
}
async decide(input: PlannerInput): Promise<{ decision: LlmDecision; model: string }> {
// Lazy import: the SDK is only needed when a fallback actually fires.
const { GoogleGenAI } = await import('@google/genai');
// vertexai:false — Vertex AI is disabled in the nomadkaraoke GCP project; this
// key bills to the AI Studio project (see project_no_ai_spend_in_gcp_project).
const ai = new GoogleGenAI({ apiKey: this.apiKey, vertexai: false });
const candidates = this.models.filter((m) => !this.unavailable.has(m));
const ordered = candidates.slice(Math.min(input.escalation, Math.max(candidates.length - 1, 0)));
let lastErr: unknown;
for (const model of ordered) {
try {
const parts: Array<{ text: string } | { inlineData: { mimeType: string; data: string } }> = [
{ text: buildPrompt(input) },
];
if (input.observation.screenshotJpegBase64) {
parts.push({ inlineData: { mimeType: 'image/jpeg', data: input.observation.screenshotJpegBase64 } });
}
const res = await ai.models.generateContent({
model,
contents: [{ role: 'user', parts }],
config: {
systemInstruction: SYSTEM_PROMPT,
responseMimeType: 'application/json',
responseJsonSchema: RESPONSE_SCHEMA,
temperature: 0,
httpOptions: { timeout: 45_000 },
},
});
const decision = JSON.parse(res.text || '{}') as LlmDecision;
if (!decision.status) throw new Error(`malformed response: ${res.text?.slice(0, 200)}`);
return { decision, model };
} catch (e) {
lastErr = e;
if (isModelUnavailable(e)) {
console.log(` 🤖 model ${model} unavailable — skipping (${String((e as Error).message).slice(0, 120)})`);
this.unavailable.add(model);
} else {
console.log(` 🤖 model ${model} error — trying next (${String((e as Error).message).slice(0, 120)})`);
}
}
}
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
}
}
@@ -0,0 +1,134 @@
// frontend/e2e/helpers/self-healing/observe.ts
import type { Page } from '@playwright/test';
import { frameUrlKey } from './actions';
import type { Secrets } from './types';
/**
* Builds the page observation the LLM fallback sees: per-frame ARIA snapshot +
* a compact list of interactive elements (attributes only, NEVER input values),
* plus a screenshot with every <input> masked.
*
* ⚠️ PCI: the real card number/expiry/CVC must never reach the LLM. Defence in
* depth: values aren't collected, textbox values in ARIA snapshots are blanked,
* PAN-like digit runs are scrubbed, every known secret is scrubbed verbatim,
* and inputs are masked in the screenshot.
*/
const MAX_SNAPSHOT_CHARS_PER_FRAME = 8_000;
const MAX_ELEMENTS_PER_FRAME = 80;
const MAX_TOTAL_CHARS = 40_000;
export function redact(text: string, secrets: Secrets): string {
let out = text
// ARIA snapshot textbox/combobox/spinbutton lines carry the current value after ':'
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n:]*?(?:"[^"\n]*")?[^\n:]*):\s.*$/gm, '$1: [value redacted]')
// Anything shaped like a card number (13-19 digits, optional space/dash separators)
.replace(/\b(?:\d[ -]?){12,18}\d\b/g, '[redacted-digits]');
for (const secret of Object.values(secrets)) {
// Short secrets (CVC "123", ZIP) would scrub unrelated text everywhere; the
// value-blanking above already covers them inside fields.
if (secret && secret.replace(/\s/g, '').length >= 5) {
out = out.split(secret).join('[redacted]');
}
}
return out;
}
interface ElementInfo {
tag: string;
type?: string;
role?: string;
id?: string;
name?: string;
ariaLabel?: string;
placeholder?: string;
autocomplete?: string;
testid?: string;
text?: string;
visible: boolean;
checked?: boolean;
disabled?: boolean;
}
export interface Observation {
url: string;
text: string;
/** frame index (as referenced in `text`) → stable frame URL key. */
frameKeys: string[];
screenshotJpegBase64?: string;
}
export async function observe(page: Page, secrets: Secrets, withScreenshot = true): Promise<Observation> {
const sections: string[] = [];
const frames = page.frames().filter((f) => !f.isDetached());
for (let i = 0; i < frames.length; i++) {
const frame = frames[i];
const key = frameUrlKey(frame.url());
if (!key || key === 'about:blank') continue;
const snapshot = await frame
.locator('body')
.ariaSnapshot({ timeout: 3_000 })
.catch(() => '');
const elements: ElementInfo[] = await frame
.evaluate((max: number) => {
const sel = 'input, button, select, textarea, a[href], label, [role], [data-testid]';
const out: ElementInfo[] = [];
for (const el of Array.from(document.querySelectorAll<HTMLElement>(sel))) {
if (out.length >= max) break;
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
const visible = r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0';
const input = el as HTMLInputElement;
const info: ElementInfo = { tag: el.tagName.toLowerCase(), visible };
const attr = (n: string) => el.getAttribute(n) || undefined;
info.type = attr('type');
info.role = attr('role');
info.id = el.id || undefined;
info.name = attr('name');
info.ariaLabel = attr('aria-label');
info.placeholder = attr('placeholder');
info.autocomplete = attr('autocomplete');
info.testid = attr('data-testid');
// Text content only for non-form elements — never read input values.
if (!['input', 'select', 'textarea'].includes(info.tag)) {
const t = (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();
if (t) info.text = t.slice(0, 60);
}
if (info.type === 'checkbox' || info.type === 'radio') info.checked = input.checked;
if ((el as HTMLButtonElement).disabled) info.disabled = true;
out.push(info);
}
return out;
}, MAX_ELEMENTS_PER_FRAME)
.catch(() => []);
if (!snapshot && elements.length === 0) continue;
const elementLines = elements
.map((e) => JSON.stringify(Object.fromEntries(Object.entries(e).filter(([, v]) => v !== undefined))))
.join('\n');
sections.push(
`### frame[${i}] url=${key}\n` +
`#### ARIA snapshot\n${snapshot.slice(0, MAX_SNAPSHOT_CHARS_PER_FRAME)}\n` +
`#### Interactive elements (attributes only)\n${elementLines}`
);
}
let text = redact(sections.join('\n\n'), secrets);
if (text.length > MAX_TOTAL_CHARS) text = text.slice(0, MAX_TOTAL_CHARS) + '\n…[truncated]';
let screenshotJpegBase64: string | undefined;
if (withScreenshot) {
const buf = await page
.screenshot({
type: 'jpeg',
quality: 50,
mask: frames.map((f) => f.locator('input, textarea')),
maskColor: '#888888',
})
.catch(() => undefined);
screenshotJpegBase64 = buf?.toString('base64');
}
return { url: frameUrlKey(page.url()), text, frameKeys: frames.map((f) => frameUrlKey(f.url())), screenshotJpegBase64 };
}
@@ -0,0 +1,130 @@
// frontend/e2e/helpers/self-healing/step-runner.ts
import * as fs from 'fs';
import * as path from 'path';
import type { Page } from '@playwright/test';
import { executeAction } from './actions';
import { healStep, pollVerify, type Planner } from './llm-agent';
import { loadLearned, mergeLearned, serialize } from './learned-store';
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext, StepOutcome } from './types';
/**
* Runs a flow as a sequence of verified sub-goals:
* learned variants (newest first) → hand-written builtins → LLM fallback.
* Each attempt is judged ONLY by the step's `verify` postcondition — never by
* "the click didn't throw" — so a silently-wrong variant can't pass.
*/
export class SelfHealingRunner {
readonly outcomes: StepOutcome[] = [];
private readonly forceLlm: Set<string>;
private readonly ctx: StepContext;
constructor(
page: Page,
secrets: Secrets,
private readonly planner: Planner | null,
private readonly learned: LearnedVariantsFile = loadLearned(),
opts: { forceLlmSteps?: string[] } = {}
) {
this.ctx = { page, secrets };
this.forceLlm = new Set(
opts.forceLlmSteps ??
(process.env.E2E_SELF_HEAL_FORCE_LLM || '').split(',').map((s) => s.trim()).filter(Boolean)
);
}
async run(step: CheckoutStep): Promise<StepOutcome> {
const outcome = await this.attempt(step);
this.outcomes.push(outcome);
const icon = { ok: '✓', healed: '🩹', skipped: '–', failed: '✘' }[outcome.status];
console.log(` ${icon} step ${step.id}: ${outcome.status}${'variant' in outcome ? ` (${outcome.via}: ${outcome.variant})` : ''}`);
return outcome;
}
private async attempt(step: CheckoutStep): Promise<StepOutcome> {
const ctx = this.ctx;
ctx.lastFilled = undefined;
const verifyMs = step.verifyTimeoutMs ?? 5_000;
// Already satisfied (e.g. card fields visible without choosing "Card")?
if (await step.verify(ctx).catch(() => false)) {
return { stepId: step.id, status: 'ok', via: 'builtin', variant: 'already-satisfied' };
}
const forced = this.forceLlm.has(step.id);
if (forced) console.log(` ⚙️ step ${step.id}: E2E_SELF_HEAL_FORCE_LLM — skipping deterministic variants`);
if (!forced) {
for (const v of this.learned.steps[step.id] || []) {
try {
for (const a of v.actions) {
const loc = await executeAction(ctx.page, a, ctx.secrets);
if (a.type === 'fill') ctx.lastFilled = loc;
}
if (await pollVerify(step, ctx, verifyMs)) {
return { stepId: step.id, status: 'ok', via: 'learned', variant: v.id };
}
} catch (e) {
console.log(` learned variant ${v.id} failed: ${(e as Error).message.split('\n')[0]}`);
}
}
for (const b of step.builtins) {
try {
await b.run(ctx);
if (await pollVerify(step, ctx, verifyMs)) {
return { stepId: step.id, status: 'ok', via: 'builtin', variant: b.name };
}
} catch (e) {
console.log(` builtin "${b.name}" failed: ${(e as Error).message.split('\n')[0]}`);
}
}
}
if (step.optional && !forced) {
return { stepId: step.id, status: 'skipped', reason: 'optional step: no variant applied (field may not exist in this layout)' };
}
if (!this.planner) {
return { stepId: step.id, status: 'failed', reason: 'all deterministic variants failed and no LLM planner is configured (GEMINI_API_KEY unset)', llmCalls: 0 };
}
console.log(` 🤖 step ${step.id}: deterministic variants exhausted — LLM fallback`);
const heal = await healStep(step, ctx, this.planner);
if (heal.success && heal.actions.length) {
return { stepId: step.id, status: 'healed', model: heal.model, actions: heal.actions, llmCalls: heal.llmCalls };
}
if (heal.success) {
// Verified with zero actions (e.g. it only needed time) — nothing to learn.
return { stepId: step.id, status: 'ok', via: 'builtin', variant: 'verified-after-wait' };
}
return { stepId: step.id, status: 'failed', reason: heal.reason || 'LLM fallback failed', llmCalls: heal.llmCalls };
}
get healed() {
return this.outcomes.filter((o): o is Extract<StepOutcome, { status: 'healed' }> => o.status === 'healed');
}
/**
* Write `<dir>/self-heal-report.json` always, and — only when the caller has
* independently confirmed the whole flow succeeded — `<dir>/learned-variants.json`
* containing the merged recipes, for the workflow to commit.
*/
writeArtifacts(dir: string, opts: { flowVerified: boolean; runUrl?: string }): { learnedWritten: boolean } {
fs.mkdirSync(dir, { recursive: true });
const healed = this.healed;
const llmCalls = this.outcomes.reduce((n, o) => n + ('llmCalls' in o ? o.llmCalls : 0), 0);
let learnedWritten = false;
let added: string[] = [];
if (opts.flowVerified && healed.length) {
const merged = mergeLearned(this.learned, healed, { runUrl: opts.runUrl });
if (merged.changed) {
fs.writeFileSync(path.join(dir, 'learned-variants.json'), serialize(merged.file));
learnedWritten = true;
added = merged.added.map((a) => `${a.stepId}:${a.variant.id}`);
}
}
fs.writeFileSync(
path.join(dir, 'self-heal-report.json'),
JSON.stringify({ flowVerified: opts.flowVerified, llmCalls, learnedWritten, added, outcomes: this.outcomes }, null, 2)
);
return { learnedWritten };
}
}
@@ -0,0 +1,91 @@
// frontend/e2e/helpers/self-healing/types.ts
import type { Locator, Page } from '@playwright/test';
/**
* Serializable description of an element. Produced by the LLM fallback and
* persisted in learned-variants.json, so it must stay plain JSON and must
* describe the element by *stable semantics* (role/name/text/attributes), never
* by snapshot refs or indexes that change per run.
*/
export interface TargetSpec {
/** Substring of the frame URL (host + path, no query) to search first. */
frameUrlIncludes?: string;
by: 'role' | 'text' | 'css' | 'placeholder' | 'label';
role?: string;
name?: string;
/** Exact (case-sensitive, whole-string) name/text match. Default false = case-insensitive substring. */
exact?: boolean;
text?: string;
css?: string;
/** Match elements hidden from the accessibility tree / not visible (clicks become dispatchEvent). */
includeHidden?: boolean;
}
export type ActionType = 'click' | 'fill' | 'select' | 'check' | 'uncheck' | 'press';
/**
* One UI action. `value` may contain secret placeholders like `{{CARD_NUMBER}}`
* which are substituted at execution time — real secrets never appear in an
* Action that is sent to or produced by the LLM, or persisted to disk.
*/
export interface Action {
type: ActionType;
target: TargetSpec;
value?: string;
}
/** Values the runner may substitute into `{{PLACEHOLDER}}` tokens. */
export type Secrets = Record<string, string>;
export interface StepContext {
page: Page;
secrets: Secrets;
/** The element most recently filled during the current step (reset per step) — lets fill-step verifies check the value landed in a plausible field. */
lastFilled?: Locator;
}
/** A deterministic, hand-written way to accomplish a step. */
export interface BuiltinVariant {
name: string;
run: (ctx: StepContext) => Promise<void>;
}
export interface CheckoutStep {
id: string;
/** Natural-language goal handed to the LLM fallback. */
goal: string;
builtins: BuiltinVariant[];
/** Postcondition: did the step actually achieve its goal? Must be side-effect free. */
verify: (ctx: StepContext) => Promise<boolean>;
/** How long verify may poll after each variant before declaring it failed. */
verifyTimeoutMs?: number;
/**
* Optional steps (e.g. a ZIP field that only some layouts have) never call
* the LLM and never fail the run — a missing field is caught by the submit
* step's verify instead, whose LLM fallback can fill whatever is required.
*/
optional?: boolean;
/** Whether the LLM may click the final Pay/submit button in this step. */
allowSubmit?: boolean;
/** Placeholders the LLM may use in this step, e.g. ['CARD_NUMBER']. */
placeholders?: string[];
}
export interface LearnedVariant {
id: string;
learnedAt: string;
runUrl?: string;
model?: string;
actions: Action[];
}
export interface LearnedVariantsFile {
version: 1;
steps: Record<string, LearnedVariant[]>;
}
export type StepOutcome =
| { stepId: string; status: 'ok'; via: 'builtin' | 'learned'; variant: string }
| { stepId: string; status: 'healed'; model: string; actions: Action[]; llmCalls: number }
| { stepId: string; status: 'skipped'; reason: string }
| { stepId: string; status: 'failed'; reason: string; llmCalls: number };
+352 -221
View File
@@ -1,46 +1,57 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page, Frame, Locator } from '@playwright/test';
import * as fs from 'fs';
import { GeminiPlanner, type Planner } from './self-healing/llm-agent';
import { SelfHealingRunner } from './self-healing/step-runner';
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './self-healing/types';
/**
* Automate Stripe's hosted checkout page (checkout.stripe.com).
*
* ⚠️ Stripe changes this page's structure without notice — likely A/B testing
* or staged rollouts, so BOTH the old and new layouts can appear on any given
* day (and can flip back). We have observed at least three variants:
* 1. Multi-method accordion of *radios* (Card / Cash App / Klarna / Bank),
* card fields inside iframes, Pay button in the top frame. (Apr 2026)
* 2. Single method (Card only): card fields render as *direct* textboxes in
* the top document, no chooser at all. (#916, Aug 17)
* 3. Multi-method Payment Element where the chooser is *buttons* (not radios)
* and the whole element — chooser, card fields AND the "Pay" button — is
* rendered inside a nested same-origin iframe. (Aug 19-20)
* or staged rollouts, so BOTH old and new layouts can appear on any given day
* (and can flip back). Observed variants (see git history for details):
* 1. Accordion of *radios* (Card / Cash App / Klarna / Bank). (Apr 2026)
* 2. Card-only: card fields as direct textboxes, no chooser. (#916, Aug 17)
* 3. Chooser as *buttons*, whole Payment Element in a nested iframe. (#919, Aug 20)
* 4. Required "Name on card" + "ZIP code" with new labels. (#945, Aug 26)
* 5. Plain "Card" label + visually-hidden "Pay with card" button. (#1115, Oct 3)
*
* DO NOT narrow this helper to a single layout — it must tolerate all of the
* above. It does so by being layout-agnostic:
* - `page.getByRole(...)` only sees the top frame, so we search EVERY frame
* (top + nested iframes) for each element via `locateVisibleInFrames`.
* - The "Card" chooser is matched as a radio OR a button.
* - Card fields are matched whether direct inputs or iframe-nested.
* If Stripe introduces yet another layout, extend the locators here rather than
* assuming a single shape.
* So the flow is a sequence of SELF-HEALING STEPS (see ./self-healing/). Each
* step has a `verify` postcondition and is attempted with:
* 1. learned variants — recipes an LLM discovered on earlier runs, auto-
* committed to self-healing/learned-variants.json by the daily workflow;
* 2. the hand-written builtin variants below;
* 3. an LLM fallback (Gemini) that drives the page one action at a time
* until `verify` passes. Card data never reaches the LLM: it uses
* `{{CARD_NUMBER}}`-style placeholders that we substitute locally, and
* observations are redacted + input-masked.
* When the LLM heals a step and the purchase is confirmed server-side, the
* daily workflow opens an auto-merging PR adding the recipe to
* learned-variants.json — the next run replays it without the LLM.
*
* You can still add builtin variants by hand, but you shouldn't need to.
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
* E2E_STRIPE_CARD_CVC, E2E_STRIPE_CARDHOLDER_NAME (optional)
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC,
* E2E_STRIPE_CARDHOLDER_NAME (optional), E2E_STRIPE_ZIP (optional)
* GEMINI_API_KEY — enables the LLM fallback (absent → deterministic only)
* E2E_SELF_HEAL_MODELS — comma-separated Gemini model ids, cheapest first
* E2E_SELF_HEAL_FORCE_LLM — comma-separated step ids to force through the LLM (testing)
*/
interface CardDetails {
number: string;
expiry: string;
cvc: string;
name?: string;
name: string;
zip: string;
}
function getCardDetailsFromEnv(): CardDetails {
const number = process.env.E2E_STRIPE_CARD_NUMBER;
const expiry = process.env.E2E_STRIPE_CARD_EXPIRY;
const cvc = process.env.E2E_STRIPE_CARD_CVC;
const name = process.env.E2E_STRIPE_CARDHOLDER_NAME;
if (!number || !expiry || !cvc) {
throw new Error(
@@ -50,7 +61,13 @@ function getCardDetailsFromEnv(): CardDetails {
// Default the name so a missing/empty secret can't leave the (now required)
// "Name on card" field blank and get the Pay click rejected.
return { number, expiry, cvc, name: name || 'E2E Test' };
return {
number,
expiry,
cvc,
name: process.env.E2E_STRIPE_CARDHOLDER_NAME || 'E2E Test',
zip: process.env.E2E_STRIPE_ZIP || '10001',
};
}
/**
@@ -80,201 +97,20 @@ async function locateVisibleInFrames(
}
/**
* Complete the Stripe Checkout page with card details from environment.
*
* @param page - Playwright page that will be redirected to checkout.stripe.com
* @returns `{ redirected }` — whether the browser was observed navigating back
* to our success/app URL after payment. The redirect can be slow or dropped
* even when the charge succeeds (Stripe→site hop, 3DS interstitial), so this
* is reported rather than thrown: callers should treat the *server-side*
* credit grant (Stripe webhook) as the source of truth and use `redirected`
* only as a best-effort UX signal. Genuine failures (no Pay button, card
* declined) still throw.
* Accessible-name, placeholder and autocomplete metadata for each Stripe card
* field, used to build robust locators that work whether Stripe renders the
* field as a direct input or inside an iframe.
*/
export async function completeStripeCheckout(page: Page): Promise<{ redirected: boolean }> {
const card = getCardDetailsFromEnv();
// Step 1: Wait for Stripe Checkout page to fully load
console.log(' Waiting for Stripe Checkout page...');
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
// The "Pay" button is one of the last elements to render and confirms the
// Payment Element is interactive. It may be in the top frame (single-method
// layout) or a nested iframe (multi-method layout). Match it exactly so the
// "Pay with Link" / "Pay with Klarna" express buttons don't shadow it.
const payButton = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
30_000
);
if (!payButton) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button.png' });
throw new Error('Stripe "Pay" button not visible in any frame after 30s');
}
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(' Stripe Checkout loaded');
// Step 2: Ensure the card fields are shown. In the single-method layout they
// are already visible; in the multi-method accordion we must expand "Card"
// (rendered as a button or radio depending on Stripe's variant).
console.log(' Selecting Card payment method...');
let cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
5_000
);
if (cardNumberField) {
console.log(' Card fields already visible — no chooser to expand');
} else {
const cardChoice = await locateVisibleInFrames(
page,
(f) =>
f
.getByRole('radio', { name: /^Card$/i })
.or(f.getByRole('button', { name: /^Card$/i })),
5_000
);
if (cardChoice) {
// force:true bypasses any overlay/accordion animation intercepting clicks.
await cardChoice.click({ force: true }).catch(() => {});
console.log(' Card payment method selected');
} else {
console.log(' No Card chooser found — waiting for card fields to render...');
}
cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
15_000
);
if (!cardNumberField) {
console.log(' WARNING: card number field not visible after selecting Card');
}
}
await page.waitForTimeout(1000);
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
// Step 3-5: Fill card number, expiry, CVC
console.log(' Filling card number...');
await fillCardField(page, 'cardNumber', card.number);
console.log(' Filling card expiry...');
await fillCardField(page, 'cardExpiry', card.expiry);
console.log(' Filling CVC...');
await fillCardField(page, 'cardCvc', card.cvc);
// Step 6: Fill cardholder name if the field exists (any frame).
// Stripe renames/relabels this field across layouts — we've seen the
// accessible name be "Cardholder name", "Name on card", or "Full name on
// card", and the placeholder be "Full name on card" or "First and last
// name". Match all known variants so an empty name field can't silently
// block the Pay button (which produced a false "payment broken" alarm — the
// Pay click was rejected with "Please provide the name on your card").
if (card.name) {
const nameInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator(
'[data-elements-stable-field-name="billingName"], #billingName, input[name="billingName"], input[placeholder="Full name on card"], input[placeholder="First and last name"]'
)
.or(f.getByRole('textbox', { name: /name on card|cardholder name/i })),
8_000
);
if (nameInput) {
console.log(' Filling cardholder name...');
await nameInput.fill(card.name);
} else {
console.log(' WARNING: cardholder name field not found — Pay may be rejected');
}
}
// Step 6b: Fill ZIP code (required for US cards) — search any frame.
// The accessible name is "ZIP code" (not exactly "ZIP"), so the regex must
// not anchor to ^zip$. Placeholder is often absent, so rely on the stable
// field name / accessible name too.
const zipInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator(
'[data-elements-stable-field-name="billingPostalCode"], #billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]'
)
.or(f.getByRole('textbox', { name: /zip|postal code/i })),
8_000
);
if (zipInput) {
console.log(' Filling ZIP code...');
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
} else {
console.log(' WARNING: ZIP code field not found — Pay may be rejected');
}
// Step 6c: Uncheck "Save my information" to avoid a phone-number requirement
const saveCheckbox = await locateVisibleInFrames(
page,
(f) => f.getByRole('checkbox', { name: /save my information/i }),
2_000
);
if (saveCheckbox && (await saveCheckbox.isChecked().catch(() => false))) {
console.log(' Unchecking "Save my information"...');
await saveCheckbox.uncheck({ force: true }).catch(() => {});
}
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
console.log(' Card details filled');
// Step 7: Click "Pay" button (re-locate in case the frame re-rendered)
console.log(' Clicking Pay button...');
const finalPay = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
10_000
);
if (!finalPay) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button-final.png' });
throw new Error('Stripe "Pay" button not visible when ready to submit');
}
await finalPay.click();
console.log(' Payment submitted, waiting for redirect...');
// Wait for redirect back to our site. The charge itself completes on Stripe's
// side and is confirmed to us via webhook; the browser redirect back is a
// separate, sometimes-slow hop (and can stall on a 3DS interstitial). So a
// redirect timeout is NOT a payment failure — report it and let the caller
// verify the credit grant server-side instead of failing the whole test.
try {
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
timeout: 60_000,
});
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
console.log(' Stripe Checkout complete — redirected to success page');
return { redirected: true };
} catch {
await page.screenshot({ path: 'test-results/stripe-checkout-no-redirect.png' });
console.warn(
' ⚠️ Payment submitted but no redirect within 60s — will verify the credit ' +
'grant server-side (charge may have succeeded with a slow/dropped redirect)'
);
return { redirected: false };
}
}
/**
* Accessible-name and placeholder metadata for each Stripe card field, used to
* build robust locators that work whether Stripe renders the field as a direct
* input (single-payment-method layout) or inside an iframe.
*/
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string }> = {
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234' },
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY' },
cardCvc: { name: /^cvc$|security code/i },
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string; autocomplete: string }> = {
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234', autocomplete: 'cc-number' },
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY', autocomplete: 'cc-exp' },
cardCvc: { name: /^cvc$|security code/i, autocomplete: 'cc-csc' },
};
/**
* Locator for a Stripe card field within a given frame. Matches by Stripe's
* stable field-name attribute, element id, input name, placeholder, or
* accessible name — whichever the current Checkout layout uses.
* stable field-name attribute, element id, input name, autocomplete token,
* placeholder, or accessible name — whichever the current layout uses.
*/
function cardFieldLocator(frame: Frame, fieldName: string): Locator {
const meta = CARD_FIELD_META[fieldName];
@@ -283,22 +119,317 @@ function cardFieldLocator(frame: Frame, fieldName: string): Locator {
`#${fieldName}`,
`input[name="${fieldName}"]`,
];
if (meta?.autocomplete) selectors.push(`input[autocomplete="${meta.autocomplete}"]`);
if (meta?.placeholder) selectors.push(`input[placeholder="${meta.placeholder}"]`);
let loc = frame.locator(selectors.join(', '));
if (meta) loc = loc.or(frame.getByRole('textbox', { name: meta.name }));
return loc.first();
}
function nameFieldLocator(f: Frame): Locator {
// Stripe has labelled this "Cardholder name", "Name on card", "Full name on
// card"; placeholder "Full name on card" or "First and last name".
return f
.locator(
'[data-elements-stable-field-name="billingName"], #billingName, input[name="billingName"], input[autocomplete="cc-name"], input[placeholder="Full name on card"], input[placeholder="First and last name"]'
)
.or(f.getByRole('textbox', { name: /name on card|cardholder name/i }));
}
function zipFieldLocator(f: Frame): Locator {
// Accessible name is "ZIP code" (not exactly "ZIP") — don't anchor the regex.
return f
.locator(
'[data-elements-stable-field-name="billingPostalCode"], #billingPostalCode, input[name="billingPostalCode"], input[autocomplete="postal-code"], input[placeholder="ZIP"]'
)
.or(f.getByRole('textbox', { name: /zip|postal code/i }));
}
async function anyVisible(page: Page, make: (f: Frame) => Locator, timeout = 1_500): Promise<boolean> {
return (await locateVisibleInFrames(page, make, timeout)) !== null;
}
/** Builtin "fill" variant: locate with `make`, type `value`, record as lastFilled. */
function fillVariant(name: string, make: (f: Frame) => Locator, value: string, typed: boolean) {
return {
name,
run: async (ctx: StepContext) => {
const input = await locateVisibleInFrames(ctx.page, make, 8_000);
if (!input) throw new Error(`${name}: field not found`);
await input.click();
if (typed) await input.pressSequentially(value, { delay: 50 });
else await input.fill(value);
ctx.lastFilled = input;
},
};
}
const digits = (s: string) => s.replace(/\D/g, '');
/**
* Fill a card field by name, searching every frame (top document + nested
* iframes). Stripe renders card fields either as direct inputs (single-payment-
* method layout) or inside the Payment Element iframe (multi-method layout).
* Fill-step postcondition: the element filled during this step holds the
* expected value AND looks like the intended field (so a fallback that typed
* the card number into, say, a phone field can't pass).
*/
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
const input = await locateVisibleInFrames(page, (f) => cardFieldLocator(f, fieldName), 15_000);
if (!input) {
throw new Error(`Could not find card field: ${fieldName} in any frame`);
function filledVerify(expected: string, fieldHint: RegExp, compare: 'digits' | 'text') {
return async (ctx: StepContext): Promise<boolean> => {
const el = ctx.lastFilled;
if (!el) return false;
const value = await el.inputValue({ timeout: 1_000 }).catch(() => '');
const ok = compare === 'digits' ? digits(value) === digits(expected) : value.trim() === expected.trim();
if (!ok) return false;
const descriptor = await el
.evaluate((node) => {
const i = node as HTMLInputElement;
const labels = Array.from(i.labels || []).map((l) => l.textContent || '');
return [i.id, i.name, i.autocomplete, i.placeholder, i.getAttribute('aria-label'), i.getAttribute('data-elements-stable-field-name'), ...labels].join(' ');
})
.catch(() => '');
return fieldHint.test(descriptor);
};
}
/**
* Back on our site after paying. Must NOT match the cancel URL
* (`gen.nomadkaraoke.com?cancelled=true`, Stripe's "Back" link).
*/
export function isSuccessRedirect(url: string): boolean {
return /nomadkaraoke\.com.*(payment\/success|\/app)/.test(url) && !/cancelled=true/.test(url);
}
/** Rate-limit the server-side paid check (verify polls every 500ms). */
function throttled(check: () => Promise<boolean>, intervalMs = 5_000): () => Promise<boolean> {
let last = 0;
let lastResult = false;
return async () => {
if (lastResult || Date.now() - last < intervalMs) return lastResult;
last = Date.now();
lastResult = await check().catch(() => false);
return lastResult;
};
}
function buildSteps(card: CardDetails, verifyPaid?: () => Promise<boolean>): CheckoutStep[] {
const paidCheck = verifyPaid ? throttled(verifyPaid) : undefined;
const cardNumberVisible = (ctx: StepContext) =>
anyVisible(ctx.page, (f) => cardFieldLocator(f, 'cardNumber'));
return [
{
id: 'selectCard',
goal: 'Make the credit/debit CARD payment form visible (card number, expiry, CVC inputs). If payment methods are listed (Card, Cash App, Klarna, Bank…), select/expand "Card". Do not choose any other method and do not pay.',
verify: cardNumberVisible,
verifyTimeoutMs: 8_000,
builtins: [
{
name: 'click Card radio/button/label',
run: async ({ page }) => {
// Older variants: radio or button named "Card". Oct 2026: plain
// "Card" label over a visually-hidden "Pay with card" button.
const choice = await locateVisibleInFrames(
page,
(f) =>
f
.getByRole('radio', { name: /^(pay with )?card$/i })
.or(f.getByRole('button', { name: /^(pay with )?card$/i }))
.or(f.getByText('Card', { exact: true })),
5_000
);
if (!choice) throw new Error('no Card chooser visible');
await choice.click({ force: true });
},
},
{
name: 'dispatch click on hidden "Pay with card"',
run: async ({ page }) => {
let fired = false;
for (const frame of page.frames()) {
if (frame.isDetached()) continue;
const btn = frame.getByRole('button', { name: /^pay with card$/i, includeHidden: true }).first();
if (await btn.count().catch(() => 0)) {
await btn.dispatchEvent('click');
fired = true;
}
}
if (!fired) throw new Error('no hidden "Pay with card" button');
},
},
],
},
{
id: 'fillCardNumber',
goal: 'Type the card number into the card number input using value "{{CARD_NUMBER}}".',
placeholders: ['CARD_NUMBER'],
verify: filledVerify(card.number, /card.?number|cc-number|1234 1234/i, 'digits'),
builtins: [fillVariant('card number field', (f) => cardFieldLocator(f, 'cardNumber'), card.number, true)],
},
{
id: 'fillCardExpiry',
goal: 'Type the card expiry date into the expiration (MM / YY) input using value "{{CARD_EXPIRY}}".',
placeholders: ['CARD_EXPIRY'],
verify: filledVerify(card.expiry, /expir|cc-exp|mm ?\/ ?yy/i, 'digits'),
builtins: [fillVariant('card expiry field', (f) => cardFieldLocator(f, 'cardExpiry'), card.expiry, true)],
},
{
id: 'fillCardCvc',
goal: 'Type the card security code into the CVC input using value "{{CARD_CVC}}".',
placeholders: ['CARD_CVC'],
verify: filledVerify(card.cvc, /cvc|cvv|security|cc-csc/i, 'digits'),
builtins: [fillVariant('card CVC field', (f) => cardFieldLocator(f, 'cardCvc'), card.cvc, true)],
},
{
id: 'fillCardholderName',
goal: 'Type the cardholder name into the "Name on card"/cardholder-name input using value "{{CARDHOLDER_NAME}}".',
placeholders: ['CARDHOLDER_NAME'],
optional: true,
verify: filledVerify(card.name, /name/i, 'text'),
builtins: [fillVariant('cardholder name field', nameFieldLocator, card.name, false)],
},
{
id: 'fillPostalCode',
goal: 'Type the billing ZIP/postal code using value "{{POSTAL_CODE}}".',
placeholders: ['POSTAL_CODE'],
optional: true,
verify: filledVerify(card.zip, /zip|postal/i, 'text'),
builtins: [fillVariant('ZIP field', zipFieldLocator, card.zip, false)],
},
{
id: 'uncheckSaveInfo',
goal: 'Make sure "Save my information for faster checkout" (Stripe Link) is NOT checked.',
optional: true,
// Avoids Link's phone-number requirement.
verify: async ({ page }) => {
const cb = await locateVisibleInFrames(page, (f) => f.getByRole('checkbox', { name: /save my information/i }), 1_000);
return !cb || !(await cb.isChecked().catch(() => false));
},
builtins: [
{
name: 'uncheck "Save my information"',
run: async ({ page }) => {
const cb = await locateVisibleInFrames(page, (f) => f.getByRole('checkbox', { name: /save my information/i }), 2_000);
if (cb) await cb.uncheck({ force: true });
},
},
],
},
{
id: 'submitPayment',
goal: 'Submit the card payment. If the form shows validation errors or empty REQUIRED fields (e.g. name, ZIP/postal code, country), fix them first using the placeholders, then click the main Pay/submit button (NOT Link/Klarna/other express buttons).',
allowSubmit: true,
placeholders: ['CARD_NUMBER', 'CARD_EXPIRY', 'CARD_CVC', 'CARDHOLDER_NAME', 'POSTAL_CODE'],
// Long: the Stripe→site redirect and webhook grant can each take a while,
// and a premature LLM fallback risks a second submit.
verifyTimeoutMs: 90_000,
verify: async ({ page }) => {
if (isSuccessRedirect(page.url())) return true;
return paidCheck ? paidCheck() : false;
},
builtins: [
{
name: 'click Pay',
run: async ({ page }) => {
const pay = await locateVisibleInFrames(page, (f) => f.getByRole('button', { name: /^Pay$/i }), 10_000);
if (!pay) throw new Error('Pay button not visible');
await pay.click();
},
},
],
},
];
}
async function dumpFrames(page: Page, file: string): Promise<void> {
// page.content() only covers the main frame; the Payment Element usually
// lives in a nested iframe, so dump every frame.
const dumps: string[] = [];
for (const frame of page.frames()) {
if (frame.isDetached()) continue;
const html = await frame.content().catch(() => '');
dumps.push(`<!-- ===== frame: ${frame.url()} ===== -->\n${html}`);
}
fs.mkdirSync('test-results', { recursive: true });
fs.writeFileSync(file, dumps.join('\n\n'));
}
export const SELF_HEAL_ARTIFACT_DIR = 'test-results/self-heal';
export interface StripeCheckoutOptions {
/**
* Server-side "did the purchase land?" check (e.g. credit balance increased).
* Used by the submit step's postcondition when the browser redirect is slow,
* so the LLM fallback never re-submits a payment that already succeeded.
*/
verifyPaid?: () => Promise<boolean>;
/** Override the LLM planner (tests inject a stub; `null` disables the fallback). Default: Gemini from env. */
planner?: Planner | null;
/** Override learned variants (tests). Default: self-healing/learned-variants.json. */
learned?: LearnedVariantsFile;
}
/**
* Complete the Stripe Checkout page with card details from environment.
*
* @returns `redirected` — whether the browser was observed navigating back to
* our site. The redirect can be slow or dropped even when the charge succeeds,
* so callers should treat the *server-side* credit grant as the source of
* truth. `selfHeal` — call `selfHeal.writeArtifacts(SELF_HEAL_ARTIFACT_DIR,
* { flowVerified: true })` once the purchase is confirmed server-side so
* any LLM-healed steps get promoted to learned variants.
*/
export async function completeStripeCheckout(
page: Page,
opts: StripeCheckoutOptions = {}
): Promise<{ redirected: boolean; selfHeal: SelfHealingRunner }> {
const card = getCardDetailsFromEnv();
const secrets: Secrets = {
CARD_NUMBER: card.number,
CARD_EXPIRY: card.expiry,
CARD_CVC: card.cvc,
CARDHOLDER_NAME: card.name,
POSTAL_CODE: card.zip,
};
const planner = opts.planner !== undefined ? opts.planner : GeminiPlanner.fromEnv();
if (!planner) console.log(' (no LLM planner — GEMINI_API_KEY unset; self-healing fallback disabled)');
const runner = new SelfHealingRunner(page, secrets, planner, opts.learned);
console.log(' Waiting for Stripe Checkout page...');
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
// Readiness: any of the Pay button, the card form or a Card chooser. Don't
// insist on one — that's exactly what Stripe keeps changing.
const ready = await locateVisibleInFrames(
page,
(f) =>
f
.getByRole('button', { name: /^Pay\b/i })
.or(cardFieldLocator(f, 'cardNumber'))
.or(f.getByText('Card', { exact: true })),
30_000
);
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(ready ? ' Stripe Checkout loaded' : ' ⚠️ Stripe Checkout readiness signal not seen — continuing with self-healing steps');
try {
for (const step of buildSteps(card, opts.verifyPaid)) {
const outcome = await runner.run(step);
if (step.id === 'selectCard') await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
if (step.id === 'uncheckSaveInfo') await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
if (outcome.status === 'failed') {
await page.screenshot({ path: `test-results/stripe-step-failed-${step.id}.png` }).catch(() => {});
await dumpFrames(page, 'test-results/stripe-checkout-dom.html');
throw new Error(`Stripe Checkout step "${step.id}" failed: ${outcome.reason}`);
}
}
} catch (e) {
runner.writeArtifacts(SELF_HEAL_ARTIFACT_DIR, { flowVerified: false });
throw e;
}
const redirected = isSuccessRedirect(page.url());
await page.screenshot({ path: `test-results/stripe-checkout-${redirected ? 'complete' : 'no-redirect'}.png` }).catch(() => {});
if (redirected) {
console.log(' Stripe Checkout complete — redirected to our site');
} else {
console.warn(' ⚠️ Payment confirmed server-side but no browser redirect observed (slow/dropped redirect)');
}
await input.click();
await input.type(value, { delay: 50 });
return { redirected, selfHeal: runner };
}
@@ -2,7 +2,7 @@
import { test, expect } from '@playwright/test';
import type { APIRequestContext } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
import { completeStripeCheckout } from '../helpers/stripe-checkout';
import { completeStripeCheckout, SELF_HEAL_ARTIFACT_DIR } from '../helpers/stripe-checkout';
import { getPageAuthToken, clickCompleteSignInGate } from '../helpers/auth';
import { URLS, TIMEOUTS } from '../helpers/constants';
import * as fs from 'fs';
@@ -229,7 +229,14 @@ test.describe('Real Credit Purchase Flow', () => {
// Complete Stripe Checkout with real card. The redirect back to our site
// is best-effort — the authoritative signal is the server-side credit grant.
const checkout = await completeStripeCheckout(page);
// verifyPaid lets the submit step confirm success server-side when the
// redirect is slow, so the self-healing fallback never re-submits.
const checkout = await completeStripeCheckout(page, {
verifyPaid: async () => {
const latest = await getCreditsViaAdmin(request, API_URL, adminToken!, inbox.emailAddress);
return latest !== null && latest > baselineCredits;
},
});
// ===== STEP 6: Verify the purchase landed (server-side source of truth) =====
console.log('\n=== STEP 6: Verify credit grant (server-side) ===');
@@ -247,6 +254,17 @@ test.describe('Real Credit Purchase Flow', () => {
).not.toBeNull();
console.log(` ✅ Server-side credit grant confirmed: ${baselineCredits} → ${newBalance}`);
// The purchase is proven end-to-end, so any step the LLM fallback healed
// is trustworthy: emit the merged learned-variants.json for the workflow
// to commit via an auto-merging PR.
const runUrl = process.env.GITHUB_RUN_ID
? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
: undefined;
const { learnedWritten } = checkout.selfHeal.writeArtifacts(SELF_HEAL_ARTIFACT_DIR, { flowVerified: true, runUrl });
if (learnedWritten) {
console.log(' 🩹 Self-healing: LLM-healed step(s) recorded — the workflow will open an auto-merge PR');
}
// Best-effort UX check: if the browser redirected to the success page,
// confirm it renders the expected confirmation. A missing redirect is only
// a UX nicety here (the charge + grant are already proven above), so don't
@@ -0,0 +1,158 @@
// frontend/e2e/self-healing/checkout-flow.spec.ts
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { completeStripeCheckout } from '../helpers/stripe-checkout';
import { emptyFile } from '../helpers/self-healing/learned-store';
import type { LearnedVariantsFile } from '../helpers/self-healing/types';
import {
CHECKOUT_URL,
ELEMENTS_FUTURE,
ELEMENTS_OCT2026,
ScriptedPlanner,
TEST_CARD,
elementsFrameIndex,
serveCheckout,
setCardEnv,
} from './fixtures';
test.beforeAll(() => {
setCardEnv();
fs.mkdirSync('test-results', { recursive: true });
});
function tmpDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'selfheal-'));
}
test('known layout (Oct 2026 hidden "Pay with card") completes via builtins — no LLM call', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026);
await page.goto(CHECKOUT_URL);
const planner = new ScriptedPlanner([]);
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
expect(result.redirected).toBe(true);
expect(planner.inputs).toHaveLength(0);
const statuses = Object.fromEntries(result.selfHeal.outcomes.map((o) => [o.stepId, o.status]));
expect(statuses).toMatchObject({
selectCard: 'ok',
fillCardNumber: 'ok',
fillCardExpiry: 'ok',
fillCardCvc: 'ok',
fillCardholderName: 'ok',
fillPostalCode: 'ok',
submitPayment: 'ok',
});
const dir = tmpDir();
expect(result.selfHeal.writeArtifacts(dir, { flowVerified: true }).learnedWritten).toBe(false);
});
test('unknown layout: LLM heals selectCard, recipe is learned, and the next run replays it without the LLM', async ({ page }) => {
await serveCheckout(page, ELEMENTS_FUTURE);
await page.goto(CHECKOUT_URL);
const planner = new ScriptedPlanner([
(input) => ({
thought: 'Card form is behind the "Credit or debit" tab',
status: 'act',
action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Credit or debit' } },
}),
]);
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
expect(result.redirected).toBe(true);
expect(planner.inputs).toHaveLength(1);
expect(planner.inputs[0].stepId).toBe('selectCard');
const healed = result.selfHeal.healed;
expect(healed).toHaveLength(1);
expect(healed[0].actions[0]).toEqual({
type: 'click',
target: { frameUrlIncludes: 'js.stripe.com/v3/elements-inner-payment.html', by: 'role', role: 'tab', name: 'Credit or debit' },
});
// Promotion only happens once the flow is verified.
const unverifiedDir = tmpDir();
expect(result.selfHeal.writeArtifacts(unverifiedDir, { flowVerified: false }).learnedWritten).toBe(false);
expect(fs.existsSync(path.join(unverifiedDir, 'learned-variants.json'))).toBe(false);
const dir = tmpDir();
expect(result.selfHeal.writeArtifacts(dir, { flowVerified: true, runUrl: 'https://example/run/1' }).learnedWritten).toBe(true);
const learned = JSON.parse(fs.readFileSync(path.join(dir, 'learned-variants.json'), 'utf8')) as LearnedVariantsFile;
expect(learned.steps.selectCard).toHaveLength(1);
expect(learned.steps.selectCard[0].runUrl).toBe('https://example/run/1');
const report = JSON.parse(fs.readFileSync(path.join(dir, 'self-heal-report.json'), 'utf8'));
expect(report.llmCalls).toBe(1);
// Second run: same unknown layout, learned recipe replayed, LLM not consulted.
const page2 = await page.context().newPage();
await serveCheckout(page2, ELEMENTS_FUTURE);
await page2.goto(CHECKOUT_URL);
const planner2 = new ScriptedPlanner([]);
const rerun = await completeStripeCheckout(page2, { planner: planner2, learned });
expect(rerun.redirected).toBe(true);
expect(planner2.inputs).toHaveLength(0);
expect(rerun.selfHeal.outcomes.find((o) => o.stepId === 'selectCard')).toMatchObject({ status: 'ok', via: 'learned' });
});
test('no secrets reach the LLM — prompts use placeholders and observations are redacted', async ({ page }) => {
await serveCheckout(page, ELEMENTS_FUTURE);
await page.goto(CHECKOUT_URL);
// Force the LLM for a fill step that runs AFTER the card number was typed,
// so the card number is present on the page while observing.
const planner = new ScriptedPlanner([
(input) => ({
thought: 'open card tab',
status: 'act',
action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Credit or debit' } },
}),
(input) => ({
thought: 'fill expiry',
status: 'act',
action: { type: 'fill', target: { frameIndex: elementsFrameIndex(input), by: 'label', text: 'Expiration' }, value: '{{CARD_EXPIRY}}' },
}),
]);
process.env.E2E_SELF_HEAL_FORCE_LLM = 'fillCardExpiry';
try {
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
expect(result.redirected).toBe(true);
} finally {
delete process.env.E2E_SELF_HEAL_FORCE_LLM;
}
expect(planner.inputs.map((i) => i.stepId)).toEqual(['selectCard', 'fillCardExpiry']);
const expiryInput = planner.inputs[1];
const everything = JSON.stringify(expiryInput);
expect(everything).not.toContain(TEST_CARD.E2E_STRIPE_CARD_NUMBER);
expect(everything).not.toContain('4242 4242');
expect(everything).not.toContain(TEST_CARD.E2E_STRIPE_CARDHOLDER_NAME);
expect(expiryInput.placeholders).toEqual(['CARD_EXPIRY']);
});
test('guardrails: LLM may not click Pay outside the submit step or pick express methods; step fails cleanly', async ({ page }) => {
await serveCheckout(page, ELEMENTS_FUTURE);
await page.goto(CHECKOUT_URL);
const planner = new ScriptedPlanner([
(input) => ({ thought: 'just pay', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'button', name: 'Pay', exact: true } } }),
(input) => ({ thought: 'use bank', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Bank' } } }),
// css target with no label — must be caught by the resolved-element guard
(input) => ({ thought: 'pay via css', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'css', css: '#pay' } } }),
{ thought: 'cannot', status: 'give_up' },
{ thought: 'cannot', status: 'give_up' },
{ thought: 'cannot', status: 'give_up' },
]);
await expect(completeStripeCheckout(page, { planner, learned: emptyFile() })).rejects.toThrow(/step "selectCard" failed/);
expect(page.url()).toContain('checkout.stripe.com'); // never submitted
const history = planner.inputs.at(-1)!.history.join('\n');
expect(history).toContain('not allowed in this step');
expect(history).toContain('alternative/express payment method');
expect(history).toContain('the target element is the final Pay/submit button');
});
test('without a planner, an unknown layout fails with a clear reason (deterministic-only mode)', async ({ page }) => {
await serveCheckout(page, ELEMENTS_FUTURE);
await page.goto(CHECKOUT_URL);
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/no LLM planner/);
expect(fs.existsSync('test-results/stripe-checkout-dom.html')).toBe(true);
});
+95
View File
@@ -0,0 +1,95 @@
// frontend/e2e/self-healing/fixtures.ts
import type { Page } from '@playwright/test';
import type { LlmDecision, Planner, PlannerInput } from '../helpers/self-healing/llm-agent';
export const CHECKOUT_URL = 'https://checkout.stripe.com/c/pay/cs_test_fixture#frag';
export const ELEMENTS_URL = 'https://js.stripe.com/v3/elements-inner-payment.html?id=abc';
export const SUCCESS_URL = 'https://gen.nomadkaraoke.com/payment/success?session_id=cs_test_fixture';
export const TEST_CARD = {
E2E_STRIPE_CARD_NUMBER: '4242424242424242',
E2E_STRIPE_CARD_EXPIRY: '12/34',
E2E_STRIPE_CARD_CVC: '123',
E2E_STRIPE_CARDHOLDER_NAME: 'Fixture Tester',
E2E_STRIPE_ZIP: '10001',
};
export function setCardEnv(): void {
Object.assign(process.env, TEST_CARD);
}
const cardFields = `
<div id="card-form" style="display:none">
<label>Card number <input id="cardNumber" autocomplete="cc-number" placeholder="1234 1234 1234 1234"></label>
<label>Expiration <input id="cardExpiry" autocomplete="cc-exp" placeholder="MM / YY"></label>
<label>CVC <input id="cardCvc" autocomplete="cc-csc"></label>
<label>Name on card <input id="billingName" autocomplete="cc-name"></label>
<label>ZIP code <input id="billingPostalCode" autocomplete="postal-code"></label>
</div>`;
/**
* Layout "oct2026": plain "Card" label with a visually-hidden "Pay with card"
* button — the layout that broke run #192. Builtins handle it.
*/
export const ELEMENTS_OCT2026 = `<!doctype html><html><body>
<div class="accordion">
<div class="item" style="position:relative">
<span>Card</span>
<button aria-label="Pay with card" style="position:absolute;inset:0;opacity:0" onclick="document.getElementById('card-form').style.display='block'"></button>
</div>
<div class="item"><span>Klarna</span></div>
</div>
${cardFields}
<button id="pay" onclick="window.top.postMessage('pay','*')">Pay</button>
</body></html>`;
/**
* Layout "future": a chooser NO builtin knows — a tab named "Credit or debit".
* Only the LLM fallback (stubbed here) can get past it.
*/
export const ELEMENTS_FUTURE = `<!doctype html><html><body>
<div role="tablist">
<div role="tab" tabindex="0" aria-selected="false" onclick="document.getElementById('card-form').style.display='block';this.setAttribute('aria-selected','true')">Credit or debit</div>
<div role="tab" tabindex="0" aria-selected="false">Bank</div>
</div>
${cardFields}
<button id="pay" onclick="window.top.postMessage('pay','*')">Pay</button>
</body></html>`;
const TOP_PAGE = `<!doctype html><html><body>
<a href="https://gen.nomadkaraoke.com?cancelled=true">Back to Nomad Karaoke</a>
<h2>Pay Nomad Karaoke</h2>
<iframe src="${ELEMENTS_URL}" style="width:600px;height:500px"></iframe>
<script>
window.addEventListener('message', (e) => {
if (e.data === 'pay') window.location.href = '${SUCCESS_URL}';
});
</script>
</body></html>`;
/** Serve a fake Stripe Checkout (top page + Payment Element iframe) and our success page. */
export async function serveCheckout(page: Page, elementsHtml: string): Promise<void> {
await page.route('https://checkout.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: TOP_PAGE }));
await page.route('https://js.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: elementsHtml }));
await page.route('https://gen.nomadkaraoke.com/**', (r) =>
r.fulfill({ contentType: 'text/html', body: '<h1>Payment successful</h1>' })
);
}
/** Planner stub: returns scripted decisions in order and records every prompt input. */
export class ScriptedPlanner implements Planner {
readonly inputs: PlannerInput[] = [];
constructor(private readonly script: Array<LlmDecision | ((input: PlannerInput) => LlmDecision)>) {}
async decide(input: PlannerInput) {
this.inputs.push(input);
const next = this.script.shift();
const decision = typeof next === 'function' ? next(input) : next ?? { thought: 'out of script', status: 'give_up' as const };
return { decision, model: 'stub-model' };
}
}
export function elementsFrameIndex(input: PlannerInput): number {
const idx = input.observation.frameKeys.findIndex((k) => k.includes('js.stripe.com'));
if (idx < 0) throw new Error('elements frame not in observation');
return idx;
}
+148
View File
@@ -0,0 +1,148 @@
// frontend/e2e/self-healing/units.spec.ts — pure-function tests (no browser page needed)
import { test, expect } from '@playwright/test';
import { frameUrlKey, substitutePlaceholders } from '../helpers/self-healing/actions';
import { buildPrompt, checkGuards, checkResolvedClick, toTargetSpec } from '../helpers/self-healing/llm-agent';
import { MAX_LEARNED_PER_STEP, emptyFile, mergeLearned, variantId } from '../helpers/self-healing/learned-store';
import { redact } from '../helpers/self-healing/observe';
import { isSuccessRedirect } from '../helpers/stripe-checkout';
import type { Action } from '../helpers/self-healing/types';
const secrets = { CARD_NUMBER: '4242424242424242', CARD_EXPIRY: '12/34', CARD_CVC: '123', CARDHOLDER_NAME: 'Fixture Tester', POSTAL_CODE: '10001' };
test.describe('redact', () => {
test('blanks textbox values and PAN-shaped digit runs, keeps structure', () => {
const snap = [
'- textbox "Card number": 4242 4242 4242 4242',
'- textbox "Expiration" [active]: 12 / 34',
'- textbox "CVC": 123',
'- textbox "Name on card"',
'- text: Total due $0.50',
'- paragraph: ref 4242-4242-4242-4242',
'- generic: Fixture Tester',
].join('\n');
const out = redact(snap, secrets);
expect(out).not.toMatch(/4242/);
expect(out).not.toContain('12 / 34');
expect(out).not.toContain(': 123');
expect(out).not.toContain('Fixture Tester');
expect(out).toContain('- textbox "Card number": [value redacted]');
expect(out).toContain('- textbox "Name on card"');
expect(out).toContain('$0.50');
});
});
test.describe('checkGuards', () => {
const step = { allowSubmit: false, placeholders: ['CARD_NUMBER'] };
const click = (name: string) => ({ type: 'click' as const, target: { by: 'role' as const, role: 'button', name } });
test('blocks final Pay outside submit step but allows "Pay with card"', () => {
expect(checkGuards(click('Pay'), step)).toMatch(/not allowed/);
expect(checkGuards(click('Pay $0.50'), step)).toMatch(/not allowed/);
expect(checkGuards(click('Pay with card'), step)).toBeNull();
expect(checkGuards(click('Pay'), { ...step, allowSubmit: true })).toBeNull();
});
test('blocks express methods and the cancel/back link', () => {
for (const n of ['Pay securely with Link', 'Pay with Klarna', 'Cash App Pay', 'Bank', 'Back to Nomad Karaoke']) {
expect(checkGuards(click(n), { ...step, allowSubmit: true }), n).not.toBeNull();
}
});
test('only allowed placeholders; no literal card-like digits', () => {
const fill = (value: string) => ({ type: 'fill' as const, target: { by: 'label' as const, text: 'Card number' }, value });
expect(checkGuards(fill('{{CARD_NUMBER}}'), step)).toBeNull();
expect(checkGuards(fill('{{CARD_CVC}}'), step)).toMatch(/not available/);
expect(checkGuards(fill('4242424242424242'), step)).toMatch(/literal digits/);
expect(checkGuards(fill('United States'), step)).toBeNull();
});
test('rejects malformed targets', () => {
expect(checkGuards({ type: 'click', target: { by: 'css' } }, step)).toMatch(/css/);
expect(checkGuards({ type: 'click', target: { by: 'role' } }, step)).toMatch(/role/);
});
});
test.describe('checkResolvedClick (guards the real element, not the model label)', () => {
const fillStep = { allowSubmit: false };
test('refuses css/unnamed targets that resolve to the submit button outside submitPayment', () => {
expect(checkResolvedClick({ testid: 'hosted-payment-submit-button', text: 'Pay' }, fillStep)).toMatch(/not allowed/);
expect(checkResolvedClick({ type: 'submit', text: 'Continue' }, fillStep)).toMatch(/not allowed/);
expect(checkResolvedClick({ text: 'Pay $0.50' }, fillStep)).toMatch(/not allowed/);
expect(checkResolvedClick({ testid: 'hosted-payment-submit-button', text: 'Pay' }, { allowSubmit: true })).toBeNull();
});
test('refuses express methods / cancel even in the submit step', () => {
expect(checkResolvedClick({ text: 'Pay securely with Link' }, { allowSubmit: true })).not.toBeNull();
expect(checkResolvedClick({ testid: 'klarna-accordion-item' }, { allowSubmit: true })).not.toBeNull();
expect(checkResolvedClick({ text: 'Back to Nomad Karaoke' }, { allowSubmit: true })).not.toBeNull();
});
test('allows the card chooser', () => {
expect(checkResolvedClick({ testid: 'card-accordion-item', text: 'Card' }, fillStep)).toBeNull();
expect(checkResolvedClick({ ariaLabel: 'Pay with card', type: 'button' }, fillStep)).toBeNull();
});
});
test('toTargetSpec maps frameIndex to a stable frame key and drops empties', () => {
const spec = toTargetSpec({ frameIndex: 1, by: 'role', role: 'tab', name: 'Card', css: '' }, ['checkout.stripe.com/c/pay/x', 'js.stripe.com/v3/inner.html']);
expect(spec).toEqual({ frameUrlIncludes: 'js.stripe.com/v3/inner.html', by: 'role', role: 'tab', name: 'Card' });
});
test('frameUrlKey strips query, hash and session-id path segments', () => {
expect(frameUrlKey('https://js.stripe.com/v3/elements-inner.html?id=abc#x')).toBe('js.stripe.com/v3/elements-inner.html');
// Real Stripe Checkout URL shape (run 37137960148): session id lives in the path.
expect(frameUrlKey('https://checkout.stripe.com/c/pay/cs_live_a1j0424mRKhVaGMhJ1P7KXkqvcueGqJ2ZWaoGi84JO7ueILw9w6Yd0tEl5#fid=x')).toBe('checkout.stripe.com/c/pay');
expect(frameUrlKey('https://checkout.stripe.com/c/pay/cs_test_abc')).toBe('checkout.stripe.com/c/pay');
expect(frameUrlKey('https://js.stripe.com/v3/elements-inner-accordion-8f2a.html')).toBe('js.stripe.com/v3/elements-inner-accordion-8f2a.html');
});
test('substitutePlaceholders substitutes known and throws on unknown', () => {
expect(substitutePlaceholders('{{CARD_CVC}}', secrets)).toBe('123');
expect(() => substitutePlaceholders('{{NOPE}}', secrets)).toThrow(/Unknown placeholder/);
});
test('buildPrompt contains goal/history but never raw secrets', () => {
const prompt = buildPrompt({
stepId: 'fillCardNumber',
goal: 'Type "{{CARD_NUMBER}}"',
allowSubmit: false,
placeholders: ['CARD_NUMBER'],
history: ['FAILED: x'],
observation: { url: 'checkout.stripe.com/c/pay', text: '- textbox "Card number": [value redacted]', frameKeys: [] },
escalation: 0,
});
expect(prompt).toContain('{{CARD_NUMBER}}');
expect(prompt).toContain('FAILED: x');
expect(prompt).toContain('Final Pay/submit button allowed in this step: NO');
});
test.describe('mergeLearned', () => {
const a1: Action[] = [{ type: 'click', target: { by: 'role', role: 'tab', name: 'Card' } }];
const a2: Action[] = [{ type: 'click', target: { by: 'text', text: 'Card', exact: true } }];
test('adds newest-first, dedupes identical recipes, is pure', () => {
const base = emptyFile();
const r1 = mergeLearned(base, [{ stepId: 'selectCard', actions: a1, model: 'm' }], { now: 't1' });
expect(r1.changed).toBe(true);
expect(base.steps).toEqual({});
const r2 = mergeLearned(r1.file, [{ stepId: 'selectCard', actions: a1 }], { now: 't2' });
expect(r2.changed).toBe(false);
const r3 = mergeLearned(r2.file, [{ stepId: 'selectCard', actions: a2 }], { now: 't3' });
expect(r3.file.steps.selectCard.map((v) => v.id)).toEqual([variantId(a2), variantId(a1)]);
});
test(`caps each step at ${MAX_LEARNED_PER_STEP}`, () => {
let file = emptyFile();
for (let i = 0; i < MAX_LEARNED_PER_STEP + 3; i++) {
file = mergeLearned(file, [{ stepId: 's', actions: [{ type: 'click', target: { by: 'text', text: `v${i}` } }] }]).file;
}
expect(file.steps.s).toHaveLength(MAX_LEARNED_PER_STEP);
expect(file.steps.s[0].actions[0].target.text).toBe(`v${MAX_LEARNED_PER_STEP + 2}`);
});
test('skips empty recipes', () => {
expect(mergeLearned(emptyFile(), [{ stepId: 's', actions: [] }]).changed).toBe(false);
});
});
test('isSuccessRedirect accepts success/app URLs but not the cancel link', () => {
expect(isSuccessRedirect('https://gen.nomadkaraoke.com/payment/success?session_id=x')).toBe(true);
expect(isSuccessRedirect('https://gen.nomadkaraoke.com/en/app')).toBe(true);
expect(isSuccessRedirect('https://gen.nomadkaraoke.com?cancelled=true')).toBe(false);
expect(isSuccessRedirect('https://checkout.stripe.com/c/pay/x')).toBe(false);
});
@@ -9,6 +9,7 @@ import {
checkFilenameMismatch,
getAvailabilityLabel,
getSearchConfidence,
isConfirmedTitleMatch,
ExtendedAudioSearchResult,
} from '../audio-search-utils'
@@ -506,3 +507,105 @@ describe('getSearchConfidence', () => {
expect(confidence.bestResult?.index).toBe(0)
})
})
// Real search from a live kjbox night (2026-10-01): "Braxton Keith - The Chair"
// returned only Spotify results. `title` is the album, `target_file` the track.
// The UI used to call this "Limited sources found" and push the singer to YouTube.
const spotify = (index: number, album: string, track: string, popularity: number, release_type = 'Album') =>
makeResult({
index, provider: 'Spotify', title: album, target_file: track, artist: 'Braxton Keith',
quality: 'FLAC 16bit WEB', release_type, view_count: popularity * 10000,
})
const braxtonKeithResults = () => [
spotify(0, 'Real Damn Deal', 'I Own This Bar', 40),
spotify(1, 'Cozy', 'Cozy', 45),
spotify(2, 'The Chair', 'The Chair', 65, 'Single'),
spotify(3, 'I Own This Bar', 'I Own This Bar', 40),
spotify(4, 'The Chair', 'Prescription', 20, 'Single'),
spotify(5, 'Highway Country', 'The Chair', 23, 'Compilation'),
spotify(6, 'pov: U fell in love', 'The Chair', 14, 'Compilation'),
]
describe('title-matched best result', () => {
it('picks the Spotify track whose name matches, most popular first', () => {
expect(getBestResult(braxtonKeithResults(), 'The Chair')?.index).toBe(2)
})
it('without a title keeps the old category/seeders behaviour', () => {
expect(getBestResult(braxtonKeithResults())?.index).toBe(2) // popularity tiebreak
})
it('a Spotify title match is a confident tier 2, not "limited sources"', () => {
const c = getSearchConfidence(braxtonKeithResults(), 'The Chair')
expect(c.tier).toBe(2)
expect(c.bestResult?.index).toBe(2)
expect(c.warnings).toEqual([])
expect(c.reason).toContain('Spotify')
})
it('Spotify with no matching track is still tier 3', () => {
const results = [spotify(0, 'Real Damn Deal', 'I Own This Bar', 40)]
expect(getSearchConfidence(results, 'The Chair').tier).toBe(3)
})
it('prefers the right track on Spotify over the wrong track on a torrent', () => {
const results = [
makeResult({ index: 0, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '03 - Prescription.flac' }),
spotify(1, 'The Chair', 'The Chair', 65, 'Single'),
]
expect(getBestResult(results, 'The Chair')?.index).toBe(1)
})
it('still prefers a matching torrent over matching Spotify', () => {
const results = [
spotify(0, 'The Chair', 'The Chair', 65, 'Single'),
makeResult({ index: 1, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '01 - The Chair.flac' }),
]
const c = getSearchConfidence(results, 'The Chair')
expect(c.bestResult?.index).toBe(1)
expect(c.tier).toBe(1)
})
it('a Spotify album named after the song is not a track match', () => {
const results = [
makeResult({ index: 0, provider: 'Spotify', title: 'The Chair', artist: 'Braxton Keith' }),
]
const c = getSearchConfidence(results, 'The Chair')
expect(c.tier).toBe(3)
})
it('isConfirmedTitleMatch needs a compared, matching track filename', () => {
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair', 1))).toBe(true)
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'Cozy', 1))).toBe(false)
expect(isConfirmedTitleMatch('Up', spotify(0, 'X', 'Up', 1))).toBe(false)
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chairman', 1))).toBe(false)
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair (feat. Someone)', 1))).toBe(true)
expect(isConfirmedTitleMatch('Hotel California',
spotify(0, 'X', 'Hotel California - 2013 Remaster', 1))).toBe(true)
expect(isConfirmedTitleMatch('Mr. Brightside', spotify(0, 'X', 'Mr. Brightside', 1))).toBe(true)
expect(isConfirmedTitleMatch('7 Rings', spotify(0, 'X', '7 rings', 1))).toBe(true)
expect(isConfirmedTitleMatch("(I Can't Get No) Satisfaction",
spotify(0, 'X', "(I Can't Get No) Satisfaction - Mono Version", 1))).toBe(true)
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair (feat. X) [Remastered]', 1))).toBe(true)
expect(isConfirmedTitleMatch('Creep',
makeResult({ index: 0, is_lossless: true, target_file: 'Pablo Honey/02 - Creep.flac' }))).toBe(true)
expect(isConfirmedTitleMatch('The Chair',
makeResult({ index: 0, provider: 'Spotify', title: 'The Chair' }))).toBe(false)
})
it('a title-matched live version beats an unranked fallback to results[0]', () => {
const results = [
spotify(0, 'Real Damn Deal', 'I Own This Bar', 40),
makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Live album', target_file: '04 - The Chair.flac' }),
]
expect(getBestResult(results, 'The Chair')?.index).toBe(1)
})
it('never promotes YouTube via a title match over a torrent', () => {
const results = [
makeResult({ index: 0, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '03 - Prescription.flac' }),
makeResult({ index: 1, provider: 'YouTube', title: 'Braxton Keith - The Chair (Official Video)' }),
]
expect(getBestResult(results, 'The Chair')?.index).toBe(0)
})
})
+67 -12
View File
@@ -158,14 +158,27 @@ const BEST_RESULT_PRIORITY = [
// Returns the single best result from the array
// Priority: BEST CHOICE > STUDIO ALBUMS > HI-RES 24-BIT > SINGLES > COMPILATIONS > SPOTIFY > YOUTUBE > OTHER
// Skips VINYL RIPS (surface noise issues for karaoke) and LIVE VERSIONS (unless nothing else)
// Within a category, prefers highest seeders
export function getBestResult(results: ExtendedAudioSearchResult[]): ExtendedAudioSearchResult | null {
// When searchTitle is given and any torrent/Spotify result's track name matches
// it, only those are considered — a mismatched file is usually a different song,
// so the right track from Spotify beats the wrong track from a better-seeded
// torrent. YouTube never wins this way: video titles nearly always "match".
// Within a category, prefers highest seeders, then popularity (view_count).
export function getBestResult(
results: ExtendedAudioSearchResult[],
searchTitle = ''
): ExtendedAudioSearchResult | null {
if (results.length === 0) return null
const titleMatches = searchTitle
? results.filter(r => !['YOUTUBE', 'VINYL RIPS'].includes(categorizeResult(r))
&& isConfirmedTitleMatch(searchTitle, r))
: []
const pool = titleMatches.length > 0 ? titleMatches : results
let best: ExtendedAudioSearchResult | null = null
let bestPriority = Infinity
for (const result of results) {
for (const result of pool) {
const category = categorizeResult(result)
// Skip vinyl rips entirely
@@ -178,17 +191,18 @@ export function getBestResult(results: ExtendedAudioSearchResult[]): ExtendedAud
best = result
bestPriority = effectivePriority
} else if (effectivePriority === bestPriority && best) {
// Same category — prefer higher seeders
// Same category — prefer higher seeders, then more popular
const currentSeeders = result.seeders ?? 0
const bestSeeders = best.seeders ?? 0
if (currentSeeders > bestSeeders) {
if (currentSeeders > bestSeeders
|| (currentSeeders === bestSeeders && (result.view_count ?? 0) > (best.view_count ?? 0))) {
best = result
}
}
}
// If nothing found (all vinyl rips), fall back to first result
return best ?? results[0]
// If nothing ranked (all vinyl rips / live), stay within the title matches
return best ?? pool[0]
}
// --- Confidence tier types and utilities ---
@@ -214,6 +228,8 @@ export interface FilenameMismatchResult {
* Check if a result's track name doesn't match the search title.
* Uses target_file for torrent/Spotify results, result.title for YouTube.
*/
const AUDIO_EXT_RE = /\.(flac|mp3|m4a|wav|ogg|opus|aac|alac|ape|wv|aiff?|dsf|mp4|webm)$/i
export function checkFilenameMismatch(
searchTitle: string,
result: ExtendedAudioSearchResult
@@ -230,7 +246,8 @@ export function checkFilenameMismatch(
// Extract filename: strip directory path
const rawFilename = result.target_file.split('/').pop() || result.target_file
// Strip extension
const withoutExt = rawFilename.replace(/\.[^.]+$/, '')
// Only real audio extensions — Spotify track names have none ("Mr. Brightside")
const withoutExt = rawFilename.replace(AUDIO_EXT_RE, '')
// Strip leading track number prefixes like "01 - ", "01. ", "1 ", "01-"
filename = withoutExt.replace(/^\d{1,3}\s*[-.\s]\s*/, '')
} else if (result.title) {
@@ -264,6 +281,38 @@ export function checkFilenameMismatch(
}
}
// Whole-title core for equality: drops only TRAILING version suffixes —
// "The Chair (feat. X)", "Hotel California - 2013 Remaster" — so "The Chairman"
// doesn't match "The Chair" and "(I Can't Get No) Satisfaction" stays intact.
function titleCore(s: string): string {
const norm = (x: string) => x.toLowerCase().replace(/[^a-z0-9\s]/g, ' ').replace(/\s+/g, ' ').trim()
let c = s
for (let i = 0; i < 3; i++) {
const next = c.replace(/\s*[([][^)\]]*[)\]]\s*$/, '').replace(/\s+-\s+[^-]*$/, '')
if (next === c) break
c = next
}
const core = norm(c)
return core.length >= 3 ? core : norm(s)
}
/**
* True only when the result's track filename was actually compared and matched.
* checkFilenameMismatch reports "no mismatch" when it can't compare (no
* target_file → album title, title < 3 chars, non-Latin filename), which must not
* count as evidence that this is the right track.
*/
export function isConfirmedTitleMatch(searchTitle: string, result: ExtendedAudioSearchResult): boolean {
if (!result.target_file) return false
const m = checkFilenameMismatch(searchTitle, result)
if (m.isMismatch || !m.filename || searchTitle.length < 3) return false
const t = titleCore(searchTitle)
if (t.length < 3) return false
// Compare with and without the track-number strip ("7 Rings" must keep its 7)
const raw = (result.target_file.split('/').pop() || result.target_file).replace(AUDIO_EXT_RE, '')
return titleCore(m.filename) === t || titleCore(raw) === t
}
/**
* Get a human-readable availability label + tooltip for a seeder count.
*/
@@ -292,7 +341,7 @@ export function getSearchConfidence(
}
}
const best = getBestResult(results)
const best = getBestResult(results, searchTitle)
const bestCat = best ? categorizeResult(best) : null
const warnings: string[] = []
@@ -315,7 +364,11 @@ export function getSearchConfidence(
return cat !== 'YOUTUBE' && cat !== 'SPOTIFY' && cat !== 'VINYL RIPS'
})
if (!hasLossless) {
// Spotify is an official release (16-bit WEB) — the right track from it is a
// good source, second only to lossless torrents and far better than YouTube.
const spotifyMatch = bestCat === 'SPOTIFY' && !!best && isConfirmedTitleMatch(searchTitle, best)
if (!hasLossless && !spotifyMatch) {
warnings.push('No lossless sources available — only YouTube/lossy or vinyl rips found')
}
@@ -332,8 +385,8 @@ export function getSearchConfidence(
return { tier: 1, reason, bestResult: best, bestCategory: bestCat, warnings }
}
// Tier 3: No results, or only lossy/vinyl, or mismatch with low availability
if (!hasLossless) {
// Tier 3: No results, or only lossy/vinyl (bar a Spotify title match), or mismatch with low availability
if (!hasLossless && !spotifyMatch) {
return { tier: 3, reason, bestResult: best, bestCategory: bestCat, warnings }
}
@@ -358,6 +411,8 @@ function buildConfidenceReason(
parts.push('High-quality lossless')
} else if (best.is_lossless) {
parts.push('Lossless')
} else if (bestCat === 'SPOTIFY') {
parts.push('Spotify audio')
} else if (best.provider === 'YouTube') {
parts.push('YouTube audio')
} else {
+450 -5
View File
@@ -70,6 +70,7 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@google/genai": "^2.27.0",
"@playwright/test": "^1.57.0",
"@tailwindcss/postcss": "^4.1.9",
"@testing-library/jest-dom": "^6.9.1",
@@ -958,6 +959,31 @@
"@formatjs/fast-memoize": "3.1.1"
}
},
"node_modules/@google/genai": {
"version": "2.27.0",
"resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.27.0.tgz",
"integrity": "sha512-W6F9Y9d4h7cVQNa85IPCOVVP9PiUzve/ZQPBvQnBmnBJcLvxstEw+R2X/RyCH0SOe0HVDQzeKDpDUf6ZRtbmdQ==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"google-auth-library": "^10.3.0",
"p-retry": "^4.6.2",
"protobufjs": "^7.5.4",
"ws": "^8.18.0"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"@modelcontextprotocol/sdk": "^1.25.2"
},
"peerDependenciesMeta": {
"@modelcontextprotocol/sdk": {
"optional": true
}
}
},
"node_modules/@hookform/resolvers": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
@@ -2398,7 +2424,7 @@
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.57.0.tgz",
"integrity": "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==",
"devOptional": true,
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.57.0"
@@ -2410,6 +2436,72 @@
"node": ">=18"
}
},
"node_modules/@protobufjs/aspromise": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
"integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/base64": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
"integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/codegen": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
"integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/eventemitter": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
"integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/fetch": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
"integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.1"
}
},
"node_modules/@protobufjs/float": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
"integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/path": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
"integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/pool": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
"integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/utf8": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
"integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@radix-ui/number": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.0.tgz",
@@ -4715,7 +4807,7 @@
"version": "19.2.7",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz",
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
"devOptional": true,
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -4725,12 +4817,19 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
}
},
"node_modules/@types/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/stack-utils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz",
@@ -5911,6 +6010,27 @@
"node": ">= 0.6.0"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.4.tgz",
@@ -5920,6 +6040,16 @@
"baseline-browser-mapping": "dist/cli.js"
}
},
"node_modules/bignumber.js": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
"integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
@@ -5987,6 +6117,13 @@
"node-int64": "^0.4.0"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -6552,6 +6689,16 @@
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/data-urls": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz",
@@ -6869,6 +7016,16 @@
"node": ">= 0.4"
}
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.266",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.266.tgz",
@@ -7742,6 +7899,13 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -7833,6 +7997,30 @@
"bser": "2.1.1"
}
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "paypal",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"dependencies": {
"node-domexception": "^1.0.0",
"web-streams-polyfill": "^3.0.3"
},
"engines": {
"node": "^12.20 || >= 14.13"
}
},
"node_modules/fflate": {
"version": "0.8.2",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
@@ -7933,6 +8121,19 @@
"node": ">= 6"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"fetch-blob": "^3.1.2"
},
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/fraction.js": {
"version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -8009,6 +8210,60 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/gaxios": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
"integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"extend": "^3.0.2",
"https-proxy-agent": "^7.0.1",
"node-fetch": "^3.3.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/gaxios/node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/gaxios/node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/gcp-metadata": {
"version": "8.1.2",
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
"integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"gaxios": "^7.0.0",
"google-logging-utils": "^1.0.0",
"json-bigint": "^1.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/generator-function": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz",
@@ -8206,6 +8461,34 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/google-auth-library": {
"version": "10.9.1",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
"integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"base64-js": "^1.3.0",
"ecdsa-sig-formatter": "^1.0.11",
"gaxios": "^7.1.4",
"gcp-metadata": "8.1.2",
"google-logging-utils": "1.1.3",
"jws": "^4.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/google-logging-utils": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
"integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=14"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -10086,6 +10369,16 @@
"node": ">=6"
}
},
"node_modules/json-bigint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"bignumber.js": "^9.0.0"
}
},
"node_modules/json-buffer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
@@ -10160,6 +10453,29 @@
"node": ">=4.0"
}
},
"node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"dev": true,
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jws": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
"dev": true,
"license": "MIT",
"dependencies": {
"jwa": "^2.0.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -10518,6 +10834,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -10938,6 +11261,46 @@
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
"license": "MIT"
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
"deprecated": "Use your platform's native DOMException instead",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "github",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"engines": {
"node": ">=10.5.0"
}
},
"node_modules/node-fetch": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"dev": true,
"license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
}
},
"node_modules/node-int64": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
@@ -11219,6 +11582,20 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/p-retry": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
"integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/retry": "0.12.0",
"retry": "^0.13.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/p-try": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
@@ -11370,7 +11747,7 @@
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz",
"integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==",
"devOptional": true,
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.57.0"
@@ -11389,7 +11766,7 @@
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz",
"integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==",
"devOptional": true,
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
@@ -11402,6 +11779,7 @@
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
@@ -11432,6 +11810,7 @@
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -11535,6 +11914,30 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/protobufjs": {
"version": "7.6.6",
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
"integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
"dev": true,
"hasInstallScript": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.2",
"@protobufjs/base64": "^1.1.2",
"@protobufjs/codegen": "^2.0.5",
"@protobufjs/eventemitter": "^1.1.1",
"@protobufjs/fetch": "^1.1.1",
"@protobufjs/float": "^1.0.2",
"@protobufjs/path": "^1.1.2",
"@protobufjs/pool": "^1.1.0",
"@protobufjs/utf8": "^1.1.1",
"@types/node": ">=13.7.0",
"long": "^5.3.2"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/psl": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
@@ -11983,6 +12386,16 @@
"node": ">=10"
}
},
"node_modules/retry": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
"integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -12058,6 +12471,27 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safe-push-apply": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
@@ -12734,6 +13168,7 @@
"version": "4.1.17",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz",
"integrity": "sha512-j9Ee2YjuQqYT9bbRTfTZht9W/ytp5H+jJpZKiYdP/bpnXARAuELt9ofP0lPnmHjbga7SNQIxdTAXCmtKVYjN+Q==",
"dev": true,
"license": "MIT"
},
"node_modules/tailwindcss-animate": {
@@ -13419,6 +13854,16 @@
"makeerror": "1.0.12"
}
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/webidl-conversions": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+1
View File
@@ -93,6 +93,7 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@google/genai": "^2.27.0",
"@playwright/test": "^1.57.0",
"@tailwindcss/postcss": "^4.1.9",
"@testing-library/jest-dom": "^6.9.1",
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Offline tests for the self-healing Stripe Checkout runner
* (e2e/helpers/self-healing). Fixture pages are served via page.route on fake
* checkout.stripe.com / js.stripe.com URLs and the LLM is a stub — no network,
* no dev server, no real Stripe, no Gemini. Runs in CI's frontend-e2e-smoke job.
*
* npx playwright test --config=playwright.selfheal.config.ts
*/
export default defineConfig({
testDir: './e2e/self-healing',
testMatch: '**/*.spec.ts',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: 0,
reporter: [['list']],
timeout: 150_000,
use: { ...devices['Desktop Chrome'] },
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
+7
View File
@@ -225,6 +225,9 @@ alert_policies = monitoring.create_alert_policies(notification_channels)
# Ephemeral GHA-runner dispatcher: log-based metrics + alerts
runner_observability = monitoring.create_ephemeral_runner_observability(notification_channels)
# Postmark SMTP-fallback failures (emails lost despite the fallback): metric + alert
email_delivery_observability = monitoring.create_email_delivery_observability(notification_channels)
# ==================== Cloud Function: GDrive Validator ====================
# Cloud Storage bucket for function source code
@@ -793,6 +796,10 @@ pulumi.export("error_rate_alert_id", alert_policies["error_rate"].name)
pulumi.export("queue_backlog_alert_id", alert_policies["queue_backlog"].name)
pulumi.export("memory_alert_id", alert_policies["memory"].name)
pulumi.export("service_unavailable_alert_id", alert_policies["service_unavailable"].name)
pulumi.export(
"smtp_fallback_failure_alert_id",
email_delivery_observability["smtp_fallback_failure_alert"].name,
)
# YouTube upload queue
pulumi.export("youtube_upload_queue", queues["youtube-upload-queue"].name)
+110
View File
@@ -500,3 +500,113 @@ def create_ephemeral_runner_observability(
)
return resources
# Matches a failed Postmark SMTP-fallback send in either service (see
# create_email_delivery_observability). Kept module-level so it can be
# sanity-checked with `gcloud logging read` before applying.
SMTP_FALLBACK_FAILURE_LOG_FILTER = (
'resource.type="cloud_run_revision" '
'AND resource.labels.service_name=("karaoke-backend" OR "karaoke-decide") '
'AND ((jsonPayload.message:"Failed to send email to" '
'AND jsonPayload.message:"via Postmark SMTP fallback") '
'OR (textPayload:"Failed to send email to" '
'AND textPayload:"via Postmark SMTP fallback"))'
)
def create_email_delivery_observability(
channels: dict[str, gcp.monitoring.NotificationChannel],
) -> dict:
"""Log-based metric + alert for failed Postmark SMTP-fallback sends.
Since 2026-09-30 Postmark's API edge blocks some shared us-central1 Cloud
Run egress IPs (IP-reputation block, confirmed by Postmark ticket
#11562402 — they won't lift it). karaoke-backend (v0.263.1+) and
karaoke-decide (v0.9.3+) fall back to Postmark SMTP on that HTML 403. If
the SMTP fallback *itself* fails, emails (magic links, order
confirmations) are being lost again — most likely Postmark has started
blocking SMTP from our IPs too. That is the trigger to add a static egress
IP (Cloud NAT); see docs/archive/2026-10-02-postmark-ip-block-options.md.
Apply gotcha: on the very first ``pulumi up`` the AlertPolicy can fail
because GCP hasn't propagated the just-created log-based metric yet
(``depends_on`` orders creation but can't wait for propagation). Re-run
``pulumi up`` a minute later and it succeeds (happened 2026-10-02).
Cost: the log-based counter metric is within the free metric allotment;
alert policies are free until 2027-09-01, then $0.35/month per metric
reference.
"""
notification_channels = _channel_names(channels)
resources: dict = {}
# Both services log "Failed to send email to <addr> via Postmark SMTP
# fallback" (logger.exception) when the fallback send raises. NOTE the
# payload field differs: karaoke-backend logs structured JSON
# (jsonPayload.message) while karaoke-decide logs plain text
# (textPayload) — the filter must match both or gen failures go unseen.
resources["smtp_fallback_failure_metric"] = gcp.logging.Metric(
"postmark-smtp-fallback-failures",
name="email/postmark_smtp_fallback_failures",
description="Counts Postmark SMTP-fallback send failures (karaoke-backend + karaoke-decide)",
filter=SMTP_FALLBACK_FAILURE_LOG_FILTER,
metric_descriptor=gcp.logging.MetricMetricDescriptorArgs(
metric_kind="DELTA",
value_type="INT64",
unit="1",
display_name="Postmark SMTP fallback failures",
),
)
resources["smtp_fallback_failure_alert"] = gcp.monitoring.AlertPolicy(
"postmark-smtp-fallback-failures-alert",
display_name="Email - Postmark SMTP fallback failing (emails being lost)",
combiner="OR",
conditions=[
gcp.monitoring.AlertPolicyConditionArgs(
display_name="Any SMTP-fallback send failure",
condition_threshold=gcp.monitoring.AlertPolicyConditionConditionThresholdArgs(
filter=(
'metric.type="logging.googleapis.com/user/email/postmark_smtp_fallback_failures" '
'AND resource.type="cloud_run_revision"'
),
comparison="COMPARISON_GT",
threshold_value=0,
duration="0s",
aggregations=[
gcp.monitoring.AlertPolicyConditionConditionThresholdAggregationArgs(
alignment_period="600s",
per_series_aligner="ALIGN_SUM",
cross_series_reducer="REDUCE_SUM",
),
],
trigger=gcp.monitoring.AlertPolicyConditionConditionThresholdTriggerArgs(
count=1,
),
),
),
],
alert_strategy=gcp.monitoring.AlertPolicyAlertStrategyArgs(
auto_close="3600s",
),
documentation=gcp.monitoring.AlertPolicyDocumentationArgs(
content=(
"An email failed to send via BOTH the Postmark API (edge-blocked, HTML 403) "
"AND the Postmark SMTP fallback. Users are not receiving magic links / "
"order emails.\n\n"
"1. Logs: `textPayload:\"via Postmark SMTP fallback\"` on karaoke-backend / "
"karaoke-decide — check the exception (SMTP 4xx/5xx, connection refused, auth).\n"
"2. If Postmark is now blocking SMTP too: add a static egress IP (Cloud NAT). "
"Options, costs and Pulumi steps: "
"`docs/archive/2026-10-02-postmark-ip-block-options.md` in karaoke-gen.\n"
"3. Postmark ticket history: #11562402."
),
mime_type="text/markdown",
),
enabled=True,
notification_channels=notification_channels,
opts=pulumi.ResourceOptions(depends_on=[resources["smtp_fallback_failure_metric"]]),
)
return resources
+8
View File
@@ -121,6 +121,14 @@ Alert policies are defined in `infrastructure/__main__.py` as Pulumi resources:
- **Severity**: Critical
- **Auto-close**: 10 minutes after resolution
### Email - Postmark SMTP fallback failing (emails being lost)
- **Defined in**: `modules/monitoring.py` → `create_email_delivery_observability()`
- **Condition**: any failed Postmark SMTP-fallback send in karaoke-backend **or** karaoke-decide in a 10-minute window. Counted by the log-based metric `email/postmark_smtp_fallback_failures`.
- **Gotcha**: the filter matches both `jsonPayload.message` (karaoke-backend logs structured JSON) and `textPayload` (karaoke-decide logs plain text). A filter on only one field silently misses the other service.
- **Meaning**: the Postmark API was edge-blocked (HTML 403) **and** the SMTP fallback failed, so users aren't getting magic links or order emails.
- **Action / options**: `docs/archive/2026-10-02-postmark-ip-block-options.md` (static egress IP via the existing Cloud NAT, ~$4–7/mo)
- **Auto-close**: 60 minutes after resolution
## Notification Channels
Notification channels are managed as Pulumi IaC in
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.263.0"
version = "0.264.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"