import type { DevframeRpcClient } from 'devframe/client' import type { SharedState } from 'devframe/utils/shared-state' import type { DevframeDockEntry, DevframeDockPanelState } from '../../types/docks' import { DEVFRAME_EVENTS } from 'devframe/constants' import { createEventEmitter } from 'devframe/utils/events' import { describe, expect, it, vi } from 'vitest' import { HUB_EVENTS } from '../../events' import { getDevframeClientContext } from '../context' import { createDevframeClientRuntime } from '../host' type DeepPartial = { [K in keyof T]?: DeepPartial } interface StubSharedState extends SharedState { /** Replace the state wholesale and emit `updated` (simulates a server patch). */ push: (next: T) => void } function createStubSharedState(initial: T): StubSharedState { let state = initial const events = createEventEmitter() return { value: () => state as any, on: events.on, mutate: (fn) => { fn(state) events.emit('updated', state, undefined, 'test') }, patch: () => {}, syncIds: new Set(), push(next) { state = next events.emit('updated', state, undefined, 'test') }, } } function createStubRpc() { const calls: any[][] = [] const states = new Map>() const definitions = new Map any }>() const partial: DeepPartial = { isTrusted: true, events: createEventEmitter(), sharedState: { async get(key: string, options?: { initialValue?: any }) { if (!states.has(key)) states.set(key, createStubSharedState(options?.initialValue)) return states.get(key)! }, }, call: async (...args: any[]) => { calls.push(args) if (args[0] === 'hub:messages:add') { return { id: 'msg-1', timestamp: 1, from: 'browser', ...args[1], } } return `rpc:${args[0]}` }, client: { definitions, register(fn: { name: string, type: string, handler?: (...args: any[]) => any }) { definitions.set(fn.name, fn) }, }, } const rpc = partial as DevframeRpcClient return { rpc, calls, states, definitions } } function iframeEntry(id: string, extra?: Record): DevframeDockEntry { return { id, title: id, icon: 'ph:cube', type: 'iframe', url: `/__${id}/`, ...extra, } as DevframeDockEntry } function groupEntry(id: string, extra?: Record): DevframeDockEntry { return { id, title: id, icon: 'ph:folder', type: 'group', ...extra, } as DevframeDockEntry } describe('createDevframeClientRuntime', () => { it('exposes panel state and emits coalesced changes', async () => { expect.assertions(6) const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc, clientType: 'embedded' }) const panelStates: DevframeDockPanelState[] = [] expect(host.context.panel.state).toEqual({ state: 'closed' }) host.context.panel.events.on( HUB_EVENTS.client.docksPanelStateChanged, panelState => panelStates.push(panelState), ) states.get('devframe:docks')!.push([ iframeEntry('one'), iframeEntry('two'), ]) host.context.panel.session.open = true const switched = host.context.docks.switchEntry('one') await switched expect(panelStates).toEqual([ { state: 'open', selectedDockId: 'one' }, ]) expect(host.context.panel.state).toEqual({ state: 'open', selectedDockId: 'one' }) host.context.panel.session.open = true host.context.panel.session.selectedDockId = 'one' await Promise.resolve() expect(panelStates).toHaveLength(1) await host.context.docks.switchEntry('two') expect(panelStates.at(-1)).toEqual({ state: 'open', selectedDockId: 'two' }) host.context.panel.session.open = false const cleared = host.context.docks.switchEntry(null) await cleared expect(panelStates.at(-1)).toEqual({ state: 'closed' }) host.dispose() }) it('publishes the global client context with the full surface', async () => { const { rpc } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) expect(getDevframeClientContext()).toBe(host.context) expect(host.context.clientType).toBe('standalone') expect(host.context.rpc).toBe(rpc) expect(host.context.panel.session.open).toBe(true) expect(host.context.when.context).toMatchObject({ clientType: 'standalone', dockOpen: true, paletteOpen: false, dockSelectedId: '', }) host.dispose() }) it('reconciles dock entries from shared state and tracks per-entry state', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const docksState = states.get('devframe:docks')! docksState.push([ iframeEntry('one'), iframeEntry('two'), ]) expect(host.context.docks.entries.map(e => e.id)).toEqual(['one', 'two']) expect(host.context.docks.getStateById('one')?.entryMeta.id).toBe('one') docksState.push([ iframeEntry('two'), ]) expect(host.context.docks.entries.map(e => e.id)).toEqual(['two']) expect(host.context.docks.getStateById('one')).toBeUndefined() host.dispose() }) it('keeps a `visibility: false` entry in the raw model, activatable by id', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) states.get('devframe:docks')!.push([ iframeEntry('anchor', { subTabs: { protocol: 'postmessage' }, visibility: 'false', }), iframeEntry('visible'), ]) // `visibility` is a render-only hint for the UI layer; the hub itself // never filters `entries`/`getStateById`/`switchEntry` by it, so the // anchor stays fully reachable. expect(host.context.docks.entries.map(e => e.id)).toEqual(['anchor', 'visible']) expect(host.context.docks.getStateById('anchor')).toBeDefined() expect(await host.context.docks.switchEntry('anchor')).toBe(true) expect(host.context.docks.selected?.id).toBe('anchor') host.dispose() }) it('groups entries by category: grouped members bucket under their group, orphans by their own', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) states.get('devframe:docks')!.push([ // (a) member with groupId + its own category → outer bucket = group's category ('framework'), // and its own 'app' category is reinterpreted as an in-group sub-category. groupEntry('nuxt', { category: 'framework' }), iframeEntry('nuxt:overview', { groupId: 'nuxt', category: 'app' }), // (b) group with no category → members bucket to 'default'. groupEntry('misc'), iframeEntry('misc:one', { groupId: 'misc', category: 'web' }), // (c) orphan member (groupId with no registered group) → its own category ('web'). iframeEntry('orphan', { groupId: 'ghost', category: 'web' }), // plain ungrouped entry keeps its own category. iframeEntry('plain', { category: 'app' }), ]) const grouped = Object.fromEntries( host.context.docks.groupedEntries.map(([cat, entries]) => [ cat, entries.map(e => e.id), ]), ) // (a) grouped member lands under the group's category, alongside the group button. expect(grouped.framework).toEqual(['nuxt', 'nuxt:overview']) // (b) group without a category, and its member, bucket to 'default'. expect(grouped.default).toEqual(['misc', 'misc:one']) // (c) orphan + plain keep their own categories. expect(grouped.web).toEqual(['orphan']) expect(grouped.app).toEqual(['plain']) // Categories sort by DEFAULT_CATEGORIES_ORDER, framework first. expect(host.context.docks.groupedEntries.map(([cat]) => cat)).toEqual([ 'framework', 'default', 'app', 'web', ]) host.dispose() }) it('merges the host-page categoryOrder option beneath DEFAULT_CATEGORIES_ORDER', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc, categoryOrder: { app: -200, web: 999 }, }) states.get('devframe:docks')!.push([ iframeEntry('app-entry', { category: 'app' }), iframeEntry('web-entry', { category: 'web' }), iframeEntry('framework-entry', { category: 'framework' }), ]) expect(host.context.docks.categoryOrder).toMatchObject({ app: -200, web: 999, framework: -100 }) // `app` (-200, from the option) now sorts ahead of `framework` (-100, default). expect(host.context.docks.groupedEntries.map(([cat]) => cat)).toEqual(['app', 'framework', 'web']) host.dispose() }) it('switches entries with activation/deactivation events and when-context updates', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) states.get('devframe:docks')!.push([ iframeEntry('one'), iframeEntry('two'), ]) const activated: string[] = [] const deactivated: string[] = [] for (const id of ['one', 'two']) { const state = host.context.docks.getStateById(id)! state.events.on('entry:activated', () => activated.push(id)) state.events.on('entry:deactivated', () => deactivated.push(id)) } expect(await host.context.docks.switchEntry('one')).toBe(true) expect(host.context.docks.selected?.id).toBe('one') expect(host.context.docks.getStateById('one')?.isActive).toBe(true) expect(host.context.when.context.dockSelectedId).toBe('one') expect(await host.context.docks.switchEntry('one')).toBe(false) // no-op expect(await host.context.docks.toggleEntry('two')).toBe(true) expect(await host.context.docks.toggleEntry('two')).toBe(true) // toggles off expect(activated).toEqual(['one', 'two']) expect(deactivated).toEqual(['one', 'two']) expect(host.context.docks.selected).toBeNull() host.dispose() }) it('keeps the latest selection when an earlier switch is still loading its page script', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const fixture = globalThis as typeof globalThis & { __DF_SLOW_SCRIPT__?: Promise } let finishScript!: () => void fixture.__DF_SLOW_SCRIPT__ = new Promise((resolve) => { finishScript = resolve }) try { states.get('devframe:docks')!.push([ iframeEntry('slow', { clientScript: { importFrom: 'data:text/javascript,export default () => globalThis.__DF_SLOW_SCRIPT__' }, }), iframeEntry('fast'), ]) const slow = host.context.docks.switchEntry('slow') expect(await host.context.docks.switchEntry('fast')).toBe(true) finishScript() expect(await slow).toBe(false) expect(host.context.docks.selected?.id).toBe('fast') } finally { host.dispose() delete fixture.__DF_SLOW_SCRIPT__ } }) it('switches the active dock when the hub broadcasts devframe:docks:activate', async () => { const { rpc, states, definitions } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) states.get('devframe:docks')!.push([ iframeEntry('one'), iframeEntry('devframes_plugin_terminals'), ]) // Simulate the hub's server→client broadcast. const handler = definitions.get('devframe:docks:activate')!.handler! handler({ dockId: 'devframes_plugin_terminals', params: { sessionId: 'sess-1' }, }) await vi.waitFor(() => expect(host.context.docks.selectedId).toBe('devframes_plugin_terminals')) // Unknown dock ids degrade to a no-op (the previous selection stands). handler({ dockId: 'ghost' }) await new Promise(r => setTimeout(r, 0)) expect(host.context.docks.selectedId).toBe('devframes_plugin_terminals') host.dispose() }) it('registers, updates, and disposes client-only docks merged with server entries', async () => { const { rpc, states } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const docks = host.context.docks states.get('devframe:docks')!.push([ iframeEntry('server'), ]) // Client-only registration is merged with the server entries. const handle = docks.register(iframeEntry('client')) expect(docks.entries.map(e => e.id)).toEqual(['server', 'client']) expect(docks.getStateById('client')?.entryMeta.id).toBe('client') // It survives a server-driven reconcile and is switchable. states.get('devframe:docks')!.push([ iframeEntry('server'), iframeEntry('server2'), ]) expect(docks.entries.map(e => e.id)).toEqual(['server', 'server2', 'client']) expect(await docks.switchEntry('client')).toBe(true) expect(docks.selected?.id).toBe('client') // A registered client dock is never pushed into shared state (client-only). expect((states.get('devframe:docks')!.value() as DevframeDockEntry[]).map(e => e.id)) .toEqual(['server', 'server2']) // Patch in place; id is immutable. handle.update({ title: 'Renamed' }) expect(docks.getStateById('client')?.entryMeta.title).toBe('Renamed') expect(() => handle.update({ id: 'other' } as any)).toThrow() // Duplicate id throws unless forced; update() requires a prior registration. expect(() => docks.register(iframeEntry('client'))).toThrow() expect(() => docks.register(iframeEntry('client'), true)).not.toThrow() expect(() => docks.update(iframeEntry('ghost'))).toThrow() // Disposing removes it from the merge. handle.dispose() expect(docks.entries.map(e => e.id)).toEqual(['server', 'server2']) expect(docks.getStateById('client')).toBeUndefined() host.dispose() }) it('imports the client script of a client-registered dock', async () => { const { rpc } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const received: any[] = [] ;(globalThis as any).__DF_TEST_CLIENT_DOCK__ = (ctx: any) => received.push(ctx) const dataUrl = `data:text/javascript,export default ctx => globalThis.__DF_TEST_CLIENT_DOCK__(ctx)` host.context.docks.register(iframeEntry('local', { clientScript: { eager: true, importFrom: dataUrl }, })) await vi.waitFor(() => expect(received).toHaveLength(1)) expect(received[0].current.entryMeta.id).toBe('local') delete (globalThis as any).__DF_TEST_CLIENT_DOCK__ host.dispose() }) it('executes client commands locally and server commands over hub:commands:execute', async () => { const { rpc, calls } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const ran: any[] = [] const off = host.context.commands.register({ id: 'test:client', title: 'Client', source: 'client', action: (...args: any[]) => { ran.push(args) }, }) await host.context.commands.execute('test:client', 1, 2) expect(ran).toEqual([ [1, 2], ]) await expect(host.context.commands.execute('srv:cmd', 'x')).resolves.toBe('rpc:hub:commands:execute') expect(calls.at(-1)).toEqual(['hub:commands:execute', 'srv:cmd', 'x']) off() expect(host.context.commands.commands.find(c => c.id === 'test:client')).toBeUndefined() host.dispose() }) it('executes nested client commands locally and resolves their default keybindings', async () => { const { rpc, calls } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const ran: string[] = [] const off = host.context.commands.register({ id: 'test:parent', title: 'Parent', source: 'client', children: [ { id: 'test:parent:child', title: 'Child', source: 'client', children: [ { id: 'test:parent:child:grandchild', title: 'Grandchild', source: 'client', keybindings: [ { key: 'Mod+Shift+C' }, ], action: (value: string) => { ran.push(value) }, }, ], }, ], }) await host.context.commands.execute('test:parent:child:grandchild', 'nested') expect(ran).toEqual(['nested']) expect(calls).toEqual([]) expect(host.context.commands.getKeybindings('test:parent:child:grandchild')).toEqual([ { key: 'Mod+Shift+C' }, ]) off() host.dispose() }) it('imports a dock entry client script and hands it the script context', async () => { const { rpc, states, calls } = createStubRpc() const host = await createDevframeClientRuntime({ rpc }) const received: any[] = [] ;(globalThis as any).__DF_TEST_SCRIPT__ = (ctx: any) => received.push(ctx) const dataUrl = `data:text/javascript,export default ctx => globalThis.__DF_TEST_SCRIPT__(ctx)` states.get('devframe:docks')!.push([ iframeEntry('scripted', { clientScript: { eager: true, importFrom: dataUrl }, }), ]) await vi.waitFor(() => expect(received).toHaveLength(1)) const scriptCtx = received[0] expect(scriptCtx.current.entryMeta.id).toBe('scripted') expect(scriptCtx.rpc).toBe(rpc) // The messages client is scoped to the entry: `category` defaults to the // entry id, and the doc'd per-level shortcuts delegate to add(). await scriptCtx.messages.add({ message: 'hello', level: 'info' }) expect(calls.at(-1)).toEqual([ 'hub:messages:add', { message: 'hello', level: 'info', category: 'scripted' }, ]) await scriptCtx.messages.warn('careful', { category: 'a11y' }) expect(calls.at(-1)).toEqual([ 'hub:messages:add', { message: 'careful', level: 'warn', category: 'a11y' }, ]) delete (globalThis as any).__DF_TEST_SCRIPT__ host.dispose() }) it('warns when a second host replaces a published context; dispose unpublishes it', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { const { rpc } = createStubRpc() const first = await createDevframeClientRuntime({ rpc }) expect(warn).not.toHaveBeenCalled() const second = await createDevframeClientRuntime({ rpc }) expect(warn).toHaveBeenCalledOnce() expect(getDevframeClientContext()).toBe(second.context) // The first host no longer owns the published context, so leave it alone. first.dispose() expect(getDevframeClientContext()).toBe(second.context) second.dispose() expect(getDevframeClientContext()).toBeUndefined() } finally { warn.mockRestore() } }) }) it('waits for trust for eager setup and activation for lazy setup in the headless runtime', async () => { expect.assertions(5) const { rpc, states } = createStubRpc() Object.assign(rpc, { isTrusted: false }) const runtime = await createDevframeClientRuntime({ rpc }) const attempt = vi.fn() const fixture = globalThis as typeof globalThis & { __DF_LAZY_TEST__?: () => void } fixture.__DF_LAZY_TEST__ = attempt const script = { importFrom: 'data:text/javascript,export default () => globalThis.__DF_LAZY_TEST__()' } const eager = iframeEntry('eager', { clientScript: { ...script, eager: true }, }) const lazy = iframeEntry('lazy', { clientScript: script }) try { states.get('devframe:docks')!.push([eager, lazy]) expect(attempt).not.toHaveBeenCalled() await expect(runtime.context.docks.switchEntry('lazy')).resolves.toBe(false) Object.assign(rpc, { isTrusted: true }) rpc.events.emit(DEVFRAME_EVENTS.client.isTrustedUpdated, true) await expect.poll(() => attempt.mock.calls.length).toBe(1) await runtime.context.docks.switchEntry('lazy') expect(attempt).toHaveBeenCalledTimes(2) await runtime.context.docks.switchEntry(null) await runtime.context.docks.switchEntry('lazy') expect(attempt).toHaveBeenCalledTimes(2) } finally { runtime.dispose() delete fixture.__DF_LAZY_TEST__ } }) it('keeps an eager custom-render renderer activation-gated in the headless runtime', async () => { expect.assertions(2) const { rpc, states } = createStubRpc() const runtime = await createDevframeClientRuntime({ rpc }) const attempt = vi.fn() const fixture = globalThis as typeof globalThis & { __DF_RENDERER_TEST__?: () => void } fixture.__DF_RENDERER_TEST__ = attempt const entry = { id: 'eager-renderer', title: 'Eager renderer', icon: 'ph:cube', type: 'custom-render', renderer: { eager: true, importFrom: 'data:text/javascript,export default () => globalThis.__DF_RENDERER_TEST__()' }, } satisfies DevframeDockEntry try { states.get('devframe:docks')!.push([entry]) // Give any eager import a chance to resolve; a renderer needs its mounted // panel, so `eager` must not run it before activation. await new Promise(resolve => setTimeout(resolve, 10)) expect(attempt).not.toHaveBeenCalled() await runtime.context.docks.switchEntry(entry.id) expect(attempt).toHaveBeenCalledTimes(1) } finally { runtime.dispose() delete fixture.__DF_RENDERER_TEST__ } }) it.each([false, true])('retries setup after trust is revoked during import (eager: %s)', async (eager) => { expect.assertions(6) const reportError = vi.spyOn(console, 'error').mockImplementation(() => {}) const { rpc, states } = createStubRpc() const runtime = await createDevframeClientRuntime({ rpc }) const docks = runtime.context.docks const fixture = globalThis as typeof globalThis & { __DF_IMPORT_GATE_HEADLESS__?: () => Promise, __DF_IMPORT_SETUP_HEADLESS__?: () => void } let releaseImport!: () => void const importGate = new Promise((resolve) => { releaseImport = resolve }) const importing = vi.fn(() => importGate) const setup = vi.fn() fixture.__DF_IMPORT_GATE_HEADLESS__ = importing fixture.__DF_IMPORT_SETUP_HEADLESS__ = setup const entry = { id: `revoked-import-${eager}`, type: 'iframe', title: 'Revoked import', icon: 'ph:browser', url: '/fixture', clientScript: { eager, importFrom: `data:text/javascript,await globalThis.__DF_IMPORT_GATE_HEADLESS__(); export default () => globalThis.__DF_IMPORT_SETUP_HEADLESS__(); // ${eager}`, }, } satisfies DevframeDockEntry try { states.get('devframe:docks')!.push([entry]) const activation = docks.switchEntry(entry.id) const rejected = expect(activation).rejects.toThrow('no longer trusted') await expect.poll(() => importing.mock.calls.length).toBe(1) Object.assign(rpc, { isTrusted: false }) rpc.events.emit(DEVFRAME_EVENTS.client.isTrustedUpdated, false) releaseImport() await rejected expect(setup).not.toHaveBeenCalled() expect(docks.selectedId).toBeNull() Object.assign(rpc, { isTrusted: true }) rpc.events.emit(DEVFRAME_EVENTS.client.isTrustedUpdated, true) await expect(docks.switchEntry(entry.id)).resolves.toBe(true) expect(setup).toHaveBeenCalledOnce() } finally { releaseImport() delete fixture.__DF_IMPORT_GATE_HEADLESS__ delete fixture.__DF_IMPORT_SETUP_HEADLESS__ reportError.mockRestore() runtime.dispose() } }) it('does not activate an iframe when trust is lost while its setup completes', async () => { expect.assertions(2) const { rpc, states } = createStubRpc() const runtime = await createDevframeClientRuntime({ rpc }) const docks = runtime.context.docks const fixture = globalThis as typeof globalThis & { __DF_SETUP_REVOKE_HEADLESS__?: () => void } fixture.__DF_SETUP_REVOKE_HEADLESS__ = () => { Object.assign(rpc, { isTrusted: false }) rpc.events.emit(DEVFRAME_EVENTS.client.isTrustedUpdated, false) } const entry = { id: 'revoked-during-setup', type: 'iframe', title: 'Revoked setup', icon: 'ph:browser', url: '/fixture', clientScript: { importFrom: 'data:text/javascript,export default async () => globalThis.__DF_SETUP_REVOKE_HEADLESS__()' }, } satisfies DevframeDockEntry try { states.get('devframe:docks')!.push([entry]) await expect(docks.switchEntry(entry.id)).resolves.toBe(false) expect(docks.selectedId).toBeNull() } finally { delete fixture.__DF_SETUP_REVOKE_HEADLESS__ runtime.dispose() } }) it('runs a toggle action as an on/off tool that hides and restores the panel', async () => { expect.assertions(12) const { rpc, states } = createStubRpc() const runtime = await createDevframeClientRuntime({ rpc }) const events: string[] = [] const setup = vi.fn((ctx: any) => { ctx.current.events.on('entry:activated', () => events.push('on')) ctx.current.events.on('entry:deactivated', () => events.push('off')) }) const fixture = globalThis as typeof globalThis & { __DF_TOGGLE_TEST__?: (ctx: any) => void } fixture.__DF_TOGGLE_TEST__ = setup const tool = { id: 'tool', title: 'Inspect', icon: 'ph:cursor', type: 'action', toggle: true, action: { importFrom: 'data:text/javascript,export default ctx => globalThis.__DF_TOGGLE_TEST__(ctx)' }, } satisfies DevframeDockEntry const { docks, panel } = runtime.context try { states.get('devframe:docks')!.push([ iframeEntry('panel'), tool, ]) await docks.switchEntry('panel') panel.session.open = true await expect(docks.switchEntry('tool')).resolves.toBe(true) expect(docks.selectedId).toBe('panel') expect(docks.getStateById('tool')!.isActive).toBe(true) expect(panel.session.open).toBe(false) // A second click turns it off and brings the panel back. await expect(docks.toggleEntry('tool')).resolves.toBe(true) expect(panel.session.open).toBe(true) await docks.switchEntry('tool') await expect(docks.setActionActive('tool', false)).resolves.toBe(true) await expect(docks.setActionActive('tool', false)).resolves.toBe(false) // A new selection wins: the tool goes off and the old panel is not restored. await docks.switchEntry('tool') await docks.switchEntry(null) expect(docks.getStateById('tool')!.isActive).toBe(false) expect(panel.session.open).toBe(false) expect(setup).toHaveBeenCalledOnce() expect(events).toEqual(['on', 'off', 'on', 'off', 'on', 'off']) } finally { runtime.dispose() delete fixture.__DF_TOGGLE_TEST__ } })