Skip to content

Commit 9421edb

Browse files
committed
fix(tui): subscribe to live session transcript updates
1 parent 04e774e commit 9421edb

9 files changed

Lines changed: 338 additions & 26 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Docs: https://docs.openclaw.ai
1313

1414
### Fixes
1515

16+
- TUI: subscribe the bundled gateway client to live transcript updates for the active session and resync idle history without widening hidden-run fanout. Fixes #38829; refs #43341. Thanks @galen2017 and @baiyiyuni.
1617
- Control UI/WebChat: keep large attachment payloads out of Lit state and optimistic chat messages, using object URL previews plus send-time payload serialization so PDF/image uploads no longer trigger `RangeError: Maximum call stack size exceeded`. Fixes #73360; refs #54378 and #63432. Thanks @hejunhui-73, @Ansub, and @christianhernandez3-afk.
1718
- Agents/models: keep per-agent primary models strict when `fallbacks` is omitted, so probe-only custom providers are not tried as hidden fallback candidates unless the agent explicitly opts in. Fixes #73332. Thanks @haumanto.
1819
- Gateway/models: add `models.pricing.enabled` so offline or restricted-network installs can skip startup OpenRouter and LiteLLM pricing-catalog fetches while keeping explicit model costs working. Fixes #53639. Thanks @callebtc, @palewire, and @rjdjohnston.

‎src/crestodian/tui-backend.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,14 @@ class CrestodianTuiBackend implements TuiBackend {
138138
return { ok: true, aborted: false };
139139
}
140140

141+
async subscribeSessionMessages(opts: Parameters<TuiBackend["subscribeSessionMessages"]>[0]) {
142+
return { subscribed: false, key: opts.key };
143+
}
144+
145+
async unsubscribeSessionMessages(opts: Parameters<TuiBackend["unsubscribeSessionMessages"]>[0]) {
146+
return { subscribed: false, key: opts.key };
147+
}
148+
141149
async loadHistory(): Promise<{
142150
sessionId: string;
143151
messages: CrestodianHistoryMessage[];

‎src/tui/embedded-backend.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,14 @@ export class EmbeddedTuiBackend implements TuiBackend {
191191
return { ok: true, aborted: true };
192192
}
193193

194+
async subscribeSessionMessages(opts: Parameters<TuiBackend["subscribeSessionMessages"]>[0]) {
195+
return { subscribed: false, key: opts.key };
196+
}
197+
198+
async unsubscribeSessionMessages(opts: Parameters<TuiBackend["unsubscribeSessionMessages"]>[0]) {
199+
return { subscribed: false, key: opts.key };
200+
}
201+
194202
async loadHistory(opts: { sessionKey: string; limit?: number }) {
195203
const { cfg, storePath, entry } = loadSessionEntry(opts.sessionKey);
196204
const sessionId = entry?.sessionId;

‎src/tui/gateway-chat.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import type {
3030
TuiBackend,
3131
TuiEvent,
3232
TuiModelChoice,
33+
TuiSessionMessageSubscriptionResult,
3334
TuiSessionList,
3435
} from "./tui-backend.js";
3536

@@ -189,6 +190,24 @@ export class GatewayChatClient implements TuiBackend {
189190
});
190191
}
191192

193+
async subscribeSessionMessages(opts: {
194+
key: string;
195+
}): Promise<TuiSessionMessageSubscriptionResult> {
196+
return await this.client.request<TuiSessionMessageSubscriptionResult>(
197+
"sessions.messages.subscribe",
198+
opts,
199+
);
200+
}
201+
202+
async unsubscribeSessionMessages(opts: {
203+
key: string;
204+
}): Promise<TuiSessionMessageSubscriptionResult> {
205+
return await this.client.request<TuiSessionMessageSubscriptionResult>(
206+
"sessions.messages.unsubscribe",
207+
opts,
208+
);
209+
}
210+
192211
async loadHistory(opts: { sessionKey: string; limit?: number }) {
193212
const startedAt = Date.now();
194213
for (;;) {

‎src/tui/tui-backend.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ export type TuiModelChoice = {
8383
reasoning?: boolean;
8484
};
8585

86+
export type TuiSessionMessageSubscriptionResult = {
87+
subscribed: boolean;
88+
key: string;
89+
};
90+
91+
export type TuiSessionMessageSubscriptionOptions = {
92+
key: string;
93+
};
94+
8695
export type TuiBackend = {
8796
connection: {
8897
url: string;
@@ -100,6 +109,12 @@ export type TuiBackend = {
100109
sessionKey: string;
101110
runId: string;
102111
}) => Promise<{ ok: boolean; aborted: boolean }>;
112+
subscribeSessionMessages: (
113+
opts: TuiSessionMessageSubscriptionOptions,
114+
) => Promise<TuiSessionMessageSubscriptionResult>;
115+
unsubscribeSessionMessages: (
116+
opts: TuiSessionMessageSubscriptionOptions,
117+
) => Promise<TuiSessionMessageSubscriptionResult>;
103118
loadHistory: (opts: { sessionKey: string; limit?: number }) => Promise<unknown>;
104119
listSessions: (opts?: SessionsListParams) => Promise<TuiSessionList>;
105120
listAgents: () => Promise<TuiAgentsList>;

‎src/tui/tui-event-handlers.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ describe("tui-event-handlers: handleAgentEvent", () => {
7878
const btw = createMockBtwPresenter();
7979
const tui = { requestRender: vi.fn() } as unknown as MockTui & HandlerTui;
8080
const setActivityStatus = vi.fn();
81+
const refreshSessionInfo = vi.fn();
8182
const loadHistory = vi.fn();
8283
const localRunIds = new Set<string>();
8384
const localBtwRunIds = new Set<string>();
@@ -100,6 +101,7 @@ describe("tui-event-handlers: handleAgentEvent", () => {
100101
tui,
101102
state,
102103
setActivityStatus,
104+
refreshSessionInfo,
103105
loadHistory,
104106
noteLocalRunId,
105107
noteLocalBtwRunId,
@@ -128,6 +130,7 @@ describe("tui-event-handlers: handleAgentEvent", () => {
128130
state,
129131
localMode: params?.localMode,
130132
setActivityStatus: context.setActivityStatus,
133+
refreshSessionInfo: context.refreshSessionInfo,
131134
loadHistory: context.loadHistory,
132135
noteLocalRunId: context.noteLocalRunId,
133136
isLocalRunId: context.isLocalRunId,
@@ -470,6 +473,80 @@ describe("tui-event-handlers: handleAgentEvent", () => {
470473
expect(loadHistory).toHaveBeenCalledTimes(1);
471474
});
472475

476+
it("reloads history when live transcript updates arrive for the active idle session", () => {
477+
const { state, refreshSessionInfo, loadHistory, handleSessionMessageEvent } =
478+
createHandlersHarness({
479+
state: {
480+
activeChatRunId: null,
481+
currentSessionKey: "agent:main:main",
482+
},
483+
});
484+
485+
handleSessionMessageEvent({
486+
sessionKey: state.currentSessionKey,
487+
message: {
488+
role: "assistant",
489+
content: [{ type: "text", text: "from telegram" }],
490+
},
491+
});
492+
493+
expect(refreshSessionInfo).toHaveBeenCalledTimes(1);
494+
expect(loadHistory).toHaveBeenCalledTimes(1);
495+
});
496+
497+
it("ignores live transcript updates for other sessions", () => {
498+
const { refreshSessionInfo, loadHistory, handleSessionMessageEvent } = createHandlersHarness({
499+
state: {
500+
activeChatRunId: null,
501+
currentSessionKey: "agent:main:main",
502+
},
503+
});
504+
505+
handleSessionMessageEvent({
506+
sessionKey: "agent:main:other",
507+
message: {
508+
role: "assistant",
509+
content: [{ type: "text", text: "other session" }],
510+
},
511+
});
512+
513+
expect(refreshSessionInfo).not.toHaveBeenCalled();
514+
expect(loadHistory).not.toHaveBeenCalled();
515+
});
516+
517+
it("defers live transcript reloads while a local stream is active", () => {
518+
const { state, loadHistory, noteLocalRunId, handleChatEvent, handleSessionMessageEvent } =
519+
createHandlersHarness({
520+
state: {
521+
activeChatRunId: "run-active",
522+
currentSessionKey: "agent:main:main",
523+
},
524+
});
525+
noteLocalRunId("run-active");
526+
527+
handleSessionMessageEvent({
528+
sessionKey: state.currentSessionKey,
529+
message: {
530+
role: "assistant",
531+
content: [{ type: "text", text: "external reply" }],
532+
},
533+
});
534+
535+
expect(loadHistory).not.toHaveBeenCalled();
536+
537+
handleChatEvent({
538+
runId: "run-active",
539+
sessionKey: state.currentSessionKey,
540+
state: "final",
541+
message: {
542+
role: "assistant",
543+
content: [{ type: "text", text: "local done" }],
544+
},
545+
});
546+
547+
expect(loadHistory).toHaveBeenCalledTimes(1);
548+
});
549+
473550
it("binds optimistic pending messages to the first gateway run id and skips history reload", () => {
474551
const { state, loadHistory, isLocalRunId, handleChatEvent } = createHandlersHarness({
475552
state: { activeChatRunId: null, pendingOptimisticUserMessage: true },

‎src/tui/tui-event-handlers.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,9 +514,32 @@ export function createEventHandlers(context: EventHandlerContext) {
514514
tui.requestRender();
515515
};
516516

517+
const handleSessionMessageEvent = (payload: unknown) => {
518+
if (!payload || typeof payload !== "object") {
519+
return;
520+
}
521+
const evt = payload as { sessionKey?: unknown };
522+
syncSessionKey();
523+
if (
524+
!isSameSessionKey(
525+
typeof evt.sessionKey === "string" ? evt.sessionKey : undefined,
526+
state.currentSessionKey,
527+
)
528+
) {
529+
return;
530+
}
531+
void refreshSessionInfo?.();
532+
if (state.activeChatRunId) {
533+
pendingHistoryRefresh = true;
534+
return;
535+
}
536+
pendingHistoryRefresh = false;
537+
void loadHistory?.();
538+
};
539+
517540
const dispose = () => {
518541
clearStreamingWatchdog();
519542
};
520543

521-
return { handleChatEvent, handleAgentEvent, handleBtwEvent, dispose };
544+
return { handleChatEvent, handleAgentEvent, handleBtwEvent, handleSessionMessageEvent, dispose };
522545
}

‎src/tui/tui.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { OpenClawConfig } from "../config/config.js";
33
import { getSlashCommands, parseCommand } from "./commands.js";
44
import {
55
createBackspaceDeduper,
6+
createTuiSessionMessageSubscriptionController,
67
drainAndStopTuiSafely,
78
isIgnorableTuiStopError,
89
resolveCodexCliBin,
@@ -179,6 +180,80 @@ describe("resolveGatewayDisconnectState", () => {
179180
});
180181
});
181182

183+
describe("createTuiSessionMessageSubscriptionController", () => {
184+
const createClient = () => ({
185+
subscribeSessionMessages: vi.fn(async ({ key }: { key: string }) => ({
186+
subscribed: true,
187+
key,
188+
})),
189+
unsubscribeSessionMessages: vi.fn(async ({ key }: { key: string }) => ({
190+
subscribed: false,
191+
key,
192+
})),
193+
});
194+
195+
it("subscribes once to the active session", async () => {
196+
const client = createClient();
197+
const controller = createTuiSessionMessageSubscriptionController({
198+
client,
199+
getSessionKey: () => "agent:main:main",
200+
});
201+
202+
await controller.syncActiveSessionSubscription();
203+
await controller.syncActiveSessionSubscription();
204+
205+
expect(client.subscribeSessionMessages).toHaveBeenCalledTimes(1);
206+
expect(client.subscribeSessionMessages).toHaveBeenCalledWith({ key: "agent:main:main" });
207+
expect(client.unsubscribeSessionMessages).not.toHaveBeenCalled();
208+
expect(controller.getActiveSubscriptionKey()).toBe("agent:main:main");
209+
});
210+
211+
it("unsubscribes the stale session before subscribing the next session", async () => {
212+
const client = createClient();
213+
let sessionKey = "agent:main:main";
214+
const controller = createTuiSessionMessageSubscriptionController({
215+
client,
216+
getSessionKey: () => sessionKey,
217+
});
218+
219+
await controller.syncActiveSessionSubscription();
220+
sessionKey = "agent:main:other";
221+
await controller.syncActiveSessionSubscription();
222+
223+
expect(client.unsubscribeSessionMessages).toHaveBeenCalledWith({ key: "agent:main:main" });
224+
expect(client.subscribeSessionMessages).toHaveBeenLastCalledWith({ key: "agent:main:other" });
225+
expect(controller.getActiveSubscriptionKey()).toBe("agent:main:other");
226+
});
227+
228+
it("resubscribes the same session after reconnect", async () => {
229+
const client = createClient();
230+
const controller = createTuiSessionMessageSubscriptionController({
231+
client,
232+
getSessionKey: () => "agent:main:main",
233+
});
234+
235+
await controller.syncActiveSessionSubscription();
236+
controller.markDisconnected();
237+
await controller.syncActiveSessionSubscription();
238+
239+
expect(client.subscribeSessionMessages).toHaveBeenCalledTimes(2);
240+
});
241+
242+
it("unsubscribes the active session on stop", async () => {
243+
const client = createClient();
244+
const controller = createTuiSessionMessageSubscriptionController({
245+
client,
246+
getSessionKey: () => "agent:main:main",
247+
});
248+
249+
await controller.syncActiveSessionSubscription();
250+
await controller.unsubscribeActiveSession();
251+
252+
expect(client.unsubscribeSessionMessages).toHaveBeenCalledWith({ key: "agent:main:main" });
253+
expect(controller.getActiveSubscriptionKey()).toBeNull();
254+
});
255+
});
256+
182257
describe("createBackspaceDeduper", () => {
183258
function createTimedDedupe(start = 1000) {
184259
let now = start;

0 commit comments

Comments
 (0)