Communitygithub.com

MolyKit Skill

MakepadでAIチャットインターフェースを構築するためのMolyKitクロスプラットフォームAIチャットツールキットのベストプラクティス。

MolyKit Skill とは?

このスキルは、Makepad上でMolyKitを使用してクロスプラットフォームのAIチャットアプリケーションを構築するためのベストプラクティスを提供します。プラットフォーム間で動作する非同期ユーティリティ(PlatformSend、spawn、ThreadToken)や、チャットウィジェット(Chat、Messages、PromptInput、Avatar)、BotClientトレイトを用いたAIプロバイダー統合、OpenAI互換クライアントによるSSEストリーミング応答の処理、そしてMCP(Model Context Protocol)サポートなどをカバーしています。MakepadやMolyKitを使用してAIチャットインターフェースを開発する開発者向けで、特にネイティブとWASMの両方をターゲットとする場合に有用です。クロスプラットフォームの非同期処理、ウィジェットのランタイム置換、UIと非同期タスクの連携など、実際のコード例を交えた詳細なパターンが解説されています。

対応✓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 Skill は何をしますか?

MakepadでMolyKit(クロスプラットフォームAIチャットアプリケーション向けツールキット)を使用した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(Model Context Protocol)サポート

クロスプラットフォーム非同期パターン

PlatformSend - ネイティブのみSend

/// ネイティブプラットフォームでのみSendを意味し、WASMでは意味しない
/// - ネイティブ: Sendを実装する型によって実装される
/// - WASM: すべての型によって実装される
pub trait PlatformSend: PlatformSendInner {}

/// クロスプラットフォーム使用のためのボックス化されたfuture型
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;

/// クロスプラットフォーム使用のためのボックス化されたstream型
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;

プラットフォームに依存しないスポーン

/// futureを独立して実行する
/// - ネイティブでは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によるタスクキャンセル

/// ドロップ時にfutureを中断するハンドル
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上の非Send型のためのThreadToken

/// スレッドローカルに非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境界を越えて使用するために非Send型をラップする
let token = ThreadToken::new(non_send_value);
spawn(async move {
    token.peek(|value| {
        // 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;       // プロバイダー内のID
    pub fn provider(&self) -> &str; // プロバイダードメイン
}

// 例: 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上の非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.

関連スキル