const CHANNEL = 'xpertai.remote_component'
const VERSION = 1
const responses = {
requestData: 'data',
requestParameterOptions: 'parameterOptions',
executeAction: 'actionResult',
executeFileAction: 'fileActionResult',
requestFileAccess: 'fileAccessResult',
invokeClientCommand: 'clientCommandResult'
} as const
type RequestType = keyof typeof responses
type RuntimeScope = {
groupId: string | null
projectId: string | null
conversationId: string | null
}
interface BridgeMessage {
channel: typeof CHANNEL
protocolVersion: typeof VERSION
type: string
instanceId?: unknown
scopeRevision?: unknown
runtimeScope?: unknown
requestId?: unknown
event?: unknown
message?: unknown
data?: unknown
result?: unknown
}
interface PendingRequest {
revision: number
responseType: string
resolve(value: unknown): void
reject(error: Error): void
timeout: number
}
let instanceId: string | null = null
let revision: number | null = null
let sequence = 0
const pending = new Map<string, PendingRequest>()
export const currentScopeRevision = () => revision
export function installBridge(handlers: {
onInit(message: BridgeMessage): void
onContextChange(scope: RuntimeScope, revision: number): void
onHostEvent(event: unknown): void
}) {
const listener = (event: MessageEvent<unknown>) => {
if (event.source !== window.parent || !isBridgeMessage(event.data)) return
const message = event.data
if (message.type === 'init') {
const scope = parseScope(message.runtimeScope)
if (typeof message.instanceId !== 'string' || !scope ||
!isRevision(message.scopeRevision)) return
if (instanceId && message.instanceId !== instanceId) return
if (revision !== null && message.scopeRevision < revision) return
if (revision !== message.scopeRevision) rejectPending('view_context_changed')
instanceId = message.instanceId
revision = message.scopeRevision
handlers.onInit(message)
return
}
if (!instanceId || message.instanceId !== instanceId) return
if (message.type === 'hostEvent') {
const change = parseContextChange(message.event)
if (change) {
if (revision !== null && change.revision <= revision) return
rejectPending('view_context_changed')
revision = change.revision
handlers.onContextChange(change.scope, revision)
return
}
handlers.onHostEvent(message.event)
return
}
if (typeof message.requestId !== 'string') return
const request = pending.get(message.requestId)
if (!request || request.revision !== revision) return
if (message.scopeRevision !== undefined && message.scopeRevision !== revision) return
if (message.type !== 'error' && message.type !== request.responseType) return
pending.delete(message.requestId)
window.clearTimeout(request.timeout)
if (message.type === 'error') {
request.reject(new Error(typeof message.message === 'string'
? message.message : 'remote_request_failed'))
} else {
request.resolve(message.data ?? message.result)
}
}
window.addEventListener('message', listener)
window.parent.postMessage({ channel: CHANNEL, protocolVersion: VERSION, type: 'ready' }, '*')
return () => {
window.removeEventListener('message', listener)
rejectPending('remote_bridge_disposed')
instanceId = null
revision = null
}
}
export function requestHost(type: RequestType, body: object) {
const requestRevision = revision
if (!instanceId || requestRevision === null) {
return Promise.reject(new Error('remote_bridge_not_initialized'))
}
const requestId = `${Date.now()}-${++sequence}`
return new Promise<unknown>((resolve, reject) => {
const timeout = window.setTimeout(() => {
pending.delete(requestId)
reject(new Error('remote_request_timeout'))
}, 30_000)
pending.set(requestId, {
revision: requestRevision, responseType: responses[type], resolve, reject, timeout
})
try {
window.parent.postMessage({
...body, channel: CHANNEL, protocolVersion: VERSION,
instanceId, scopeRevision: requestRevision, type, requestId
}, '*')
} catch {
pending.delete(requestId)
window.clearTimeout(timeout)
reject(new Error('remote_request_not_cloneable'))
}
})
}
function rejectPending(code: string) {
for (const request of pending.values()) {
window.clearTimeout(request.timeout)
request.reject(new Error(code))
}
pending.clear()
}
function isRevision(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
}
function isId(value: unknown): value is string | null {
return value === null || typeof value === 'string'
}
function parseScope(value: unknown): RuntimeScope | null {
if (!value || typeof value !== 'object' ||
!('projectId' in value) || !isId(value.projectId) ||
!('conversationId' in value) || !isId(value.conversationId)) return null
const groupId = 'groupId' in value ? value.groupId : null
if (!isId(groupId)) return null
return { groupId, projectId: value.projectId, conversationId: value.conversationId }
}
function parseContextChange(value: unknown) {
if (!value || typeof value !== 'object' || !('type' in value) ||
value.type !== 'view.context.changed' || !('data' in value)) return null
const data = value.data
if (!data || typeof data !== 'object' || !('revision' in data) ||
!isRevision(data.revision) || !('runtimeScope' in data)) return null
const scope = parseScope(data.runtimeScope)
return scope ? { revision: data.revision, scope } : null
}
function isBridgeMessage(value: unknown): value is BridgeMessage {
return !!value && typeof value === 'object' && !Array.isArray(value) &&
'channel' in value && value.channel === CHANNEL &&
'protocolVersion' in value && value.protocolVersion === VERSION &&
'type' in value && typeof value.type === 'string'
}