1- import { readSessionMessageIdentity } from "@openclaw/gateway-client/browser" ;
21import { asNullableRecord } from "@openclaw/normalization-core/record-coerce" ;
32import type { SessionObserverDigest } from "../../../../packages/gateway-protocol/src/schema/sessions.js" ;
4- import {
5- isToolCallContentType ,
6- isToolResultContentType ,
7- } from "../../../../src/chat/tool-content.js" ;
83import type { GatewayEventFrame } from "../../api/gateway.ts" ;
94import { fireFirstReplyConfetti } from "../../components/confetti.ts" ;
105import { isGitHubPullRequestLink } from "../../components/github-link-target.ts" ;
@@ -45,8 +40,6 @@ import { refreshCurrentChatSessionList } from "./chat-session.ts";
4540import type { ChatPageHost } from "./chat-state-host.ts" ;
4641import { requestChatPageUpdate } from "./chat-state-render.ts" ;
4742import { resolveChatAgentId , selectedChatSessionRow } from "./chat-state-route.ts" ;
48- import { transcriptRunId } from "./chat-thread-run-identity.ts" ;
49- import { safeNormalizeMessage } from "./chat-turn-boundary.ts" ;
5043import { handleBackgroundTasksEvent } from "./components/chat-background-tasks.ts" ;
5144import {
5245 refreshSessionWorkspace ,
@@ -70,10 +63,12 @@ import {
7063import { applySessionMessagePayload } from "./session-message-apply.ts" ;
7164import { isSidebarSlotVisible } from "./sidebar-layout.ts" ;
7265import { rememberAuthoritativeTerminal } from "./terminal-message-identity.ts" ;
66+ import { readTerminalReplyRecoveryState } from "./terminal-reply-recovery.ts" ;
7367import { handleAgentEvent , handleSessionOperationEvent } from "./tool-stream.ts" ;
7468
7569const BRANCH_TOPOLOGY_REASONS = new Set ( [ "rewind" , "branch-switch" , "fork" , "reset" , "new" ] ) ;
7670const MISSING_TERMINAL_HISTORY_RETRY_DELAYS_MS = [ 100 , 400 , 1_500 , 3_000 ] as const ;
71+ const MAX_REMEMBERED_TERMINAL_RECOVERY_CLAIMS = 64 ;
7772type ChatPanePresentation = ( ) => boolean ;
7873
7974function sessionMessageMatchesChat (
@@ -230,43 +225,79 @@ function replayPendingSessionMessageReload(
230225 return true ;
231226}
232227
233- function hasRecoveredTerminalReply ( state : ChatPageHost , runId : string ) : boolean {
234- const scope = readChatSessionProjectionScope ( state ) ;
235- const projection = getChatSessionProjection ( state , state . chatMessages , scope ) ;
236- const message =
237- projection . runs [ runId ] ?. message ??
238- projection . messages . findLast (
239- ( candidate ) =>
240- readSessionMessageIdentity ( candidate ) ?. role === "assistant" &&
241- transcriptRunId ( candidate ) === runId ,
242- ) ;
243- const text = extractText ( message ) ;
244- if (
245- typeof text === "string" &&
246- text . trim ( ) . length > 0 &&
247- ! isHiddenAssistantStreamText ( text ) &&
248- ! shouldHideAssistantChatMessage ( message )
249- ) {
250- return true ;
251- }
252- if ( shouldHideAssistantChatMessage ( message ) ) {
253- return false ;
254- }
255- return ( safeNormalizeMessage ( message ) ?. content ?? [ ] ) . some ( ( block ) => {
256- const type = block . type ;
257- return type !== "text" && ! isToolCallContentType ( type ) && ! isToolResultContentType ( type ) ;
258- } ) ;
259- }
260-
261228type TerminalRecoveryOwnership = {
262229 sessionKey : string ;
263230 agentId : string ;
264231 runId : string ;
265232 client : ChatPageHost [ "client" ] ;
266233 connectionEpoch : number ;
267234 runLifecycleGeneration : number ;
235+ initialTerminalReplySignatures : ReadonlySet < string > ;
268236} ;
269237
238+ const terminalRecoveryClaimsByPane = new WeakMap < object , Map < string , ChatPageHost [ "client" ] > > ( ) ;
239+
240+ function createTerminalRecoveryOwnership (
241+ state : ChatPageHost ,
242+ payload : ChatEventPayload ,
243+ ) : TerminalRecoveryOwnership | null {
244+ const runId = payload . runId ;
245+ if ( ! runId ) {
246+ return null ;
247+ }
248+ return {
249+ sessionKey : payload . sessionKey ,
250+ agentId : resolveChatAgentId ( state ) ,
251+ runId,
252+ client : state . client ,
253+ connectionEpoch : state . connectionEpoch ,
254+ runLifecycleGeneration : state . chatRunLifecycleGeneration ?? 0 ,
255+ initialTerminalReplySignatures : readTerminalReplyRecoveryState ( state , runId )
256+ . terminalReplySignatures ,
257+ } ;
258+ }
259+
260+ function claimTerminalRecovery ( state : ChatPageHost , ownership : TerminalRecoveryOwnership ) : boolean {
261+ let claims = terminalRecoveryClaimsByPane . get ( state ) ;
262+ if ( ! claims ) {
263+ claims = new Map ( ) ;
264+ terminalRecoveryClaimsByPane . set ( state , claims ) ;
265+ }
266+ const key = [
267+ ownership . connectionEpoch ,
268+ ownership . runLifecycleGeneration ,
269+ ownership . agentId ,
270+ ownership . sessionKey ,
271+ ownership . runId ,
272+ ] . join ( "\0" ) ;
273+ if ( claims . has ( key ) && claims . get ( key ) === ownership . client ) {
274+ return false ;
275+ }
276+ claims . delete ( key ) ;
277+ claims . set ( key , ownership . client ) ;
278+ while ( claims . size > MAX_REMEMBERED_TERMINAL_RECOVERY_CLAIMS ) {
279+ const oldest = claims . keys ( ) . next ( ) . value ;
280+ if ( typeof oldest !== "string" ) {
281+ break ;
282+ }
283+ claims . delete ( oldest ) ;
284+ }
285+ return true ;
286+ }
287+
288+ function hasRecoveredTerminalReply (
289+ state : ChatPageHost ,
290+ ownership : TerminalRecoveryOwnership ,
291+ ) : boolean {
292+ const recovery = readTerminalReplyRecoveryState ( state , ownership . runId ) ;
293+ return (
294+ recovery . acceptedFinal ||
295+ [ ...recovery . terminalReplySignatures ] . some (
296+ ( signature ) => ! ownership . initialTerminalReplySignatures . has ( signature ) ,
297+ )
298+ ) ;
299+ }
300+
270301function terminalRecoveryStillOwned (
271302 state : ChatPageHost ,
272303 ownership : TerminalRecoveryOwnership ,
@@ -279,28 +310,15 @@ function terminalRecoveryStillOwned(
279310 resolveChatAgentId ( state ) === ownership . agentId &&
280311 ( state . chatRunId === null || state . chatRunId === ownership . runId ) &&
281312 ( state . chatRunLifecycleGeneration ?? 0 ) === ownership . runLifecycleGeneration &&
282- ! hasRecoveredTerminalReply ( state , ownership . runId )
313+ ! hasRecoveredTerminalReply ( state , ownership )
283314 ) ;
284315}
285316
286317async function recoverMissingTerminalReply (
287318 state : ChatPageHost ,
288- payload : ChatEventPayload ,
319+ ownership : TerminalRecoveryOwnership ,
289320 presentation : ChatPanePresentation ,
290321) : Promise < void > {
291- const sessionKey = payload . sessionKey ;
292- const runId = payload . runId ;
293- if ( ! runId ) {
294- return ;
295- }
296- const ownership : TerminalRecoveryOwnership = {
297- sessionKey,
298- agentId : resolveChatAgentId ( state ) ,
299- runId,
300- client : state . client ,
301- connectionEpoch : state . connectionEpoch ,
302- runLifecycleGeneration : state . chatRunLifecycleGeneration ?? 0 ,
303- } ;
304322 for ( let attempt = 0 ; ; attempt += 1 ) {
305323 if ( ! terminalRecoveryStillOwned ( state , ownership ) ) {
306324 return ;
@@ -547,10 +565,6 @@ export function handlePageGatewayEvent(
547565 ? payload . runId
548566 : null ;
549567 const recoveryScope = recoveryRunId ? readChatSessionProjectionScope ( state ) : null ;
550- const projectedRunBeforeEvent =
551- recoveryRunId && recoveryScope
552- ? getChatSessionProjection ( state , state . chatMessages , recoveryScope ) . runs [ recoveryRunId ]
553- : undefined ;
554568 if (
555569 payload ?. state === "delta" &&
556570 typeof payload . runId === "string" &&
@@ -605,17 +619,26 @@ export function handlePageGatewayEvent(
605619 const shouldRecoverMissingTerminal = Boolean (
606620 recoveryRunId &&
607621 recoveryScope &&
608- ( projectedRunBeforeEvent === undefined || projectedRunBeforeEvent . status === "streaming" ) &&
609622 getChatSessionProjection ( state , state . chatMessages , recoveryScope ) . runs [ recoveryRunId ]
610623 ?. status === "completed" ,
611624 ) ;
612- if ( shouldRecoverMissingTerminal && payload ) {
625+ const recoveryOwnership =
626+ shouldRecoverMissingTerminal && payload
627+ ? createTerminalRecoveryOwnership ( state , payload )
628+ : null ;
629+ const recoveryClaimed = recoveryOwnership
630+ ? claimTerminalRecovery ( state , recoveryOwnership )
631+ : false ;
632+ if ( recoveryOwnership && recoveryClaimed ) {
613633 state . pendingSessionMessageReloadSessionKey = null ;
614- // Only the first owned completion can recover history. Replayed, yielded,
615- // or background-run terminals must not repeat I/O or disturb the foreground pane.
634+ // The first owned message-less terminal recovers history even when an
635+ // earlier snapshot already marked the run complete. Replays, yielded, or
636+ // background-run terminals must not repeat I/O or disturb the foreground pane.
616637 // Persistence can trail the terminal event, so retry bounded authoritative
617638 // snapshots until the completed run's reply becomes visible.
618- void recoverMissingTerminalReply ( state , payload , isPresented ) . catch ( ( ) => undefined ) ;
639+ void recoverMissingTerminalReply ( state , recoveryOwnership , isPresented ) . catch (
640+ ( ) => undefined ,
641+ ) ;
619642 } else {
620643 replayPendingSessionMessageReload ( state , payload , isPresented ) ;
621644 }
0 commit comments