MolyKit Skill
Mejores prácticas para construir interfaces de chat AI con Makepad usando MolyKit, un kit de herramientas para aplicaciones de chat AI multiplataforma.
Código fuente: /Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit
Cuándo usar
Usa este skill cuando:
- Construyas interfaces de chat AI con Makepad
- Integres OpenAI u otras APIs de LLM
- Implementes async multiplataforma para entornos nativos y WASM
- Crear widgets de chat (mensajes, prompts, avatares)
- Manejar respuestas con streaming SSE
- Palabras clave: molykit, moly-kit, chat ai, bot client, openai makepad, chat widget, sse streaming
Resumen
MolyKit proporciona:
- Utilidades de async multiplataforma (PlatformSend, spawn(), ThreadToken)
- Widgets de chat listos para usar (Chat, Messages, PromptInput, Avatar)
- Trait BotClient para integración con proveedores de IA
- Cliente compatible con OpenAI y streaming SSE
- Tipos de protocolo para mensajes, bots y llamadas a herramientas
- Soporte para MCP (Model Context Protocol)
Patrones de async multiplataforma
PlatformSend - Solo enviar en nativo
/// Implica Send solo en plataformas nativas, no en WASM
/// - En nativo: implementado por tipos que implementan Send
/// - En WASM: implementado por TODOS los tipos
pub trait PlatformSend: PlatformSendInner {}
/// Tipo de future empaquetado para uso multiplataforma
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;
/// Tipo de stream empaquetado para uso multiplataforma
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;
Spawning agnóstico de plataforma
/// Ejecuta un future de forma independiente
/// - Usa tokio en nativo (requiere Send)
/// - Usa wasm-bindgen-futures en WASM (no requiere Send)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);
// Uso
spawn(async move {
let result = fetch_data().await;
Cx::post_action(DataReady(result));
SignalToUI::set_ui_signal();
});
Cancelación de tareas con AbortOnDropHandle
/// Manejador que aborta su future al soltarse
pub struct AbortOnDropHandle(AbortHandle);
// Uso - la tarea se cancela cuando el widget se suelta
#[rust]
task_handle: Option<AbortOnDropHandle>,
fn start_task(&mut self) {
let (future, handle) = abort_on_drop(async move {
// trabajo asíncrono...
});
self.task_handle = Some(handle);
spawn(async move { let _ = future.await; });
}
ThreadToken para tipos no Send en WASM
/// Almacena un valor no Send en un hilo-local, accede mediante token
pub struct ThreadToken<T: 'static>;
impl<T> ThreadToken<T> {
pub fn new(value: T) -> Self;
pub fn peek<R>(&self, f: impl FnOnce(&T) -> R) -> R;
pub fn peek_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}
// Uso - envuelve un tipo no Send para usarlo a través de límites Send
let token = ThreadToken::new(non_send_value);
spawn(async move {
token.peek(|value| {
// usar valor...
});
});
Trait BotClient
Implementación de integración con proveedores de IA
pub trait BotClient: Send {
/// Envía mensaje con respuesta en stream
fn send(
&mut self,
bot_id: &BotId,
messages: &[Message],
tools: &[Tool],
) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;
/// Obtiene bots/modelos disponibles
fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;
/// Clonar para pasar alrededor
fn clone_box(&self) -> Box<dyn BotClient>;
}
// Uso
let client = OpenAIClient::new("https://api.openai.com/v1".into());
client.set_key("sk-...")?;
let context = BotContext::from(client);
BotContext - Envoltorio compartible
/// Envoltorio compartible con bots cargados para acceso síncrono a UI
pub struct BotContext(Arc<Mutex<InnerBotContext>>);
impl BotContext {
pub fn load(&mut self) -> BoxPlatformSendFuture<ClientResult<()>>;
pub fn bots(&self) -> Vec<Bot>;
pub fn get_bot(&self, id: &BotId) -> Option<Bot>;
pub fn client(&self) -> Box<dyn BotClient>;
}
// Uso
let mut context = BotContext::from(client);
spawn(async move {
if let Err(errors) = context.load().await.into_result() {
// manejar errores
}
Cx::post_action(BotsLoaded);
});
Tipos de protocolo
Estructura de Mensaje
pub struct Message {
pub from: EntityId, // Usuario, Sistema, Bot(BotId), App
pub metadata: MessageMetadata,
pub content: MessageContent,
}
pub struct MessageContent {
pub text: String, // Contenido principal (markdown)
pub reasoning: String, // Razonamiento/pensamiento de IA
pub citations: Vec<String>, // URLs de fuentes
pub attachments: Vec<Attachment>,
pub tool_calls: Vec<ToolCall>,
pub tool_results: Vec<ToolResult>,
}
pub struct MessageMetadata {
pub is_writing: bool, // Aún se está transmitiendo
pub created_at: DateTime<Utc>,
}
Identificación de Bot
/// ID de bot único global: <len>;<id>@<provider>
pub struct BotId(Arc<str>);
impl BotId {
pub fn new(id: &str, provider: &str) -> Self;
pub fn id(&self) -> &str; // id local del proveedor
pub fn provider(&self) -> &str; // dominio del proveedor
}
// Ejemplo: BotId::new("gpt-4", "api.openai.com")
// -> "5;[email protected]"
Patrones de widgets
Widget Slot - Reemplazo de contenido en tiempo de ejecución
live_design! {
pub Slot = {{Slot}} {
width: Fill, height: Fit,
slot = <View> {} // contenido por defecto
}
}
// Uso - reemplaza contenido en tiempo de ejecución
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
slot.replace(custom);
} else {
slot.restore(); // vuelve al defecto
slot.default().as_standard_message_content().set_content(cx, &content);
}
Widget Avatar - Alternar texto/imagen
live_design! {
pub Avatar = {{Avatar}} <View> {
grapheme = <RoundedView> {
visible: false,
label = <Label> { text: "P" }
}
dependency = <RoundedView> {
visible: false,
image = <Image> {}
}
}
}
impl Widget for Avatar {
fn draw_walk(&mut self, cx: &mut Cx2d, ...) -> DrawStep {
if let Some(avatar) = &self.avatar {
match avatar {
Picture::Grapheme(g) => {
self.view(id!(grapheme)).set_visible(cx, true);
self.view(id!(dependency)).set_visible(cx, false);
self.label(id!(label)).set_text(cx, &g);
}
Picture::Dependency(d) => {
self.view(id!(dependency)).set_visible(cx, true);
self.view(id!(grapheme)).set_visible(cx, false);
self.image(id!(image)).load_image_dep_by_path(cx, d.as_str());
}
}
}
self.deref.draw_walk(cx, scope, walk)
}
}
Widget PromptInput
#[derive(Live, Widget)]
pub struct PromptInput {
#[deref] deref: CommandTextInput,
#[live] pub send_icon: LiveValue,
#[live] pub stop_icon: LiveValue,
#[rust] pub task: Task, // Enviar o Detener
#[rust] pub interactivity: Interactivity,
}
impl PromptInput {
pub fn submitted(&self, actions: &Actions) -> bool;
pub fn reset(&mut self, cx: &mut Cx);
pub fn set_send(&mut self);
pub fn set_stop(&mut self);
pub fn enable(&mut self);
pub fn disable(&mut self);
}
Widget Messages - Vista de conversación
#[derive(Live, Widget)]
pub struct Messages {
#[deref] deref: View,
#[rust] pub messages: Vec<Message>,
#[rust] pub bot_context: Option<BotContext>,
}
impl Messages {
pub fn set_messages(&mut self, messages: Vec<Message>, scroll_to_bottom: bool);
pub fn scroll_to_bottom(&mut self, cx: &mut Cx, triggered_by_stream: bool);
pub fn is_at_bottom(&self) -> bool;
}
Patrón UiRunner para Async-a-UI
impl Widget for PromptInput {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
self.deref.handle_event(cx, event, scope);
self.ui_runner().handle(cx, event, scope, self);
if self.button(id!(attach)).clicked(event.actions()) {
let ui = self.ui_runner();
Attachment::pick_multiple(move |result| match result {
Ok(attachments) => {
ui.defer_with_redraw(move |me, cx, _| {
me.attachment_list_ref().write().attachments.extend(attachments);
});
}
Err(_) => {}
});
}
}
}
Streaming SSE
/// Analiza un stream de bytes SSE en un stream de mensajes
pub fn parse_sse<S, B, E>(s: S) -> impl Stream<Item = Result<String, E>>
where
S: Stream<Item = Result<B, E>>,
B: AsRef<[u8]>,
{
// Dividir en "\n\n", extraer contenido "data:"
// Filtrar comentarios y mensajes [DONE]
}
// Uso en BotClient::send
fn send(&mut self, ...) -> BoxPlatformSendStream<...> {
let stream = stream! {
let response = client.post(url).send().await?;
let events = parse_sse(response.bytes_stream());
for await event in events {
let completion: Completion = serde_json::from_str(&event)?;
content.text.push_str(&completion.delta.content);
yield ClientResult::new_ok(content.clone());
}
};
Box::pin(stream)
}
Mejores prácticas
- Usa PlatformSend para multiplataforma: El mismo código funciona en nativo y WASM
- Usa spawn() no tokio::spawn: Spawning de tareas agnóstico de plataforma
- Usa AbortOnDropHandle: Cancela tareas cuando se suelta el widget
- Usa ThreadToken para tipos no Send en WASM: Almacenamiento en hilo-local con acceso mediante token
- Usa Slot para contenido personalizado: Permite que BotClient proporcione widgets personalizados
- Usa el patrón read()/write(): Acceso seguro mediante préstamos a través de WidgetRef
- Usa UiRunner::defer_with_redraw: Actualiza el widget desde un contexto asíncrono
- Maneja ClientResult con éxito parcial: Puede tener valor Y errores
Archivos de referencia
llms.txt- Referencia completa de la API de MolyKit