Skip to content

Commit ed8a66d

Browse files
committed
fix(client): initialize shared state once per key across trust flips
1 parent 48aa791 commit ed8a66d

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { createEventEmitter } from 'devframe/utils/events'
2+
import { describe, expect, it } from 'vitest'
3+
import { createRpcSharedStateClientHost } from './rpc-shared-state'
4+
5+
function makeFakeRpc() {
6+
const events = createEventEmitter<any>()
7+
const setCalls: any[][] = []
8+
const rpc = {
9+
connectionMeta: { backend: 'websocket' },
10+
isTrusted: false,
11+
events,
12+
client: { register: () => {} },
13+
callEvent: (name: string, ...args: any[]) => {
14+
if (name === 'devframe:rpc:server-state:set')
15+
setCalls.push(args)
16+
},
17+
call: async () => undefined,
18+
} as any
19+
return { rpc, events, setCalls }
20+
}
21+
22+
describe('client shared state', () => {
23+
it('registers the server-sync bridge once across repeated trust flips', async () => {
24+
const { rpc, events, setCalls } = makeFakeRpc()
25+
const host = createRpcSharedStateClientHost(rpc)
26+
const state = await host.get('k', { initialValue: { a: 1 } })
27+
28+
events.emit('rpc:is-trusted:updated', true)
29+
events.emit('rpc:is-trusted:updated', true) // second flip must not re-register
30+
31+
state.mutate((d: any) => {
32+
d.a = 2
33+
})
34+
expect(setCalls).toHaveLength(1) // exactly one server-state:set, not two
35+
})
36+
})

packages/devframe/src/client/rpc-shared-state.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,10 @@ export function createRpcSharedStateClientHost(rpc: DevframeRpcClient): RpcShare
114114
return new Promise<SharedState<T>>((resolve) => {
115115
if (!rpc.isTrusted) {
116116
resolve(state)
117+
let initialized = false
117118
rpc.events.on('rpc:is-trusted:updated', (isTrusted) => {
118-
if (isTrusted) {
119+
if (isTrusted && !initialized) {
120+
initialized = true
119121
initSharedState()
120122
}
121123
})

0 commit comments

Comments
 (0)