Skip to content

fix: improve UI error handling and add webhook support - #41

Merged
bokelley merged 3 commits into
mainfrom
bokelley/test-instructions
Oct 10, 2025
Merged

bokelley merged 3 commits into
mainfrom
bokelley/test-instructions

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Improves the AdCP Testing UI with better error handling, proper webhook integration, and removal of non-standard SSE monitoring.

Error Handling Improvements

Debug Log Formatting

  • Enhanced error message display with better formatting for Pydantic validation errors
  • Added formatErrorMessage() function that intelligently formats validation errors with proper indentation
  • Improved readability with field names as bullet points and indented error details
  • Added red error styling to distinguish errors visually in debug panel
  • Increased debug log max-height from 200px to 400px for better visibility

Media Buy Error Detection

  • Fixed: Media buys with validation errors were incorrectly shown as success
  • Now properly checks for errors array in response before claiming success
  • Validates presence of media_buy_id before treating as successful creation
  • Shows detailed error messages with codes and details in alert
  • Prevents adding failed media buys to the Active Media Buys list
  • Keeps modal open on error so users can fix issues and retry

View Button Implementation

  • Fixed: View button did nothing (only logged to console)
  • Added functional media buy detail view modal with comprehensive information
  • Shows budget, spent, impressions, CTR, status, and timestamps in formatted table
  • Includes full JSON preview for debugging purposes

SSE Removal

Removed Server-Sent Events (SSE) monitoring feature as it's not part of the official AdCP specification:

  • AdCP uses webhooks for async notifications per the spec (not SSE)
  • Removed all SSE connection functions (connectSSE, disconnectSSE, startMonitoring, stopMonitoring)
  • Removed SSE UI elements (Monitor/Stop buttons, auto-connect checkbox)
  • Removed SSE global variables (sseConnection, mediaBuyMonitors)
  • Cleaned up all references and dependencies

Webhook Integration

Added proper webhook support using the library's built-in functionality:

  • Automatic polling of /api/events endpoint every 3 seconds
  • Real-time display of webhook events in debug panel with 📡 icon
  • Automatic status updates for media buys when webhook events arrive
  • No configuration needed - starts polling automatically on page load
  • Uses official AdCP webhook pattern (status: "submitted" with webhook callbacks)
  • Displays full event details including operation ID, agent ID, status, and payload

Testing UI Updates

  • Updated promoted_offering field placeholder with natural language test instruction examples
  • Added 4 AI-powered test scenario presets in dropdown:
    • Test: Delayed Response (10s)
    • Test: Rejection Scenario
    • Test: Human Approval Workflow
    • Test: Slow Delivery + Outage
  • Updated scenario descriptions to reflect current AI-powered capabilities

Testing

  • ✅ Build passes successfully
  • ✅ No SSE/EventSource references remaining
  • ✅ Webhook polling starts automatically
  • ✅ Error responses properly detected and displayed
  • ✅ View button shows media buy details modal

Breaking Changes

None - this is purely additive and fixes existing bugs.

bokelley and others added 3 commits October 10, 2025 12:05
## Error Handling Improvements

### Debug Log Formatting
- Enhanced error message display with better formatting
- Added formatErrorMessage() function for Pydantic validation errors
- Improved readability with proper indentation and line breaks
- Added red error styling to distinguish errors visually
- Increased debug log max-height to 400px for better visibility

### Media Buy Error Detection
- Fixed false-positive success on media buy creation with errors
- Now properly checks for errors array in response
- Validates presence of media_buy_id before success
- Shows detailed error messages with codes and details
- Prevents adding failed media buys to the list
- Keeps modal open on error for user to fix issues

### View Button Implementation
- Added functional media buy detail view modal
- Shows comprehensive media buy information in formatted table
- Displays budget, spent, impressions, CTR, and timestamps
- Includes full JSON preview for debugging

## SSE Removal

Removed Server-Sent Events (SSE) monitoring feature:
- SSE is not part of official AdCP specification
- AdCP uses webhooks for async notifications per the spec
- Removed all SSE functions, UI elements, and global variables
- Removed Monitor/Stop buttons from media buy actions
- Removed auto-connect SSE checkbox

## Webhook Integration

Added proper webhook support using the library's built-in functionality:
- Automatic polling of /api/events every 3 seconds
- Real-time display of webhook events in debug panel
- Automatic media buy status updates from webhooks
- No configuration needed - works automatically
- Uses official AdCP webhook pattern (submitted status with webhooks)

## Testing UI Updates

- Updated promoted_offering placeholder with natural language test instruction examples
- Added 4 AI-powered test scenario presets
- Updated scenario descriptions to reflect current capabilities

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

Co-Authored-By: Claude <[email protected]>
Prevents calling functions before they're defined which was causing
script to fail to load and leaving toggleAllProducts undefined.
@bokelley
bokelley merged commit 08dfe52 into main Oct 10, 2025
This was referenced Oct 10, 2025
bokelley added a commit that referenced this pull request Apr 20, 2026
#641

- Alert #41 (js/prototype-pollution-utility, medium): GovernanceMiddleware
  setAtPath() already blocked __proto__/constructor/prototype via
  FORBIDDEN_PATH_SEGMENTS set, but CodeQL's pattern matcher only
  recognizes inline equality checks. Added explicit `part === '__proto__'
  || part === 'constructor' || part === 'prototype'` inline guard, plus
  hasOwnProperty traversal check so a malicious prototype-chained value
  can't be followed mid-path. Belt-and-suspenders.
- Alerts #28 and #29 (js/clear-text-logging, high): manual test script
  .catch() handlers logged the full error object, which CodeQL traced
  back to OAuth metadata on auth failures. Narrowed to error.name and
  error.message; full stack restored via DEBUG=1.

Test suite: 4288 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 20, 2026
* feat: 5.2.2 client integration ergonomics

Five additive changes unblocking external client adoption after the 5.2.1
spec-compliance rollup.

- match() helper on TaskResult (src/lib/core/match.ts): exhaustive,
  compile-time-checked discriminated-union dispatcher. Eliminates manual
  `if (result.status === 'completed')` narrowing at response sites.
  Optional `_` catchall makes handlers optional.
- createAdcpServer.signedRequests auto-wires the RFC 9421 verifier when
  the seller declares the `signed-requests` specialism. Startup-fails
  when one is declared without the other — closes the footgun where
  claiming the specialism didn't enforce it.
- docs/guides/idempotency-crash-recovery.md: worked buyer-side recipe
  stitching IdempotencyConflictError + IdempotencyExpiredError +
  natural-key lookup + metadata.replayed into an end-to-end recovery
  flow. Cross-linked from README, llms.txt, and the seller SKILL.
- skills/build-seller-agent/SKILL.md governance extension: GDPR Art 22
  / EU AI Act Annex III worked example — plan.human_review_required
  threaded through createMediaBuy, buildHumanOverride on approval,
  decision table, regulated-category constants.
- Webhook HMAC-SHA256 deprecated: one-time console.warn on first use
  (suppress with ADCP_SUPPRESS_HMAC_WARNING=1), @deprecated JSDoc on
  WebhookAuthentication.hmac_sha256, removal target @adcp/client 6.0.0.
  Migration guide section added.

Test suite: 4277 pass, 1 pre-existing flake (task-executor timing,
unrelated), 12 skipped. New tests: match (6), auto-signed-requests (10),
webhook-hmac-deprecation (4) — all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address expert review feedback on 5.2.2 ergonomics

Addresses review findings on PR #641 from code-reviewer, security-reviewer,
dx-expert, and ad-tech-protocol-expert. Also fixes a production resource
leak discovered by new test coverage.

Blocking fixes:

- Rewrite GDPR governance worked example in skills/build-seller-agent/SKILL.md
  to compile against real handler types (taskToolResponse for submitted path,
  state-store for persistence, guarded ctx.account access, separate approval
  function taking AdcpStateStore rather than stale ctx reference).
- Fix resource leak on 401 path: buildSignedRequestsPreTransport now races
  the next-callback against the response's 'finish'/'close' events so the
  verifier's terminal 401 (which doesn't call next) resolves the wrapper
  promise. Without this every unsigned mutating request hung server-side
  and agentServer.close() never fired — slow resource exhaustion under
  signing-attack floods.

Protocol alignment:

- required_for default now derives from capabilities.request_signing.required_for
  (fallback chain: explicit signedRequests.required_for → capability →
  MUTATING_TASKS). Prevents SDK enforcing beyond what the seller advertises.
- Specialism guard now throws when signed-requests is claimed but
  capabilities.request_signing.supported !== true (was a silent log;
  storyboard would skip the conformance run).

DX:

- Add TaskResult.match() fluent method via attachMatch() installer at public
  exit points (TaskExecutor, SingleAgentClient). Method and free function
  both exported; method form is discoverable via autocomplete. Non-enumerable
  property to keep JSON.stringify / spread clean.
- Add match() and signedRequests auto-wire sections to docs/llms.txt so
  LLMs writing seller code find both via the primary doc.

HMAC language softening (spec still supports HMAC as legacy fallback):

- Warning message, migration doc, @deprecated tag, and changeset all reframe
  as SDK-flagged deprecation rather than hard-committing to 6.0.0 removal.
  SDK keeps supporting HMAC; guidance is to migrate when counterparties ready.

Consistency + polish:

- Error logging in create-adcp-server.ts and serve.ts narrowed to name+code
  (instead of full err object) to avoid JWKS URLs leaking into shared log
  aggregators.
- Cookbook line 104: removed redundant getOrCreateKey call; carry the
  rotated/persisted key forward in a single variable.
- 5 new signed-requests tests (non-mutating pass, required_for honors list,
  agentServer close on 401, WWW-Authenticate shape, replay-scope via auto-wire).

Test suite: 4238 pass, 0 fail, 12 skipped. New production-bug regression
test (401 close-spy) now passes with the hang-fix above.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: round-2 review — signature bypass, proto guard, llms.txt, schema sync

Addresses round-2 expert review of PR #641:

- SECURITY: Fix signature bypass on client-disconnect race. The previous
  fix raced `res.once('finish')` and `res.once('close')` against the
  verifier's next-callback, but on 'close' (client aborted mid-JWKS-fetch)
  `handled` stayed false — serve.ts fell through to MCP dispatch and
  executed the tool handler WITHOUT a verified signature. Now tracks
  `verifierCompleted` and sets `handled=true` when close fires before the
  verifier resolves, so an attacker dropping TCP mid-flight cannot trigger
  side effects on unsigned requests. Regression test added.
- Guard `match()` dispatch against prototype pollution: use
  `Object.prototype.hasOwnProperty.call(handlers, result.status)` before
  lookup so a hostile `result.status === '__proto__'` resolves to the `_`
  catchall instead of calling `Object.prototype` as a handler.
- Fix docs/llms.txt match() example field accessors: `r.submitted?.taskId`
  / `r.metadata.taskId` / `r.deferred?.token` / `r.metadata.inputRequest?`
  — previous example used `r.task_id` which doesn't exist on any
  TaskResult variant. Also documents the `!` (non-null assertion) for TS
  users since `.match` is declared optional.
- Schema sync: upstream AdCP added `governance-aware-seller` specialism.
  Ran `npm run sync-schemas && npm run generate-types` — regenerated
  core.generated.ts, tools.generated.ts, schemas.generated.ts.

Test suite: 4302 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(generator): add match() + crash-recovery to llms.txt template

docs/llms.txt is generated by scripts/generate-agent-docs.ts; direct
edits get clobbered on regen. Moved the match() fluent dispatcher
example and the crash-recovery cookbook cross-link into the generator
template so they survive `npm run generate-agent-docs` and pass the
ci:docs-check step.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): address three pre-existing CodeQL alerts surfacing on PR #641

- Alert #41 (js/prototype-pollution-utility, medium): GovernanceMiddleware
  setAtPath() already blocked __proto__/constructor/prototype via
  FORBIDDEN_PATH_SEGMENTS set, but CodeQL's pattern matcher only
  recognizes inline equality checks. Added explicit `part === '__proto__'
  || part === 'constructor' || part === 'prototype'` inline guard, plus
  hasOwnProperty traversal check so a malicious prototype-chained value
  can't be followed mid-path. Belt-and-suspenders.
- Alerts #28 and #29 (js/clear-text-logging, high): manual test script
  .catch() handlers logged the full error object, which CodeQL traced
  back to OAuth metadata on auth failures. Narrowed to error.name and
  error.message; full stack restored via DEBUG=1.

Test suite: 4288 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): drop redundant err truthiness check inside if (err) blocks

CodeQL flagged 'useless conditional' in the verifier/preTransport error
handlers. The err variable is already guaranteed truthy inside the
guarded branch, so err && (err as Error).name collapses to just
(err as Error).name.

Both sites in src/lib/server/create-adcp-server.ts (line 1228) and
src/lib/server/serve.ts (line 277) cleaned up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(server): boot diagnostics + webhook suppressLegacyWarnings + reviewer followups

Addresses final-pass reviewer feedback on PR #641:

- ADCP_SIGNED_REQUESTS_STATE symbol + AdcpSignedRequestsState type
  on the returned McpServer. Carries {autoWired, specialismClaimed,
  capabilitySupported, mismatch} so operator boot diagnostics and
  integration tests can assert the wiring without parsing log output.
  Closes the claim-without-config asymmetry concern — the state is
  structured and testable; the logger.error still fires for the legacy
  manual-wiring path.
- createWebhookEmitter({ suppressLegacyWarnings: true }) — programmatic
  equivalent of ADCP_SUPPRESS_HMAC_WARNING=1 for libraries embedded in
  agents where env vars are awkward. Threaded through
  deliverOnce → buildHeaders → maybeWarnHmacDeprecation.
- attachMatch JSDoc: explicit note that shallow clones ({...result})
  don't carry the non-enumerable method — use the free function or
  attachMatch() on clones.
- Migration doc: HMAC timing window ("post-2026 H2 when buyer 9421
  adoption telemetry stabilizes") + two suppression paths documented
  side-by-side (env var vs programmatic).

New tests in test/server-auto-signed-requests.test.js:
- exposes auto-wire state via ADCP_SIGNED_REQUESTS_STATE symbol
- flags claim_without_config in state on legacy manual-wiring path
- asserts specific error messages for each misconfig pattern (config
  + no claim; claim + supported:false; claim + request_signing omitted)
- accepts non-tools/call JSON-RPC body (notifications/initialized)
  without triggering 401 — verifies operation=undefined falls through
- populates VerifyResult.agent_url when agentUrlForKeyid returns a URL
  (direct unit test on verifyRequestSignature)

Test suite: 4301 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(auth): audience-binding + multi-host caveats + diagnose oauth subcommand alias

Addresses final reviewer feedback on PR #641:

1. Audience-binding caveat — auth.ts JSDoc now calls out that custom
   authenticate callbacks (not using verifyBearer) MUST validate aud
   themselves. Same-tenant tokens are replayable against any agent
   sharing the tenant without per-resource isolation. verifyBearer's
   audience is already required and strictly validated; this just
   documents the custom-auth footgun.
2. Multi-host caveat on serve().publicUrl — JSDoc expanded to name
   the exact failure mode: one Node process fronting multiple hostnames
   silently advertises the wrong resource to all but one. Run one
   serve() per host until a host-aware helper ships.
3. `adcp diagnose oauth <alias>` subcommand alias for `adcp diagnose-auth`.
   Canonical form stays hyphenated; the `<noun> <verb>` alias matches
   what some docs expect. Usage line updated.

All four requested probe checks (wire trace, token claims pre/post
refresh, well-known cross-wiring detection, WWW-Authenticate check)
are already implemented by runAuthDiagnosis — H1 specifically is the
"Resource URL mismatch between well-known and agent host" hypothesis
that catches the cross-wiring case.

PR #562 body updated separately via gh pr edit to close the
"401 after successful authentication" known-limitation note — fully
diagnosed as server-side (no verifier wired + well-known cross-wiring);
client-side fix is complete.

Test suite: 4305 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant