diff --git a/docs/content/8.references/6.hub-api.md b/docs/content/8.references/6.hub-api.md index a79606e3..982eefec 100644 --- a/docs/content/8.references/6.hub-api.md +++ b/docs/content/8.references/6.hub-api.md @@ -15,9 +15,11 @@ What `DevframeHubContext` adds to `DevframeNodeContext`: [Hub](/guide/hub). |---|---|---| | `ctx.docks` | `register / update / values / activate` | Dock entries (iframes, launchers, custom-render) and groups; `activate(dockId, params?)` sets the active dock ([Cross-iframe dock activation](/guide/hub#cross-iframe-dock-activation)). | | `ctx.terminals` | `register / startChildProcess / startPtySession` | Aggregate terminal sessions, streaming output ([Terminals](/add-ons/devframes/terminals#hub-aggregation)). | -| `ctx.messages` | `add / update / remove / clear` | Server-side toast/notification queue (FIFO, capped at 1000). | +| `ctx.messages` | `add / update / remove / clear / listSince` | Server-side toast/notification queue (FIFO, capped at 1000). | | `ctx.commands` | `register / execute / list` | Hierarchical command palette with keybindings and `when` clauses. | +For incremental message reads, call `ctx.messages.listSince(version, instanceId)` with both values from the previous result. A missing or foreign `instanceId` returns a full snapshot, as does an expired version. When `full` is true, replace the cached list. Otherwise, apply `removedIds` before adding or updating `entries`. Numeric-only callers remain supported through full snapshots. + ## Launcher fields The optional `launcher` fields that make a `type: 'launcher'` dock entry a live process controller: [Process-control launchers](/guide/hub#process-control-launchers). diff --git a/packages/hub-ui/src/client/components/display/ToastOverlay.stories.ts b/packages/hub-ui/src/client/components/display/ToastOverlay.stories.ts index da27c69f..7ffc5082 100644 --- a/packages/hub-ui/src/client/components/display/ToastOverlay.stories.ts +++ b/packages/hub-ui/src/client/components/display/ToastOverlay.stories.ts @@ -1,7 +1,7 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite' import { h, onMounted } from 'vue' import { MESSAGES_DOCK_ID } from '../../constants' -import { addToast } from '../../state/toasts' +import { createToastStore } from '../../state/toasts' import { message } from '../../stories/fixtures' import ToastOverlay from './ToastOverlay.vue' @@ -28,28 +28,29 @@ type Story = StoryObj export const Stack: Story = { render: () => ({ setup() { + const toastStore = createToastStore() onMounted(() => { - addToast(message({ + toastStore.add(message({ level: 'error', message: 'Build failed', description: '2 errors in 1 file', notify: true, autoDismiss: 10 ** 7, })) - addToast(message({ + toastStore.add(message({ level: 'warn', message: 'Slow HMR update (820ms)', notify: true, autoDismiss: 10 ** 7, })) - addToast(message({ + toastStore.add(message({ level: 'success', message: 'Server ready on :5173', notify: true, autoDismiss: 10 ** 7, })) }) - return () => h(ToastOverlay) + return () => h(ToastOverlay, { toastStore }) }, }), } @@ -58,8 +59,9 @@ export const Stack: Story = { export const WithAction: Story = { render: () => ({ setup() { + const toastStore = createToastStore() onMounted(() => { - addToast(message({ + toastStore.add(message({ level: 'warn', message: 'New a11y violation detected', notify: true, @@ -74,7 +76,7 @@ export const WithAction: Story = { ], })) }) - return () => h(ToastOverlay) + return () => h(ToastOverlay, { toastStore }) }, }), } diff --git a/packages/hub-ui/src/client/components/display/ToastOverlay.vue b/packages/hub-ui/src/client/components/display/ToastOverlay.vue index b54ce2f3..65ae3d89 100644 --- a/packages/hub-ui/src/client/components/display/ToastOverlay.vue +++ b/packages/hub-ui/src/client/components/display/ToastOverlay.vue @@ -1,25 +1,24 @@ diff --git a/packages/hub-ui/src/client/components/dock/DockStandaloneShell.vue b/packages/hub-ui/src/client/components/dock/DockStandaloneShell.vue new file mode 100644 index 00000000..2c112d65 --- /dev/null +++ b/packages/hub-ui/src/client/components/dock/DockStandaloneShell.vue @@ -0,0 +1,109 @@ + + + diff --git a/packages/hub-ui/src/client/state/messages.test.ts b/packages/hub-ui/src/client/state/messages.test.ts index f2e19e97..2d8a1ec5 100644 --- a/packages/hub-ui/src/client/state/messages.test.ts +++ b/packages/hub-ui/src/client/state/messages.test.ts @@ -1,12 +1,8 @@ import type { DevframeMessageEntry, DevframeMessagesListDelta } from '@devframes/hub' import type { DocksContext } from '@devframes/hub/client' -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' -afterEach(async () => { - const { dismissToast, useToasts } = await import('./toasts') - for (const toast of [ - ...useToasts(), - ]) dismissToast(toast.id) +afterEach(() => { vi.restoreAllMocks() vi.resetModules() vi.useRealTimers() @@ -14,7 +10,6 @@ afterEach(async () => { async function fixture() { const { useMessages } = await import('./messages') - const { useToasts } = await import('./toasts') let delta: DevframeMessagesListDelta = { entries: [], removedIds: [], @@ -24,7 +19,7 @@ async function fixture() { let refresh = () => {} const call = vi.fn(async () => delta) // eslint-disable-next-line slop/no-chained-type-assertions -- Only the RPC feed participates in this state test. - const state = useMessages({ + const context = { rpc: { call, isTrusted: true, @@ -33,12 +28,19 @@ async function fixture() { register: (command: { handler: () => void }) => { refresh = command.handler }, }, }, - } as unknown as DocksContext) + } as unknown as DocksContext + const state = useMessages(context) + onTestFinished(() => { + for (const toast of [...state.toasts.items]) + state.toasts.dismiss(toast.id) + }) await vi.waitUntil(() => call.mock.calls.length === 1) await Promise.resolve() async function publish(next: DevframeMessagesListDelta) { delta = next + const previousCalls = call.mock.calls.length refresh() + await vi.waitUntil(() => call.mock.calls.length > previousCalls) await Promise.resolve() } const message: DevframeMessageEntry = { @@ -58,7 +60,9 @@ async function fixture() { }) return { state, - toasts: useToasts(), + context, + call, + toasts: state.toasts.items, publish, message, } @@ -96,3 +100,81 @@ it('keeps surviving toasts and unread counts when receiving a full snapshot', as expect(toasts).toHaveLength(1) expect(state.unreadCount).toBe(1) }) + +it('passes the instance ID with the next cursor and replaces stale messages', async () => { + const { state, call, publish, message } = await fixture() + await publish({ + entries: [message], + removedIds: [], + version: 1, + instanceId: 'old', + full: true, + }) + await publish({ + entries: [ + { ...message, id: 'new' }, + ], + removedIds: [], + version: 1, + instanceId: 'new', + full: true, + }) + expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list', 1, 'old') + expect(state.entries.map(entry => entry.id)).toEqual(['new']) + await publish({ + entries: [], + removedIds: ['new'], + version: 2, + instanceId: 'new', + full: false, + }) + expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list', 1, 'new') + expect(state.entries).toEqual([]) +}) + +it('keeps messages and toasts with their RPC client after a replacement', async () => { + const first = await fixture() + const second = await fixture() + const { useMessages } = await import('./messages') + expect(useMessages(second.context)).toBe(second.state) + expect(second.state).not.toBe(first.state) + await first.publish({ + entries: [ + { ...first.message, message: 'late update from the old connection' }, + ], + removedIds: [], + version: 2, + full: false, + }) + expect(second.state.entries).toEqual([second.message]) + expect(second.toasts.map(toast => toast.entry)).toEqual([second.message]) + first.state.toasts.dismiss(first.message.id) + expect(second.toasts).toHaveLength(1) +}) + +it('rebuilds the feed in snapshot order and discards old notifications across instances', async () => { + const { message, publish, state, toasts } = await fixture() + const other = { ...message, id: 'other', notify: false } + await publish({ + entries: [message, other], + removedIds: [], + version: 2, + instanceId: 'first', + full: true, + }) + state.pendingSelectId = message.id + await publish({ + entries: [ + other, + { ...message, notify: false }, + ], + removedIds: [], + version: 2, + instanceId: 'second', + full: true, + }) + expect(toasts).toEqual([]) + expect(state.entries.map(entry => entry.id)).toEqual(['other', message.id]) + expect(state.pendingSelectId).toBeNull() + expect(state.unreadCount).toBe(2) +}) diff --git a/packages/hub-ui/src/client/state/messages.ts b/packages/hub-ui/src/client/state/messages.ts index 7ceac85d..94b6d0de 100644 --- a/packages/hub-ui/src/client/state/messages.ts +++ b/packages/hub-ui/src/client/state/messages.ts @@ -1,11 +1,13 @@ -import type { DevframeMessageEntry, DevframeMessagesListDelta, DevframeRpcClientFunctions } from '@devframes/hub' +import type { DevframeMessageEntry, DevframeMessagesListDelta } from '@devframes/hub' import type { DocksContext } from '@devframes/hub/client' import type { Reactive } from 'vue' +import { HUB_EVENTS } from '@devframes/hub/constants' import { reactive } from 'vue' -import { addToast, dismissToast } from './toasts' +import { createToastStore } from './toasts' export interface MessagesState { entries: DevframeMessageEntry[] + toasts: ReturnType unreadCount: number pendingSelectId: string | null } @@ -21,32 +23,46 @@ function shouldToast(entry: DevframeMessageEntry, prev: DevframeMessageEntry | u return JSON.stringify(entry) !== JSON.stringify(prev) } -let _messagesState: Reactive | undefined +const states = new WeakMap>() -export function useMessages(context: DocksContext): Reactive { - if (_messagesState) - return _messagesState +export function useMessages({ rpc }: DocksContext): Reactive { + const cached = states.get(rpc) + if (cached) + return cached - const state: Reactive = _messagesState = reactive({ + const state: Reactive = reactive({ entries: [], + toasts: createToastStore(), unreadCount: 0, pendingSelectId: null, }) + states.set(rpc, state) + const entryMap = new Map() let isInitialFetch = true let lastVersion: number | null = null + let lastInstanceId: string | null = null async function updateMessages() { // The feed is served by `@devframes/plugin-messages` (the hub itself ships // no list RPC). Cast because the plugin's RPC augmentation is not imported // here; hub-ui must not depend on the plugin package. - const result = await context.rpc.call( + const result = await rpc.call( 'devframes:plugin:messages:list' as any, lastVersion, + lastInstanceId, ) as DevframeMessagesListDelta let newCount = 0 + if (result.full && lastInstanceId != null && result.instanceId != null && lastInstanceId !== result.instanceId) { + for (const id of entryMap.keys()) + state.toasts.dismiss(id) + entryMap.clear() + state.pendingSelectId = null + state.unreadCount = 0 + } + /** Preserve surviving entries so a full snapshot does not notify them again. */ let removedIds = result.removedIds if (result.full) { @@ -57,7 +73,7 @@ export function useMessages(context: DocksContext): Reactive { } for (const id of removedIds) { entryMap.delete(id) - dismissToast(id) + state.toasts.dismiss(id) } // Apply new/updated entries. On initial fetch (page refresh) only entries @@ -67,34 +83,34 @@ export function useMessages(context: DocksContext): Reactive { if (!prev) newCount++ if (shouldToast(entry, prev, isInitialFetch)) - addToast(entry) + state.toasts.add(entry) entryMap.set(entry.id, entry) } state.entries = Array.from(entryMap.values()) state.unreadCount += newCount lastVersion = result.version + lastInstanceId = result.instanceId ?? null isInitialFetch = false } // A hub without `@devframes/plugin-messages` serves no list RPC, so degrade // to an empty feed instead of surfacing unhandled rejections. - const refresh = () => updateMessages().catch(() => {}) + let queue = Promise.resolve() + const refresh = () => { + queue = queue.then(updateMessages).catch(() => {}) + return queue + } - context.rpc.client.register({ - name: 'devframe:messages:updated' satisfies keyof DevframeRpcClientFunctions, + rpc.client.register({ + name: HUB_EVENTS.broadcast.messagesUpdated, type: 'action', handler: () => { - if (context.rpc.isTrusted) + if (rpc.isTrusted) refresh() }, }) - context.rpc.ensureTrusted().then(() => refresh()) + rpc.ensureTrusted().then(() => refresh()) return state } - -export function selectMessage(id: string): void { - if (_messagesState) - _messagesState.pendingSelectId = id -} diff --git a/packages/hub-ui/src/client/state/toasts.test.ts b/packages/hub-ui/src/client/state/toasts.test.ts index 0defa2bc..05b14567 100644 --- a/packages/hub-ui/src/client/state/toasts.test.ts +++ b/packages/hub-ui/src/client/state/toasts.test.ts @@ -1,6 +1,6 @@ import type { DevframeMessageEntry } from '@devframes/hub' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { addToast, dismissToast, useToasts } from './toasts' +import { createToastStore } from './toasts' function createMessage(id: string, autoDismiss: number | false): DevframeMessageEntry { return { @@ -13,59 +13,53 @@ function createMessage(id: string, autoDismiss: number | false): DevframeMessage } } -function dismissAllToasts(): void { - for (const toast of [ - ...useToasts(), - ]) - dismissToast(toast.id) -} - describe('toast auto-dismiss', () => { + let store: ReturnType + beforeEach(() => { vi.useFakeTimers() - dismissAllToasts() + store = createToastStore() }) afterEach(() => { - dismissAllToasts() vi.useRealTimers() }) it('keeps a persistent toast visible until it is explicitly dismissed', () => { - addToast(createMessage('persistent', false)) + store.add(createMessage('persistent', false)) expect(vi.getTimerCount()).toBe(0) vi.advanceTimersByTime(60_000) - expect(useToasts()).toHaveLength(1) + expect(store.items).toHaveLength(1) - dismissToast('persistent') + store.dismiss('persistent') - expect(useToasts()).toHaveLength(0) + expect(store.items).toHaveLength(0) }) it('cancels an existing auto-dismiss timer when its toast becomes persistent', () => { - addToast(createMessage('updated', 1_000)) + store.add(createMessage('updated', 1_000)) expect(vi.getTimerCount()).toBe(1) - addToast(createMessage('updated', false)) + store.add(createMessage('updated', false)) expect(vi.getTimerCount()).toBe(0) vi.advanceTimersByTime(60_000) - expect(useToasts()).toHaveLength(1) + expect(store.items).toHaveLength(1) }) it('continues to auto-dismiss timed toasts', () => { - addToast(createMessage('timed', 1_000)) + store.add(createMessage('timed', 1_000)) vi.advanceTimersByTime(999) - expect(useToasts()).toHaveLength(1) + expect(store.items).toHaveLength(1) vi.advanceTimersByTime(1) - expect(useToasts()).toHaveLength(0) + expect(store.items).toHaveLength(0) }) }) diff --git a/packages/hub-ui/src/client/state/toasts.ts b/packages/hub-ui/src/client/state/toasts.ts index de2d8341..367f48a8 100644 --- a/packages/hub-ui/src/client/state/toasts.ts +++ b/packages/hub-ui/src/client/state/toasts.ts @@ -2,50 +2,43 @@ import type { DevframeMessageEntry } from '@devframes/hub' import type { Reactive } from 'vue' import { reactive } from 'vue' -export interface ToastItem { +interface ToastItem { id: string entry: DevframeMessageEntry } -const toasts: Reactive = reactive([]) -const timers = new Map>() +export function createToastStore() { + const items: Reactive = reactive([]) + const timers = new Map>() -export function useToasts(): Reactive { - return toasts -} - -export function addToast(entry: DevframeMessageEntry): void { - // Dedupe: update existing toast with same id - const existing = toasts.find(t => t.id === entry.id) - if (existing) { - existing.entry = entry - // Reset auto-dismiss timer - const timer = timers.get(entry.id) - if (timer) { + function cancelTimer(id: string): void { + const timer = timers.get(id) + if (timer !== undefined) { clearTimeout(timer) - timers.delete(entry.id) + timers.delete(id) } - const timeout = entry.autoDismiss ?? 5000 - if (timeout !== false) - timers.set(entry.id, setTimeout(dismissToast, timeout, entry.id)) - return } - const item: ToastItem = { id: entry.id, entry } - toasts.push(item) - - const timeout = entry.autoDismiss ?? 5000 - if (timeout !== false) - timers.set(entry.id, setTimeout(dismissToast, timeout, entry.id)) -} + function dismiss(id: string): void { + const index = items.findIndex(toast => toast.id === id) + if (index !== -1) + items.splice(index, 1) + cancelTimer(id) + } -export function dismissToast(id: string): void { - const idx = toasts.findIndex(t => t.id === id) - if (idx !== -1) - toasts.splice(idx, 1) - const timer = timers.get(id) - if (timer) { - clearTimeout(timer) - timers.delete(id) + function add(entry: DevframeMessageEntry): void { + const existing = items.find(toast => toast.id === entry.id) + if (existing) { + existing.entry = entry + cancelTimer(entry.id) + } + else { + items.push({ id: entry.id, entry }) + } + const timeout = entry.autoDismiss ?? 5000 + if (timeout !== false) + timers.set(entry.id, setTimeout(dismiss, timeout, entry.id)) } + + return { items, add, dismiss } } diff --git a/packages/hub/src/node/__tests__/host-messages.test.ts b/packages/hub/src/node/__tests__/host-messages.test.ts index 8ff8eb10..4062ab71 100644 --- a/packages/hub/src/node/__tests__/host-messages.test.ts +++ b/packages/hub/src/node/__tests__/host-messages.test.ts @@ -40,6 +40,33 @@ describe('devframeMessagesHost', () => { }) describe('listSince', () => { + it.each([1, 2, 3])('replaces a foreign cursor when the new clock is %s', async (count) => { + const previous = new DevframeMessagesHost({} as DevframeHubContext) + await previous.info('old first', { id: 'old:1' }) + await previous.info('old second', { id: 'old:2' }) + const cursor = previous.listSince() + + const current = new DevframeMessagesHost({} as DevframeHubContext) + for (let i = 0; i < count; i++) + await current.info(`new ${i}`, { id: `new:${i}` }) + + const result = current.listSince(cursor.version, cursor.instanceId) + expect(result.full).toBe(true) + expect(result.entries.map(entry => entry.id)).toEqual(Array.from({ length: count }, (_, i) => `new:${i}`)) + expect(result.instanceId).not.toBe(cursor.instanceId) + }) + + it('returns a full snapshot for a legacy numeric-only cursor', async () => { + const host = new DevframeMessagesHost({} as DevframeHubContext) + await host.info('first', { id: 'first' }) + const { version } = host.listSince() + await host.info('second', { id: 'second' }) + + const result = host.listSince(version) + expect(result.full).toBe(true) + expect(result.entries.map(entry => entry.id)).toEqual(['first', 'second']) + }) + it('returns a full snapshot without a cursor', async () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) @@ -55,12 +82,12 @@ describe('devframeMessagesHost', () => { it('returns only entries modified after the cursor', async () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) - const { version } = host.listSince() + const { version, instanceId } = host.listSince() await host.add({ id: 'b', level: 'info', message: 'b' }) await host.update('a', { message: 'a2' }) - const delta = host.listSince(version) + const delta = host.listSince(version, instanceId) expect(delta.full).toBe(false) expect(delta.entries.map(e => e.id).sort()).toEqual(['a', 'b']) expect(delta.removedIds).toEqual([]) @@ -71,11 +98,11 @@ describe('devframeMessagesHost', () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) await host.add({ id: 'b', level: 'info', message: 'b' }) - const { version } = host.listSince() + const { version, instanceId } = host.listSince() await host.remove('a') - const delta = host.listSince(version) + const delta = host.listSince(version, instanceId) expect(delta.full).toBe(false) expect(delta.entries).toEqual([]) expect(delta.removedIds).toEqual(['a']) @@ -85,11 +112,11 @@ describe('devframeMessagesHost', () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) await host.add({ id: 'b', level: 'info', message: 'b' }) - const { version } = host.listSince() + const { version, instanceId } = host.listSince() await host.clear() - const delta = host.listSince(version) + const delta = host.listSince(version, instanceId) expect(delta.entries).toEqual([]) expect(delta.removedIds.sort()).toEqual(['a', 'b']) }) @@ -97,9 +124,9 @@ describe('devframeMessagesHost', () => { it('returns an empty delta when nothing changed', async () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) - const { version } = host.listSince() + const { version, instanceId } = host.listSince() - const delta = host.listSince(version) + const delta = host.listSince(version, instanceId) expect(delta.full).toBe(false) expect(delta.entries).toEqual([]) expect(delta.removedIds).toEqual([]) @@ -109,7 +136,7 @@ describe('devframeMessagesHost', () => { it('falls back to a full snapshot when the cursor predates trimmed removals', async () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'stale', level: 'info', message: 'stale cursor target' }) - const { version } = host.listSince() + const { version, instanceId } = host.listSince() // Overflow the removal log so records after `version` get trimmed. for (let i = 0; i < 1005; i++) { @@ -118,7 +145,7 @@ describe('devframeMessagesHost', () => { await host.remove(id) } - const result = host.listSince(version) + const result = host.listSince(version, instanceId) expect(result.full).toBe(true) expect(result.entries.map(e => e.id)).toEqual(['stale']) expect(result.removedIds).toEqual([]) @@ -128,7 +155,7 @@ describe('devframeMessagesHost', () => { const host = new DevframeMessagesHost({} as DevframeHubContext) await host.add({ id: 'a', level: 'info', message: 'a' }) - const result = host.listSince(9999) + const result = host.listSince(9999, host.listSince().instanceId) expect(result.full).toBe(true) expect(result.entries.map(e => e.id)).toEqual(['a']) }) diff --git a/packages/hub/src/node/host-messages.ts b/packages/hub/src/node/host-messages.ts index 4c05ca9c..8f6a4790 100644 --- a/packages/hub/src/node/host-messages.ts +++ b/packages/hub/src/node/host-messages.ts @@ -24,6 +24,7 @@ export class DevframeMessagesHost implements DevframeMessagesHostType { readonly removals: Array<{ id: string, time: number }> = [] private _autoDeleteTimers = new Map>() + private readonly _instanceId = nanoid() private _clock = 0 /** * The tick of the newest removal record dropped from the capped @@ -159,16 +160,16 @@ export class DevframeMessagesHost implements DevframeMessagesHostType { this.events.emit(HUB_EVENTS.bus.messagesCleared) } - listSince(since?: number | null): DevframeMessagesListDelta { + listSince(since?: number | null, instanceId?: string | null): DevframeMessagesListDelta { const version = this._clock - // Fall back to a full snapshot when there is no cursor, when the cursor - // predates removal records already trimmed from the capped log, or when - // it comes from another host incarnation (ahead of our clock). - if (since == null || since < this._removalsTrimmedAt || since > version) { + // A numeric cursor alone cannot identify the instance that issued it. + // Legacy readers receive full snapshots until they return the instance ID. + if (instanceId !== this._instanceId || since == null || since < this._removalsTrimmedAt || since > version) { return { entries: Array.from(this.entries.values()), removedIds: [], version, + instanceId: this._instanceId, full: true, } } @@ -188,6 +189,7 @@ export class DevframeMessagesHost implements DevframeMessagesHostType { entries, removedIds, version, + instanceId: this._instanceId, full: false, } } diff --git a/packages/hub/src/types/messages.ts b/packages/hub/src/types/messages.ts index f35eae10..e26e8416 100644 --- a/packages/hub/src/types/messages.ts +++ b/packages/hub/src/types/messages.ts @@ -187,7 +187,7 @@ export interface DevframeMessagesClient extends DevframeMessagesLevelShortcuts { /** * A snapshot or delta of the message list, as returned by * {@link DevframeMessagesHost.listSince}. Consumers apply `removedIds` - * first, then upsert `entries`, and pass `version` back as `since` on the + * first, then upsert `entries`, and pass `version` and `instanceId` back on the * next call. */ export interface DevframeMessagesListDelta { @@ -197,6 +197,8 @@ export interface DevframeMessagesListDelta { removedIds: string[] /** The version cursor; pass back as `since` on the next call */ version: number + /** Instance that issued the cursor, when supplied by the messages host. */ + instanceId?: string /** * When `true`, `entries` is the complete snapshot and any locally cached * list must be reset before applying it. @@ -232,11 +234,12 @@ export interface DevframeMessagesHost extends DevframeMessagesLevelShortcuts { clear: () => Promise /** * Read the message list incrementally. Pass the `version` from the - * previous result as `since` to receive only the entries modified and the - * ids removed after that point; pass `null`/`undefined` for the initial + * previous result as `since`, together with its `instanceId`, to receive + * only the entries modified and the ids removed after that point; pass `null`/`undefined` for the initial * full snapshot. When the host can no longer compute a reliable delta for * the given cursor (trimmed removal history, or a cursor from another host * incarnation), the result carries `full: true` with the complete list. + * Calls without an instance ID also receive a full snapshot. */ - listSince: (since?: number | null) => DevframeMessagesListDelta + listSince: (since?: number | null, instanceId?: string | null) => DevframeMessagesListDelta } diff --git a/plugins/messages/app/client/state/messages.ts b/plugins/messages/app/client/state/messages.ts index 5d5e85d1..bdf2692f 100644 --- a/plugins/messages/app/client/state/messages.ts +++ b/plugins/messages/app/client/state/messages.ts @@ -31,6 +31,7 @@ export function useMessages(rpc: DevframeRpcClient): Reactive { const entryMap = new Map() let lastVersion: number | null = null + let lastInstanceId: string | null = null // Serialize refreshes so a broadcast landing mid-fetch can't interleave // cursor updates; the cursor keeps each pass cheap. @@ -41,7 +42,7 @@ export function useMessages(rpc: DevframeRpcClient): Reactive { // no-args snapshot; live servers return the full list either way. const result = (lastVersion == null ? await rpc.call('devframes:plugin:messages:list') - : await rpc.call('devframes:plugin:messages:list', lastVersion)) as DevframeMessagesListDelta + : await rpc.call('devframes:plugin:messages:list', lastVersion, lastInstanceId)) as DevframeMessagesListDelta if (result.full) entryMap.clear() // Apply removals before upserts, since an id can be evicted and re-added @@ -52,6 +53,7 @@ export function useMessages(rpc: DevframeRpcClient): Reactive { entryMap.set(entry.id, entry) state!.entries = Array.from(entryMap.values()) lastVersion = result.version + lastInstanceId = result.instanceId ?? null }).catch(() => { // Transport hiccup; the next broadcast or trust flip retries. }) diff --git a/plugins/messages/src/node/rpc/functions/list.ts b/plugins/messages/src/node/rpc/functions/list.ts index bcdb605b..da63c462 100644 --- a/plugins/messages/src/node/rpc/functions/list.ts +++ b/plugins/messages/src/node/rpc/functions/list.ts @@ -1,11 +1,12 @@ import type { DevframeMessagesListDelta } from '@devframes/hub/types' +import type { DevframeNodeRpcSessionMeta } from 'devframe/types' import { defineRpcFunction } from 'devframe' import { getMessagesHost } from './_define' /** * Read the message list incrementally. Pass the `version` from the previous - * result as `since` to receive only what changed; omit it for the initial - * full snapshot. Apply `removedIds` before upserting `entries`. + * result as `since`, together with its `instanceId`, to receive only what + * changed. Omit both for the initial full snapshot. Apply `removedIds` before upserting `entries`. * * `snapshot: true` bakes the full list into static builds, so the panel * renders the last captured feed without a live server. @@ -19,18 +20,34 @@ export const messagesList = defineRpcFunction({ title: 'List messages', description: 'List the hub message feed: diagnostics, notifications, and tool output entries with level, category, labels, and positions.', }, - setup: ctx => ({ - handler: async (since?: number | null): Promise => { - const host = getMessagesHost(ctx) - if (!host) { - return { - entries: [], - removedIds: [], - version: 0, - full: true, + setup: (ctx) => { + const cursors = new WeakMap>() + return { + async handler(this: { $meta?: DevframeNodeRpcSessionMeta } | void, since?: number | null, instanceId?: string | null): Promise { + const host = getMessagesHost(ctx) + if (!host) { + return { + entries: [], + removedIds: [], + version: 0, + full: true, + } } - } - return host.listSince(since) - }, - }), + + // Live RPC binds the peer to the handler. Local reads and static builds + // have no peer and need no connection-specific cursor. + const peer = this?.$meta + const initial = peer && cursors.get(peer) + const knownInstance = instanceId === undefined && initial && since != null && since >= initial.version + ? initial.instanceId + : instanceId + const result = host.listSince(since, knownInstance) + // Keep the first snapshot cursor on this connection so overlapping + // numeric reads can still see removals since that snapshot. + if (peer && instanceId === undefined && result.full && (!initial || initial.instanceId !== result.instanceId)) + cursors.set(peer, { version: result.version, instanceId: result.instanceId }) + return result + }, + } + }, }) diff --git a/plugins/messages/test/dev-server.test.ts b/plugins/messages/test/dev-server.test.ts index 7c7157ce..9f827a73 100644 --- a/plugins/messages/test/dev-server.test.ts +++ b/plugins/messages/test/dev-server.test.ts @@ -68,12 +68,53 @@ describe('messages dev-server (hub context)', () => { await server.ctx.messages.add({ id: 'later', level: 'warn', message: 'later' }) await server.ctx.messages.remove('from-server') - const delta = await rpc.$call('devframes:plugin:messages:list', full.version) as DevframeMessagesListDelta + const delta = await rpc.$call('devframes:plugin:messages:list', full.version, full.instanceId) as DevframeMessagesListDelta expect(delta.full).toBe(false) expect(delta.entries.map(e => e.id)).toEqual(['later']) expect(delta.removedIds).toContain('from-server') }) + it('returns a removal to a legacy panel after its no-argument snapshot', async () => { + const rpc = connect(server) + const id = 'legacy-panel' + await server.ctx.messages.info('original', { id }) + const snapshot = await rpc.$call('devframes:plugin:messages:list') as DevframeMessagesListDelta + await server.ctx.messages.remove(id) + await server.ctx.messages.info('replacement', { id }) + + const delta = await rpc.$call('devframes:plugin:messages:list', snapshot.version) as DevframeMessagesListDelta + expect(delta.full).toBe(false) + expect(delta.removedIds).toEqual([id]) + expect(delta.entries).toMatchObject([ + { id, message: 'replacement' }, + ]) + + const foreign = await rpc.$call('devframes:plugin:messages:list', snapshot.version, 'previous-instance') as DevframeMessagesListDelta + expect(foreign.full).toBe(true) + expect(foreign.instanceId).toBe(snapshot.instanceId) + }) + + it('keeps the removal when a legacy reader sees an ID reused on its connection', async () => { + const rpc = connect(server) + await server.ctx.messages.info('old toast', { id: 'reused', notify: true }) + const snapshot = await rpc.$call('devframes:plugin:messages:list', null) as DevframeMessagesListDelta + const fresh = connect(server) + const unknown = await fresh.$call('devframes:plugin:messages:list', snapshot.version) as DevframeMessagesListDelta + expect(unknown.full).toBe(true) + await server.ctx.messages.info('another entry', { id: 'other' }) + await rpc.$call('devframes:plugin:messages:list', snapshot.version) + await server.ctx.messages.remove('reused') + await server.ctx.messages.info('replacement', { id: 'reused', notify: false }) + + const delta = await rpc.$call('devframes:plugin:messages:list', snapshot.version) as DevframeMessagesListDelta + expect(delta.full).toBe(false) + expect(delta.removedIds).toEqual(['reused']) + expect(delta.entries.map(entry => entry.id)).toEqual(['other', 'reused']) + expect(delta.entries[1]).toMatchObject({ message: 'replacement', notify: false }) + const resumed = await fresh.$call('devframes:plugin:messages:list', unknown.version) as DevframeMessagesListDelta + expect(resumed).toEqual(delta) + }) + it('add stamps browser origin; update patches; clear empties', async () => { const rpc = connect(server) diff --git a/plugins/messages/test/message-state.test.ts b/plugins/messages/test/message-state.test.ts new file mode 100644 index 00000000..c0c8a19c --- /dev/null +++ b/plugins/messages/test/message-state.test.ts @@ -0,0 +1,43 @@ +import type { DevframeHubContext } from '@devframes/hub/node' +import type { DevframeRpcClient } from 'devframe/client' +import { DevframeMessagesHost } from '@devframes/hub/node' +import { expect, it, vi } from 'vitest' +import { useMessages } from '../app/client/state/messages' + +it.each([1, 2, 3])('replaces cached messages after a trust refresh at new version %s', async (count) => { + const previous = new DevframeMessagesHost({} as DevframeHubContext) + await previous.info('old first', { id: 'old:1' }) + await previous.info('old second', { id: 'old:2' }) + let host = previous + let trusted: (value: boolean) => void = () => {} + const call = vi.fn(async (_name: string, since?: number | null, instanceId?: string | null) => host.listSince(since, instanceId)) + const rpc = { + call, + client: { + definitions: new Map(), + register: vi.fn(), + }, + events: { + on: (_name: string, handler: typeof trusted) => { trusted = handler }, + }, + } + // eslint-disable-next-line slop/no-chained-type-assertions -- Only message reads and trust events participate in this test. + const state = useMessages(rpc as unknown as DevframeRpcClient) + await vi.waitFor(() => expect(state.entries.map(entry => entry.id)).toEqual(['old:1', 'old:2'])) + expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list') + const oldCursor = host.listSince() + + const current = new DevframeMessagesHost({} as DevframeHubContext) + host = current + for (let i = 0; i < count; i++) + await host.info(`new ${i}`, { id: `new:${i}` }) + trusted(true) + await vi.waitFor(() => expect(state.entries.map(entry => entry.id)).toEqual(Array.from({ length: count }, (_, i) => `new:${i}`))) + expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list', oldCursor.version, oldCursor.instanceId) + + const cursor = host.listSince() + await host.remove('new:0') + trusted(true) + await vi.waitFor(() => expect(state.entries).toHaveLength(count - 1)) + expect(call).toHaveBeenLastCalledWith('devframes:plugin:messages:list', cursor.version, cursor.instanceId) +}) diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts index 2e0043b2..1044353d 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts @@ -216,7 +216,7 @@ export interface DevframeMessagesHost extends DevframeMessagesLevelShortcuts { update: (_: string, _: Partial) => Promise; remove: (_: string) => Promise; clear: () => Promise; - listSince: (_?: number | null) => DevframeMessagesListDelta; + listSince: (_?: number | null, _?: string | null) => DevframeMessagesListDelta; } export interface DevframeMessagesLevelShortcuts { info: (_: string, _?: DevframeMessageShortcutInput) => Promise; @@ -229,6 +229,7 @@ export interface DevframeMessagesListDelta { entries: DevframeMessageEntry[]; removedIds: string[]; version: number; + instanceId?: string; full: boolean; } export interface DevframePtyExecuteOptions { diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.d.ts index 255274e5..78c73524 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.d.ts @@ -69,6 +69,7 @@ export declare class DevframeMessagesHost implements DevframeMessagesHost$1 { time: number; }>; private _autoDeleteTimers; + private readonly _instanceId; private _clock; private _removalsTrimmedAt; private _tick; @@ -83,7 +84,7 @@ export declare class DevframeMessagesHost implements DevframeMessagesHost$1 { success(_: string, _?: DevframeMessageShortcutInput): Promise; debug(_: string, _?: DevframeMessageShortcutInput): Promise; clear(): Promise; - listSince(_?: number | null): DevframeMessagesListDelta; + listSince(_?: number | null, _?: string | null): DevframeMessagesListDelta; private _createHandle; } export declare class DevframeTerminalsHost implements DevframeTerminalsHost$1 { diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.js b/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.js index 877c5d52..39543a62 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.js +++ b/tests/__snapshots__/tsnapi/@devframes/hub/node.snapshot.js @@ -42,6 +42,7 @@ export class DevframeMessagesHost { lastModified removals _autoDeleteTimers + _instanceId _clock _removalsTrimmedAt _tick() {} @@ -56,7 +57,7 @@ export class DevframeMessagesHost { success(_, _) {} debug(_, _) {} async clear() {} - listSince(_) {} + listSince(_, _) {} _createHandle(_) {} } export class DevframeTerminalsHost { diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts index b5bfa454..9bc34691 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts @@ -216,7 +216,7 @@ export interface DevframeMessagesHost extends DevframeMessagesLevelShortcuts { update: (_: string, _: Partial) => Promise; remove: (_: string) => Promise; clear: () => Promise; - listSince: (_?: number | null) => DevframeMessagesListDelta; + listSince: (_?: number | null, _?: string | null) => DevframeMessagesListDelta; } export interface DevframeMessagesLevelShortcuts { info: (_: string, _?: DevframeMessageShortcutInput) => Promise; @@ -229,6 +229,7 @@ export interface DevframeMessagesListDelta { entries: DevframeMessageEntry[]; removedIds: string[]; version: number; + instanceId?: string; full: boolean; } export interface DevframePtyExecuteOptions { diff --git a/tests/__snapshots__/tsnapi/@devframes/plugin-messages/rpc.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/plugin-messages/rpc.snapshot.d.ts index 177725b0..982dbb77 100644 --- a/tests/__snapshots__/tsnapi/@devframes/plugin-messages/rpc.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/plugin-messages/rpc.snapshot.d.ts @@ -2,5 +2,5 @@ * Generated by tsnapi — public API snapshot of `@devframes/plugin-messages/rpc` */ // #region Variables -export declare const serverFunctions: readonly [import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:list", "query", [since?: number | null | undefined], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:add", "action", [input: import("@devframes/hub/types").DevframeMessageEntryInput], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:update", "action", [id: string, patch: Partial], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:remove", "action", [id: string], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:clear", "action", [], Promise, undefined, undefined, import("devframe").DevframeNodeContext>]; +export declare const serverFunctions: readonly [import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:list", "query", [since?: number | null | undefined, instanceId?: string | null | undefined], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:add", "action", [input: import("@devframes/hub/types").DevframeMessageEntryInput], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:update", "action", [id: string, patch: Partial], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:remove", "action", [id: string], Promise, undefined, undefined, import("devframe").DevframeNodeContext>, import("devframe/rpc").RpcFunctionDefinitionWithoutSchemas<"devframes:plugin:messages:clear", "action", [], Promise, undefined, undefined, import("devframe").DevframeNodeContext>]; // #endregion \ No newline at end of file