Repository navigation
feat(chat): client + react entries — session client, reconnecting stream, useChatSession - #6205
Conversation
…ssion client, hooks subscribeToSession: injected WebSocket factory + URL builder, since-cursor resume, declared delta channels, reset-to-refetch signal, exponential backoff. sessionClient wraps an injected transport typed off ChatRouter (type-only, via tsconfig paths — no package dependency edge, which would cycle the workspace graph). useChatSession seeds getSession+getItems through reduceMany then tails live with one commit per injected frame, clears the outbox on clientId echo, pages older history, and auto-resyncs on reset; useTimeline/useApprovals memoize the derived views. chat-runtime grows a test-only ./testing export and ChatRouterInputs/Outputs types so the chat package never imports @trpc/server. Claude-Session: https://claude.ai/code/session_01XRFCEPsfmJHu2SenDKYJ2h
|
Important Review skippedReview was skipped due to path filters ⛔ Files ignored due to path filters (1)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThe PR adds public ChangesChat session API
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant useChatSession
participant SessionClient
participant subscribeToSession
participant ChatRuntime
useChatSession->>SessionClient: load session and items
useChatSession->>SessionClient: subscribe with delta channels
SessionClient->>subscribeToSession: create stream
subscribeToSession->>ChatRuntime: request session envelopes
ChatRuntime-->>subscribeToSession: deliver envelopes or reset
subscribeToSession-->>useChatSession: update session snapshot
useChatSession->>SessionClient: resynchronize items after reset
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
⚔️ Resolve merge conflicts 💡
🧪 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 |
Greptile SummaryThis PR adds typed chat session clients, resumable WebSocket streaming, and React hooks that seed, reduce, paginate, and live-update chat state.
Confidence Score: 4/5The initialization failure path must be handled before merging because a transient seed request rejection permanently prevents the chat session from becoming live. The hook creates its subscription only after two unguarded asynchronous seed requests, so a normal transport rejection leaves the UI loading and disconnected with no recovery path. Files Needing Attention: packages/chat/src/react/useChatSession/useChatSession.ts
|
| Filename | Overview |
|---|---|
| packages/chat/src/react/useChatSession/useChatSession.ts | Adds the seed-to-live React session lifecycle, but an initialization rejection leaves the hook permanently loading without a stream. |
| packages/chat/src/client/subscribeToSession/subscribeToSession.ts | Adds validated envelope parsing, cursor resume, reset handling, reconnect backoff, and explicit teardown. |
| packages/chat/src/client/sessionClient/sessionClient.ts | Adds typed command, pagination, subscription, and multi-stream lifecycle wrappers over the chat transport. |
| packages/chat/package.json | Exposes client and React subpaths and adds React/testing dependencies consistent with sibling packages. |
| packages/chat-runtime/src/router/router/router.ts | Exports inferred router input and output types for the structural client transport. |
Sequence Diagram
sequenceDiagram
participant UI as React consumer
participant Hook as useChatSession
participant Client as SessionClient
participant API as Chat transport
participant WS as Session stream
UI->>Hook: mount
Hook->>Client: getSession()
Client->>API: getSession
API-->>Client: session + cursor
Hook->>Client: getItems()
Client->>API: getItems
API-->>Client: seed envelopes
Hook->>Hook: reduce seed and mark ready
Hook->>Client: subscribe(seed cursor)
Client->>WS: open resumable stream
WS-->>Hook: live envelopes
Hook->>Hook: frame-batched reduce
alt reset envelope
WS-->>Hook: reset
Hook->>Client: getItems() resync
end
Prompt To Fix All With AI
### Issue 1
packages/chat/src/react/useChatSession/useChatSession.ts:162-163
**Seed failure stalls session initialization**
When either `getSession()` or `getItems()` rejects during initialization, the unhandled rejection exits `seed()` before the hook marks the session ready or creates its live subscription, leaving the UI permanently loading and disconnected.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Reviews (1): Last reviewed commit: "feat(chat): client + react entries — rec..." | Re-trigger Greptile
| const session = await client.getSession(); | ||
| const page = await client.getItems({ limit: pageSize }); |
There was a problem hiding this comment.
Seed failure stalls session initialization
When either getSession() or getItems() rejects during initialization, the unhandled rejection exits seed() before the hook marks the session ready or creates its live subscription, leaving the UI permanently loading and disconnected.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/chat/src/react/useChatSession/useChatSession.ts
Line: 162-163
Comment:
**Seed failure stalls session initialization**
When either `getSession()` or `getItems()` rejects during initialization, the unhandled rejection exits `seed()` before the hook marks the session ready or creates its live subscription, leaving the UI permanently loading and disconnected.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
packages/chat/src/client/subscribeToSession/subscribeToSession.ts (2)
88-105: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider surfacing dropped frames to the caller.
handleFramediscards a frame silently in three cases: a non-string payload at line 89, aJSON.parsefailure at line 93, and a schema rejection at line 97. Dropping the frame is the correct safe fallback. The problem is that nothing reports the drop.If the server and the client disagree on the envelope schema, every frame fails validation. The socket stays open, the cursor never advances, and the caller sees no status change and no error. The stall is then hard to diagnose in production.
Add an optional diagnostic callback to
SubscribeToSessionOptionsand call it on each discarded frame.♻️ Proposed change
onStatusChange?(status: StreamStatus): void; + onInvalidFrame?(data: unknown): void; backoffInitialMs?: number;const handleFrame = (data: unknown) => { - if (typeof data !== "string") return; + if (typeof data !== "string") { + options.onInvalidFrame?.(data); + return; + } let raw: unknown; try { raw = JSON.parse(data); } catch { + options.onInvalidFrame?.(data); return; } const parsed = envelopeSchema.safeParse(raw); - if (!parsed.success) return; + if (!parsed.success) { + options.onInvalidFrame?.(raw); + return; + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/chat/src/client/subscribeToSession/subscribeToSession.ts` around lines 88 - 105, Update SubscribeToSessionOptions to expose an optional diagnostic callback, then use it in handleFrame for each discarded payload: non-string data, JSON.parse failures, and envelopeSchema validation failures. Preserve the existing safe early returns and provide the callback with enough context to distinguish the discard reason.
107-115: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider adding jitter to the reconnect delay.
The delay is fully deterministic:
initialMs * 2 ** (attempts - 1), capped atmaxMs. Every client that loses its connection in the same event computes the same delay sequence.If a server restarts and drops all sessions at once, every client then reconnects in lockstep and repeats that pattern at each backoff step. The synchronized retries can prevent the server from recovering.
Add bounded random jitter to the computed delay. Keep the deterministic sequence available so the assertions at
subscribeToSession.test.tslines 181-186 stay stable, for example by making the jitter source injectable and defaulting it to no jitter in tests.♻️ Proposed change
onStatusChange?(status: StreamStatus): void; + random?(): number; backoffInitialMs?: number;const scheduleReconnect = () => { if (closed) return; attempts += 1; - const delayMs = Math.min(initialMs * 2 ** (attempts - 1), maxMs); + const ceilingMs = Math.min(initialMs * 2 ** (attempts - 1), maxMs); + const random = options.random; + const delayMs = random + ? Math.round(ceilingMs * (0.5 + random() * 0.5)) + : ceilingMs; cancelReconnect = wait(() => {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/chat/src/client/subscribeToSession/subscribeToSession.ts` around lines 107 - 115, Update scheduleReconnect to apply bounded random jitter to the exponential delay while preserving the initialMs/maxMs backoff bounds. Make the jitter source or strategy injectable, defaulting to the existing deterministic behavior in subscribeToSession tests so their delay assertions remain stable, and use randomized jitter in normal client operation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/chat/src/client/sessionClient/sessionClient.test.ts`:
- Around line 98-101: Add explicit success assertions before the early-return
narrowing in both sites: in
packages/chat/src/client/sessionClient/sessionClient.test.ts lines 98-101,
assert older.ok before if (!older.ok) return; and in lines 133-134, assert
page.ok before if (!page.ok) return;. Preserve the existing cursor and
deduplication assertions.
In `@packages/chat/src/client/sessionClient/sessionClient.ts`:
- Line 67: Update the mintId fallback in createSessionClient to avoid direct
crypto.randomUUID() usage on React Native and non-secure browser environments.
Reuse the existing injected or shared React Native–safe UUID source, such as the
expo-crypto-backed implementation, while preserving options.mintId when
provided.
- Around line 91-114: Update the session client methods cancelTurn,
respondToApproval, and setMode to accept an optional commandId parameter and
pass it through to their corresponding options.transport calls, while retaining
mintId() as the fallback when callers omit it. Keep the existing session, turn,
approval, decision, and mode arguments unchanged.
In `@packages/chat/src/react/useChatSession/useChatSession.ts`:
- Around line 125-142: Handle rejected SessionClient promises across
useChatSession: in packages/chat/src/react/useChatSession/useChatSession.ts
lines 125-142, catch getItems failures in resync and expose retryable recovery
state; in lines 161-183, catch seed getSession/getItems failures so the hook
leaves loading in a recoverable failure state; in lines 217-237, restore
nextBeforeRef.current when pagination getItems rejects so loadOlder can retry.
In packages/chat/src/react/useChatSession/useChatSession.test.tsx lines 116-298,
add rejection coverage for seed, reset resync, and pagination while preserving
existing resolved-error handling.
---
Nitpick comments:
In `@packages/chat/src/client/subscribeToSession/subscribeToSession.ts`:
- Around line 88-105: Update SubscribeToSessionOptions to expose an optional
diagnostic callback, then use it in handleFrame for each discarded payload:
non-string data, JSON.parse failures, and envelopeSchema validation failures.
Preserve the existing safe early returns and provide the callback with enough
context to distinguish the discard reason.
- Around line 107-115: Update scheduleReconnect to apply bounded random jitter
to the exponential delay while preserving the initialMs/maxMs backoff bounds.
Make the jitter source or strategy injectable, defaulting to the existing
deterministic behavior in subscribeToSession tests so their delay assertions
remain stable, and use randomized jitter in normal client operation.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: fea21407-9da2-454c-92ad-85f55727bd45
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (31)
packages/chat-runtime/README.mdpackages/chat-runtime/package.jsonpackages/chat-runtime/src/router/index.tspackages/chat-runtime/src/router/router/index.tspackages/chat-runtime/src/router/router/router.tspackages/chat-runtime/src/testing/index.tspackages/chat/package.jsonpackages/chat/src/client/index.tspackages/chat/src/client/sessionClient/index.tspackages/chat/src/client/sessionClient/sessionClient.test.tspackages/chat/src/client/sessionClient/sessionClient.tspackages/chat/src/client/subscribeToSession/index.tspackages/chat/src/client/subscribeToSession/subscribeToSession.test.tspackages/chat/src/client/subscribeToSession/subscribeToSession.tspackages/chat/src/react/index.tspackages/chat/src/react/useApprovals/index.tspackages/chat/src/react/useApprovals/useApprovals.test.tsxpackages/chat/src/react/useApprovals/useApprovals.tspackages/chat/src/react/useChatSession/index.tspackages/chat/src/react/useChatSession/useChatSession.test.tsxpackages/chat/src/react/useChatSession/useChatSession.tspackages/chat/src/react/useTimeline/index.tspackages/chat/src/react/useTimeline/useTimeline.test.tsxpackages/chat/src/react/useTimeline/useTimeline.tspackages/chat/src/testing/manualWait/index.tspackages/chat/src/testing/manualWait/manualWait.tspackages/chat/src/testing/memoryStream/index.tspackages/chat/src/testing/memoryStream/memoryStream.tspackages/chat/src/testing/registerDom/index.tspackages/chat/src/testing/registerDom/registerDom.tspackages/chat/tsconfig.json
| if (!older.ok) return; | ||
| expect(older.envelopes.at(-1)?.cursor.seq).toBe( | ||
| (newest.nextBefore?.seq ?? 0) - 1, | ||
| ); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Two tests can pass silently when getItems fails. Both sites use a !result.ok early return to narrow the result type, but neither asserts ok first. If getItems returns a failure, the test returns before its real assertions and still reports success. Line 89 shows the correct order for newest: assert ok, then narrow.
packages/chat/src/client/sessionClient/sessionClient.test.ts#L98-L101: addexpect(older.ok).toBe(true);beforeif (!older.ok) return;so the older-page cursor assertions always run.packages/chat/src/client/sessionClient/sessionClient.test.ts#L133-L134: addexpect(page.ok).toBe(true);beforeif (!page.ok) return;so the deduplication assertions always run.
📍 Affects 1 file
packages/chat/src/client/sessionClient/sessionClient.test.ts#L98-L101(this comment)packages/chat/src/client/sessionClient/sessionClient.test.ts#L133-L134
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/chat/src/client/sessionClient/sessionClient.test.ts` around lines 98
- 101, Add explicit success assertions before the early-return narrowing in both
sites: in packages/chat/src/client/sessionClient/sessionClient.test.ts lines
98-101, assert older.ok before if (!older.ok) return; and in lines 133-134,
assert page.ok before if (!page.ok) return;. Preserve the existing cursor and
deduplication assertions.
| export function createSessionClient( | ||
| options: SessionClientOptions, | ||
| ): SessionClient { | ||
| const mintId = options.mintId ?? (() => crypto.randomUUID()); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
crypto.randomUUID availability React Native secure context requirement
💡 Result:
The crypto.randomUUID() method is not natively available in the global scope of a standard React Native environment [1][2][3]. Unlike web browsers, where crypto.randomUUID() is widely supported in secure contexts (HTTPS) [4], React Native does not implement the full Web Crypto API by default [2][3][5]. Availability and Solutions: 1. Polyfills: To use crypto.randomUUID() or dependencies that rely on crypto.getRandomValues() (such as many UUID libraries), you must use third-party polyfills [1][2][6][3]. Libraries like react-native-get-random-values [2] or react-native-random-uuid [7][6] are commonly used to provide this functionality. 2. Framework-Specific APIs: If you are using Expo, the expo-crypto library provides a native implementation of Crypto.randomUUID() that works across Android, iOS, and other platforms [8]. 3. Secure Context Requirement: The "secure context" requirement (HTTPS) associated with crypto.randomUUID() in web browsers [4] does not apply directly to React Native, as native mobile applications operate outside of the browser security model. However, you are still responsible for ensuring the cryptographic security of your implementation by using trusted, native-backed libraries [2][3]. Recommendation: - If you are in an Expo managed workflow, use expo-crypto for native, secure UUID generation [8]. - If you are using React Native CLI or need a global polyfill for other libraries (like uuid), install react-native-get-random-values and import it at the very top of your entry file (e.g., index.js or App.js) to ensure it executes before any other dependencies [1][2][9].
Citations:
- 1: https://www.github.com/uuidjs/uuid
- 2: https://www.npmjs.com/package/react-native-get-random-values
- 3: https://github.com/fintoda/react-native-crypto-lib
- 4: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
- 5: https://www.npmjs.com/package/node-libs-expo
- 6: https://github.com/LinusU/react-native-random-uuid
- 7: https://www.npmjs.com/package/react-native-random-uuid
- 8: https://docs.expo.dev/versions/latest/sdk/crypto/
- 9: https://docs.metamask.io/metamask-connect/multichain/quickstart/react-native/
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files matching sessionClient.ts:"
fd -a 'sessionClient\.ts$' . || true
echo
echo "Package/workspace files matching chat:"
fd -a 'package\.json$' . | rg 'packages/[^/]+/package\.json$|(^|/)package\.json$' | sed -n '1,80p'
echo
echo "Target file excerpt:"
if [ -f packages/chat/src/client/sessionClient/sessionClient.ts ]; then
wc -l packages/chat/src/client/sessionClient/sessionClient.ts
cat -n packages/chat/src/client/sessionClient/sessionClient.ts
fi
echo
echo "Search for sessionClient and mintId usages:"
rg -n "sessionClient|mintId|useChatSession" packages -S || trueRepository: superset-sh/superset
Length of output: 12634
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import json
for p in Path('.').rglob('package.json'):
if 'node_modules' in p.parts or '.git' in p.parts:
continue
try:
data = json.loads(p.read_text())
except Exception:
continue
if any(key in data for key in ['dependencies','devDependencies','peerDependencies','react-native','expo','bun']):
deps = {}
for sec in ['dependencies','devDependencies','peerDependencies']:
deps.update(data.get(sec) or {})
hits = {name: vers for name, vers in deps.items() if name in ('react-native','expo','crypto','node-forge','uuid') or 'crypto' in name.lower() or 'random' in name.lower()}
if hits:
print(p)
for name, vers in hits.items():
print(f" {name}: {vers}")
PYRepository: superset-sh/superset
Length of output: 514
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "mobile package scripts/deps excerpt:"
jq '{scripts,dependencies,recommendedDependencies,peerDependencies}' apps/mobile/package.json
echo
echo "chat package dependencies:"
jq '{dependencies,peerDependencies}' packages/chat/package.json
echo
echo "chat runtime dependencies:"
jq '{dependencies,peerDependencies}' packages/chat-runtime/package.json
echo
echo "mobile imports/setup for react-native-get-random-values"
rg -n "random-values|Expo|expo-crypto|createSessionClient|useChatSession|SessionClientOptions" apps packages -S || true
echo
echo "sessionClient tests around mintId:"
sed -n '1,180p' packages/chat/src/client/sessionClient/sessionClient.test.tsRepository: superset-sh/superset
Length of output: 27486
Use a React Native–safe default for mintId.
createSessionClient defaults to crypto.randomUUID(), while the React Native entry loads react-native-get-random-values and already uses expo-crypto.randomUUID(). Make the fallback use an injected RN-safe UUID source, or call a shared seeded UUID if one exists, to avoid crypto.randomUUID() on React Native / non-secure browser web targets.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/chat/src/client/sessionClient/sessionClient.ts` at line 67, Update
the mintId fallback in createSessionClient to avoid direct crypto.randomUUID()
usage on React Native and non-secure browser environments. Reuse the existing
injected or shared React Native–safe UUID source, such as the expo-crypto-backed
implementation, while preserving options.mintId when provided.
| cancelTurn: async (turnId) => { | ||
| await options.transport.cancelTurn({ | ||
| commandId: mintId(), | ||
| sessionId, | ||
| turnId, | ||
| }); | ||
| }, | ||
|
|
||
| respondToApproval: async (approvalId, decision) => { | ||
| await options.transport.respondToApproval({ | ||
| commandId: mintId(), | ||
| sessionId, | ||
| approvalId, | ||
| decision, | ||
| }); | ||
| }, | ||
|
|
||
| setMode: async (modeId) => { | ||
| await options.transport.setMode({ | ||
| commandId: mintId(), | ||
| sessionId, | ||
| modeId, | ||
| }); | ||
| }, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Inspect runtime handling of respondToApproval and command dedupe.
set -euo pipefail
fd -t f -e ts . packages/chat-runtime/src | xargs rg -n -C 6 'respondToApproval' || true
# Locate the command dedupe path keyed by commandId.
rg -n -C 8 --type=ts 'commandId' packages/chat-runtime/src | rg -n -C 4 'dedup|already|seen|cache|idempot' || trueRepository: superset-sh/superset
Length of output: 38387
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- sessionClient outline ---\n'
ast-grep outline packages/chat/src/client/sessionClient/sessionClient.ts || true
printf '\n--- sessionClient relevant lines ---\n'
sed -n '1,150p' packages/chat/src/client/sessionClient/sessionClient.ts | nl -ba
printf '\n--- sessionClient tests relevant lines ---\n'
sed -n '90,140p' packages/chat/src/client/sessionClient/sessionClient.test.ts | nl -ba
printf '\n--- protocol schema commands ---\n'
fd -t f -e ts . packages | rg 'package.*protocol|protocol' | head -20
fd -t f -e ts '.*' packages | rg 'commands|schema|zod' | rg protocol || true
rg -n -C 5 'cancelTurnInputSchema|respondToApprovalInputSchema|setModeInputSchema|PromptInput|commandId' packages -g '*.ts' -g '*.tsx' | head -200Repository: superset-sh/superset
Length of output: 249
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- sessionClient outline ---'
ast-grep outline packages/chat/src/client/sessionClient/sessionClient.ts || true
printf '%s\n' ''
printf '%s\n' '--- sessionClient relevant lines ---'
sed -n '1,150p' packages/chat/src/client/sessionClient/sessionClient.ts | nl -ba
printf '%s\n' ''
printf '%s\n' '--- sessionClient tests relevant lines ---'
sed -n '90,140p' packages/chat/src/client/sessionClient/sessionClient.test.ts | nl -ba
printf '%s\n' ''
printf '%s\n' '--- protocol/schema command IDs ---'
rg -n -C 5 'cancelTurnInputSchema|respondToApprovalInputSchema|setModeInputSchema|promptInputSchema|commandId' packages -g '*.ts' -g '*.tsx' | head -220Repository: superset-sh/superset
Length of output: 583
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- sessionClient relevant lines ---'
sed -n '1,150p' packages/chat/src/client/sessionClient/sessionClient.ts
printf '%s\n' ''
printf '%s\n' '--- sessionClient tests relevant lines ---'
sed -n '90,140p' packages/chat/src/client/sessionClient/sessionClient.test.ts
printf '%s\n' ''
printf '%s\n' '--- runtime command handlers and commandId usage ---'
sed -n '680,712p' packages/chat-runtime/src/commands/commands/commands.ts
printf '%s\n' ''
printf '%s\n' '--- protocol command schemas ---'
sed -n '1,220p' $(fd -t f -e ts '.*' packages | rg 'protocol|schema|chat' | head -80 | rg 'command|schema|protocol' | head -5 | tail -1) 2>/dev/null || true
printf '%s\n' ''
printf '%s\n' '--- commandId declarations with context ---'
rg -n -C 3 'commandId\??:|commandId;|z\.optional|commandId' packages -g '*.ts' -g '*.tsx' | head -260Repository: superset-sh/superset
Length of output: 28400
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- sessionClient.test.ts lines 160-230 ---'
sed -n '160,230p' packages/chat/src/client/sessionClient/sessionClient.test.ts
printf '%s\n' ''
printf '%s\n' '--- commands.ts response/input command keys ---'
sed -n '111,142p' packages/chat-runtime/src/commands/commands/commands.ts
printf '%s\n' ''
printf '%s\n' '--- protocol command schemas all ---'
sed -n '1,120p' packages/chat/src/protocol/commands.tsRepository: superset-sh/superset
Length of output: 4882
Let callers supply a stable commandId for the mutating commands.
promptOptions.commandId is optional and maps to the runtime prompt:${commandId} dedupe key, but cancelTurn, respondToApproval, and setMode always mint a fresh commandId. A caller that retries these mutating commands after an ambiguous transport failure can send a second distinct command. respondToApproval is the most consequential because it can submit a second decision for the same pending approvalId.
Add an optional commandId to these methods and pass it through to the transport calls.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/chat/src/client/sessionClient/sessionClient.ts` around lines 91 -
114, Update the session client methods cancelTurn, respondToApproval, and
setMode to accept an optional commandId parameter and pass it through to their
corresponding options.transport calls, while retaining mintId() as the fallback
when callers omit it. Keep the existing session, turn, approval, decision, and
mode arguments unchanged.
| const resync = useCallback(async () => { | ||
| if (resyncingRef.current) return; | ||
| resyncingRef.current = true; | ||
| try { | ||
| const page = await client.getItems({ limit: pageSize }); | ||
| if (clientRef.current !== client) return; | ||
| if (!page.ok) return; | ||
| nextBeforeRef.current = page.nextBefore; | ||
| setHasOlder(page.nextBefore !== null); | ||
| setSnapshot((prev) => | ||
| reduceMany( | ||
| { ...prev, cursor: null, pendingReset: null }, | ||
| page.envelopes, | ||
| ), | ||
| ); | ||
| } finally { | ||
| resyncingRef.current = false; | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Handle rejected SessionClient calls.
page.ok handles resolved application errors. A rejected getSession or getItems promise bypasses those checks. The initial seed then remains in "loading" without a stream. Reset recovery leaves the existing reset state without retry. Pagination clears nextBeforeRef, so later loadOlder() calls cannot retry.
packages/chat/src/react/useChatSession/useChatSession.ts#L125-L142: Catch resync failures and provide a retryable recovery state.packages/chat/src/react/useChatSession/useChatSession.ts#L161-L183: Catch seed failures and expose a recoverable failure state instead of leaving the hook loading.packages/chat/src/react/useChatSession/useChatSession.ts#L217-L237: RestorenextBeforeRef.currentwhengetItemsrejects.packages/chat/src/react/useChatSession/useChatSession.test.tsx#L116-L298: Add rejection tests for seed, reset resync, and pagination.
📍 Affects 2 files
packages/chat/src/react/useChatSession/useChatSession.ts#L125-L142(this comment)packages/chat/src/react/useChatSession/useChatSession.ts#L161-L183packages/chat/src/react/useChatSession/useChatSession.ts#L217-L237packages/chat/src/react/useChatSession/useChatSession.test.tsx#L116-L298
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/chat/src/react/useChatSession/useChatSession.ts` around lines 125 -
142, Handle rejected SessionClient promises across useChatSession: in
packages/chat/src/react/useChatSession/useChatSession.ts lines 125-142, catch
getItems failures in resync and expose retryable recovery state; in lines
161-183, catch seed getSession/getItems failures so the hook leaves loading in a
recoverable failure state; in lines 217-237, restore nextBeforeRef.current when
pagination getItems rejects so loadOlder can retry. In
packages/chat/src/react/useChatSession/useChatSession.test.tsx lines 116-298,
add rejection coverage for seed, reset resync, and pagination while preserving
existing resolved-error handling.
There was a problem hiding this comment.
9 issues found across 32 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/chat/src/react/useChatSession/useChatSession.ts">
<violation number="1" location="packages/chat/src/react/useChatSession/useChatSession.ts:126">
P2: Switching the hook to a new client while a previous resync is pending can strand the new client's reset because the shared in-flight guard suppresses its fetch. Scope the guard to the client/generation or reset and re-run it when the client changes.</violation>
<violation number="2" location="packages/chat/src/react/useChatSession/useChatSession.ts:131">
P2: A failed reset fetch leaves `pendingReset` permanently set without retrying or exposing an error, so the hook can remain in reset state while subsequent stream frames are reduced against the stale snapshot. Handle the failed page result with an explicit retry/error transition rather than silently returning.</violation>
<violation number="3" location="packages/chat/src/react/useChatSession/useChatSession.ts:167">
P2: A prompt echoed in a fetched page can remain in the outbox even though its durable item is already included in the snapshot; when seed advances the stream cursor past that item, no later echo clears it and retry can submit a duplicate. Apply the same client-id echo confirmation to every fetched page before replacing or merging the snapshot.</violation>
<violation number="4" location="packages/chat/src/react/useChatSession/useChatSession.ts:183">
P2: A transport rejection during initial seed or reset resync becomes an unhandled promise rejection, leaving the hook stuck in `loading` or with stale reset state. Catch these asynchronous flows and surface a recoverable error or retry state instead of discarding the returned promise.</violation>
</file>
<file name="packages/chat/src/react/useChatSession/useChatSession.test.tsx">
<violation number="1" location="packages/chat/src/react/useChatSession/useChatSession.test.tsx:94">
P3: The module-level `latest`/`renders` state in the shared `Probe` component is never reset between tests, so tests are coupled through shared mutable globals (e.g., `renders` accumulates across the whole file). This is fragile if tests are ever run concurrently or reordered, since `session()` reads whichever render wrote `latest` last. Prefer returning the hook result from each test or resetting the counters in a `beforeEach`.</violation>
<violation number="2" location="packages/chat/src/react/useChatSession/useChatSession.test.tsx:238">
P3: The `while (session().hasOlder)` loop in the loadOlder test has no upper bound, so if the hook's paging logic regresses (e.g., `nextBefore` never becomes `null` or `hasOlder` stays true), this test never terminates and hangs until the runner timeout instead of failing fast with a readable failure. Add a max-iteration guard so a regression produces a clear assertion failure rather than a hang.</violation>
</file>
<file name="packages/chat/tsconfig.json">
<violation number="1" location="packages/chat/tsconfig.json:7">
P3: The paths bridge is not actually type-only: src/testing/memoryStream/memoryStream.ts value-imports `createWsSink` from "@superset/chat-runtime", and value imports from "@superset/chat-runtime/testing" appear in tests, while chat's package.json declares no @superset/chat-runtime dependency. This resolves only because tsconfig paths point at the sibling package's source plus Bun's workspace symlinks, so it silently depends on the monorepo layout and pulls chat-runtime's transitive deps (@trpc/server, better-sqlite3, drizzle-orm) into chat's type-check scope. Consider declaring @superset/chat-runtime as a devDependency (matching how other packages declare workspace deps) so the value imports resolve through package exports rather than the hardcoded ../chat-runtime/src path, or keep these truly type-only.</violation>
</file>
<file name="packages/chat/src/client/subscribeToSession/subscribeToSession.ts">
<violation number="1" location="packages/chat/src/client/subscribeToSession/subscribeToSession.ts:130">
P2: For open-then-immediately-dropped connections (flapping), the exponential backoff never escalates: `attempts` is reset to 0 on every `onopen`, so each open→close cycle reconnects after just `backoffInitialMs`, producing a tight reconnect loop instead of backing off. The current test even asserts delays stay at `[100, 100]` after a successful open. Consider only resetting `attempts` to 0 once a connection has been stable for some duration (for example reset it in `onopen` only if the previous connection stayed open past a threshold, or track consecutive quick-open-then-close failures separately) so genuine backoff still kicks in for flapping endpoints.</violation>
<violation number="2" location="packages/chat/src/client/subscribeToSession/subscribeToSession.ts:143">
P3: The `onerror` handler is empty, so the stream relies entirely on `onclose` to detect and schedule reconnects. Since `createSocket` is an injectable transport (not only a browser WebSocket, where error is guaranteed to be followed by close), a transport that surfaces failure via `error` without a `close` leaves the stream wedged in 'connecting' forever and the failure is invisible to `onStatusChange`. Consider wiring `onerror` to at least reconcile state (e.g. treat it like a close and schedule a reconnect) rather than ignoring it.</violation>
</file>
Architecture diagram
sequenceDiagram
participant App as React App
participant useChat as useChatSession Hook
participant Outbox as Outbox
participant SessionClient as SessionClient
participant Transport as ChatTransport (tRPC caller)
participant WS as subscribeToSession WS Stream
participant Runtime as ChatRuntime
participant DB as Database (via Runtime)
participant MemStream as MemoryStreamServer (test)
Note over App,MemStream: PR introduces: client WS reconnecting stream, typed session client, and React hooks
App->>useChat: mount with client, deltas, pageSize
useChat->>SessionClient: getSession()
SessionClient->>Transport: getSession({sessionId})
Transport-->>SessionClient: session metadata + cursor
useChat->>SessionClient: getItems({limit: pageSize})
SessionClient->>Transport: getItems({sessionId, limit})
Transport-->>SessionClient: page of envelopes + nextBefore cursor
useChat->>useChat: reduceMany(emptySnapshot, page envelopes)
useChat->>useChat: set status = "ready"
useChat->>SessionClient: subscribe({deltas, since, onEnvelope, onReset, onStatusChange})
SessionClient->>WS: subscribeToSession({url(since), createSocket, ...})
Note over WS: NEW: Reconnecting WS consumer with cursor resume, exponential backoff
WS->>WS: connect to ws://.../sessions/{id}/stream?since=...&deltas=...
WS-->>SessionClient: onStatusChange("open")
App->>useChat: sendPrompt([{type:"text", text:"hello"}])
useChat->>Outbox: enqueue(content)
Outbox-->>useChat: outbox snapshot (1 pending)
useChat->>Outbox: flush()
Outbox->>SessionClient: prompt({clientId, commandId, content})
SessionClient->>Transport: prompt({sessionId, commandId, clientId, content})
Transport->>Runtime: execute prompt command
Runtime->>DB: persist user message
Runtime->>Runtime: publish envelopes (turn start, item, turn end, session idle)
Runtime-->>WS: broadcast envelopes via subscription sink
WS-->>SessionClient: onEnvelope(envelope)
SessionClient->>useChat: enqueue(envelope)
Note over useChat: NEW: One commit per frame with RN-safe scheduler fallback
alt Frame scheduler fires
useChat->>useChat: confirmEchoes(outbox, batch) — clears outbox on clientId echo
useChat->>useChat: reduceMany(prev, batch)
useChat-->>App: re-render with updated snapshot
end
alt Stream drops (network error)
WS-->>SessionClient: onStatusChange("closed")
SessionClient->>useChat: setConnection("closed")
WS->>WS: scheduleReconnect() with exponential backoff
Note over WS: CHANGED: Reset-keeps-connection, injectable backoff
WS-->>SessionClient: onStatusChange("connecting")
alt Reconnect succeeds
WS->>WS: connect with last known cursor
Runtime-->>WS: replay missed envelopes from cursor
WS-->>SessionClient: onStatusChange("open")
end
end
alt Stream sends reset envelope (epoch changed)
Runtime->>Runtime: publish reset envelope
WS-->>SessionClient: onEnvelope(reset)
WS->>WS: cursor = null
WS-->>SessionClient: onReset("epoch_changed")
SessionClient->>useChat: enqueue(reset)
useChat->>useChat: set pendingReset
useChat->>SessionClient: getItems({limit: pageSize}) — auto-resync
SessionClient->>Transport: getItems({sessionId, limit})
Transport-->>SessionClient: full page of envelopes
useChat->>useChat: reduceMany(prev with cursor=null), clear pendingReset
end
App->>useChat: loadOlder()
useChat->>SessionClient: getItems({before: nextBefore, limit: pageSize})
SessionClient->>Transport: getItems({sessionId, before, limit})
Transport-->>SessionClient: older page + new nextBefore
Note over useChat: NEW: Older-merges-under semantics (older turns/items prepended)
useChat->>useChat: merge older turns/items before current ones
useChat-->>App: re-render
App->>useChat: respondToApproval(approvalId, decision)
useChat->>SessionClient: respondToApproval(approvalId, decision)
Note over useChat: NEW: useApprovals hook derives pending approvals via useMemo
App->>useChat: setMode(modeId)
useChat->>SessionClient: setMode(modeId)
App->>useChat: unmount
useChat->>SessionClient: close()
SessionClient->>WS: close()
WS-->>SessionClient: onStatusChange("closed")
Note over MemStream: NEW: In-memory stream server for tests (createMemoryStreamServer)
Note over MemStream: simulates WS open/close/drop, parse since+deltas from URL
Note over useChat: 32 tests cover reconnect, pagination, hook parity
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| ); | ||
|
|
||
| const resync = useCallback(async () => { | ||
| if (resyncingRef.current) return; |
There was a problem hiding this comment.
P2: Switching the hook to a new client while a previous resync is pending can strand the new client's reset because the shared in-flight guard suppresses its fetch. Scope the guard to the client/generation or reset and re-run it when the client changes.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.ts, line 126:
<comment>Switching the hook to a new client while a previous resync is pending can strand the new client's reset because the shared in-flight guard suppresses its fetch. Scope the guard to the client/generation or reset and re-run it when the client changes.</comment>
<file context>
@@ -0,0 +1,267 @@
+ );
+
+ const resync = useCallback(async () => {
+ if (resyncingRef.current) return;
+ resyncingRef.current = true;
+ try {
</file context>
| try { | ||
| const page = await client.getItems({ limit: pageSize }); | ||
| if (clientRef.current !== client) return; | ||
| if (!page.ok) return; |
There was a problem hiding this comment.
P2: A failed reset fetch leaves pendingReset permanently set without retrying or exposing an error, so the hook can remain in reset state while subsequent stream frames are reduced against the stale snapshot. Handle the failed page result with an explicit retry/error transition rather than silently returning.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.ts, line 131:
<comment>A failed reset fetch leaves `pendingReset` permanently set without retrying or exposing an error, so the hook can remain in reset state while subsequent stream frames are reduced against the stale snapshot. Handle the failed page result with an explicit retry/error transition rather than silently returning.</comment>
<file context>
@@ -0,0 +1,267 @@
+ try {
+ const page = await client.getItems({ limit: pageSize });
+ if (clientRef.current !== client) return;
+ if (!page.ok) return;
+ nextBeforeRef.current = page.nextBefore;
+ setHasOlder(page.nextBefore !== null);
</file context>
| if (cancelled) return; | ||
| let seeded = emptySnapshot(); | ||
| if (page.ok) { | ||
| seeded = reduceMany(seeded, page.envelopes); |
There was a problem hiding this comment.
P2: A prompt echoed in a fetched page can remain in the outbox even though its durable item is already included in the snapshot; when seed advances the stream cursor past that item, no later echo clears it and retry can submit a duplicate. Apply the same client-id echo confirmation to every fetched page before replacing or merging the snapshot.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.ts, line 167:
<comment>A prompt echoed in a fetched page can remain in the outbox even though its durable item is already included in the snapshot; when seed advances the stream cursor past that item, no later echo clears it and retry can submit a duplicate. Apply the same client-id echo confirmation to every fetched page before replacing or merging the snapshot.</comment>
<file context>
@@ -0,0 +1,267 @@
+ if (cancelled) return;
+ let seeded = emptySnapshot();
+ if (page.ok) {
+ seeded = reduceMany(seeded, page.envelopes);
+ nextBeforeRef.current = page.nextBefore;
+ setHasOlder(page.nextBefore !== null);
</file context>
| onStatusChange: setConnection, | ||
| }); | ||
| }; | ||
| void seed(); |
There was a problem hiding this comment.
P2: A transport rejection during initial seed or reset resync becomes an unhandled promise rejection, leaving the hook stuck in loading or with stale reset state. Catch these asynchronous flows and surface a recoverable error or retry state instead of discarding the returned promise.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.ts, line 183:
<comment>A transport rejection during initial seed or reset resync becomes an unhandled promise rejection, leaving the hook stuck in `loading` or with stale reset state. Catch these asynchronous flows and surface a recoverable error or retry state instead of discarding the returned promise.</comment>
<file context>
@@ -0,0 +1,267 @@
+ onStatusChange: setConnection,
+ });
+ };
+ void seed();
+
+ return () => {
</file context>
| socket = next; | ||
| next.onopen = () => { | ||
| if (socket !== next) return; | ||
| attempts = 0; |
There was a problem hiding this comment.
P2: For open-then-immediately-dropped connections (flapping), the exponential backoff never escalates: attempts is reset to 0 on every onopen, so each open→close cycle reconnects after just backoffInitialMs, producing a tight reconnect loop instead of backing off. The current test even asserts delays stay at [100, 100] after a successful open. Consider only resetting attempts to 0 once a connection has been stable for some duration (for example reset it in onopen only if the previous connection stayed open past a threshold, or track consecutive quick-open-then-close failures separately) so genuine backoff still kicks in for flapping endpoints.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/client/subscribeToSession/subscribeToSession.ts, line 130:
<comment>For open-then-immediately-dropped connections (flapping), the exponential backoff never escalates: `attempts` is reset to 0 on every `onopen`, so each open→close cycle reconnects after just `backoffInitialMs`, producing a tight reconnect loop instead of backing off. The current test even asserts delays stay at `[100, 100]` after a successful open. Consider only resetting `attempts` to 0 once a connection has been stable for some duration (for example reset it in `onopen` only if the previous connection stayed open past a threshold, or track consecutive quick-open-then-close failures separately) so genuine backoff still kicks in for flapping endpoints.</comment>
<file context>
@@ -0,0 +1,161 @@
+ socket = next;
+ next.onopen = () => {
+ if (socket !== next) return;
+ attempts = 0;
+ setStatus("open");
+ };
</file context>
| } | ||
|
|
||
| let latest: ChatSession | null = null; | ||
| let renders = 0; |
There was a problem hiding this comment.
P3: The module-level latest/renders state in the shared Probe component is never reset between tests, so tests are coupled through shared mutable globals (e.g., renders accumulates across the whole file). This is fragile if tests are ever run concurrently or reordered, since session() reads whichever render wrote latest last. Prefer returning the hook result from each test or resetting the counters in a beforeEach.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.test.tsx, line 94:
<comment>The module-level `latest`/`renders` state in the shared `Probe` component is never reset between tests, so tests are coupled through shared mutable globals (e.g., `renders` accumulates across the whole file). This is fragile if tests are ever run concurrently or reordered, since `session()` reads whichever render wrote `latest` last. Prefer returning the hook result from each test or resetting the counters in a `beforeEach`.</comment>
<file context>
@@ -0,0 +1,298 @@
+}
+
+let latest: ChatSession | null = null;
+let renders = 0;
+
+function Probe(props: {
</file context>
| expect(session().hasOlder).toBe(true); | ||
| const seededCount = session().snapshot.items.size; | ||
|
|
||
| while (session().hasOlder) { |
There was a problem hiding this comment.
P3: The while (session().hasOlder) loop in the loadOlder test has no upper bound, so if the hook's paging logic regresses (e.g., nextBefore never becomes null or hasOlder stays true), this test never terminates and hangs until the runner timeout instead of failing fast with a readable failure. Add a max-iteration guard so a regression produces a clear assertion failure rather than a hang.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/react/useChatSession/useChatSession.test.tsx, line 238:
<comment>The `while (session().hasOlder)` loop in the loadOlder test has no upper bound, so if the hook's paging logic regresses (e.g., `nextBefore` never becomes `null` or `hasOlder` stays true), this test never terminates and hangs until the runner timeout instead of failing fast with a readable failure. Add a max-iteration guard so a regression produces a clear assertion failure rather than a hang.</comment>
<file context>
@@ -0,0 +1,298 @@
+ expect(session().hasOlder).toBe(true);
+ const seededCount = session().snapshot.items.size;
+
+ while (session().hasOlder) {
+ await act(async () => {
+ await session().loadOlder();
</file context>
| "lib": ["ES2022"], | ||
| "jsx": "react-jsx", | ||
| "paths": { | ||
| "@superset/chat-runtime": ["../chat-runtime/src/index.ts"], |
There was a problem hiding this comment.
P3: The paths bridge is not actually type-only: src/testing/memoryStream/memoryStream.ts value-imports createWsSink from "@superset/chat-runtime", and value imports from "@superset/chat-runtime/testing" appear in tests, while chat's package.json declares no @superset/chat-runtime dependency. This resolves only because tsconfig paths point at the sibling package's source plus Bun's workspace symlinks, so it silently depends on the monorepo layout and pulls chat-runtime's transitive deps (@trpc/server, better-sqlite3, drizzle-orm) into chat's type-check scope. Consider declaring @superset/chat-runtime as a devDependency (matching how other packages declare workspace deps) so the value imports resolve through package exports rather than the hardcoded ../chat-runtime/src path, or keep these truly type-only.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/tsconfig.json, line 7:
<comment>The paths bridge is not actually type-only: src/testing/memoryStream/memoryStream.ts value-imports `createWsSink` from "@superset/chat-runtime", and value imports from "@superset/chat-runtime/testing" appear in tests, while chat's package.json declares no @superset/chat-runtime dependency. This resolves only because tsconfig paths point at the sibling package's source plus Bun's workspace symlinks, so it silently depends on the monorepo layout and pulls chat-runtime's transitive deps (@trpc/server, better-sqlite3, drizzle-orm) into chat's type-check scope. Consider declaring @superset/chat-runtime as a devDependency (matching how other packages declare workspace deps) so the value imports resolve through package exports rather than the hardcoded ../chat-runtime/src path, or keep these truly type-only.</comment>
<file context>
@@ -1,9 +1,13 @@
+ "lib": ["ES2022"],
+ "jsx": "react-jsx",
+ "paths": {
+ "@superset/chat-runtime": ["../chat-runtime/src/index.ts"],
+ "@superset/chat-runtime/testing": ["../chat-runtime/src/testing/index.ts"]
+ }
</file context>
| setStatus("closed"); | ||
| scheduleReconnect(); | ||
| }; | ||
| next.onerror = () => {}; |
There was a problem hiding this comment.
P3: The onerror handler is empty, so the stream relies entirely on onclose to detect and schedule reconnects. Since createSocket is an injectable transport (not only a browser WebSocket, where error is guaranteed to be followed by close), a transport that surfaces failure via error without a close leaves the stream wedged in 'connecting' forever and the failure is invisible to onStatusChange. Consider wiring onerror to at least reconcile state (e.g. treat it like a close and schedule a reconnect) rather than ignoring it.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat/src/client/subscribeToSession/subscribeToSession.ts, line 143:
<comment>The `onerror` handler is empty, so the stream relies entirely on `onclose` to detect and schedule reconnects. Since `createSocket` is an injectable transport (not only a browser WebSocket, where error is guaranteed to be followed by close), a transport that surfaces failure via `error` without a `close` leaves the stream wedged in 'connecting' forever and the failure is invisible to `onStatusChange`. Consider wiring `onerror` to at least reconcile state (e.g. treat it like a close and schedule a reconnect) rather than ignoring it.</comment>
<file context>
@@ -0,0 +1,161 @@
+ setStatus("closed");
+ scheduleReconnect();
+ };
+ next.onerror = () => {};
+ }
+
</file context>
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
Chunk B of plans/chat-v3-pane-mount.md. ./client: reconnecting WS consumer (envelope-parsed frames, cursor resume, reset-keeps-connection, injectable backoff) + sessionClient over a structural ChatTransport typed via type-only ChatRouterInputs/Outputs — no runtime dep on chat-runtime (tsconfig-paths type bridge; avoids the turbo package cycle) and no @trpc/server in the client package. ./react: useChatSession (seed→reduce→live tail, outbox clientId-echo clearing, one commit per frame with RN-safe scheduler fallback, loadOlder with older-merges-under semantics, auto-resync on reset) + useTimeline/useApprovals. 32 tests incl. hook-level reconnect parity against a real runtime over an in-memory socket pair.
https://claude.ai/code/session_01XRFCEPsfmJHu2SenDKYJ2h
Summary by cubic
Adds a reconnecting session stream, a typed session client, and React hooks for chat sessions. This delivers reliable live updates with resume, pagination, and a simple API for apps.
New Features
@superset/chatclientsubscribeToSession: reconnecting stream with since-cursor resume, reset handling, and configurable exponential backoff.createSessionClient: typed transport overChatRouterInputs/Outputs(no runtime dep), prompt dedupe bycommandId, item pagination, approvals/mode/turn controls, and multiple managed streams.@superset/chatReactuseChatSession: seeds viagetSession+getItems, batches live frames into one commit per animation frame (RN-safe timeout fallback), clears outbox on clientId echo, loads older pages, and auto-resyncs on stream reset.useTimelineanduseApprovals: memoized derived views of the session snapshot.Refactors
@superset/chat-runtime: adds./testingexport for cross-package tests and exposesChatRouterInputs/Outputsfor client typing.@superset/chat: adds./clientand./reactentry points; uses a tsconfig type-only bridge to avoid a package cycle; no@trpc/serverin the client.Written for commit f98ceec. Summary will update on new commits.
Summary by CodeRabbit
New Features
Tests