Back to Skills

Convex Agents Messages

Sstobo
Updated Today
79 views
5
5
View on GitHub
Designdesign

About

This skill provides message management for agent conversations, allowing developers to send, save, and retrieve messages. Use it for displaying conversation history, handling user input, and implementing optimistic UI updates. It also supports UIMessages for rich rendering and filtering tool messages from the displayed history.

Quick Install

Claude Code

Recommended
Plugin CommandRecommended
/plugin add https://github.com/Sstobo/convex-skills
Git CloneAlternative
git clone https://github.com/Sstobo/convex-skills.git ~/.claude/skills/Convex Agents Messages

Copy and paste this command in Claude Code to install this skill

Documentation

Purpose

Messages represent individual exchanges in a conversation thread. This skill covers saving, retrieving, displaying, and managing messages.

When to Use This Skill

  • Displaying conversation history to users
  • Saving user messages before generating responses
  • Implementing optimistic message updates in UI
  • Working with UIMessages for rich formatting
  • Filtering tool messages from displayed history

Retrieve Messages

import { listUIMessages } from "@convex-dev/agent";

export const listThreadMessages = query({
  args: { threadId: v.string(), paginationOpts: paginationOptsValidator },
  handler: async (ctx, { threadId, paginationOpts }) => {
    return await listUIMessages(ctx, components.agent, {
      threadId,
      paginationOpts,
    });
  },
});

Display in React

import { useUIMessages } from "@convex-dev/agent/react";

function ChatComponent({ threadId }: { threadId: string }) {
  const { results } = useUIMessages(
    api.messages.listThreadMessages,
    { threadId },
    { initialNumItems: 20 }
  );

  return (
    <div>
      {results?.map((message) => (
        <div key={message.key}>{message.text}</div>
      ))}
    </div>
  );
}

Save a Message Manually

import { saveMessage } from "@convex-dev/agent";

export const saveUserMessage = mutation({
  args: { threadId: v.string(), prompt: v.string() },
  handler: async (ctx, { threadId, prompt }) => {
    const { messageId } = await saveMessage(ctx, components.agent, {
      threadId,
      prompt,
      skipEmbeddings: true,
    });
    return { messageId };
  },
});

Optimistic Updates

Show messages immediately before they're saved:

const sendMessage = useMutation(api.chat.generateResponse).withOptimisticUpdate(
  optimisticallySendMessage(api.messages.listThreadMessages)
);

Delete Messages

await myAgent.deleteMessage(ctx, { messageId });
await myAgent.deleteMessages(ctx, { messageIds });
await myAgent.deleteMessageRange(ctx, { threadId, startOrder, endOrder });

UIMessage Type

Extended message with agent-specific fields:

interface UIMessage {
  key: string;
  role: "user" | "assistant" | "system";
  text: string;
  status: "saved" | "streaming" | "finished" | "aborted";
  agentName?: string;
  _creationTime?: Date;
  parts?: MessagePart[];
}

Key Principles

  • UIMessages vs MessageDocs: Use UIMessages for UI, MessageDocs for backend
  • Message ordering: Maintained automatically by order and stepOrder
  • Optimistic updates: Better UX showing messages before save
  • Skip embeddings in mutations: Use when saving in mutations

Next Steps

  • See streaming for real-time message updates
  • See files for attaching media to messages
  • See threads for managing message containers

GitHub Repository

Sstobo/convex-skills
Path: convex-agents-messages

Related Skills

content-collections

Meta

This skill provides a production-tested setup for Content Collections, a TypeScript-first tool that transforms Markdown/MDX files into type-safe data collections with Zod validation. Use it when building blogs, documentation sites, or content-heavy Vite + React applications to ensure type safety and automatic content validation. It covers everything from Vite plugin configuration and MDX compilation to deployment optimization and schema validation.

View skill

creating-opencode-plugins

Meta

This skill provides the structure and API specifications for creating OpenCode plugins that hook into 25+ event types like commands, files, and LSP operations. It offers implementation patterns for JavaScript/TypeScript modules that intercept and extend the AI assistant's lifecycle. Use it when you need to build event-driven plugins for monitoring, custom handling, or extending OpenCode's capabilities.

View skill

polymarket

Meta

This skill enables developers to build applications with the Polymarket prediction markets platform, including API integration for trading and market data. It also provides real-time data streaming via WebSocket to monitor live trades and market activity. Use it for implementing trading strategies or creating tools that process live market updates.

View skill

cloudflare-turnstile

Meta

This skill provides comprehensive guidance for implementing Cloudflare Turnstile as a CAPTCHA-alternative bot protection system. It covers integration for forms, login pages, API endpoints, and frameworks like React/Next.js/Hono, while handling invisible challenges that maintain user experience. Use it when migrating from reCAPTCHA, debugging error codes, or implementing token validation and E2E tests.

View skill