Skip to content

Commit 0bf2316

Browse files
committed
fix(hub-ui): isolate message feeds and toasts by connection
Keep the feed, toast timers and message selection with their RPC client. On a full snapshot from another Hub instance, drop the previous entries and notifications before applying the new list in order.
1 parent c98a81e commit 0bf2316

7 files changed

Lines changed: 155 additions & 106 deletions

File tree

‎packages/hub-ui/src/client/components/display/ToastOverlay.stories.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { Meta, StoryObj } from '@storybook/vue3-vite'
22
import { h, onMounted } from 'vue'
33
import { MESSAGES_DOCK_ID } from '../../constants'
4-
import { addToast } from '../../state/toasts'
4+
import { createToastStore } from '../../state/toasts'
55
import { message } from '../../stories/fixtures'
66
import ToastOverlay from './ToastOverlay.vue'
77

@@ -28,28 +28,29 @@ type Story = StoryObj<typeof meta>
2828
export const Stack: Story = {
2929
render: () => ({
3030
setup() {
31+
const toastStore = createToastStore()
3132
onMounted(() => {
32-
addToast(message({
33+
toastStore.add(message({
3334
level: 'error',
3435
message: 'Build failed',
3536
description: '2 errors in 1 file',
3637
notify: true,
3738
autoDismiss: 10 ** 7,
3839
}))
39-
addToast(message({
40+
toastStore.add(message({
4041
level: 'warn',
4142
message: 'Slow HMR update (820ms)',
4243
notify: true,
4344
autoDismiss: 10 ** 7,
4445
}))
45-
addToast(message({
46+
toastStore.add(message({
4647
level: 'success',
4748
message: 'Server ready on :5173',
4849
notify: true,
4950
autoDismiss: 10 ** 7,
5051
}))
5152
})
52-
return () => h(ToastOverlay)
53+
return () => h(ToastOverlay, { toastStore })
5354
},
5455
}),
5556
}
@@ -58,8 +59,9 @@ export const Stack: Story = {
5859
export const WithAction: Story = {
5960
render: () => ({
6061
setup() {
62+
const toastStore = createToastStore()
6163
onMounted(() => {
62-
addToast(message({
64+
toastStore.add(message({
6365
level: 'warn',
6466
message: 'New a11y violation detected',
6567
notify: true,
@@ -74,7 +76,7 @@ export const WithAction: Story = {
7476
],
7577
}))
7678
})
77-
return () => h(ToastOverlay)
79+
return () => h(ToastOverlay, { toastStore })
7880
},
7981
}),
8082
}

‎packages/hub-ui/src/client/components/display/ToastOverlay.vue‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
11
<script setup lang="ts">
22
import type { DevframeMessageAction } from '@devframes/hub'
33
import type { DocksContext } from '@devframes/hub/client'
4+
import type { createToastStore } from '../../state/toasts'
5+
import { computed } from 'vue'
46
import { MESSAGES_DOCK_ID } from '../../constants'
5-
import { selectMessage, useMessages } from '../../state/messages'
6-
import { dismissToast, useToasts } from '../../state/toasts'
7+
import { useMessages } from '../../state/messages'
78
import MessageItem from '../message/MessageItem.vue'
89
910
const props = defineProps<{
1011
context?: DocksContext
12+
toastStore?: ReturnType<typeof createToastStore>
1113
}>()
1214
13-
// Initialize messages state early so the RPC handler is registered
14-
// and toasts are triggered even before the messages panel is opened
15-
if (props.context)
16-
useMessages(props.context)
17-
18-
const toasts = useToasts()
15+
const messages = computed(() => props.context && useMessages(props.context))
16+
const toasts = computed(() => messages.value?.toasts ?? props.toastStore)
1917
2018
function openMessages(toastId: string) {
21-
dismissToast(toastId)
22-
selectMessage(toastId)
19+
toasts.value?.dismiss(toastId)
20+
if (messages.value)
21+
messages.value.pendingSelectId = toastId
2322
// Open the messages panel provided by `@devframes/plugin-messages`
2423
// (its dock id is the plugin's devframe id).
2524
props.context?.docks.switchEntry(MESSAGES_DOCK_ID)
@@ -42,7 +41,7 @@ function dispatchAction(action: DevframeMessageAction) {
4241

4342
<template>
4443
<div
45-
v-if="toasts.length > 0"
44+
v-if="toasts?.items.length"
4645
class="fixed bottom-4 right-4 z-dock-toast flex flex-col gap-2 pointer-events-auto w-72"
4746
>
4847
<TransitionGroup
@@ -52,7 +51,7 @@ function dispatchAction(action: DevframeMessageAction) {
5251
leave-to-class="opacity-0 translate-x-4"
5352
>
5453
<div
55-
v-for="toast of toasts"
54+
v-for="toast of toasts.items"
5655
:key="toast.id"
5756
class="bg-toast-glass border color-base border-base shadow-xl cursor-pointer transition-colors rounded"
5857
@click="openMessages(toast.id)"
@@ -69,7 +68,7 @@ function dispatchAction(action: DevframeMessageAction) {
6968
</button>
7069
<button
7170
class="flex-none op30 hover:op100 p-0.5 rounded hover:bg-active transition"
72-
@click.stop="dismissToast(toast.id)"
71+
@click.stop="toasts.dismiss(toast.id)"
7372
>
7473
<div class="i-ph-x w-3 h-3" />
7574
</button>

‎packages/hub-ui/src/client/components/dock/DockStandalone.vue‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ function switchEntry(id: string | undefined) {
103103
</div>
104104
<FloatingElements />
105105
<CommandPalette :context />
106-
<ToastOverlay :context />
106+
<ToastOverlay :context="props.context" />
107107
<Confirm />
108108
</ColorSchemeRoot>
109109
</template>

‎packages/hub-ui/src/client/state/messages.test.ts‎

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
11
import type { DevframeMessageEntry, DevframeMessagesListDelta } from '@devframes/hub'
22
import type { DocksContext } from '@devframes/hub/client'
3-
import { afterEach, expect, it, vi } from 'vitest'
3+
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
44

5-
afterEach(async () => {
6-
const { dismissToast, useToasts } = await import('./toasts')
7-
for (const toast of [
8-
...useToasts(),
9-
]) dismissToast(toast.id)
5+
afterEach(() => {
106
vi.restoreAllMocks()
117
vi.resetModules()
128
vi.useRealTimers()
139
})
1410

1511
async function fixture() {
1612
const { useMessages } = await import('./messages')
17-
const { useToasts } = await import('./toasts')
1813
let delta: DevframeMessagesListDelta = {
1914
entries: [],
2015
removedIds: [],
@@ -24,7 +19,7 @@ async function fixture() {
2419
let refresh = () => {}
2520
const call = vi.fn(async () => delta)
2621
// eslint-disable-next-line slop/no-chained-type-assertions -- Only the RPC feed participates in this state test.
27-
const state = useMessages({
22+
const context = {
2823
rpc: {
2924
call,
3025
isTrusted: true,
@@ -33,7 +28,12 @@ async function fixture() {
3328
register: (command: { handler: () => void }) => { refresh = command.handler },
3429
},
3530
},
36-
} as unknown as DocksContext)
31+
} as unknown as DocksContext
32+
const state = useMessages(context)
33+
onTestFinished(() => {
34+
for (const toast of [...state.toasts.items])
35+
state.toasts.dismiss(toast.id)
36+
})
3737
await vi.waitUntil(() => call.mock.calls.length === 1)
3838
await Promise.resolve()
3939
async function publish(next: DevframeMessagesListDelta) {
@@ -60,8 +60,9 @@ async function fixture() {
6060
})
6161
return {
6262
state,
63+
context,
6364
call,
64-
toasts: useToasts(),
65+
toasts: state.toasts.items,
6566
publish,
6667
message,
6768
}
@@ -130,3 +131,50 @@ it('passes the instance ID with the next cursor and replaces stale messages', as
130131
expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list', 1, 'new')
131132
expect(state.entries).toEqual([])
132133
})
134+
135+
it('keeps messages and toasts with their RPC client after a replacement', async () => {
136+
const first = await fixture()
137+
const second = await fixture()
138+
const { useMessages } = await import('./messages')
139+
expect(useMessages(second.context)).toBe(second.state)
140+
expect(second.state).not.toBe(first.state)
141+
await first.publish({
142+
entries: [
143+
{ ...first.message, message: 'late update from the old connection' },
144+
],
145+
removedIds: [],
146+
version: 2,
147+
full: false,
148+
})
149+
expect(second.state.entries).toEqual([second.message])
150+
expect(second.toasts.map(toast => toast.entry)).toEqual([second.message])
151+
first.state.toasts.dismiss(first.message.id)
152+
expect(second.toasts).toHaveLength(1)
153+
})
154+
155+
it('rebuilds the feed in snapshot order and discards old notifications across instances', async () => {
156+
const { message, publish, state, toasts } = await fixture()
157+
const other = { ...message, id: 'other', notify: false }
158+
await publish({
159+
entries: [message, other],
160+
removedIds: [],
161+
version: 2,
162+
instanceId: 'first',
163+
full: true,
164+
})
165+
state.pendingSelectId = message.id
166+
await publish({
167+
entries: [
168+
other,
169+
{ ...message, notify: false },
170+
],
171+
removedIds: [],
172+
version: 2,
173+
instanceId: 'second',
174+
full: true,
175+
})
176+
expect(toasts).toEqual([])
177+
expect(state.entries.map(entry => entry.id)).toEqual(['other', message.id])
178+
expect(state.pendingSelectId).toBeNull()
179+
expect(state.unreadCount).toBe(2)
180+
})

‎packages/hub-ui/src/client/state/messages.ts‎

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import type { DevframeMessageEntry, DevframeMessagesListDelta, DevframeRpcClientFunctions } from '@devframes/hub'
1+
import type { DevframeMessageEntry, DevframeMessagesListDelta } from '@devframes/hub'
22
import type { DocksContext } from '@devframes/hub/client'
33
import type { Reactive } from 'vue'
4+
import { HUB_EVENTS } from '@devframes/hub/constants'
45
import { reactive } from 'vue'
5-
import { addToast, dismissToast } from './toasts'
6+
import { createToastStore } from './toasts'
67

78
export interface MessagesState {
89
entries: DevframeMessageEntry[]
10+
toasts: ReturnType<typeof createToastStore>
911
unreadCount: number
1012
pendingSelectId: string | null
1113
}
@@ -21,18 +23,22 @@ function shouldToast(entry: DevframeMessageEntry, prev: DevframeMessageEntry | u
2123
return JSON.stringify(entry) !== JSON.stringify(prev)
2224
}
2325

24-
let _messagesState: Reactive<MessagesState> | undefined
26+
const states = new WeakMap<DocksContext['rpc'], Reactive<MessagesState>>()
2527

26-
export function useMessages(context: DocksContext): Reactive<MessagesState> {
27-
if (_messagesState)
28-
return _messagesState
28+
export function useMessages({ rpc }: DocksContext): Reactive<MessagesState> {
29+
const cached = states.get(rpc)
30+
if (cached)
31+
return cached
2932

30-
const state: Reactive<MessagesState> = _messagesState = reactive({
33+
const state: Reactive<MessagesState> = reactive({
3134
entries: [],
35+
toasts: createToastStore(),
3236
unreadCount: 0,
3337
pendingSelectId: null,
3438
})
3539

40+
states.set(rpc, state)
41+
3642
const entryMap = new Map<string, DevframeMessageEntry>()
3743
let isInitialFetch = true
3844
let lastVersion: number | null = null
@@ -42,13 +48,21 @@ export function useMessages(context: DocksContext): Reactive<MessagesState> {
4248
// The feed is served by `@devframes/plugin-messages` (the hub itself ships
4349
// no list RPC). Cast because the plugin's RPC augmentation is not imported
4450
// here; hub-ui must not depend on the plugin package.
45-
const result = await context.rpc.call(
51+
const result = await rpc.call(
4652
'devframes:plugin:messages:list' as any,
4753
lastVersion,
4854
lastInstanceId,
4955
) as DevframeMessagesListDelta
5056
let newCount = 0
5157

58+
if (result.full && lastInstanceId != null && result.instanceId != null && lastInstanceId !== result.instanceId) {
59+
for (const id of entryMap.keys())
60+
state.toasts.dismiss(id)
61+
entryMap.clear()
62+
state.pendingSelectId = null
63+
state.unreadCount = 0
64+
}
65+
5266
/** Preserve surviving entries so a full snapshot does not notify them again. */
5367
let removedIds = result.removedIds
5468
if (result.full) {
@@ -59,7 +73,7 @@ export function useMessages(context: DocksContext): Reactive<MessagesState> {
5973
}
6074
for (const id of removedIds) {
6175
entryMap.delete(id)
62-
dismissToast(id)
76+
state.toasts.dismiss(id)
6377
}
6478

6579
// Apply new/updated entries. On initial fetch (page refresh) only entries
@@ -69,7 +83,7 @@ export function useMessages(context: DocksContext): Reactive<MessagesState> {
6983
if (!prev)
7084
newCount++
7185
if (shouldToast(entry, prev, isInitialFetch))
72-
addToast(entry)
86+
state.toasts.add(entry)
7387
entryMap.set(entry.id, entry)
7488
}
7589

@@ -82,22 +96,21 @@ export function useMessages(context: DocksContext): Reactive<MessagesState> {
8296

8397
// A hub without `@devframes/plugin-messages` serves no list RPC, so degrade
8498
// to an empty feed instead of surfacing unhandled rejections.
85-
const refresh = () => updateMessages().catch(() => {})
99+
let queue = Promise.resolve()
100+
const refresh = () => {
101+
queue = queue.then(updateMessages).catch(() => {})
102+
return queue
103+
}
86104

87-
context.rpc.client.register({
88-
name: 'devframe:messages:updated' satisfies keyof DevframeRpcClientFunctions,
105+
rpc.client.register({
106+
name: HUB_EVENTS.broadcast.messagesUpdated,
89107
type: 'action',
90108
handler: () => {
91-
if (context.rpc.isTrusted)
109+
if (rpc.isTrusted)
92110
refresh()
93111
},
94112
})
95113

96-
context.rpc.ensureTrusted().then(() => refresh())
114+
rpc.ensureTrusted().then(() => refresh())
97115
return state
98116
}
99-
100-
export function selectMessage(id: string): void {
101-
if (_messagesState)
102-
_messagesState.pendingSelectId = id
103-
}

0 commit comments

Comments
 (0)