Repository navigation
fix(tui): subscribe to live session transcript updates - #73402
vincentkoc wants to merge 1 commit into
Conversation
🔒 Aisle Security AnalysisWe found 4 potential security issue(s) in this PR:
1. 🟠 Missing authorization on sessions.messages.subscribe/unsubscribe allows subscribing to arbitrary session transcripts
DescriptionThe gateway RPC handlers for live session message subscriptions accept a caller-supplied
As a result, any client with access to these RPC methods can subscribe to message events for any session key they can guess/obtain, potentially receiving other users’/tenants’ conversation data. Vulnerable code: const key = requireSessionKey((params as { key?: unknown }).key, respond);
...
const { canonicalKey } = loadSessionEntry(key);
if (connId) {
context.subscribeSessionMessageEvents(connId, canonicalKey);
respond(true, { subscribed: true, key: canonicalKey }, undefined);
return;
}RecommendationEnforce per-session authorization before subscribing/unsubscribing. At minimum, verify that the authenticated client identity (operator/user/plugin) is allowed to access the target session. For example, if sessions have an owner field (e.g. Example (sketch): const { entry, canonicalKey } = loadSessionEntry(key);
if (!entry) {
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unknown session"));
return;
}
const pluginOwnerId = normalizeOptionalString(client?.internal?.pluginRuntimeOwnerId);
if (pluginOwnerId && normalizeOptionalString(entry.pluginOwnerId) !== pluginOwnerId) {
respond(false, undefined, errorShape(ErrorCodes.FORBIDDEN, "not authorized for session"));
return;
}
context.subscribeSessionMessageEvents(connId, canonicalKey);Additionally:
2. 🟡 Client-side DoS via unthrottled `session.message` events triggering repeated `loadHistory()`
Description
Vulnerable code: void refreshSessionInfo?.();
if (state.activeChatRunId) {
pendingHistoryRefresh = true;
return;
}
pendingHistoryRefresh = false;
void loadHistory?.();RecommendationDebounce/coalesce Example (simple debounce with in-flight guard): let historyRefreshTimer: NodeJS.Timeout | null = null;
let historyRefreshInFlight = false;
const scheduleHistoryRefresh = () => {
if (historyRefreshTimer) clearTimeout(historyRefreshTimer);
historyRefreshTimer = setTimeout(async () => {
if (historyRefreshInFlight) return;
historyRefreshInFlight = true;
try {
await refreshSessionInfo?.();
if (!state.activeChatRunId) {
await loadHistory?.();
} else {
pendingHistoryRefresh = true;
}
} finally {
historyRefreshInFlight = false;
}
}, 250); // tune window
};Also consider:
3. 🟡 Terminal control-sequence injection via unsanitized error text in TUI system messages
DescriptionThe TUI surfaces subscription errors directly into the chat log without sanitizing control characters:
This can allow terminal/control-sequence injection (e.g., screen clearing, cursor movement, deceptive prompts) and also risks leaking sensitive internal error details into the UI. Vulnerable code: const report = (action: string, key: string, err: unknown) => {
params.onError?.(`session message ${action} failed for ${key}: ${String(err)}`);
};and the sink: onError: (message) => {
chatLog.addSystem(message);
tui.requestRender();
},RecommendationSanitize/escape untrusted strings before rendering them in the terminal, and avoid echoing raw error objects.
Example fix: function stripTerminalControls(input: string): string {
// Remove ANSI escape codes
const noAnsi = input.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
// Remove other control chars except tab/newline if you want to keep them
return noAnsi.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
}
const report = (action: string, key: string, err: unknown) => {
const safeKey = stripTerminalControls(String(key));
const safeErr = stripTerminalControls(err instanceof Error ? (err.message ?? String(err)) : String(err));
params.onError?.(`session message ${action} failed for ${safeKey}: ${safeErr}`);
};Optionally, replace 4. 🔵 Subscription confusion via trusting server-returned session key for unsubscribe operations
DescriptionThe session message subscription controller stores the server-returned
If the gateway/server is buggy, malicious, or compromised, it can return an arbitrary key (including keys for other sessions or keys containing control characters). This can cause the client to send unsubscribe requests for a different session than intended (subscription confusion / confused-deputy style behavior). In systems where server-side authorization checks are imperfect, this could impact other sessions’ message streams. Even with correct server auth, allowing arbitrary keys may lead to log/UI injection if the key is ever surfaced elsewhere. Vulnerable code: const result = await params.client.subscribeSessionMessages({ key });
if (syncGeneration === generation && result.key.trim()) {
activeKey = result.key;
}RecommendationDo not trust
Example fix (strict equality): const result = await params.client.subscribeSessionMessages({ key });
if (syncGeneration === generation) {
if (typeof result.key === "string" && result.key.trim() === key) {
activeKey = key;
} else {
// ignore/raise error; keep activeKey as the requested key or null
activeKey = key;
params.onError?.(`Unexpected subscription key returned by server`);
}
}If canonicalization is required, implement a Analyzed PR: #73402 at commit Last updated on: 2026-04-28T08:00:40Z |
Greptile SummaryThis PR adds live transcript subscription support to the bundled TUI gateway client, fixing the real-time message delivery gap reported in #38829. It introduces a generation-based Confidence Score: 4/5Safe to merge; two minor P2 issues that do not affect correctness on the happy path. No P0 or P1 issues found. Two P2 findings: (1) activeKey stored without trimming while the dedup guard uses a trimmed comparison, which could cause spurious resubscription cycles if the server returns keys with whitespace; (2) handleSessionMessageEvent omits the conventional tui.requestRender() call present in all other handlers, risking a stale paint in the deferred-refresh path. Logic for session filtering, concurrency safety, and deferred reloads is sound and well-covered by new tests. src/tui/tui.ts (key trimming in subscription controller) and src/tui/tui-event-handlers.ts (missing render call). Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/tui/tui-event-handlers.ts
Line: 517-538
Comment:
**Missing `tui.requestRender()` breaks the handler convention**
Every other handler (`handleChatEvent`, `handleAgentEvent`, `handleBtwEvent`) ends with `tui.requestRender()`. `handleSessionMessageEvent` never calls it. When a live message arrives and `state.activeChatRunId` is set, the function sets `pendingHistoryRefresh = true` and returns without scheduling a render; `refreshSessionInfo` is fire-and-forget (`void`). If the session-info callback doesn't internally call `requestRender`, the activity-status update from that call won't be painted until the next unrelated event triggers a render cycle.
```suggestion
void refreshSessionInfo?.();
if (state.activeChatRunId) {
pendingHistoryRefresh = true;
tui.requestRender();
return;
}
pendingHistoryRefresh = false;
void loadHistory?.();
tui.requestRender();
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/tui/tui.ts
Line: 113-117
Comment:
**Inconsistent key trimming may cause repeated resubscription**
`activeKey` is stored directly as `result.key` without trimming, but the early-exit guard compares the trimmed `getSessionKey()` output against `activeKey`. If the server echoes back the key with surrounding whitespace, `"session:A" === " session:A "` is false, so every subsequent `syncActiveSessionSubscription` call bypasses the dedup check and issues a fresh unsubscribe + subscribe without ever converging.
Consider storing `result.key.trim()` into `activeKey` to match the trimmed comparison used in the guard condition.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(tui): subscribe to live session tran..." | Re-trigger Greptile |
| const handleSessionMessageEvent = (payload: unknown) => { | ||
| if (!payload || typeof payload !== "object") { | ||
| return; | ||
| } | ||
| const evt = payload as { sessionKey?: unknown }; | ||
| syncSessionKey(); | ||
| if ( | ||
| !isSameSessionKey( | ||
| typeof evt.sessionKey === "string" ? evt.sessionKey : undefined, | ||
| state.currentSessionKey, | ||
| ) | ||
| ) { | ||
| return; | ||
| } | ||
| void refreshSessionInfo?.(); | ||
| if (state.activeChatRunId) { | ||
| pendingHistoryRefresh = true; | ||
| return; | ||
| } | ||
| pendingHistoryRefresh = false; | ||
| void loadHistory?.(); | ||
| }; |
There was a problem hiding this comment.
Missing
tui.requestRender() breaks the handler convention
Every other handler (handleChatEvent, handleAgentEvent, handleBtwEvent) ends with tui.requestRender(). handleSessionMessageEvent never calls it. When a live message arrives and state.activeChatRunId is set, the function sets pendingHistoryRefresh = true and returns without scheduling a render; refreshSessionInfo is fire-and-forget (void). If the session-info callback doesn't internally call requestRender, the activity-status update from that call won't be painted until the next unrelated event triggers a render cycle.
| const handleSessionMessageEvent = (payload: unknown) => { | |
| if (!payload || typeof payload !== "object") { | |
| return; | |
| } | |
| const evt = payload as { sessionKey?: unknown }; | |
| syncSessionKey(); | |
| if ( | |
| !isSameSessionKey( | |
| typeof evt.sessionKey === "string" ? evt.sessionKey : undefined, | |
| state.currentSessionKey, | |
| ) | |
| ) { | |
| return; | |
| } | |
| void refreshSessionInfo?.(); | |
| if (state.activeChatRunId) { | |
| pendingHistoryRefresh = true; | |
| return; | |
| } | |
| pendingHistoryRefresh = false; | |
| void loadHistory?.(); | |
| }; | |
| void refreshSessionInfo?.(); | |
| if (state.activeChatRunId) { | |
| pendingHistoryRefresh = true; | |
| tui.requestRender(); | |
| return; | |
| } | |
| pendingHistoryRefresh = false; | |
| void loadHistory?.(); | |
| tui.requestRender(); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/tui/tui-event-handlers.ts
Line: 517-538
Comment:
**Missing `tui.requestRender()` breaks the handler convention**
Every other handler (`handleChatEvent`, `handleAgentEvent`, `handleBtwEvent`) ends with `tui.requestRender()`. `handleSessionMessageEvent` never calls it. When a live message arrives and `state.activeChatRunId` is set, the function sets `pendingHistoryRefresh = true` and returns without scheduling a render; `refreshSessionInfo` is fire-and-forget (`void`). If the session-info callback doesn't internally call `requestRender`, the activity-status update from that call won't be painted until the next unrelated event triggers a render cycle.
```suggestion
void refreshSessionInfo?.();
if (state.activeChatRunId) {
pendingHistoryRefresh = true;
tui.requestRender();
return;
}
pendingHistoryRefresh = false;
void loadHistory?.();
tui.requestRender();
```
How can I resolve this? If you propose a fix, please make it concise.| try { | ||
| const result = await params.client.subscribeSessionMessages({ key }); | ||
| if (syncGeneration === generation && result.key.trim()) { | ||
| activeKey = result.key; | ||
| } |
There was a problem hiding this comment.
Inconsistent key trimming may cause repeated resubscription
activeKey is stored directly as result.key without trimming, but the early-exit guard compares the trimmed getSessionKey() output against activeKey. If the server echoes back the key with surrounding whitespace, "session:A" === " session:A " is false, so every subsequent syncActiveSessionSubscription call bypasses the dedup check and issues a fresh unsubscribe + subscribe without ever converging.
Consider storing result.key.trim() into activeKey to match the trimmed comparison used in the guard condition.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/tui/tui.ts
Line: 113-117
Comment:
**Inconsistent key trimming may cause repeated resubscription**
`activeKey` is stored directly as `result.key` without trimming, but the early-exit guard compares the trimmed `getSessionKey()` output against `activeKey`. If the server echoes back the key with surrounding whitespace, `"session:A" === " session:A "` is false, so every subsequent `syncActiveSessionSubscription` call bypasses the dedup check and issues a fresh unsubscribe + subscribe without ever converging.
Consider storing `result.key.trim()` into `activeKey` to match the trimmed comparison used in the guard condition.
How can I resolve this? If you propose a fix, please make it concise.|
Codex review: found issues before merge. Reviewed June 15, 2026, 1:17 PM ET / 17:17 UTC. Summary PR surface: Source +159, Tests +152, Docs +1. Total +312 across 9 files. Reproducibility: yes. at source level: current main exposes Review metrics: none identified. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Mantis proof suggestion Risk before merge
Maintainer options:
Next step before merge
Security Review findings
Review detailsBest possible solution: Carry the TUI subscription behavior onto current main, integrate it with the newer handler lifecycle, sanitize terminal-visible subscription errors, and verify a real Gateway-to-TUI live transcript update before merge. Do we have a high-confidence way to reproduce the issue? Yes, at source level: current main exposes Is this the best way to solve the issue? No, not as submitted: using the existing Gateway session-message subscription is the right owner-boundary direction, but the branch needs a main refresh and sanitized terminal error handling before it is the best mergeable fix. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 8ded75628437. Label changesLabel justifications:
Evidence reviewedPR surface: Source +159, Tests +152, Docs +1. Total +312 across 9 files. View PR surface stats
Security concerns:
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
|
|
Closing this generated ProjectClownfish fix attempt. The refreshed cluster result from https://github.com/openclaw/clownfish/actions/runs/27594977909 routes #73402 and its linked live refs through central security handling, not autonomous merge/repair. The branch is also conflicting and still lacks passing real-behavior proof, so keeping this PR open only blocks queue cleanup for ghcrawl-156978-autonomous-smoke. |
Summary
Plan
session.messageupdates by appending or reloading history in a way that does not disrupt an active local stream.Validation
pnpm check:changedCredit
Thanks @galen2017 for #38829 and @baiyiyuni for #43341. Their reports define the canonical and duplicate reproduction paths for this fix.
ProjectClownfish replacement details: