Skip to content

feat(chat): runtime clientData validation for custom agents - #4646

Open
gtremper wants to merge 6 commits into
triggerdotdev:mainfrom
gtremper:graham/custom-agent-validation
Open

feat(chat): runtime clientData validation for custom agents#4646
gtremper wants to merge 6 commits into
triggerdotdev:mainfrom
gtremper:graham/custom-agent-validation

Conversation

@gtremper

@gtremper gtremper commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Summary

chat.withClientData({ schema }).customAgent() now parses payload.metadata before passing it to run, chat.messages, or chat.createSession. Schema defaults and transforms are preserved.

Custom agents without a schema keep the existing pass-through behavior. This does not change chat.agent(). Raw custom agents do not expose an action schema, so payload.action remains unknown.

Validation failures

Invalid client data is logged and never passed to user code. The client receives a fixed Invalid client data error; validator details stay in the task log and onClientDataValidationError.

  • Submitted turns and async reads write the error followed by turn-complete, then wait for the next valid frame. This settles the invalid input before the raw read returns. Callers that need to coordinate validation with their own persistence or settlement should omit the schema and validate the full frame in their loop.
  • Messageless preload and continuation boots call onClientDataValidationError and wait without writing a terminal frame.
  • Active chat.messages.on() subscriptions skip invalid frames and call onClientDataValidationError without ending the response. off() stops new frames. A valid frame accepted before off() finishes validation and is delivered; an invalid pending frame is logged without invoking user callbacks.
  • chat.messages.peek() throws synchronously.
  • Invalid head-start handovers fail closed. A skip ends the run. A real handover writes the validation error after the warm output, writes turn-complete, and ends the run.

Validation is automatic when a schema is declared. We can make it opt-in or return a typed failure if maintainers prefer that contract.

Testing

  • pnpm --filter @trigger.dev/sdk run test -- --run
  • pnpm --filter @trigger.dev/sdk run typecheck
  • pnpm run build --filter @trigger.dev/sdk
  • pnpm run lint
  • Formatting checks pass

✅ Checklist

  • I followed the contributing guide
  • The PR title follows the convention
  • I ran and tested the change

Changelog

Custom chat agents now validate and parse client data declared with chat.withClientData({ schema }) before passing it to agent code.

Screenshots

Not applicable.

@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The SDK adds schema-based validation and parsing for custom-agent client data. Invalid initial and subsequent frames are excluded from agent code, with configurable validation-error reporting. Message APIs and subscriptions now validate metadata and preserve stream behavior. ChatTurn and createChatSession carry generic client-data types. Documentation describes managed-agent and custom-agent behavior, and tests cover parsing, retries, ordering, buffering, callbacks, handover recovery, error timing, and schema-free pass-through.

Merge Risk: 🟡 Moderate · up to 19585

Schema-enabled custom agents can still receive unvalidated client metadata through chat.messages.next(), and invalid-input errors may be lost or arrive after turn completion in some subscription flows. These bounded security and reliability issues require owner follow-up before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 4 files. (5 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: runtime clientData validation for custom agents.
Description check ✅ Passed The description explains the implementation, validation-failure behavior, testing performed, checklist status, changelog, and screenshots status. It does not include a Closes issue reference, but the …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the implementation, validation-failure behavior, testing performed, checklist status, changelog, and screenshots status. It does not include a Closes issue reference, but the required content is otherwise substantially complete.

Full details: Docstring Coverage

Explanation

Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 4 files. (5 skipped: 5 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

Hi @gtremper, thanks for your interest in contributing!

This project requires that pull request authors are vouched, and you are not in the list of vouched users.

This PR will be closed automatically. See https://github.com/triggerdotdev/trigger.dev/blob/main/CONTRIBUTING.md for more details.

@github-actions github-actions Bot closed this Aug 17, 2026
@gtremper gtremper changed the title feat(chat): runtime clientData validation for custom agents feat(chat): validate custom agent client data Aug 17, 2026
@matt-aitken matt-aitken reopened this Aug 17, 2026
@changeset-bot

changeset-bot Bot commented Aug 17, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 19585dc

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 27 packages
Name Type
@trigger.dev/sdk Patch
@trigger.dev/python Patch
@internal/dashboard-agent Patch
@trigger.dev/build Patch
@trigger.dev/core Patch
@trigger.dev/react-hooks Patch
@trigger.dev/redis-worker Patch
@trigger.dev/rsc Patch
@trigger.dev/schema-to-json Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
@trigger.dev/rbac Patch
@trigger.dev/sso Patch
trigger.dev Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@internal/metrics-pipeline Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@internal/tracing Patch
@internal/webhook-engine Patch
@internal/webhook-sources Patch
@internal/testcontainers Patch
@internal/cache Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@matt-aitken
matt-aitken marked this pull request as ready for review August 17, 2026 08:38
coderabbitai[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@gtremper gtremper changed the title feat(chat): validate custom agent client data feat(chat): runtime clientData validation for custom agents Aug 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts (1)

539-542: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document why a single microtask hop is required.

Both tests place await Promise.resolve() between firstDoneStarted.promise and releaseParser.resolve(). This encodes an assumption about how many microtask ticks the runtime needs to detach the subscription before the parse settles. If the detach path in subscribeToValidatedChatMessages or next() gains or loses an await, the test exercises a different branch and the failure reason is not obvious.

Add a short comment stating the ordering the hop establishes.

♻️ Proposed comment for the ordering requirement
             releaseFirstTurn.resolve();
             await firstDoneStarted.promise;
+            // Let `turn.done()` detach the subscription before the parse
+            // settles, so the frame lands in the after-off buffer path.
             await Promise.resolve();
             releaseParser.resolve();

Also applies to: 619-622


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 72a14094-6875-4d36-8a2b-ede7d52e17cc

📥 Commits

Reviewing files that changed from the base of the PR and between 80790a7 and cb35a3a.

📒 Files selected for processing (3)
  • docs/ai-chat/custom-agents.mdx
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/ai-chat/custom-agents.mdx

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.

📜 Review details
🧰 Additional context used
📓 Path-based instructions (8)
packages/trigger-sdk/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

In the Trigger.dev SDK (packages/trigger-sdk), prefer isomorphic code like fetch and ReadableStream instead of Node.js-specific code

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic imports. Only use dynamic import() when:

  • Circular dependencies cannot be resolved otherwise
  • Code splitting is genuinely needed for performance
  • The module must be loaded conditionally at runtime
    Zod is pinned to a single version across the entire monorepo (currently 3.25.76). When adding zod to a new or existing package, use the exact same version as the rest of the repo - never a different version or a range. Mismatched zod versions cause runtime type incompatibilities (e.g., schemas from one package can't be used as body validators in another).
    Do not reintroduce V1.
    Add crumbs as you write code — not just when debugging.
    Do not invent new namespaces — pick from this table or ask first.

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

We use vitest exclusively. Never mock anything - use testcontainers instead.

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
packages/trigger-sdk/**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (packages/trigger-sdk/CLAUDE.md)

Always import from @trigger.dev/sdk. Never use @trigger.dev/sdk/v3 (deprecated path alias)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/**/*.{ts,tsx}: - Public packages (packages/*): Use build.
Always import from @trigger.dev/sdk. Never use @trigger.dev/sdk/v3 or deprecated client.defineJob.

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Test files go next to source files (e.g., MyService.ts -> MyService.test.ts).

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
🧠 Learnings (17)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In this repo’s trigger.dev codebase, the “never mock — use testcontainers” guideline should only be applied to integration tests that talk to real external services (e.g., Redis, Postgres, S2). For unit tests that validate in-memory logic (e.g., deduplication/cache behavior in StandardRealtimeStreamsManager and similar module-boundary call counting), it is allowed to use Vitest mocks like `vi.fn()` and to stub/mock `ApiClient` objects to count calls or simulate in-process collaborators. Do not flag `vi.fn()`-based mocks as policy violations in these unit-test scenarios; reserve the rule for true external-service integration tests.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
📚 Learning: 2026-05-19T22:37:47.286Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3671
File: packages/trigger-sdk/test/recovery-boot.test.ts:456-457
Timestamp: 2026-05-19T22:37:47.286Z
Learning: In `packages/trigger-sdk` (Trigger.dev SDK), `logger.warn` (and other SDK logger methods) should route to the Trigger.dev structured logger sink, not to `console.warn`. In SDK tests, `vi.spyOn(console, "warn")` (or similar console spies) should only be used to suppress stray console output; reviewers should not suggest asserting on `console.warn` spies to verify SDK-internal warning/fallback log behavior. Use the SDK’s structured-logger outputs/capture approach instead of console spies.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
📚 Learning: 2026-08-16T18:36:58.179Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4537
File: packages/trigger-sdk/test/normalizeKeyString.test.ts:1-2
Timestamp: 2026-08-16T18:36:58.179Z
Learning: For related SDK `chat.agent` tests in the Trigger.dev repository—including chat channels, handover, snapshot, and transport-event coverage—keep new test files under `packages/trigger-sdk/test/` rather than colocating them with the `packages/trigger-sdk/src/v3/` source files.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
📚 Learning: 2026-03-31T21:37:27.212Z
Learnt from: isshaddad
Repo: triggerdotdev/trigger.dev PR: 3283
File: docs/migration-n8n.mdx:19-21
Timestamp: 2026-03-31T21:37:27.212Z
Learning: When reviewing code in `packages/trigger-sdk/src/v3`, treat `tasks.triggerAndWait()` and `tasks.batchTriggerAndWait()` as real exported APIs. They are defined in `shared.ts` and re-exported via the `tasks` object in `tasks.ts`, and they take the task ID string as their first argument (not a task instance). This is distinct from the instance methods `yourTask.triggerAndWait()` and `yourTask.batchTriggerAndWait()`. Do not flag calls to `tasks.triggerAndWait()` or `tasks.batchTriggerAndWait()` as non-existent or incorrectly invoked.

Applied to files:

  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-05-17T08:08:12.370Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3644
File: packages/trigger-sdk/src/v3/ai.ts:8695-8746
Timestamp: 2026-05-17T08:08:12.370Z
Learning: In the Trigger v3 session resume/streams logic, ensure session resumption uses sequence cursors rather than timestamps. Specifically: for each turn-complete control record written to `session.out`, include a `session-in-event-id` header whose value is the committed-consume cursor (`session.in.lastDispatchedSeqNum`). On boot/resume, scan `session.out` for the latest turn-complete record, read the `session-in-event-id` header, and seed the `sessionStreams` manager for `.in` using both `lastSeqNum` and `lastDispatchedSeqNum` so previously processed user messages are not replayed. Do not use `setMinTimestamp`/`lastOutTimestamp` for resume ordering in this flow.

Applied to files:

  • packages/trigger-sdk/src/v3/ai.ts
📚 Learning: 2026-05-18T14:19:56.437Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3655
File: packages/trigger-sdk/src/v3/ai.ts:8667-8731
Timestamp: 2026-05-18T14:19:56.437Z
Learning: In the Trigger SDK (v3) when making raw `fetch` calls to the Trigger API (including override paths such as `createChatStartSessionAction`), set the request headers to match `ApiClient`: `Content-Type`, `Authorization`, and `x-trigger-source: "sdk"`. Also forward the current preview branch by setting `x-trigger-branch` to `apiClientManager.branchName`. Prefer using the shared `overrideRequestHeaders(accessToken)` helper instead of manually constructing headers, so requests route correctly to preview environments.

Applied to files:

  • packages/trigger-sdk/src/v3/ai.ts
🔇 Additional comments (13)
packages/trigger-sdk/src/v3/ai.ts (8)

1456-1465: LGTM!

Also applies to: 1467-1503


1505-1556: LGTM!

Also applies to: 1558-1589


1723-1741: LGTM!

Also applies to: 1743-1790, 1792-1799


1817-1825: LGTM!

Also applies to: 1853-1855, 1868-1876, 1891-1897


5589-5617: LGTM!


5627-5631: LGTM!

Also applies to: 5658-5669, 5682-5752


9821-9829: LGTM!

Also applies to: 9928-9931, 10036-10036, 10091-10091, 10223-10227


9959-9975: LGTM!

Also applies to: 10048-10074, 10121-10187, 10404-10404

packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts (5)

8-14: LGTM!

Also applies to: 16-22, 24-31


145-150: LGTM!

Also applies to: 159-161, 178-219


304-311: LGTM!

Also applies to: 321-341, 352-366


368-412: LGTM!


681-688: LGTM!

Also applies to: 702-706, 722-761

devin-ai-integration[bot]

This comment was marked as resolved.

…router

The branch was 129 commits behind and its delivery layer was built on
`getChatSession().in.on<ChatInputChunk>()`, which the session.in router
replaced. Only one line of the validation work depended on that, so the
validation itself is unchanged; what moved is where it attaches.

- `subscribeToRawChatMessages` now sits on the router's `messages` route
- the steering path gets `observeValidatedChatMessages`, which validates in
  wire order without consuming, because a record that is not injected has to
  stay queued for a later turn
- boot validation, the parser locals and the read-path validation on `peek`,
  `once`, `wait` and `waitWithIdleTimeout` are re-attached to the router bodies
- `trackActiveChatSessionIterator` is generic over its turn type so a typed
  `clientData` threads through

Two behaviour changes, both deliberate.

The validated subscription no longer awaits the user handler inside its
delivery chain. Parses stay serialised, since wire-order validation is the
point, but awaiting the handler meant one slow handler stalled every later
message, and only when a schema was declared. Raw delivery has always been
fire-and-forget, so this also stops handler concurrency differing between the
two paths. `drain()` still covers the parse chain.

Observing does not consume, so a record could be seen by both the observer and
a turn's read, and with a schema attached both would parse it. The observer now
claims a sequence synchronously on arrival; a read that pulls a claimed record
returns it and waits for the claim to resolve. Exactly one of them validates,
and the schema runs once per frame.

`clientDataValidationErrorTiming` chooses when a mid-turn failure reaches the
client: `"turn-end"` by default, so a bad send cannot truncate an answer being
read, or `"arrival"` to surface it immediately. The handler and the task log
fire on arrival either way, and the frame is never delivered as a turn.
…Data

The error-timing knob sat on the customAgent config as
`clientDataValidationErrorTiming`, which needed the prefix to say what it
applied to. Moved inside `withClientData`, where the schema already establishes
the subject, it is just `reportErrorAt`. The validation callback gets the same
treatment as `onValidationError`, composing with the task-level hook the way
the builder's other hooks already do.

The customAgent config keeps `clientDataSchema` and
`onClientDataValidationError` for callers that configure it directly rather
than through the builder, and the internal field is renamed to match.
@coderabbitai

coderabbitai Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

Devin Review

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Consuming message read skips client-data validation

When a custom agent declares a client-data schema, next() returns the record's payload without parsing metadata, unlike the other reads (once, wait, waitWithIdleTimeout, peek) that this change validates. A hand-rolled loop calling it receives raw, unvalidated client data, and schema transforms and defaults never apply.

(Refers to this code)

Prompt for agents
The chat.messages.next() method in messagesInput (packages/trigger-sdk/src/v3/ai.ts, around lines 2032-2050) returns the raw chunk.payload without running client-data validation, whereas once(), wait(), waitWithIdleTimeout(), and peek() were all updated to validate/parse payload.metadata against the configured schema. This means a custom agent that consumes messages via chat.messages.next() receives unvalidated metadata, bypassing the documented guarantee that invalid frames are not passed to user code and that parsed clientData (with transforms/defaults) is delivered. Consider validating the payload before returning: reuse validateChatCustomAgentPayload / shouldValidateChatCustomAgentPayload (async) so an invalid frame is reported and skipped consistently with the other reads, while preserving the returned ChatMessageRecord shape (id, seqNum, parsed payload). Note next() is a single, consuming, optionally-timed read, so decide how a skipped invalid frame interacts with the timeout (e.g. loop like once()).
Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2faa6fb4-653d-4d8e-8654-c495bdf83f63

📥 Commits

Reviewing files that changed from the base of the PR and between 4e00651 and 19585dc.

📒 Files selected for processing (9)
  • .changeset/quiet-chats-validate.md
  • docs/ai-chat/client-protocol.mdx
  • docs/ai-chat/custom-agents.mdx
  • docs/ai-chat/reference.mdx
  • docs/ai-chat/types.mdx
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/chat.ts
  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/trigger-sdk/src/v3/chat.ts
  • .changeset/quiet-chats-validate.md
  • docs/ai-chat/reference.mdx
  • packages/trigger-sdk/test/custom-agent-client-data-validation.test.ts
  • docs/ai-chat/client-protocol.mdx
  • docs/ai-chat/types.mdx
  • docs/ai-chat/custom-agents.mdx
  • packages/trigger-sdk/src/v3/ai.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📜 Review details
⏰ Context from checks skipped due to timeout. (32)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (13, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (18, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (17, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (16, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (20, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (24, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (19, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (21, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (15, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (14, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 24)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp (1, 2)
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: fk-cascade-guard / fk-cascade-guard
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp (2, 2)
  • GitHub Check: code-quality / code-quality
🧰 Additional context used
📓 Path-based instructions (10)
Always import from `@trigger.dev/sdk`. Never use `@trigger.dev/sdk/v3` or deprecated `client.defineJob`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
We use vitest exclusively. **Never mock anything** - use testcontainers instead.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
**Prefer static imports over dynamic imports.** Only use dynamic `import()` when:

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
Add crumbs as you write code — not just when debugging. Mark lines with

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
Always import from `@trigger.dev/sdk`. Never use `@trigger.dev/sdk/v3` (deprecated path alias)

📄 CodeRabbit inference engine (packages/trigger-sdk/CLAUDE.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
In the Trigger.dev SDK (packages/trigger-sdk), prefer isomorphic code like fetch and ReadableStream instead of Node.js-specific code

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
Use vitest for all tests in the Trigger.dev repository

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
Use function declarations instead of default exports

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
Use types over interfaces for TypeScript

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

Files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts
🧠 Learnings (1)
📚 Learning: 2026-08-16T18:36:58.179Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4537
File: packages/trigger-sdk/test/normalizeKeyString.test.ts:1-2
Timestamp: 2026-08-16T18:36:58.179Z
Learning: For related SDK `chat.agent` tests in the Trigger.dev repository—including chat channels, handover, snapshot, and transport-event coverage—keep new test files under `packages/trigger-sdk/test/` rather than colocating them with the `packages/trigger-sdk/src/v3/` source files.

Applied to files:

  • packages/trigger-sdk/test/custom-agent-client-data-error-timing.test.ts

import { mockChatAgent } from "../src/v3/test/index.js";

import { describe, expect, it } from "vitest";
import { chat } from "../src/v3/ai.js";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Import chat from the SDK package.

Replace the relative ../src/v3/ai.js import with @trigger.dev/sdk. As per coding guidelines, packages/trigger-sdk/**/*.ts must always import from @trigger.dev/sdk.

Proposed fix
-import { chat } from "../src/v3/ai.js";
+import { chat } from "`@trigger.dev/sdk`";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { chat } from "../src/v3/ai.js";
import { chat } from "@trigger.dev/sdk";

Source: Coding guidelines

Comment on lines +102 to +103
await first;
return { chunksWhileOpen, chunksAfter: errorChunks(harness).length, validationErrors };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the deferred error after the turn releases.

Lines 102-103 calculate chunksAfter, but Lines 110-115 never assert it. The default case passes if validation errors are never written after the open turn ends. Wait for the deferred chunk after first completes, then assert that chunksAfter is positive.

Proposed fix
       releaseFirstTurn.resolve();
       await first;
+      await waitFor(() => errorChunks(harness).length > 0, "deferred error written");
       return { chunksWhileOpen, chunksAfter: errorChunks(harness).length, validationErrors };
@@
     expect(result.validationErrors).toHaveLength(1);
     expect(result.chunksWhileOpen).toBe(0);
+    expect(result.chunksAfter).toBeGreaterThan(0);

Also applies to: 110-115

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.

3 participants