feat(sdk,core): close resumed chat streams promptly when caught up#4349
feat(sdk,core): close resumed chat streams promptly when caught up#4349ericallam wants to merge 3 commits into
Conversation
Resuming a chat session stream (page reload or reconnect) held the SSE connection open for the whole long-poll window even after every buffered output record had already arrived. The client now detects when it has caught up to the latest output and closes the resumed stream right away, so reconnecting to an idle chat settles immediately. Detection reuses the stream's tail-carrying heartbeat: batch and ping frames now carry the tail, and CaughtUpTracker from @s2-dev/streamstore 0.25.0 turns "last delivered seq + 1 === tail" into a caught-up signal. When the tail is absent (older self-hosted stream backends) the client keeps its previous behavior, so nothing regresses. Also moves to the current S2 hosts that 0.25.0 defaults to.
In local development, Vite's dev-server CORS middleware reflected the request Origin on every Express response, on top of the app's own CORS handling. The two layers produced a duplicated Access-Control-Allow-Origin header, which browsers reject, breaking cross-origin API calls from a separate frontend in dev. Disabling Vite's dev CORS lets the app be the single source of CORS headers. Dev-only; production is unaffected.
🦋 Changeset detectedLatest commit: 8725815 The changes in this PR will be included in the next version bump. This PR includes changesets to release 26 packages
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 |
WalkthroughS2 Streamstore dependencies and REST endpoint defaults are updated to use the newer 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/trigger-sdk/src/v3/chat.ts (1)
1767-1777: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRetain the subscription after auth recovery.
The 401/403 retry branch restores
readerandprimedbut never assignssub = opened.subscription. Consequently, Lines 1805-1814 skip caught-up settlement after a token refresh, preserving the long-poll delay on exactly those resumed streams.Proposed fix
reader = opened.reader; primed = opened.primed; + sub = opened.subscription; } else {
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c901d07e-a3f2-4071-974a-3b850bd12d3c
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (12)
.changeset/chat-session-caught-up-resume.mdapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tsapps/webapp/package.jsonapps/webapp/vite.config.tspackages/cli-v3/package.jsonpackages/core/package.jsonpackages/core/src/v3/apiClient/index.tspackages/core/src/v3/apiClient/runStream.test.tspackages/core/src/v3/apiClient/runStream.tspackages/core/src/v3/sessionStreams/manager.tspackages/trigger-sdk/src/v3/chat.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (29)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: sdk-compat / Cloudflare Workers
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
- GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
- GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: sdk-compat / Bun Runtime
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
- GitHub Check: typecheck / typecheck
- GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: internal / 🧪 Unit Tests: Internal
- GitHub Check: code-quality / code-quality
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Build and publish previews
🧰 Additional context used
📓 Path-based instructions (16)
**/package.json
📄 CodeRabbit inference engine (AGENTS.md)
When adding Zod, use the exact repository-wide pinned version
3.25.76, never a different version or range.
Files:
apps/webapp/package.jsonpackages/cli-v3/package.jsonpackages/core/package.json
apps/webapp/**/package.json
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
For the webapp, never run
pnpm run build --filter webappto verify changes; usepnpm run typecheck --filter webappafter major changes. Public packages underpackages/*usebuildinstead.
Files:
apps/webapp/package.json
**/*.{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 dynamicimport(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from@trigger.dev/sdk; never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with//@Crumbsor blocks with `// `#region` `@crumbs, and strip them before merging.
Files:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/core/src/v3/apiClient/runStream.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Files:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathDo not reintroduce the removed v1 execution path;
RunEngineVersion.V1branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.
Files:
apps/webapp/vite.config.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
apps/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For apps, use
typecheckfor verification and never usebuildas the correctness check.
Files:
apps/webapp/vite.config.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
packages/core/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (packages/core/CLAUDE.md)
Never import the root package (
@trigger.dev/core). Always use subpath imports such as@trigger.dev/core/v3,@trigger.dev/core/v3/utils,@trigger.dev/core/logger, or@trigger.dev/core/schemas
Files:
packages/core/src/v3/sessionStreams/manager.tspackages/core/src/v3/apiClient/runStream.test.tspackages/core/src/v3/apiClient/index.tspackages/core/src/v3/apiClient/runStream.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For public packages, use
buildfor verification.
Files:
packages/core/src/v3/sessionStreams/manager.tspackages/core/src/v3/apiClient/runStream.test.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.ts
packages/core/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Import
@trigger.dev/coresubpaths only; never import from the package root.
Files:
packages/core/src/v3/sessionStreams/manager.tspackages/core/src/v3/apiClient/runStream.test.tspackages/core/src/v3/apiClient/index.tspackages/core/src/v3/apiClient/runStream.ts
apps/webapp/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
UseuseCallbackanduseMemoonly for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.
Files:
apps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
apps/webapp/app/**/*.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/**/*.ts: Never userequest.signalto detect client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.ts, which is wired to Express response close events.
Access environment variables through theenvexport fromapp/env.server.ts; never useprocess.envdirectly.
Always use PrismafindFirstinstead offindUnique.
Always use the$transactionhelper from~/db.server, never callprisma.$transactionor$replica.$transactiondirectly. Pass isolation levels as strings, useSerializablefor correctness-critical read-then-write invariants, and guard possibly undefined helper results when a definite value is required.
Files:
apps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.
Files:
packages/core/src/v3/apiClient/runStream.test.ts
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/src/v3/chat.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/src/v3/chat.ts
🧠 Learnings (23)
📚 Learning: 2026-04-27T16:46:03.861Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3456
File: apps/webapp/package.json:152-152
Timestamp: 2026-04-27T16:46:03.861Z
Learning: In `apps/webapp/package.json`, treat the `effect` npm package as an intentional runtime dependency (not unused/misplaced) for the Schedule + Fiber-based metadata update logic. This should apply when reviewing `apps/webapp` code paths used by `apps/webapp/app/utils/updateMetadata.server.ts` (and closely related modules) that use Effect APIs such as `Duration.divide`, `STM.cond`, namespace exports for `Effect`/`Schedule`/`Duration`/`Fiber`, and the `Fiber.RuntimeFiber` type.
Applied to files:
apps/webapp/package.json
📚 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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.ts
📚 Learning: 2026-05-01T15:45:08.099Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3499
File: packages/plugins/tsup.config.ts:3-3
Timestamp: 2026-05-01T15:45:08.099Z
Learning: In build/tool configuration files (e.g., tsup.config.ts, vite.config.ts, vitest.config.ts), follow the tool’s documented export pattern and use `export default defineConfig(...)` (or the equivalent documented default export). The repo-wide guideline “use named exports instead of default exports” should apply only to application code (*.{ts,tsx,js,jsx}), not to these build/tool config files—so do not flag `export default defineConfig(...)` in these config files as a violation.
Applied to files:
apps/webapp/vite.config.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/vite.config.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.
Applied to files:
apps/webapp/vite.config.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.
Applied to files:
apps/webapp/vite.config.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.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:
apps/webapp/vite.config.tspackages/core/src/v3/sessionStreams/manager.tsapps/webapp/app/services/realtime/s2realtimeStreams.server.tspackages/core/src/v3/apiClient/runStream.test.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.tspackages/core/src/v3/apiClient/index.tspackages/trigger-sdk/src/v3/chat.tspackages/core/src/v3/apiClient/runStream.ts
📚 Learning: 2026-03-26T09:02:07.973Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 3274
File: apps/webapp/app/services/runsReplicationService.server.ts:922-924
Timestamp: 2026-03-26T09:02:07.973Z
Learning: When parsing Trigger.dev task run annotations in server-side services, keep `TaskRun.annotations` strictly conforming to the `RunAnnotations` schema from `trigger.dev/core/v3`. If the code already uses `RunAnnotations.safeParse` (e.g., in a `#parseAnnotations` helper), treat that as intentional/necessary for atomic, schema-accurate annotation handling. Do not recommend relaxing the annotation payload schema or using a permissive “passthrough” parse path, since the annotations are expected to be written atomically in one operation and should not contain partial/legacy payloads that would require a looser parser.
Applied to files:
apps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.
Applied to files:
apps/webapp/app/services/realtime/s2realtimeStreams.server.tsapps/webapp/app/services/realtime/streamBasinProvisioner.server.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/core/src/v3/apiClient/runStream.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/core/src/v3/apiClient/runStream.test.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/core/src/v3/apiClient/runStream.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/chat.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/chat.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/chat.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/src/v3/chat.ts
🔇 Additional comments (8)
apps/webapp/package.json (1)
106-106: LGTM!packages/cli-v3/package.json (1)
98-98: LGTM!packages/core/package.json (1)
210-210: LGTM!apps/webapp/vite.config.ts (1)
33-33: LGTM!apps/webapp/app/services/realtime/s2realtimeStreams.server.ts (1)
110-111: 🗄️ Data Integrity & IntegrationVerify the S2 account-management hostname migration.
S2’s basin data-plane hostname is consistent with the documented pattern, but account-level references currently differ between
aws.s2.devanda.s2.dev. Confirma.s2.devfor the exact Streamstore0.25.0deployment before merging. (s2.dev)
apps/webapp/app/services/realtime/s2realtimeStreams.server.ts#L110-L111: verify the account URL used for access-token issuance.apps/webapp/app/services/realtime/streamBasinProvisioner.server.ts#L188-L188: verify the basin-creation endpoint.apps/webapp/app/services/realtime/streamBasinProvisioner.server.ts#L225-L225: verify the basin-reconfiguration endpoint.Source: MCP tools
packages/core/src/v3/apiClient/runStream.test.ts (1)
603-732: LGTM!packages/core/src/v3/apiClient/index.ts (1)
1413-1436: LGTM!packages/core/src/v3/sessionStreams/manager.ts (1)
469-473: LGTM!
caughtUp() is documented to reject when the stream ends before reaching the tail, but cancel(), non-retryable HTTP responses, and the user-abort branches closed or errored the stream without ending the tracker, so a caller awaiting caughtUp() could stay pending forever. End the tracker on every terminal path. Also removes a stray closing tag from the changeset and applies oxfmt formatting.
@trigger.dev/build
trigger.dev
@trigger.dev/core
@trigger.dev/python
@trigger.dev/react-hooks
@trigger.dev/redis-worker
@trigger.dev/rsc
@trigger.dev/schema-to-json
@trigger.dev/sdk
commit: |
Summary
Resuming a chat session stream (page reload, tab refocus, reconnect) is one of the most frequent things a live chat does, and it was doing more work than it needed to. On a resume the client either held the SSE connection open for the entire long-poll window or issued a separate probe request to decide whether the stream had settled, even when every buffered record had already been delivered. This makes the client detect when it has caught up to the latest output and close the resumed stream immediately.
Net effect on the resume path: one network round-trip instead of two, one connection instead of two, and an idle reconnect that settles in tens of milliseconds instead of waiting out the poll window.
Mechanism
S2's per-stream heartbeat already fires the moment a reader crosses the tail. As of
@s2-dev/streamstore0.25.0 both the batch frame and the heartbeatpingcarry the stream tail ({seq_num, timestamp}), so "last delivered seq + 1 === tail" is a reliable caught-up signal with no extra request.SSEStreamSubscriptionfeeds those raw wire signals intoCaughtUpTracker(a public export in 0.25.0, so no vendoring) and exposescaughtUp(). The SDK's resume path awaits that and closes the connection the moment the tracker reaches the tail, replacing the old readiness probe.One correctness note worth calling out: command records (trim, fence) consume a sequence number and count toward the tail, but are never delivered to consumers. The tracker therefore keys off raw wire counts, not post-filter counts, otherwise it would never register as caught up on a stream that ends with a trim. The tracker is also ended on every terminal path (cancel, non-retryable status, user abort, done, auth error, max retries) so a pending
caughtUp()can never leak.Impact
Before writing any of this I ran a standalone red/green benchmark of the current approach against the caught-up primitive, on real cloud S2, taking medians across storage classes. Absolute latencies are RTT-dominated (a local reader talking to cloud S2 has a ~100ms floor); in production the reader sits next to S2, so the durable win is the reduction in round-trips and connections, with latency following.
Express storage class (our default), median:
End to end in a real browser against cloud S2: after a completed turn, a reload settled to ready in about 50ms with no duplicated records, and a follow-up turn streamed cleanly.
Compatibility
Fully backward compatible and feature-detected. When the tail is absent (older self-hosted stream backends that do not emit it yet),
CaughtUpTrackernever reports caught up and the client falls back to the previous readiness behavior, so existing clients and self-hosters are unaffected. The change bumps@s2-dev/streamstoreto 0.25.0 across core, webapp, and cli, and moves to the S2 hosts that version defaults to.Dev CORS fix (bundled)
While testing this end to end, the dev server was returning a duplicated
Access-Control-Allow-Originheader: Vite's dev-server CORS middleware reflects the request Origin on every Express response, on top of the app's ownapiCors, and browsers reject the doubled value. Settingserver.cors: falseinapps/webapp/vite.config.tsmakes the app the single source of CORS headers. Dev-only; production builds do not run the Vite middleware, so they are unaffected.