Communitygithub.com

MolyKit 스킬

Makepad과 MolyKit을 사용하여 크로스 플랫폼 AI 채팅 인터페이스를 구축하기 위한 모범 사례를 제공합니다.

MolyKit 스킬란 무엇인가요?

이 스킬은 크로스 플랫폼 AI 채팅 애플리케이션을 위한 툴킷인 MolyKit을 사용하여 Makepad로 AI 챗 인터페이스를 구축하는 개발자를 위한 포괄적인 가이드입니다. 주요 기능으로는 최신 Rust 비동기 패턴(PlatformSend, spawn(), ThreadToken)을 활용한 크로스 플랫폼 비동기 유틸리티, OpenAI 호환 클라이언트와 SSE 스트리밍을 포함한 BotClient 트레이트 기반의 AI 제공자 통합, 그리고 Chat, Messages, PromptInput, Avatar와 같은 재사용 가능한 위젯이 포함되어 있습니다. 또한 Slot 위젯을 통한 런타임 콘텐츠 교체, UiRunner 패턴을 통한 비동기-UI 업데이트, 그리고 모델 컨텍스트 프로토콜(MCP) 지원과 같은 고급 패턴을 다룹니다. 이 스킬은 Claude Code, Cursor, Codex와 같은 AI 에이전트 도구에서 MolyKit 기반 프로젝트 작업 시 참조할 수 있도록 설계되었습니다.

지원 대상✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/majiayu000/claude-skill-registry/tree/HEAD/skills/ai-llm/molykit-galacticvraj-vraj-portfolio

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

MolyKit 스킬은(는) 무엇을 하나요?

Makepad과 MolyKit을 사용하여 크로스 플랫폼 AI 채팅 인터페이스를 구축하기 위한 모범 사례입니다. MolyKit은 크로스 플랫폼 AI 채팅 애플리케이션을 위한 툴킷입니다.

소스 코드베이스: /Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit

사용 시기

다음과 같은 경우 이 스킬을 사용하세요:

  • Makepad로 AI 채팅 인터페이스 구축
  • OpenAI 또는 기타 LLM API 통합
  • 네이티브 및 WASM을 위한 크로스 플랫폼 비동기 구현
  • 채팅 위젯(메시지, 프롬프트, 아바타) 생성
  • SSE 스트리밍 응답 처리
  • 키워드: molykit, moly-kit, ai chat, bot client, openai makepad, chat widget, sse streaming

개요

MolyKit은 다음을 제공합니다:

  • 크로스 플랫폼 비동기 유틸리티 (PlatformSend, spawn(), ThreadToken)
  • 바로 사용 가능한 채팅 위젯 (Chat, Messages, PromptInput, Avatar)
  • AI 제공자 통합을 위한 BotClient 트레이트
  • SSE 스트리밍을 지원하는 OpenAI 호환 클라이언트
  • 메시지, 봇 및 도구 호출을 위한 프로토콜 타입
  • MCP (모델 컨텍스트 프로토콜) 지원

크로스 플랫폼 비동기 패턴

PlatformSend - 네이티브에서만 전송 가능

/// 네이티브 플랫폼에서만 Send를 의미하며 WASM에서는 아님
/// - 네이티브: Send를 구현하는 타입에 의해 구현됨
/// - WASM: 모든 타입에 의해 구현됨
pub trait PlatformSend: PlatformSendInner {}

/// 크로스 플랫폼 사용을 위한 박스형 퓨처 타입
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;

/// 크로스 플랫폼 사용을 위한 박스형 스트림 타입
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;

플랫폼에 구애받지 않는 생성(Spawning)

/// 퓨처를 독립적으로 실행합니다.
/// - 네이티브에서는 tokio 사용 (Send 필요)
/// - WASM에서는 wasm-bindgen-futures 사용 (Send 불필요)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);

// 사용법
spawn(async move {
    let result = fetch_data().await;
    Cx::post_action(DataReady(result));
    SignalToUI::set_ui_signal();
});

AbortOnDropHandle을 사용한 작업 취소

/// 드롭될 때 퓨처를 중단하는 핸들
pub struct AbortOnDropHandle(AbortHandle);

// 사용법 - 위젯이 드롭되면 작업 취소됨
#[rust]
task_handle: Option<AbortOnDropHandle>,

fn start_task(&mut self) {
    let (future, handle) = abort_on_drop(async move {
        // 비동기 작업...
    });
    self.task_handle = Some(handle);
    spawn(async move { let _ = future.await; });
}

WASM에서 Non-Send 타입을 위한 ThreadToken

/// Non-Send 값을 스레드 로컬에 저장하고 토큰을 통해 접근
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;
}

// 사용법 - Send 경계를 넘어 사용하기 위해 non-Send 타입 래핑
let token = ThreadToken::new(non_send_value);
spawn(async move {
    token.peek(|value| {
        // 값 사용...
    });
});

BotClient 트레이트

AI 제공자 통합 구현

pub trait BotClient: Send {
    /// 스트리밍 응답으로 메시지 전송
    fn send(
        &mut self,
        bot_id: &BotId,
        messages: &[Message],
        tools: &[Tool],
    ) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;

    /// 사용 가능한 봇/모델 가져오기
    fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;

    /// 전달을 위한 복제
    fn clone_box(&self) -> Box<dyn BotClient>;
}

// 사용법
let client = OpenAIClient::new("https://api.openai.com/v1".into());
client.set_key("sk-...")?;
let context = BotContext::from(client);

BotContext - 공유 가능한 래퍼

/// 동기 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>;
}

// 사용법
let mut context = BotContext::from(client);
spawn(async move {
    if let Err(errors) = context.load().await.into_result() {
        // 오류 처리
    }
    Cx::post_action(BotsLoaded);
});

프로토콜 타입

메시지 구조체

pub struct Message {
    pub from: EntityId,         // User, System, Bot(BotId), App
    pub metadata: MessageMetadata,
    pub content: MessageContent,
}

pub struct MessageContent {
    pub text: String,           // 주요 내용 (마크다운)
    pub reasoning: String,      // AI 추론/사고
    pub citations: Vec<String>, // 출처 URL
    pub attachments: Vec<Attachment>,
    pub tool_calls: Vec<ToolCall>,
    pub tool_results: Vec<ToolResult>,
}

pub struct MessageMetadata {
    pub is_writing: bool,       // 아직 스트리밍 중
    pub created_at: DateTime<Utc>,
}

봇 식별

/// 전역 고유 봇 ID: <len>;<id>@<provider>
pub struct BotId(Arc<str>);

impl BotId {
    pub fn new(id: &str, provider: &str) -> Self;
    pub fn id(&self) -> &str;       // provider-local id
    pub fn provider(&self) -> &str; // provider domain
}

// 예제: BotId::new("gpt-4", "api.openai.com")
// -> "5;[email protected]"

위젯 패턴

Slot 위젯 - 런타임 콘텐츠 교체

live_design! {
    pub Slot = {{Slot}} {
        width: Fill, height: Fit,
        slot = <View> {}  // 기본 콘텐츠
    }
}

// 사용법 - 런타임에 콘텐츠 교체
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
    slot.replace(custom);
} else {
    slot.restore();  // 기본값으로 복원
    slot.default().as_standard_message_content().set_content(cx, &content);
}

Avatar 위젯 - 텍스트/이미지 전환

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)
    }
}

PromptInput 위젯

#[derive(Live, Widget)]
pub struct PromptInput {
    #[deref] deref: CommandTextInput,
    #[live] pub send_icon: LiveValue,
    #[live] pub stop_icon: LiveValue,
    #[rust] pub task: Task,           // Send 또는 Stop
    #[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);
}

Messages 위젯 - 대화 보기

#[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;
}

비동기-UI를 위한 UiRunner 패턴

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(_) => {}
            });
        }
    }
}

SSE 스트리밍

/// SSE 바이트 스트림을 메시지 스트림으로 파싱
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]>,
{
    // "\n\n"로 분할, "data:" 콘텐츠 추출
    // 주석 및 [DONE] 메시지 필터링
}

// 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)
}

모범 사례

  1. 크로스 플랫폼을 위해 PlatformSend 사용: 네이티브와 WASM에서 동일한 코드 작동
  2. tokio::spawn 대신 spawn() 사용: 플랫폼에 구애받지 않는 작업 생성
  3. AbortOnDropHandle 사용: 위젯 드롭 시 작업 취소
  4. WASM에서 non-Send를 위해 ThreadToken 사용: 토큰 접근을 통한 스레드 로컬 저장소
  5. 사용자 정의 콘텐츠를 위해 Slot 사용: BotClient가 사용자 정의 위젯을 제공할 수 있도록 함
  6. read()/write() 패턴 사용: WidgetRef를 통한 안전한 빌림 접근
  7. UiRunner::defer_with_redraw 사용: 비동기 컨텍스트에서 위젯 업데이트
  8. ClientResult 부분 성공 처리: 값과 오류를 모두 가질 수 있음

참조 파일

  • llms.txt - 전체 MolyKit API 참조

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

majiayu000/claude-skill-registry

Builds, edit or validate Agent Skill through conversational discovery. Use when the user requests to "Create an Agent", "Optimize an Agent" or "Edit an Agent".

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Analyzes current state and user query to answer BMad questions or recommend the next workflow or agent. Use when user says what should I do next, what do I do now, or asks a question about BMad

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Portfolio allocation and rebalancing optimizer. Manages asset allocation across stocks/cash/bonds, performs periodic rebalancing, and ensures diversification according to market regime and risk tolerance.

majiayu000/claude-skill-registry

Create a hilarious and ultra-realistic video of an anthropomorphic animal acting like a human vlogger in a real-world setting.

majiayu000/claude-skill-registry

Speech-to-text transcription and translation via OpenAI Audio API -- models, response formats, timestamps, prompting, streaming, chunking, and diarization

majiayu000/claude-skill-registry

BlockRun works with Claude Code and Google Antigravity.

majiayu000/claude-skill-registry

This skill should be used when the user asks about libraries, frameworks, API references, or needs code examples. Activates for setup questions, code generation involving libraries, or mentions of specific frameworks like React, Vue, Next.js, Prisma, Supabase, etc.

majiayu000/claude-skill-registry

小省导购员数字人带货版即梦视频提示词生成系统,基于四大智能体协同(提示词生成师、质量管控师、知识库运维师、跨环节适配师),按照"主体+运动+场景+(镜头语言+光影+氛围)"公式输出中英文双版提示词,适配5s短视频。确保人物一致性、视觉连贯性、情绪连贯性,支持知识库智能复用和跨工具适配(Suno音乐、AI绘画),为数字人带货视频提供高质量提示词生成服务。

majiayu000/claude-skill-registry

Upload and manage files using Google Gemini File API via scripts/. Use for uploading images, audio, video, PDFs, and other files for use with Gemini models. Supports file upload, status checking, and file management. Triggers on "upload file", "file API", "upload image", "upload PDF", "upload video", "file management".

majiayu000/claude-skill-registry

AI and machine learning workflow covering LLM application development, RAG implementation, agent architecture, ML pipelines, and AI-powered features.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Conduct domain and industry research. Use when the user says "lets create a research report on [domain or industry]

majiayu000/claude-skill-registry

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

관련 스킬