Skip to content

feat(sdk): return lastEventId from writeTurnComplete and typed capture result#4304

Merged
matt-aitken merged 3 commits into
mainfrom
feat/sdk-chat-turn-complete-and-capture
Jul 21, 2026
Merged

feat(sdk): return lastEventId from writeTurnComplete and typed capture result#4304
matt-aitken merged 3 commits into
mainfrom
feat/sdk-chat-turn-complete-and-capture

Conversation

@matt-aitken

Copy link
Copy Markdown
Member

Summary

Two ergonomic additions for custom chat-agent loops that own the turn loop (chat.customAgent, chat.createSession, and the hand-rolled primitives).

chat.writeTurnComplete() now resolves to { lastEventId }, the resume cursor for the start of the next turn. A custom loop can persist it straight from the task instead of round-tripping it back from the client after the turn ends. The value was already produced internally by the turn-complete write; the public wrapper simply discarded it.

chat.pipeAndCapture() no longer throws when a stream is stopped or fails. It now resolves to a PipeAndCaptureResult carrying any partial message captured before the stop or failure, a typed status ("complete" | "aborted" | "error"), and the error on failure. Previously a failed stream threw and the partial was lost, and an abort was captured only when the AI SDK happened to fire onFinish in time.

const { message, status, error } = await chat.pipeAndCapture(result, { signal });
if (message) conversation.addResponse(message);
if (status === "error") logger.error("turn failed", { error });

const { lastEventId } = await chat.writeTurnComplete();
await db.chats.update(chatId, { lastEventId });

Design

pipeAndCapture wraps the pipe in a try/catch and classifies the outcome from the abort signal (a stop drains the source stream cleanly rather than throwing) versus a thrown error. It also races the onFinish capture against a timeout so a hard stop that prevents onFinish from firing can't hang the caller. This mirrors the capture path chat.agent already uses internally.

The finishReason from onFinish is surfaced too, since it was already captured on the built-in path.

The internal turn.complete() helper keeps its existing contract: it still returns UIMessage | undefined, still throws on a genuine stream failure, and still discards output on a full run cancel.

Breaking change

chat.pipeAndCapture previously resolved to UIMessage | undefined. Call sites now read .message off the result. This is a young, low-level API; the docs examples are updated in this PR.

@changeset-bot

changeset-bot Bot commented Jul 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a6d0ddb

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

This PR includes changesets to release 26 packages
Name Type
@trigger.dev/sdk Patch
@trigger.dev/python Patch
@internal/dashboard-agent Patch
@internal/sdk-compat-tests 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/cache Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/tsql 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

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c19b6ea2-7f44-4d4b-a3b2-cba4f64cf95f

📥 Commits

Reviewing files that changed from the base of the PR and between a83bfbd and a6d0ddb.

📒 Files selected for processing (7)
  • .changeset/chat-custom-agent-capture.md
  • docs/ai-chat/custom-agents.mdx
  • docs/ai-chat/pending-messages.mdx
  • docs/ai-chat/reference.mdx
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/test/test-session-handle.ts
  • packages/trigger-sdk/test/chat-pipe-and-capture.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • docs/ai-chat/pending-messages.mdx
  • packages/trigger-sdk/test/chat-pipe-and-capture.test.ts
  • .changeset/chat-custom-agent-capture.md
  • packages/trigger-sdk/src/v3/test/test-session-handle.ts
  • docs/ai-chat/custom-agents.mdx
  • packages/trigger-sdk/src/v3/ai.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (31)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: typecheck / typecheck
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: code-quality / code-quality
  • GitHub Check: audit
  • GitHub Check: audit
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build and publish previews
🧰 Additional context used
📓 Path-based instructions (1)
docs/**/*.mdx

📄 CodeRabbit inference engine (docs/CLAUDE.md)

docs/**/*.mdx: MDX documentation pages must include frontmatter with title (required), description (required), and sidebarTitle (optional) in YAML format
Use Mintlify components for structured content: , , , , , , /, /
Always import from @trigger.dev/sdk in code examples (never from @trigger.dev/sdk/v3)
Code examples must be complete and runnable where possible
Use language tags in code fences: typescript, bash, json

Documentation in docs/ uses MDX conventions defined by the documentation guidance.

Files:

  • docs/ai-chat/reference.mdx
🧠 Learnings (4)
📚 Learning: 2026-03-10T12:44:14.176Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3200
File: docs/config/config-file.mdx:353-368
Timestamp: 2026-03-10T12:44:14.176Z
Learning: In the trigger.dev repo, docs PRs are often companions to implementation PRs. When reviewing docs PRs (MDX files under docs/), check the PR description for any companion/related PR references and verify that the documented features exist in those companion PRs before flagging missing implementations. This ensures docs stay in sync with code changes across related PRs.

Applied to files:

  • docs/ai-chat/reference.mdx
📚 Learning: 2026-04-30T20:30:29.458Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3226
File: docs/ai-chat/quick-start.mdx:13-13
Timestamp: 2026-04-30T20:30:29.458Z
Learning: In this repo’s documentation MDX files (`docs/**/*.mdx`), use `ts` and `tsx` (not `typescript`) as the code-fence language tags for TypeScript/TSX snippets. Do not flag `ts`/`tsx` code-fence language tags as incorrect in any docs MDX file, since this is the site-wide Mintlify-compatible convention.

Applied to files:

  • docs/ai-chat/reference.mdx
📚 Learning: 2026-06-16T13:14:09.440Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3964
File: docs/ai-chat/reference.mdx:482-482
Timestamp: 2026-06-16T13:14:09.440Z
Learning: When documenting or reviewing usage of `ChatTurn.complete(source?)` (in `packages/trigger-sdk/src/v3/ai.ts`), note that `source` is optional (`source?: UIMessageStreamable`). Calling `complete()` with no `source` is valid specifically for a final head-start handover (`handover.isFinal`), because the warm partial already contains the response. If examples or guidance omit `source`, ensure they are in this final-hand-over context so they remain correct.

Applied to files:

  • docs/ai-chat/reference.mdx
📚 Learning: 2026-06-16T13:14:14.382Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3964
File: docs/ai-chat/reference.mdx:478-478
Timestamp: 2026-06-16T13:14:14.382Z
Learning: When reviewing RC-gated `ai-chat` docs under `docs/ai-chat/`, don’t immediately flag missing SDK type fields or implementation details just because the field isn’t present on the docs branch yet. Instead, find and cross-check the companion implementation PR that’s intended to land alongside the docs PR, and only report missing/incorrect fields if they are also absent in the companion SDK/type changes.

Applied to files:

  • docs/ai-chat/reference.mdx
🔇 Additional comments (1)
docs/ai-chat/reference.mdx (1)

507-507: LGTM!


Walkthrough

The SDK updates chat.writeTurnComplete() to return lastEventId and changes chat.pipeAndCapture() to return structured message, status, finish reason, and error data. Stream outcomes are classified as complete, aborted, or error, with timeout handling. Session turn completion now processes these results according to cancellation and error status. AI chat documentation and examples were updated to use message destructuring and the new return contracts.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change, but it does not follow the required template and is missing Closes, checklist, Testing, Changelog, and Screenshots sections. Rewrite the PR description using the repository template: add Closes #, checklist items, Testing, Changelog, and Screenshots sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main SDK API change, though it omits the added session cursor detail.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/sdk-chat-turn-complete-and-capture

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.

@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: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Open in Devin Review

…e result

chat.writeTurnComplete() now resolves to { lastEventId }, the resume cursor
for the next turn, so a custom-agent loop can persist it straight from the
task instead of round-tripping it back from the client.

chat.pipeAndCapture() no longer throws when a stream is stopped or fails. It
resolves to a PipeAndCaptureResult carrying any partial message captured
before the stop or failure, a typed status (complete | aborted | error), and
the error on failure. The internal turn.complete() path keeps its existing
contract (returns UIMessage | undefined, still throws on a genuine stream
failure and discards output on full cancel).
@matt-aitken
matt-aitken force-pushed the feat/sdk-chat-turn-complete-and-capture branch from 3343ef5 to 335c087 Compare July 20, 2026 12:46
@pkg-pr-new

pkg-pr-new Bot commented Jul 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@a6d0ddb

trigger.dev

npm i https://pkg.pr.new/trigger.dev@a6d0ddb

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@a6d0ddb

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@a6d0ddb

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@a6d0ddb

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@a6d0ddb

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@a6d0ddb

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@a6d0ddb

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@a6d0ddb

commit: a6d0ddb

coderabbitai[bot]

This comment was marked as resolved.

…omplete lastEventId

Adds unit tests for the new chat.pipeAndCapture result shape (complete /
aborted-with-partial / error) and for chat.writeTurnComplete returning a
resume cursor. Extends the in-memory session test harness so its .out
writeControl projects a synthetic seq_num and its pipe propagates
source-stream errors (mirroring production) instead of swallowing them.
devin-ai-integration[bot]

This comment was marked as resolved.

Comment thread packages/trigger-sdk/src/v3/ai.ts
Comment thread packages/trigger-sdk/src/v3/ai.ts Outdated
…rden test pipe

Address PR review:
- pipeAndCapture now reconstructs the partial message from buffered chunks
  when a transport failure abandons the stream before onFinish fires, so the
  partial is preserved on the hard-error path, not just on abort.
- writeTurnComplete also returns sessionInEventId (the committed .in consume
  cursor) alongside lastEventId, so a raw loop can correlate both turn-boundary
  cursors server-side.
- The in-memory session test harness no longer hangs if stream setup throws
  before the read loop; stream setup now runs inside the guarded block.
- Docs and the pipeAndCapture error-path test updated to match.
@matt-aitken
matt-aitken enabled auto-merge (squash) July 21, 2026 13:15
@matt-aitken
matt-aitken merged commit e2d3b83 into main Jul 21, 2026
58 checks passed
@matt-aitken
matt-aitken deleted the feat/sdk-chat-turn-complete-and-capture branch July 21, 2026 15:08
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