@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
22
33const peerModeMock = vi . hoisted ( ( ) => ( { active : true } ) ) ;
44const stateMachineMock = vi . hoisted ( ( ) => ( {
5+ getOrCreate : vi . fn ( ) ,
56 get : vi . fn ( ( ) => ( {
67 getCurrentState : ( ) => 'idle' ,
78 getContext : ( ) => ( { lastUpdateTime : 0 } ) ,
@@ -20,9 +21,11 @@ vi.mock('@/infrastructure/peer-device/peerModeFlag', () => ({
2021
2122vi . mock ( '../../state-machine' , ( ) => ( {
2223 stateMachineManager : stateMachineMock ,
24+ SessionExecutionEvent : { START : 'start' } ,
2325} ) ) ;
2426
25- vi . mock ( '../liveSessionInteractionStore' , ( ) => ( {
27+ vi . mock ( '../liveSessionInteractionStore' , async importOriginal => ( {
28+ ...await importOriginal < typeof import ( '../liveSessionInteractionStore' ) > ( ) ,
2629 installLiveSessionInteractionMailbox : vi . fn ( ) ,
2730} ) ) ;
2831
@@ -42,9 +45,15 @@ import {
4245 runtimeProjectionCaughtUp ,
4346} from './PeerSessionRefreshModule' ;
4447import { processToolEvent } from './ToolEventModule' ;
48+ import { processNormalTextChunkInternal } from './TextChunkModule' ;
49+ import { convertDialogTurnToBackendFormat } from './PersistenceModule' ;
50+ import { resetDeviceSurfaceSwitchedForTest } from '@/infrastructure/peer-device/deviceSurfaceReconcile' ;
4551import {
52+ isRuntimeSessionProjectionStale ,
4653 markRuntimeSessionProjectionStale ,
54+ readRuntimeSessionProgress ,
4755 resetRuntimeSessionEventGateForTest ,
56+ routeRuntimeSessionEvent ,
4857} from '@/infrastructure/peer-device/runtimeSessionEventGate' ;
4958
5059describe ( 'PeerSessionRefreshModule' , ( ) => {
@@ -1067,6 +1076,8 @@ describe('PeerSessionRefreshModule journal apply', () => {
10671076 vi . useFakeTimers ( ) ;
10681077 peerModeMock . active = true ;
10691078 resetRuntimeSessionEventGateForTest ( ) ;
1079+ resetDeviceSurfaceSwitchedForTest ( ) ;
1080+ activateSurface ( LOCAL_SURFACE_ID ) ;
10701081 stateMachineMock . get . mockReturnValue ( {
10711082 getCurrentState : ( ) => 'processing' ,
10721083 getContext : ( ) => ( { lastUpdateTime : Date . now ( ) , version : 0 } ) ,
@@ -1094,10 +1105,160 @@ describe('PeerSessionRefreshModule journal apply', () => {
10941105 activeSessionId : null ,
10951106 } ) ) ;
10961107 vi . clearAllMocks ( ) ;
1108+ vi . restoreAllMocks ( ) ;
10971109 vi . unstubAllGlobals ( ) ;
10981110 vi . useRealTimers ( ) ;
10991111 } ) ;
11001112
1113+ it . each ( [ true , false ] ) ( 'replays a pristine local active restore when refresh is installed before hydrate: %s' , async installBeforeHydrate => {
1114+ peerModeMock . active = false ;
1115+ const store = FlowChatStore . getInstance ( ) ;
1116+ const sessionId = 'local-reload' ;
1117+ const turnId = 'turn-live' ;
1118+ const roundId = 'round-live' ;
1119+ store . setState ( prev => ( {
1120+ ...prev ,
1121+ activeSessionId : sessionId ,
1122+ sessions : new Map ( [ [ sessionId , {
1123+ sessionId,
1124+ title : 'Local reload' ,
1125+ workspaceId : 'workspace-1' ,
1126+ workspacePath : '/repo/OpenBitFun' ,
1127+ historyState : 'metadata-only' ,
1128+ isHistorical : true ,
1129+ isTransient : false ,
1130+ dialogTurns : [ ] ,
1131+ config : { agentType : 'PaperWriting' } ,
1132+ createdAt : 1 ,
1133+ lastActiveAt : 1 ,
1134+ todos : [ ] ,
1135+ } as any ] ] ) ,
1136+ } ) ) ;
1137+ const context = {
1138+ flowChatStore : store ,
1139+ eventBatcher : { flushNow : vi . fn ( ) , clear : vi . fn ( ) , getBufferSize : ( ) => 0 } ,
1140+ contentBuffers : new Map ( ) ,
1141+ activeTextItems : new Map ( ) ,
1142+ runtimeStatusTimers : new Map ( ) ,
1143+ saveDebouncers : new Map ( ) ,
1144+ lastSaveTimestamps : new Map ( ) ,
1145+ lastSaveHashes : new Map ( ) ,
1146+ turnSaveInFlight : new Map ( ) ,
1147+ turnSavePending : new Set ( ) ,
1148+ } as any ;
1149+ const apply = ( eventName : string , payload : any ) : boolean => {
1150+ if ( eventName === 'agentic://model-round-started' ) {
1151+ store . addModelRound ( sessionId , turnId , {
1152+ id : roundId , index : 0 , items : [ ] , status : 'streaming' ,
1153+ isStreaming : true , isComplete : false , startTime : 1 ,
1154+ } ) ;
1155+ } else if ( eventName === 'agentic://text-chunk' ) {
1156+ processNormalTextChunkInternal ( context , sessionId , turnId , roundId , payload . text ) ;
1157+ } else if ( eventName === 'agentic://tool-event' ) {
1158+ processToolEvent ( context , sessionId , turnId , roundId , payload . toolEvent ) ;
1159+ }
1160+ return true ;
1161+ } ;
1162+ agenticListenerMock . dispatchExternal . mockImplementation ( apply ) ;
1163+ const events = [
1164+ { eventName : 'agentic://dialog-turn-started' , payload : { sessionId, turnId } } ,
1165+ { eventName : 'agentic://model-round-started' , payload : { sessionId, turnId, roundId } } ,
1166+ { eventName : 'agentic://text-chunk' , payload : { sessionId, turnId, roundId, text : 'Hello' } } ,
1167+ { eventName : 'agentic://tool-event' , payload : { sessionId, turnId, roundId, toolEvent : {
1168+ event_type : 'Started' , tool_id : 'read-1' , tool_name : 'Read' , params : { file_path : 'main.tex' } ,
1169+ } } } ,
1170+ { eventName : 'agentic://tool-event' , payload : { sessionId, turnId, roundId, toolEvent : {
1171+ event_type : 'Completed' , tool_id : 'read-1' , tool_name : 'Read' , result : 'source' ,
1172+ } } } ,
1173+ ] ;
1174+ const view = {
1175+ session : { sessionId, agentType : 'PaperWriting' , state : 'Processing' , createdAt : 1 , turnCount : 7 } ,
1176+ turns : [ {
1177+ turnId, turnIndex : 6 , sessionId, timestamp : 1 ,
1178+ userMessage : { id : 'user-live' , content : 'Open LaTeX' , timestamp : 1 } ,
1179+ modelRounds : [ ] , startTime : 1 , status : 'inprogress' ,
1180+ } ] ,
1181+ contextRestoreState : 'pending' , isPartial : true , loadedTurnCount : 1 , totalTurnCount : 7 ,
1182+ turnCatalog : { schemaVersion : 1 , sessionId, revision : 'catalog-1' , complete : true ,
1183+ totalTurnCount : 7 , entries : [ ] } ,
1184+ runtimeEventSnapshot : { sessionId, streamId : 'runtime-local' , cursor : 5 , activeTurnId : turnId , events } ,
1185+ } as any ;
1186+ let resolveRefresh ! : ( value : any ) => void ;
1187+ const restore = vi . spyOn ( agentAPI , 'restoreSessionView' )
1188+ . mockResolvedValueOnce ( view )
1189+ . mockImplementationOnce ( ( ) => new Promise ( resolve => { resolveRefresh = resolve ; } ) ) ;
1190+ let cleanup : ( ( ) => void ) | undefined ;
1191+ try {
1192+ if ( installBeforeHydrate ) cleanup = installPeerSessionRefresh ( context ) ;
1193+ await store . loadSessionHistory ( sessionId ) ;
1194+ expect ( store . getState ( ) . sessions . get ( sessionId ) ?. dialogTurns [ 0 ] . modelRounds ) . toEqual ( [ ] ) ;
1195+ expect ( isRuntimeSessionProjectionStale ( LOCAL_SURFACE_ID , sessionId ) ) . toBe ( true ) ;
1196+ if ( ! installBeforeHydrate ) cleanup = installPeerSessionRefresh ( context ) ;
1197+ await vi . advanceTimersByTimeAsync ( 1 ) ;
1198+ expect ( restore ) . toHaveBeenCalledTimes ( 2 ) ;
1199+
1200+ // Live delivery races the host read: the covered prefix must not repeat,
1201+ // and the suffix must wait for the journal's model round to exist.
1202+ const deliver = ( cursor : number , text : string ) => routeRuntimeSessionEvent (
1203+ LOCAL_SURFACE_ID , 'agentic://text-chunk' , {
1204+ sessionId, turnId, roundId, text,
1205+ __openbitfunRuntimeStreamId : 'runtime-local' , __openbitfunRuntimeEventCursor : cursor ,
1206+ } , payload => { apply ( 'agentic://text-chunk' , payload ) ; } ,
1207+ ) ;
1208+ deliver ( 3 , 'Hello' ) ;
1209+ deliver ( 6 , ' world' ) ;
1210+ expect ( agenticListenerMock . dispatchExternal ) . not . toHaveBeenCalled ( ) ;
1211+ resolveRefresh ( view ) ;
1212+ await vi . advanceTimersByTimeAsync ( 1 ) ;
1213+
1214+ const turn = store . getState ( ) . sessions . get ( sessionId ) ! . dialogTurns [ 0 ] ;
1215+ expect ( turn . modelRounds ) . toHaveLength ( 1 ) ;
1216+ expect ( turn . modelRounds [ 0 ] . items . find ( item => item . type === 'text' ) ) . toMatchObject ( { content : 'Hello world' } ) ;
1217+ expect ( store . findToolItem ( sessionId , turnId , 'read-1' ) ?. status ) . toBe ( 'completed' ) ;
1218+ expect ( convertDialogTurnToBackendFormat ( turn ) . modelRounds ) . toHaveLength ( 1 ) ;
1219+ expect ( readRuntimeSessionProgress ( LOCAL_SURFACE_ID , sessionId ) ) . toEqual ( { streamId : 'runtime-local' , cursor : 6 } ) ;
1220+ expect ( isRuntimeSessionProjectionStale ( LOCAL_SURFACE_ID , sessionId ) ) . toBe ( false ) ;
1221+ await vi . advanceTimersByTimeAsync ( 60_000 ) ;
1222+ expect ( restore ) . toHaveBeenCalledTimes ( 2 ) ;
1223+ } finally {
1224+ cleanup ?.( ) ;
1225+ }
1226+ } ) ;
1227+
1228+ it . each ( [ 'Idle' , 'Processing' ] ) ( 'keeps pristine local persisted content without extra reads when a %s host has no journal' , async state => {
1229+ peerModeMock . active = false ;
1230+ const store = FlowChatStore . getInstance ( ) ;
1231+ const sessionId = 'local-legacy' ;
1232+ store . setState ( prev => ( { ...prev , activeSessionId : sessionId , sessions : new Map ( [ [ sessionId , {
1233+ sessionId, title : 'Local' , workspaceId : 'workspace-1' , workspacePath : '/repo/OpenBitFun' ,
1234+ historyState : 'metadata-only' , isHistorical : true , isTransient : false ,
1235+ dialogTurns : [ ] , config : { agentType : 'PaperWriting' } , createdAt : 1 , lastActiveAt : 1 , todos : [ ] ,
1236+ } as any ] ] ) } ) ) ;
1237+ const restore = vi . spyOn ( agentAPI , 'restoreSessionView' ) . mockResolvedValue ( {
1238+ session : { sessionId, state, agentType : 'PaperWriting' , createdAt : 1 } ,
1239+ turns : [ {
1240+ turnId : 'turn-legacy' , turnIndex : 0 , sessionId, timestamp : 1 ,
1241+ userMessage : { id : 'user-legacy' , content : 'Open LaTeX' , timestamp : 1 } ,
1242+ modelRounds : [ { id : 'round-legacy' , roundIndex : 0 , startTime : 1 , status : 'streaming' ,
1243+ textItems : [ { id : 'text-legacy' , content : 'Persisted reply' , timestamp : 1 } ] , toolItems : [ ] , thinkingItems : [ ] } ] ,
1244+ startTime : 1 , status : state === 'Idle' ? 'completed' : 'inprogress' ,
1245+ } ] , contextRestoreState : 'ready' ,
1246+ } as any ) ;
1247+ const cleanup = installPeerSessionRefresh ( {
1248+ flowChatStore : store , eventBatcher : { flushNow : vi . fn ( ) , clear : vi . fn ( ) } ,
1249+ contentBuffers : new Map ( ) , activeTextItems : new Map ( ) ,
1250+ } as any ) ;
1251+ try {
1252+ await store . loadSessionHistory ( sessionId ) ;
1253+ await vi . advanceTimersByTimeAsync ( 60_000 ) ;
1254+ expect ( store . getState ( ) . sessions . get ( sessionId ) ?. dialogTurns [ 0 ] . modelRounds [ 0 ] . items [ 0 ] ) . toMatchObject ( { content : 'Persisted reply' } ) ;
1255+ expect ( restore ) . toHaveBeenCalledTimes ( 1 ) ;
1256+ expect ( agenticListenerMock . dispatchExternal ) . not . toHaveBeenCalled ( ) ;
1257+ } finally {
1258+ cleanup ( ) ;
1259+ }
1260+ } ) ;
1261+
11011262 it ( 'replays a cursor-covered ToolEnd until the card is completed' , async ( ) => {
11021263 const store = FlowChatStore . getInstance ( ) ;
11031264 store . setState ( prev => ( {
0 commit comments