Skip to content

fix(sdk): watch-mode chat subscriptions survive quiet windows - #4548

Open
kathiekiwi wants to merge 14 commits into
feat/agent-storybook-galleryfrom
fix/watch-mode-keepalive-tri-13065
Open

fix(sdk): watch-mode chat subscriptions survive quiet windows#4548
kathiekiwi wants to merge 14 commits into
feat/agent-storybook-galleryfrom
fix/watch-mode-keepalive-tri-13065

Conversation

@kathiekiwi

@kathiekiwi kathiekiwi commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Two related fixes to the chat transport's watch/read-only subscription lifecycle.

TRI-13065 — In watch mode the chat stream died at the first long-poll window boundary after a turn completed: the EOF-reconnect path was gated on isStreaming, which turn-complete clears, so a watcher stopped hearing later turns. Watch mode now keeps reconnecting across quiet windows and only stops on abort or a settled session. The bounded give-up budget still applies to normal (mid-turn) streams, but not to watch mode, where empty windows are expected.

TRI-13070reconnectToStream derived mutation rights from mere signal presence (sendStopOnAbort: !!options.abortSignal), so a passive/read-only subscriber that passed an abortSignal would append a {kind:"stop"} to .in on unmount and could stop a turn it didn't own. Subscription lifecycle is not session ownership: reconnectToStream now takes an explicit stopOnAbort option that defaults to false, and the owning turn paths (sendMessages, sendAction) pass sendStopOnAbort: true explicitly. A read-only subscription ending never mutates the session; it still cancels its own request.

@changeset-bot

changeset-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 8c72806

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
@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/metrics-pipeline 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 Aug 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e3f12d4-3589-484c-8155-071472a27085

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

Watch mode now reconnects after completed turns and idle-window EOFs. It continues beyond the normal EOF resubscribe limit. The subscription stops when the session is settled or the operation is aborted. Tests cover reconnect behavior, settled-session termination, aborts during backoff, and updated SSE fixtures. A patch changeset documents the SDK change.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the primary watch-mode chat subscription fix.
Description check ✅ Passed The description clearly explains both fixes and their intended behavior, but it omits the template checklist and explicit testing, changelog, and screenshots sections.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/watch-mode-keepalive-tri-13065

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.

@pkg-pr-new

pkg-pr-new Bot commented Aug 10, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

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

trigger.dev

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

@trigger.dev/core

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

@trigger.dev/python

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

@trigger.dev/react-hooks

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

@trigger.dev/redis-worker

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

@trigger.dev/rsc

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

@trigger.dev/schema-to-json

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

@trigger.dev/sdk

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

commit: 8c72806

@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 4 potential issues.

Open in Devin Review

Comment thread packages/trigger-sdk/src/v3/chat.ts
Comment thread packages/trigger-sdk/src/v3/chat.ts
return this.subscribeToSessionStream(state, abortSignal, options.chatId, {
resumed: true,
sendStopOnAbort: !!options.abortSignal,
sendStopOnAbort: options.stopOnAbort ?? false,

@devin-ai-integration devin-ai-integration Bot Aug 10, 2026

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.

📝 Info: stopOnAbort default flip mostly affects direct callers, not the AI SDK

ChatTransport.reconnectToStream in the AI SDK is invoked with { chatId } & ChatRequestOptions, which carries headers/body/metadata but no abortSignal, so !!options.abortSignal was already falsy on the AI-SDK-driven resume path. The behavioural change is therefore limited to code that calls reconnectToStream directly with a signal — those callers now need stopOnAbort: true to preserve the old "abort stops the turn" behaviour. No such caller exists in this repo (only tests), but external/embedding apps built on this SDK will silently lose the stop-on-unmount side effect.

Open in Devin Review

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

Comment on lines +1798 to +1804
// Watch mode is a standing subscription: it outlives turn-complete
// (which clears `isStreaming`) and idle windows EOF by design, so the
// give-up budget doesn't apply. Only abort or a settled session ends it.
while (
state.isStreaming &&
(this.watchMode || (state.isStreaming && eofResubscribes < MAX_EOF_RESUBSCRIBES)) &&
!currentSubscription?.sessionSettled &&
!combinedSignal.aborted &&
eofResubscribes < MAX_EOF_RESUBSCRIBES
!combinedSignal.aborted

@devin-ai-integration devin-ai-integration Bot Aug 10, 2026

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.

🔍 Watch subscription keeps running but persisted state says not streaming, so a remount can't resubscribe

In watch mode a turn-complete still sets state.isStreaming = false and persists it (packages/trigger-sdk/src/v3/chat.ts:2000-2001) while the loop keeps reconnecting. reconnectToStream bails early when state.isStreaming === false (packages/trigger-sdk/src/v3/chat.ts:1154), so once the first turn completes, any remount of the watch component (StrictMode double-mount, route re-entry, tab restore) can no longer open a subscription — nothing ever flips isStreaming back to true for a passive viewer. Pre-existing, but this PR makes the standing watch subscription the supported flow, so the resume-after-remount gap becomes more visible.

Open in Devin Review

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

devin-ai-integration[bot]

This comment was marked as resolved.

@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 2 new potential issues.

Open in Devin Review

Comment thread packages/trigger-sdk/src/v3/chat.ts
Comment on lines +1798 to 1805
// Watch mode is a standing subscription: it outlives turn-complete
// (which clears `isStreaming`) and idle windows EOF by design, so the
// give-up budget doesn't apply. Only abort or a settled session ends it.
while (
state.isStreaming &&
(this.watchMode || (state.isStreaming && eofResubscribes < MAX_EOF_RESUBSCRIBES)) &&
!currentSubscription?.sessionSettled &&
!combinedSignal.aborted &&
eofResubscribes < MAX_EOF_RESUBSCRIBES
!combinedSignal.aborted
) {

@devin-ai-integration devin-ai-integration Bot Aug 10, 2026

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.

🔍 Watch mode's only documented clean exit (settled session) is unreachable in production

peekSettled: !this.watchMode means a watch-mode subscription never sends X-Peek-Settled: 1. On the server, X-Session-Settled: true is emitted only on the opt-in peek path (apps/webapp/app/services/realtime/s2realtimeStreams.server.ts:417-437, gated by the X-Peek-Settled header at apps/webapp/app/routes/realtime.v1.sessions.$session.$io.ts:184). Therefore currentSubscription.sessionSettled can never become true for a watch client in production, and the loop comment at packages/trigger-sdk/src/v3/chat.ts:1800-1802 ("Only abort or a settled session ends it") is only half true: abort is the sole exit. Practical consequence: a viewer opened on a chat whose session is long finished keeps re-issuing 120s long-polls forever (one standing server request per watcher) until the consumer aborts or cancels. The new tests exercise the settled exit only by synthesising the header in the mock, so they don't cover the production shape. Worth confirming this unbounded standing poll is the intended cost of the fix, or whether watch mode needs a separate terminal signal (e.g. session closed/expired).

Open in Devin Review

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

…ate on give-up

- reconnect no longer peek-settles in watch mode, so a settled peek between
  turns can't close the standing subscription before the next turn.
- the returned stream now aborts its resubscribe loop when the reader is
  cancelled, instead of leaking it.
- clear and persist isStreaming before the budget-exhaustion throw so a
  reload doesn't reopen a doomed subscription.
…stream-error

A consumer cancelling the watch stream aborts the resubscribe loop, which
reaches controller.close() on an already-closed controller. The resulting
'Invalid state' throw was surfaced as a bogus stream-error on every clean
watch-viewer unmount. Wrap the remaining bare close sites to match the
existing pattern.

@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.

Open in Devin Review

Comment on lines +1833 to +1846
if (
state.isStreaming &&
!currentSubscription?.sessionSettled &&
!combinedSignal.aborted
) {
// Clear + persist before throwing so the surfaced error leaves
// consistent state — otherwise a reload sees isStreaming: true
// and reopens a doomed subscription.
state.isStreaming = false;
this.notifySessionChange(chatId, state);
throw new Error(
"Chat stream ended before the turn completed (reconnect budget exhausted)."
);
}

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.

🔍 Non-watch streams now hard-error after ~10 minutes of complete silence

The budget is 5 resubscribes and each window is streamTimeoutSeconds (default 120s, packages/trigger-sdk/src/v3/chat.ts:163), so a turn that emits no record at all for roughly 10 minutes now surfaces stream-error and errors the AI SDK stream instead of closing quietly — even though the agent may still be running. eofResubscribes is reset by any record (packages/trigger-sdk/src/v3/chat.ts:1930), so only fully silent stretches count; server keepalive comments do not produce records and therefore do not re-earn budget. Consider whether long tool calls / deep reasoning pauses can realistically exceed that window before this ships.

Open in Devin Review

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

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