Back to Cherry Studio

Cherry Studio Documentation

docs/README.md

2.0.821.5 KB
Original Source

Cherry Studio Documentation

<!-- Generated by scripts/gen-doc-index.ts — do not edit by hand; run `pnpm docs:index`. -->

Contrib

DocumentDescription
ContributingHow to contribute code
App Update ArchitectureHow clients check for updates through the managed release service, with channels and the release history feed
🌿 Branching StrategyBranch model for contributions, pull request guidelines, and version tag management targeting main
🖥️ DevelopDeveloper environment setup covering IDE configuration, Windows symlink support, and project install steps
Feishu Notification ScriptCLI script that sends Feishu webhook card notifications from GitHub Actions workflows, with command reference
Linux PackagingLinux packaging flow using pinned better-sqlite3 prebuilds, with build commands and prebuild update steps
Test PlanThe Test Plan process for beta and rc testing, covering user participation and maintainer PR workflow

References

AI

DocumentDescription
AI ReferenceEntry point mapping the AI pipeline docs, src/main/ai code layout, chat-turn flow, runtimes, and key invariants
Adapter FamilyHow each endpoint config's adapterFamily field selects the @ai-sdk package, and the two write paths that set it
Adding an Agent RuntimeOperational checklist for adding an agent runtime via a capability descriptor and a main-process driver package
Agent LoopThe Agent class wrapping single-pass AI SDK streaming with composeHooks-merged hook contributions and error semantics
Agent Prompt LayersPrecedence and lifecycle of agent prompt sources — System Prompt, workspace system.md, SOUL.md persona, and variables
Agent Session RuntimeHost/driver split for agent sessions — turn lifecycle, follow-up queue, resume tokens, and shared prompt materializer
AI Usage RecordsImmutable ai_usage_record analytics — capture ownership, frozen attribution snapshots, and MessageStats projection
Chat AttachmentsPer-attachment routing to native file parts or capped extracted text, with read_file paging for truncated overflow
Core ArchitectureEnd-to-end chat turn flow from renderer IPC transport through AiStreamManager and Agent loop to persistence
Execution OverlayRenderer stream overlay — TopicStreamSubscription demux by execution and anchor feeding readUIMessageStream snapshots
Image-Generation Parameterized ArchitectureData-driven image-generation params — registry supports to form fields, canonical bag to vendor wire via WireProfile
IPC TransportIpcChatTransport bridging useChat to Main over ai.stream.* IpcApi routes, with dispatch ack coordination and detach vs abort
Model Retry & FallbackUser-configurable same-model retry plus fallback models via ai-retry wrapModel, driven by chat.retry.* preferences
ObservabilityOTel tracing for AI calls and agent runtimes — Cherry roots, SDK adapters, runtime spans, local projection, and sinks
Params PipelinebuildAgentParams and the RequestFeature model composing plugins, tools, hooks, and provider quirks per request
Provider ResolutionEndpoint resolution chain from provider.endpointConfigs and adapterFamily to the AI SDK provider id and variants
AiStreamManagerAiStreamManager active-stream registry — listener fan-out, reconnect replay, abort, steering, and persistence triggers
Tool ApprovalMain-as-writer tool approval through ai.tool.respond_approval, approval-requested parts, and persistent MCP decisions
Tool RegistryUnified aiSdk ToolEntry registry — built-in web/kb tools, MCP sync, meta-tools, and deferred exposition

API Gateway

DocumentDescription
API Gateway ReferenceLocal HTTP gateway for OpenAI, Anthropic, Gemini, Cherry REST, and MCP-compatible clients

Architecture

DocumentDescription
Architecture OverviewCross-process architecture entry point covering the Electron process model, data flow, data systems, and monorepo map
Main Process Architecture (src/main)Canonical reference for src/main top-level directories, the closed category set, and inter-directory dependency rules
Naming ConventionsAuthoritative naming rules for files, directories, and identifiers, including singular/plural and barrel policies
Renderer ArchitectureCanonical reference for the src/renderer type-by-domain layout and its strictly downward dependency layering
Shared Layer Architecture (src/shared / @shared)Defines what belongs in the @shared cross-process primitive layer, its closed top-level set, and import rules

Binary Manager

DocumentDescription
BinaryManager ReferenceLifecycle service that acquires third-party CLI binaries through mise, with tool registry, snapshots, and IPC

Chat

DocumentDescription
Chat ReferenceCurrent chat-domain map covering shared renderer modules, page-owned adapters, rich clipboard, and the message tree
Composer Rich ClipboardPrivate clipboard format that preserves composer tokens across copy/paste between message surfaces and the composer
Message TreeMessage-tree model for topic chat: adjacency list, virtual root, sibling groups, invariants, delete semantics

Command

DocumentDescription
Command SystemCurrent command-backed action model across shared definitions, renderer and main handlers, keybindings, and menus
Command System — UsageHow to consume command UI and hooks, register handlers and context keys, build menus, and add a command

Components

DocumentDescription
Components ReferenceEntry point for component references covering code block rendering, code execution, image previews, and data-ui
Code Block RenderingHow CodeBlock classifies Markdown code and CodeBlockView renders the fenced-code workbench across streaming states
Code ExecutionCurrent Python code-block execution path through CodeBlockView, PyodideService, and the Pyodide Web Worker
Image Preview ComponentsCurrent Mermaid, PlantUML, SVG, and Graphviz preview pipeline with sanitized Shadow DOM rendering and shared controls
UI Semantic ContractThe data-ui semantic selector contract for themes, tests, and automation, and its build-time generation pipeline

Data

DocumentDescription
Data System ReferenceEntry point for Cherry Studio data systems - decision guide across BootConfig, Cache, Preference, DataApi, app_state
API Design GuidelinesRESTful path, status code, Zod DTO, and scope/side-effect boundary rules for designing DataApi endpoints
Data API Type SystemDataApi type system reference - request/response types, path resolution, pagination types, and error handling
App State System Overviewapp_state SQLite table for durable owner-private completion and reconciliation markers
Default Values & NullabilityRules for column nullability and single-source default placement across DB, Drizzle, Zod, and service layers
Layered Preset Configuration PatternCurrent preset layering patterns for Preference-backed catalogs and SQLite-backed entities
Boot Config System OverviewSynchronous file-based BootConfig system for process-level settings loaded before the app lifecycle starts
Boot Config Schema GuideHow to add boot config keys to the auto-generated schema, plus the V1-to-V2 boot config migration pipeline
Cache System OverviewThree-tier cache architecture (memory, shared, persist) - key types, design invariants, process responsibilities
Cache Schema GuideAdding fixed and template cache keys to the cache schemas - naming rules and fixed/template/casual selection
Cache Usage GuideCache usage examples - useCache/useSharedCache/usePersistCache hooks and direct CacheService APIs per tier
DataApi in Main ProcessImplementing DataApi handlers and services in main - HandlersFor typing, cross-service table access, adapters
DataApi in RendererRenderer DataApi usage - useQuery, useMutation, useInfiniteQuery hooks and data change notifications
DataApi System OverviewDataApi architecture for SQLite-backed business data - typed IPC pipeline from renderer client to main handlers
Ordering GuideFractional-indexing ordering spec for sortable resources - orderKey column, order endpoints, and useReorder hook
Pagination GuideCanonical pagination spec - offset vs cursor (keyset) modes, wire contract, server codec, and renderer hooks
Database Construction (Build, Migrations, Custom SQL, FTS5)How the SQLite DB is built at boot - drizzle migrations, CUSTOM_SQL_STATEMENTS replay, FTS5 fts_rowid, rebuilds
Database Schema GuidelinesDatabase schema authoring patterns - file organization, naming, column helpers, write serialization (withWriteTx)
Database Seeding GuideSeeding architecture - SeedRunner journal in app_state, execution policies, version strategies, adding seeders
Preference System OverviewPreference architecture - generated key schema, SQLite ownership, BootConfig routing, renderer cache, and cross-window sync
Preference Schema GuideHow to add Preference keys through the data-classify generator without editing generated schemas
Preference Usage GuideCurrent usePreference, useMultiplePreferences, and direct PreferenceService APIs
Migration V2 (Main Process)One-shot v1-to-v2 migration engine - upgrade gate, migrator contracts, data source readers, status tracking

Diagnostics

DocumentDescription
Performance DiagnosticsOpt-in main-process performance instrumentation gated by CS_DIAGNOSTICS, with signals and CPU profile capture

File

DocumentDescription
File ReferenceEntry point for current FileManager, directory-tree, cleanup, watcher, and directory-search references
File Module ArchitectureCurrent file-domain boundaries, shared types, renderer transports, and business-reference ownership
Directory Tree ArchitectureLive directory-tree snapshots, watcher mutations, IpcApi ownership, and renderer mirror lifecycle
File Entry CleanupScan-based cleanup of unreferenced file entries using the per-entry cleanup policy
FileManager ArchitectureCurrent FileManager storage, lifecycle, atomic-write, watcher, dangling-cache, and orphan-cleanup behavior
Fuzzy Search for Directory ListingsCurrent list and fuzzy-search behavior for the legacy directory-listing IPC methods

i18n

DocumentDescription
Internationalization (i18n) Guidei18n workflow covering locale catalogs, the en-us source of truth, automation scripts, and translation practices

IPC

DocumentDescription
IpcApi ReferenceEntry point for IpcApi docs — subsystem boundary, naming quick reference, migration status, and doc navigation
IpcApi Migration GuidePer-domain migration of legacy ipcMain and preload channels into IpcApi schemas, handlers, and renderer call sites
IpcApi OverviewWhy IpcApi is an independent RPC channel beside REST DataApi — layering, trust boundary, IpcContext, error model
IpcApi Schema GuideAuthoring IpcApi schemas — per-domain files, route and event naming rules, derived types, ESLint key enforcement
IpcApi UsageAdding an IpcApi request route or main-to-renderer event — schema, handler, broadcast and send, useIpcOn subscribe

Job And Scheduler

DocumentDescription
Job & SchedulerEntry point for the job and scheduler docs — doc map and quick navigation for JobManager and SchedulerService
Concurrency & Locks (Four-Layer Model)Four-layer lock model for JobManager dispatch — write transactions, queue mutex, concurrency caps, business locks
Handler AuthoringWriting a JobHandler — onInit registration timing, minimal echo example, and JobRegistry type binding
Migration ChecklistPer-handler checklist for migrating existing background services to JobManager — recovery, queues, tests, data moves
Job & Scheduler — Architecture OverviewJob and scheduler architecture — two-service split, DB-driven dispatch, six-state machine, and startup recovery
Scheduler Usage — Decision TreeDecision tree for choosing JobManager, SchedulerService, BaseService.registerInterval, or a raw timer

Knowledge

DocumentDescription
Knowledge ReferenceEntry point for the current Knowledge backend, ingestion workflow, retrieval, and operation guards
Knowledge ServiceCurrent Knowledge backend - persistence, IPC, ingestion, retrieval, Concept IDs, and agent tools
Knowledge Operation GuardsGuard and recovery semantics for Knowledge add, delete, reindex, and embedding-enable operations
Knowledge Workflow ArchitectureKnowledge workflow architecture: scheduling model, durable JobManager jobs, per-base mutation lock, crash semantics
Knowledge Storage and Retrieval ImplementationCurrent Knowledge storage and retrieval implementation - raw files, per-base index schema, invariants, and migration validation

LAN Transfer

DocumentDescription
Cherry Studio LAN Transfer Protocol SpecificationLAN transfer protocol spec for desktop-mobile sync covering mDNS discovery, TCP handshake, and file transfer

Lifecycle

DocumentDescription
Lifecycle & Application ReferenceEntry point for lifecycle docs — pattern decision table, doc navigation, and lifecycle vs direct-import singleton rules
Application OverviewHow the Application orchestrator registers services, runs the three-phase bootstrap, and controls runtime shutdown
Lifecycle Decision GuideDecision framework for whether a main-process service belongs in the lifecycle system or stays a plain singleton
Lifecycle Migration GuideConverting legacy singleton, raw-new, and free-function services to lifecycle decorators and registry entries
Lifecycle OverviewLifecycle internals — bootstrap phases, hooks, service states, events, and parallel initialization ordering
Lifecycle Usage GuideCode examples for lifecycle decorators, IPC and timer helpers, error handling, conditional activation, pause/resume

Logging

DocumentDescription
How to use the LoggerServiceHow to log through the unified LoggerService in main and renderer, with levels, contexts, and env filtering

Provider Model

DocumentDescription
Provider & Model ReferenceHome for provider and model reference docs covering the preset registry and its merge with user data
Provider & Model Registry SystemHow preset provider and model registry data is loaded, normalized, seeded, and merged with user data

Security

DocumentDescription
Security ReferenceHome for security reference docs covering safe main-process handling of untrusted network input
Remote Fetch SafetySSRF-safe rules for main-process fetches of untrusted URLs, with DNS pinning and private-address rejection

Testing

DocumentDescription
Testing ReferenceHome for testing reference docs covering frontend test policy and the SQLite database test harness
Database Testing GuideHow to test SQLite-backed main-process code with the setupTestDatabase harness and production migrations
Frontend Testing GuidelinesNormative test rules for renderer, packages/ui, and E2E code covering layer choice, mocking, and review gates

Window Manager

DocumentDescription
WindowManager ReferenceEntry point for WindowManager docs — configuration layers, bounds persistence, runtime setters, and doc navigation
WindowManager API ReferenceFull WindowManager method tables — open/close/create/destroy, window ops, queries, broadcast, pools, behavior setters
Window Migration GuideMigrating direct BrowserWindow creation to WindowManager — WindowType enum, registry entry, and open/close call sites
WindowManager OverviewWindowManager architecture — core type relationships, the three lifecycle modes, and the event timing contract
Window Platform ConfigurationPer-window platform configuration — static platformOverrides, declarative behavior layer, and macOS quirks patches
WindowManager Usage GuideConsumer guide for WindowManager — registering window types, opening windows, event hooks, and useWindowInitData
Warmup MechanicsWarmup state machine for pooled and singleton windows — idle queue, GC ticks, standby vs recycle axes, reuse IPC