ChatJS Documentation

repository·main·Indexed 22 days ago

https://github.com/franciscomoretti/chat-js

A production-ready foundation for building AI chat applications. Features include integrated authentication, access to 120+ AI models (Claude, GPT, Gemini, Grok), resumable streaming, branching conversations, and MCP support. Includes a CLI for scaffolding, a Runtime Registry for persistent application state, and tools for packaging as a native desktop app via Electron for macOS, Windows, and Linux.

Tokens
86.1K
Snippets
263
Records
427
Agent score
77%

What's inside ChatJS

  1. Overview of ChatJS features

    main

    ChatJS provides a wide range of tools to extend AI capabilities. Key features include:

    • Web Search: Real-time search using Tavily or Firecrawl to ground responses in current information.
    • Deep Research: A multi-step research agent for investigating topics and producing reports.
    • Code Execution: Secure sandboxed execution of Python and JavaScript code snippets.
    • Image Generation: Generation and iterative editing of images using dedicated models or multimodal LLMs.
    • MCP: Support for the Model Context Protocol to extend capabilities with external tools.
    • Canvas: AI-assisted creation and editing of text documents, code, and spreadsheets.
    • Reasoning: Extended thinking for complex queries with collapsible chain-of-thought UI.
    • Attachments: Multimodal support via drag-and-drop for images, PDFs, and documents.
    • Sharing: Public link sharing with per-chat visibility controls.
    • Branching: Conversation forking and sibling navigation to explore alternative paths.
    • Parallel Responses: Side-by-side comparison of answers from multiple models sent simultaneously.
    • Follow-up Suggestions: Contextual, clickable AI-generated questions to continue conversations.
    • Projects: Workspace organization with custom instructions, icons, and colors.
  2. Understand the ChatJS Project Structure

    main

    ChatJS is organized into a Next.js App Router architecture with a clear separation between the UI layer, AI integration logic, and the data layer.

    Core Directories

    • app/: Contains the Next.js App Router, including authentication routes (auth), the main chat interface (chat), and API routes.
    • components/: The UI layer, subdivided into ui/ (base shadcn/ui), chat/ (chat-specific UI), ai-elements/ (registry components), and part/ (tool result renderers).
    • lib/: The core logic layer containing ai/ (SDK integration and gateways), db/ (Drizzle ORM schema and queries), models/, and stores/ (Zustand state).
    • trpc/: Contains tRPC routers and procedures for type-safe API communication.
    • hooks/ & providers/: React hooks and context providers.
    ├── app/                    # Next.js App Router
    │   ├── (auth)/            # Auth routes (login, register)
    │   ├── (chat)/            # Main chat interface
    │   ├── api/               # API routes (chat, auth, trpc)
    │   └── actions/           # Server Actions
    ├── components/
    │   ├── ai-elements/       # AI Elements registry components
    │   ├── chat/              # Chat UI components
    │   ├── part/              # Tool part renderers
    │   ├── settings/          # Settings pages
    │   └── ui/                # shadcn/ui components
    ├── lib/
    │   ├── ai/                # AI SDK integration, tools, prompts
    │   │   └── gateways/      # Gateway abstraction (Vercel, OpenRouter)
    │   ├── db/                # Database schema, queries, and data access
    │   ├── models/            # Model types and utilities
    │   └── stores/            # Zustand stores
    ├── trpc/                   # tRPC routers and procedures
    ├── hooks/                  # React hooks
    ├── providers/              # React context providers
    └── evals/                  # AI evaluation tests
  3. Core features of ChatJS

    main

    ChatJS provides a foundation for AI chat applications with the following built-in capabilities:

    • Model Access: Unified API for 120+ models (Claude, GPT, Gemini, Grok).
    • Authentication: Pre-configured support for GitHub, Google, and anonymous users.
    • Conversation Management: Branching (forking conversations), sharing via public links, and resumable streams (persisting generation after page refresh).
    • Advanced AI Tools: Web search integration, image generation, code execution in a sandbox, and Model Context Protocol (MCP) support.
    • File Handling: Drag-and-drop support for images, PDFs, and documents.
    • Deployment: Ability to package as a native desktop app (macOS, Windows, Linux) using Electron.
  4. Understand the @chat-js/registry package

    main

    The @chat-js/registry package serves as the central repository for ChatJS registry artifacts and authoring types. It is distributed via npm and provides the necessary manifests that the @chat-js/cli uses to discover tools.

    Key components included in the package:

    • index.json: The registry index.
    • items/*.json: Generated manifests for individual registry tools.
    • ToolEnvVars: TypeScript types used for defining static toolEnvVars exports within a tool.ts file.
  5. Overview of ChatJS Authentication

    main

    ChatJS uses Better Auth for session-based OAuth authentication. There is no email/password flow; all users sign in via social providers (GitHub, Google, or Vercel). Sessions are stored in Postgres and validated via signed cookies with a short-lived cache to minimize database load.

    There are two user modes:

    • Authenticated users: Signed in via OAuth. They have full access to chat history, all enabled models, and all features.
    • Anonymous users: No sign-in required. They use a cookie-based session with credit limits to try the app without an account.
  6. Understand the Chat Runtime Model

    main

    In ChatJS, the Runtime is the primary unit of execution. Instead of chat logic being tied to a specific URL route, a runtime is a persistent entity that manages the lifecycle of a chat independently of the UI view. This allows for features like background streaming, concurrent chats, and optimistic (provisional) UI rendering.

    A runtime tracks several key properties:

    • chatId: The unique identifier for the chat.
    • runtimeId: The unique identifier for the runtime instance.
    • projectId: The associated project.
    • store: The local state instance owned by the runtime.
    • persistenceStatus: Either provisional (optimistic/draft) or confirmed (persisted in DB).
    • streamStatus: The current state of the AI stream (idle, submitted, streaming, complete, error, or stopped).
    • pendingSubmission and submittedMessage: Data related to the current message being processed.
  7. Use Model IDs with the OpenAI Gateway

    main

    When using the OpenAI gateway, you use bare model IDs (e.g., gpt-4o) instead of the provider/model format used by other gateways like Vercel or OpenRouter.

    Because the gateway uses the @ai-sdk/openai SDK, model IDs are type-safe and provide autocomplete within your chat.config.ts file. The gateway fetches the full list of models available to your API key at runtime and caches them for 1 hour.

    - `gpt-5-mini`
    - `gpt-5-nano`
    - `gpt-4o`
    - `o3-mini`
  8. Understand Canvas types and use cases

    main

    Canvas is a side-panel feature that allows you to create and edit substantial content directly within the chat. There are three supported types:

    • Text: Best for essays, emails, reports, and documentation. Supports Markdown, diff view, version history, and a 'polish' tool.
    • Code: Best for Python, JavaScript, TypeScript, and other code files. Supports syntax highlighting, version history, and Python execution via Pyodide.
    • Sheet: Best for data tables, datasets, and CSV files. Includes a spreadsheet editor, CSV export, and Python-based data visualization.
  9. Understand the Thread Run Model and concurrency

    main

    Every assistant response lifecycle is represented by a RunRecord.

    Key Concepts

    • Run vs. Message ID: Run IDs and response message IDs are separate. A RunRecord exists as soon as a request is submitted, even before an assistant message is created. The message ID is only bound once the AI SDK publishes the response.
    • Concurrency: You can start multiple runs from the same user message to create assistant siblings, or start runs from different leaves to update branches concurrently. Each run has its own independent status, error, and cancellation controls.
    • Run Invariant: A new live run requires a non-assistant response parent. You cannot call startRun directly from an assistant message. To branch from an assistant, you must use sendMessage to attach a new user message to that assistant node, which then triggers a new response.

    Run Record Structure

    A RunRecord contains:

    • aborted: Boolean indicating if the run was cancelled.
    • chat: The ThreadRunChat instance for that specific run.
    • error: Any error encountered during the run.
    • finished: A Promise that resolves when the run completes.
    • spec: The ThreadRunSpec used.
    • status: The current ChatStatus of the run.
  10. File structure for an installable tool

    main

    Each installable tool is organized into its own folder within the project. The following files are required for a complete tool package:

    FilePurpose
    tools/chatjs/{name}/tool.tsBackend tool: Contains the schema and the execute function.
    tools/chatjs/{name}/renderer.tsxFrontend renderer: The React component used to display tool output.
    tools/chatjs/tools.tsServer registry: CLI-managed file where tool imports and entries are injected.
    tools/chatjs/ui.tsClient registry: CLI-managed file where renderer imports and entries are injected.