CodePapr Tutorial
v0.1.0 macOS + Windows Tauri Desktop ← Home 中

CodePapr Tutorial

Local coding agent workbench: read the project, edit files, run commands, preview results — with byte-level optimization for the LLM prefix cache.

CodePapr Introduction

Design notes

  • Local-first: files and commands run in the workspace
  • Single runtime: Agent, Session, ToolRegistry, Provider share one semantics
  • Cache-first: stable content first, volatile last
  • Structured edits: Search/Replace diffs, validate then write

Supported LLM Providers

DeepSeek (Native) OpenAI (Compatible) Claude / Anthropic (Compatible) Local OpenAI-Compatible Endpoint

Installation & Environment Setup

Requirements

ComponentMinimum VersionPurpose
Node.js20.19+Runtime and package management
npm9+Dependency management
Rust toolchain + CargostableDesktop build (debug/release/publish)
.NET SDK-C# Roslyn analyzer (required for release builds)
Note: Rust is not optional: this is a dual Node workspace + Cargo workspace, and npm run build runs build:host-server to compile codepapr-server, so it requires the Rust toolchain. Only narrow commands such as npm run lint or the pure-vitest part of npm run test avoid Rust.

Standard Installation

# After cloning the repository
npm install
npm run build

The desktop build (cargo check / npm run debug / release / publish) pulls tree-sitter and language grammars from crates.io; it no longer depends on .cargo-vendor/* submodules. npm run build already compiles the codepapr-server host, leaving a usable host binary on disk; when the desktop starts, it launches that binary as a Tauri externalBin sidecar.

Installation Verification

npm run verify

Passing this step confirms that your machine at least satisfies: correctly installed Node dependencies, successful workspace build (including the codepapr-server compile), passing workspace tests, and passing Tauri cargo check.

Supported Platforms

PlatformArchitectureStatus
macOSarm64 (Apple Silicon)Supported (outputs .dmg installer)
Windowsx64Supported (outputs .msi installer)

Both platforms share the same Rust backend and frontend codebase; the release pipeline outputs dmg/msi installers simultaneously.

External Dependencies

Depending on your operations, you may also need:

  • A valid model API key (DeepSeek / OpenAI / Claude or a local compatible endpoint)
  • Chrome or a Chromium-compatible browser (for browser interaction and screenshots)
  • VS Code (optional, for workspace tasks and debugging configuration)

Three Launch Modes

CommandPurpose
npm run debugDevelopment debugging with hot reload; suitable for long sessions and daily use
npm run releaseDirectly launch the optimized desktop runtime (no installer packaging)
npm run publishGenerate platform installer (.dmg / .msi) and organize into Release/

API Setup & Model Configuration

Configuration Storage Locations

LevelPathPurpose
App-level~/.codepapr/codepapr.sqliteProvider, model, API key, language, sampling parameters
Project-level<workspace>/.CodePapr/Project state, session records, rules, Agents, Skills

Provider Modes

ModeDescriptionUse Case
deepseekDeepSeek official providerRecommended default; best cache optimization
openaiOpenAI-compatible formatConnecting to OpenAI or compatible services
claudeClaude/Anthropic-compatible formatConnecting to Claude or compatible endpoints

DeepSeek API Reference URL

# OpenAI format (used by DeepSeek provider by default)
https://api.deepseek.com/v1

CodePapr's DeepSeek provider always uses the OpenAI-compatible https://api.deepseek.com/v1. If you want to use the Anthropic protocol with DeepSeek, select Claude as the provider and set baseURL to DeepSeek's Anthropic-compatible endpoint.

Environment Variable Fallback Order

The desktop provider compatibility layer reads API keys in the following order:

  1. DEEPSEEK_API_KEY
  2. OPENAI_API_KEY
  3. ANTHROPIC_API_KEY

App-Level Settings

LLM Settings

  • provider — Model provider
  • model — Model name
  • baseURL — Custom endpoint URL
  • API key — Authentication key
  • temperature — Generation temperature
  • maxTokens — Maximum output tokens
  • thinkingEnabled / thinkingEffort — Thinking mode

Routing Settings

  • fast model switch — Whether to enable the fast model
  • fast model name — Fast model name (default deepseek-flash)
  • max tool rounds — Maximum tool rounds (default 500)
  • max context tokens — Model input context window (default 200K; applies uniformly to DeepSeek, OpenAI-compatible, and Claude providers — no per-provider clamping; usage reaching 90% of it triggers auto-compaction)

Fast Model Routing

ScenarioModel UsedTemperature
Main Agent conversationPrimary model (default deepseek-v4-pro)Default
Context compression (internal Compactor agent)compactionModel tier (default fast model deepseek-flash, switchable to primary)0.1
Sub-agent dispatch (heavy/execution type)Primary modelUser configured
Sub-agent dispatch (Explore/Scout fast mode)Fast model (switchable to primary)User configured
Slash commands declaring model: fast (e.g. /search, /lint, /clean, /commit, /summary)Fast model (falls back to primary if not enabled)0.3
Settings: General / LLM / Search / Sub-agents / Advanced / App. Voice lives on the character panel.

First Use

Three Steps to Start

  1. API key, provider, model in settings
  2. Pick a project folder
  3. Ask / Plan / Agent / App

Shortest Path

npm install
npm run build
npm run debug

First Use Workflow

  1. Open settings, fill in provider, model, and API key
  2. Select a project folder
  3. Choose the current task mode among Ask, Plan, Agent, and App
  4. Enter a task description and let the agent execute or analyze
  5. Review results in the file tree, editor, Git, and preview panels
Auto-recovery: The desktop app remembers your last opened project directory and automatically restores that project and its project-level chat history on next launch. You will only see an empty workspace if the project path is invalid or you open a different directory.

Entry Points

Entry PointBest For
Desktop WorkbenchLong sessions, file tree, Git, preview, browser interaction — a visual workbench

Note: The three built-in sub-agents — Explore, Scout, and Mentor — can be enabled and configured in the desktop settings panel (Mentor tab); the internal Verifier / Compactor model tiers are configured in the Advanced tab (verifierModelTier / compactionModel) and are never exposed via the task tool.

Work Modes: Ask / Plan / Agent / App

Ask, Plan, Agent, and App are not different products but four working modes of the same Runtime.

Ask Analysis Mode

Best for: Explaining architecture, clarifying module responsibilities, analyzing error causes, asking questions before deciding whether to execute.

Characteristics:

  • Read-only: mutating tools (write/edit/bash/git, etc.) are blocked at the tool-registration layer, preventing accidental file changes by construction
  • For time-sensitive questions, prefers read-only time/web tools for verification
  • Only enters the read-only toolchain when you explicitly request project-based verification

Plan Planning Mode

Best for: Producing execution plans before large changes, confirming affected files and verification approach, breaking complex tasks into clear steps.

Characteristics:

  • Provides a task checklist and implementation strategy first
  • Analyzes affected files, execution order, verification methods, and potential risks
  • When requirements are ambiguous, invokes the question tool to clarify decisions with the user

Agent Execution Mode

Best for: Fixing bugs, implementing features, running tests and verification, tasks that require actual file read/write and tool invocation.

Characteristics:

  • Actively searches projects, reads/writes files, runs commands, performs verification
  • Uses workspace tools, bash command execution, preview, and browser capabilities
  • The main Agent execution loop runs in a Web Worker; long tasks won't block the UI
  • Long-running commands like bash display execution status and logs in tool call cards
  • Main execution defaults to a maximum of 500 consecutive internal tool rounds
  • After file changes, background diagnostics are dispatched asynchronously; identical failure fingerprints won't trigger repeated fixes

App Application Generation Mode

Best for: Data exploration and visualization, generating interactive charts and dashboards, turning analysis results into interactive apps with a single sentence.

Core Philosophy:

  • Your output is not a Markdown answer — it is a complete app (a split-file .papr app)
  • Like instantly building a purpose-built tool for the current problem
  • Fundamentally different from the coding Agent — it's an "app factory," not a "code writer"

Workflow:

  1. Explore data: use list / read / grep to understand data structure
  2. Write the app: use write to save manifest.json, a shell index.html, css/theme.css, and js/*.js split by responsibility under .CodePapr/apps/<appId>/
  3. Open it: call app_render({ appId }) to mount it in the right-side Application panel (does not write files)

App conventions:

  • Split files: index.html is a shell only; styles in css/theme.css; logic in js/*.js by responsibility (native ES modules, no bundler)
  • Reference chart libraries via CDN (D3, ECharts, Mermaid, MapLibre, Leaflet, Three.js, etc.)
  • Runs in a sandboxed iframe (sandbox="allow-scripts allow-same-origin")
  • Use Papr SDK (window.papr) to call Agent, storage, HTTP, and filesystem capabilities
  • Kanban/canvas apps that should receive coding-Agent pushes declare inbox in the manifest and subscribe with papr.events.on(channel, cb) — the contract is copied into session context "## Enabled plugins"; Agent mode calls app_publish from that catalog (do not use app_list); history replays via papr.db.get('inbox:<channel>'). Self-refreshing widgets must not declare inbox.
  • papr.agent.run uses a 300-second idle timeout: as long as the Agent keeps emitting progress events (streaming output / tool calls) it can run indefinitely; only 300s of total silence triggers a timeout. Tool rounds are bounded by maxToolRounds (default/cap 50; search calls count toward the total)
  • appId must be kebab-case; after editing files call app_render({ appId }) again to refresh — supports iterative refinement

Session Isolation:

  • App and coding modes (Ask/Plan/Agent) are session-level isolated - once App is selected, the session is locked to App 🔒, cannot switch to other modes
  • Coding sessions hide the App option - a session that started coding cannot switch to App
  • Ask / Plan / Agent can switch freely between each other without creating a new session
  • App ↔ coding mode switch -> create a new session

Model Strategy: Always uses the primary model to ensure app generation quality.

App Management: The right panel's "Apps" tab shows all registered .papr apps. Green/red dots indicate running status. Bottom toolbar: ▶ Start / Open / ■ Stop / 🗑 Delete. LLM manages app lifecycle via app_list, app_start, app_stop, app_delete tools. For full development and plugin specifications, see the App Mode & Plugin Generation section.

Permission model: Apps declare access with local (none / read / write) × network (true / false). Settings → App Tab can narrow the global default and per-app overrides; saving restarts running backends with the new sandbox.

App Mode Example Scenarios

  • Database analysis: "Analyze this SQLite schema and generate a Database Explorer"
  • Relationship diagrams: "Make a D3 force-directed graph of character relationships"
  • Stock dashboards: "Generate a dashboard with candlestick charts and order flow"
  • Document analysis: "Analyze paper-map — citation network, author relationships, topic clusters"
  • Geo-visualization: "Analyze the geographic distribution of Tang Dynasty chancellors as a zoomable map"

How to Write Effective Tasks

CodePapr's actual performance depends heavily on task description quality. The most effective prompts typically include:

  • What is the goal
  • Where is the scope of changes
  • Where is the reference implementation
  • What must not be touched
  • What are the verification criteria

Recommended Style

Fix the issue in packages/@codepapr/ui where background processes aren't stopped after preview closes.
First find the binding logic between the current preview session and background processes, then make a minimal fix.
After the change, at least run verification for the affected scope; if no narrow verification exists, explain why.

Less Effective Style

Help me fix the preview.
Pro tip: Treat it as an engineering agent capable of executing tasks, not a pure chatbot, and you will get more consistent results.

Desktop Workbench

Interface Structure

  • Left: Session list and quick access
  • Center: Chat area showing messages, tool calls, status, and execution summaries
  • Right: File tree and code preview
  • Auxiliary areas: Git panel, background processes, web preview

Full Desktop Capabilities

  • Project file tree browsing
  • Monaco code preview (VS Code engine)
  • Multi-language LSP hover, definition, and problem markers
  • Ask / Plan / Agent / App mode switching
  • Tool call process visualization
  • Git diff, recent commits, branch switching, and safe rollback
  • Background process management
  • In-app web preview
  • Browser page interaction and screenshots
  • Project configuration entry (Rules, Agents, Skills)
  • Visual Code Review panel (line-by-line comments, review status)
  • Non-blocking Toast notifications
  • External path access permission dialog

Code Review Panel

Click Review in the top AgentOps toolbar to open the Code Review panel:

  • Default diff compares HEAD~1..HEAD
  • Left file list shows added/modified/deleted/renamed files
  • Monaco diff editor displays both original / modified sides
  • Click the line number gutter on either side to add line-level comments
  • Comments can be marked as resolved / unresolved
  • Overall review status can be set: Pending Review / Approved / Changes Requested / Commented

Round Navigation

A compact indicator bar on the right edge of the chat area shows one tick per user message:

  • Hover the bar → panel opens, listing all rounds (#1 number + user's first sentence)
  • The currently visible round is highlighted in both the bar and panel
  • Click any round → smooth-scroll to that message
  • Panel auto-closes when mouse leaves (200ms delay to prevent accidental dismiss)

Global Search

The toolbar search box supports both conversation and file search via Chat | Files tabs:

  • Chat tab: Search current session messages, filter by role (All / You / AI), ↑↓ navigate Enter jump
  • Files tab — Content mode: Search file contents across the workspace, results show path + line + matching line
  • Files tab — Filename mode: Search file paths and names
  • Click a file result → open the file and jump to the matching line in the editor
  • Results panel is viewport-centered, 300ms debounced, backend search only runs when Files tab is active

Toast Notifications

The desktop uses non-blocking toasts instead of alerts:

  • Four colors: info / success / warning / error
  • Default 4.5 seconds auto-dismiss; error defaults to 8 seconds
  • Maximum 5 simultaneously displayed; drops the oldest when exceeded

External Path Permissions

When the Agent requests to read or list absolute paths outside the project, the desktop shows a permission dialog:

  • Deny: Block this access
  • Allow this file: Only permit this file
  • Allow this folder: Permit this directory and its children

Authorization results are saved in a whitelist; subsequent accesses to the same path won't trigger the dialog again. Write, edit, and command execution remain restricted to the workspace.

When to Prefer the Desktop

  • You are doing multi-round fixes or refactoring
  • You need to see the file tree while the agent works
  • You need Git diff, page preview, or page automation
  • You want to consolidate sessions, files, and verification in one interface

Git Integration

  • Git Panel: Shows staged/unstaged diff, recent commit history, branch creation/switch, local commits, safe discard of local changes
  • 8 Agent Git Tools: status, diff, history, branch_checkout, stage, commit, restore, reset — all powered by built-in libgit2 Tauri commands (no system git required)
  • Auto-init: If the workspace doesn't have a Git repo yet, the panel can initialize one via built-in libgit2 (no system git required)

Conversation Reset (Shadow Git Snapshot)

Before each user message, CodePapr captures a code snapshot via its own internal Shadow Git repo at .CodePapr/git/ (powered by libgit2 — no system Git CLI required):

  • IgnoreResolver scans the workspace file tree, respecting .gitignore and auto-excluding node_modules/, dist/, .next/, large files (>100MB), etc.
  • Files are added one-by-one via index.add_path and committed as checkpoint #N · "message preview"

When you need to roll back:

  • Hover over any user message and click "Reset to here"
  • Restore Plan: CodePapr computes exactly which files will change — showing you the count of files to restore/delete/unchanged before executing anything
  • Execute: After confirmation, the system resets to the checkpoint snapshot
  • A backup ref refs/codepapr-backup-before-reset is created automatically — you can undo the reset anytime
  • The message list is synchronously truncated; all subsequent conversation is removed

Tool Capabilities

The Agent registers a comprehensive toolset covering file operations, ProjectGraph analysis, Git, preview, browser, Shell, LSP, and all local development scenarios. Below are the key tools grouped by capability.

graph — Core Project Understanding

A unified project semantic graph tool that selects operations via the action parameter. Simultaneously returns a directory tree, code structure skeleton, and file/symbol relationship graph, serving as the foundation for all symbol lookup, dependency analysis, and impact analysis.

Tool / ActionCapability
graph fullGenerate full ProjectGraph: directory tree + code structure skeleton + dependency graph
graph overviewLightweight overview (no full code skeleton); good for quickly perceiving project shape
graph lookupLook up symbols by name/path; returns symbolId, file, and line number
graph dependencyExtract dependency subgraph; supports incoming / outgoing / both
graph entrypointsFind project entry files and entry symbols
graph impactReverse impact analysis: what would be affected by modifying a given symbol
graph implementationsFind implementations/derived symbols of an interface or base class
graph smart_contextIntelligently retrieve the most relevant project context based on a task description
graph dead_codeDetect unused symbols (classes, functions, variables)
graph circular_depsDetect circular import dependencies between files
graph type_hierarchyBuild inheritance/implementation hierarchy tree for classes, interfaces, and types
graph suggest_refactorsBased on code structure analysis, suggest extractable methods and symbols that could become standalone files
graph test_impactAnalyze which existing tests would be affected by a list of changed files
graph generate_testsAuto-generate test skeletons for exported testable symbols in the project

File Operations

ToolCapability
readRead file content; supports line ranges, line windows, context lines, and byte limits
writeCreate or fully overwrite a file; use edit for partial modifications
editSingle-file precise SEARCH/REPLACE modification; search must exactly match source file
patchMulti-file atomic SEARCH/REPLACE; all blocks validated successfully before writing together; any failure rolls back all
grepRegex search file contents; returns match locations with context; semantic:true switches to LSP semantic search
globSearch project files by filename glob patterns; supports regex union
listBrowse project directory tree, embeds lightweight per-file symbols (AST); no-AST languages return path only

LSP Language Intelligence

Tool / ActionCapability
lsp definition / referencesLanguage service read-only navigation: jump to definition, find all references
lsp_edit rename / code_action / formatLanguage service semantic edits: rename, code actions, formatting
diagnosticsSingle-file LSP diagnostics or project-level lint / typecheck

Command Execution

Tool / ActionCapability
bash run / list / stop / stop_allRun shell commands in the project (through a shell; pipes/&&/variables supported); blocks by default, background:true runs in background returning a pid, workdir sets the working directory; list/stop/stop_all manage background processes

Git Operations

Tool / ActionCapability
git status / diff / logRead workspace status, diff, and commit history
git branch / stage / commitSwitch or create branches, stage changes, create commits
git restore / resetRestore changes or safe rollback (auto-creates backup branch and snapshot)

Browser & Preview

Tool / ActionCapability
browser open / navigate / reload / closeBuilt-in browser: open URL, navigate, refresh, close
browser click / type / read / screenshot / getBrowser interaction: click elements, type text, read DOM, screenshot, read state

App Render

ToolCapability
app_renderOpen a .papr App already on disk into the Application panel. Pass appId only. Write manifest.json and the entry HTML with write/edit/patch under .CodePapr/apps/<appId>/ first. Access lives in the manifest (local/network; legacy level 0-3 still works). HTML uses window.papr SDK. Call again after edits to refresh.
app_listList all registered .papr apps (name, kind, pinned, has backend, is running, inbox). App mode only: call before creating to check for duplicates. Coding-Agent publish contracts live in session context, not this tool.
app_startStart backend service by appId. Checks port availability, turns status green.
app_stopStop backend service by appId. Turns status red.
app_deleteDelete app by appId. Stops backend, removes files, clears storage. Irreversible.
app_publishPush content to an app/plugin channel (app_publish({ appId, channel, payload })). Only publish to targets listed in session context "## Enabled plugins" (enabled + declared inbox); do not call app_list first. Events are appended atomically (concurrency-safe, last 200 kept) and delivered live via papr://event when the app is mounted; when unmounted they are briefly queued (~30s) so a shortly-opening app still receives them live. Canvas/kanban: after analysis → push a scene or a card using the example.

Web Tools

ToolCapability
websearchOnline web search, aggregating multi-source results
webfetchRead web page content, auto-extracting body text and converting to plain text; save: true downloads raw content to the project and returns the path

Other Tools

ToolCapability
skillLoad Skill instruction files from the project's .CodePapr/skills/ directory
local_time_nowGet current local time, date, and timezone; suitable for time-sensitive queries (market open/close, event deadlines, etc.)
questionAsk the user questions in Plan mode; supports predefined options and multi-select
taskDelegate sub-tasks to declarative sub-agents (Explore / Scout / Mentor) for execution
todoPlan and track multi-step task checklists; supports initialization, progress reporting, and re-planning

External Path Permissions

In the desktop, read / list operations on absolute paths outside the project trigger a PermissionDialog popup for authorization; writes remain restricted to the workspace. For a file directly under the filesystem root, choosing "Allow this folder" is automatically downgraded to granting that single file only, so one click can never grant the entire filesystem root.

File Size Limits

A single read / write / edit / patch operation is capped at 20MB, covering most source code and binary resource files, though large files will significantly increase token consumption.

Tool Design Principle: The LLM sees simplified "merged tools" (30 total), which delegate to 40+ independent tools under the hood. The Agent can use all tools simultaneously; sub-agents are restricted by tools config allowlists. For code modifications, prefer edit/patch via Search/Replace Diff; use write only for new files. For command execution, use bash uniformly: short commands via bash(command: ...), long-lived processes via bash(command: ..., background: true), and manage background processes via bash(action: list/stop). For web access, use websearch (search) and webfetch (read pages; save: true to download files); opening in the system browser uses bash.

Character Roleplay Experimental

Experimental feature, off by default: enable "Characters" under Settings → General → Experimental features to reveal the toolbar entry. CodePapr supports creating, importing, and managing AI characters, allowing the Agent to converse with you in a specific persona. Once enabled, the profile is injected into the Session Bootstrap (assembled in promptBuilders.ts / characterTypes.ts), not core promptSystem.ts and not ImmutablePrefix.

Character Data Model

Each character includes the following fields:

FieldDescription
NameCharacter display name
AvatarUploaded image, also shown in the chat interface
DescriptionAppearance, backstory, identity setting
PersonalitySpeaking style, character traits, behavioral habits
ScenarioThe situation in which the current conversation takes place
First MessageWhat the character would say in their first conversation
Example DialoguesMultiple dialogue groups separated by <START>, guiding the LLM to understand the character's style
System PromptAdditional instructions appended after the character persona
TagsCustom tags for categorization and search

Roleplay Format Conventions (roleplay mode only)

In roleplay mode, the system prompt specifies the following format rules so TTS can correctly distinguish dialogue from actions. In Ask / Plan modes the character is always injected as a coding persona and this format does not apply:

FormatMeaningTTS Behavior
*Action description*Narration, scene description, character actionsNot spoken
Plain textCharacter speechSpoken
**Bold text**Emphasis, stressSpoken with emphasis
(Parentheses) or (whisper)Tone cuesNot spoken

Creating a Character

  1. Click the Character Button (avatar icon) in the toolbar to open the character management panel
  2. Click "New Character"
  3. In the Basic tab, fill in name, description, personality, scenario, first message, example dialogues, etc.
  4. Optionally upload an avatar image (PNG/JPG)
  5. In the Voice tab, configure voice synthesis (optional; see next section)
  6. Click Save

Importing Character Cards (CCv3 / SillyTavern Compatible)

CodePapr is compatible with the chara-card-v3 specification and can import characters from other tools:

  1. Click the "Import Character Card" button in the character panel
  2. Select a PNG file (JSON embedded in the image's tEXt/iTXt chunk) or a JSON file
  3. Character information is automatically parsed; PNG images are automatically set as avatars
  4. Review and adjust the imported fields, then click save

Supported PNG chunk keywords: chara, ccv3, character, character_card

Exporting Character Cards

Click a character's Export button in the character list to export it as a PNG character card. The PNG embeds the complete CCv3 JSON and can be used in tools like SillyTavern. Portable voice settings (speed, sample steps, sentences per chunk, playback mode, languages) are written to extensions.codepapr.voice; local reference-audio and fine-tuned-model file paths are not exported with the card.

Activating/Switching Characters

Click Enable on the editor to apply the character to the current session only; unsaved edits in the panel are saved automatically first. Clicking a name in the list opens it for editing and does not activate it. Opening the panel selects the character already enabled for this session. In an empty session, switching characters replaces the previous character's greeting with the new one.

Character personas are placed in the Session Bootstrap (not in the system prompt's ImmutablePrefix), so switching characters does not break the LLM prefix cache. In Ask / Plan modes the character is always injected as a coding persona; the roleplay format only applies in Agent mode. New sessions start with no character.

Tip: Character roleplay does not affect the Agent's code understanding and execution abilities. The Agent can still search projects, modify files, and run commands — only the output tone and style will match the character setting.

Voice Synthesis (TTS) Experimental

Experimental feature, off by default: enable "Voice" under Settings → General → Experimental features to reveal voice controls; auto-read also requires "Characters" enabled with voice configured on the active character. CodePapr integrates the GPT-SoVITS voice cloning engine, capable of synthesizing a character's text replies into speech locally. Only 3-10 seconds of reference audio are needed to clone a character's voice.

TTS Data Flow: ChatPanel → useTtsPlayer (React Hook): streaming text → sentence splitting → queue management → Rust TTS module → GPT-SoVITS Python Server (local port 9880) → rodio (Rust audio library) playback

Installing GPT-SoVITS

First-time voice usage requires installing GPT-SoVITS. There are two installation entry points:

  • Click the TTS speaker button on the ChatPanel; if not installed, an installation wizard will auto-launch
  • Trigger installation in the Voice Tab of the character editing panel

The installation wizard auto-completes 5 steps: check Python → clone GPT-SoVITS repository → pip install dependencies → download pretrained models (about 2GB, using hf-mirror source) → verify.

Requires Python 3.10+ already installed on the system. The installation process writes to ~/.codepapr/gpt-sovits/.

Configuring Voice for a Character

  1. Click the Character Avatar Button in the toolbar to open the character editing panel
  2. Switch to the Voice Tab
  3. Upload Reference Audio:
    • Duration 3-10 seconds (5 seconds recommended); too short gives poor cloning, too long gets truncated
    • Format WAV / MP3 / M4A / AAC; sample rate 16kHz or higher
    • Content: clear human voice, no background music, noise, or reverb
  4. Fill in Reference Text: must match the audio content word-for-word; otherwise cloning quality will be poor
  5. Select Reference Audio Language and Speaking Language (supports Chinese, Cantonese, English, Japanese, Korean, and mixed modes)
  6. Adjust parameters:
    • Speed: 50% - 200%
    • Synthesis Speed: only 4 / 8 / 16 tiers. 4=fastest, 8=balanced, 16=highest quality
    • Merge Sentences: 1-5, merge this many sentences in one synthesis batch to reduce round trips
    • Playback Mode: defaults to ws-batch; streamed-pipeline / streamed-pcm / whole also selectable
  7. Click the "Preview" button to preview the effect
  8. Flip the "Enable Voice Output" switch (it refuses to turn on while the reference audio or reference text is missing), then click Save

Playback Modes

The Voice Tab exposes four playback modes. The default and recommended one is WebSocket batch streaming (ws-batch): sentences are first merged into chunks per the "Merge Sentences" setting (3 by default), then each chunk is sent over a single persistent WebSocket connection and returned one by one, with first-word latency around 1-2 seconds and smooth inter-sentence transitions.

The other three: streamed-pipeline / streamed-pcm (per-sentence HTTP requests with PCM pushed straight to the player; best compatibility) and whole (waits for the complete reply, then synthesizes and plays it in one go; slowest start but the most coherent).

Voice Fine-tuning

For higher audio quality requirements, use the fine-tuning feature in the Voice Tab:

  1. Ensure reference audio and reference text are configured and the preview passes
  2. Click "Generate Training Data": the LLM generates about 500 words of dialogue script based on the character setting; GPT-SoVITS auto-synthesizes about 2 minutes of training audio, no manual recording needed
  3. Click "Start Fine-tuning": background training, typically 30-60 minutes; you can close the window
  4. After training completes, check "Use Fine-tuned Model": timbre is more stable, synthesis is faster, synthesis speed can drop to 4 (fastest tier)

Playback Controls

  • Auto-read: Characters with voice enabled will auto-read their AI replies aloud
  • Replay: Hover over any AI reply to see a “Replay” button to re-read that message
  • Stop: Canceling the current Agent message will interrupt ongoing reading
  • Service Control: The TTS speaker button on the ChatPanel starts the GPT-SoVITS service or views service logs/status
GPU Warmup (Apple Silicon): On M-series Macs, after starting the TTS service for the first time, you can manually click the “GPU Warmup” button in the Voice Tab of the character editing panel. This pre-compiles the Metal GPU kernel to avoid a 5-15 second stall on the first synthesis. Warmup is only effective on Apple Silicon.
Audio Quality Tip: Reference audio is best recorded in a quiet environment, avoiding background noise. Reference text must match the audio content exactly. Quality improves significantly after fine-tuning, especially for Chinese and Japanese.

Config Files & Rules

.CodePapr/AGENTS.md — Global Project Rules

Project-wide rules are injected into the main Agent and all sub-agents. Good for:

  • Code style and directory conventions
  • Build, test, and release commands
  • Paths or behaviors that must not be changed
  • Project background and acceptance criteria
Auto-injection Flow: The agent reads the rule file .CodePapr/AGENTS.md and merges it into the stable system prompt. Missing files are silently skipped.

Memory panel — cross-session project memory

Cross-session memory is a single file in your workspace, .CodePapr/MEMORY.md (three sections: user preferences & constraints / tech stack & environment / architecture & known facts) — readable, diffable, git-friendly. The built-in memory curator (internal subagent) maintains it in the background, and the memory panel is its editor. Layers and timing: Context layering.

  • Two checkpoints: delivery (end of turn; runs only when your message carries a memory cue — remember / must / never / always — or the turn has a verified test/build command) and pre-compaction (runs unconditionally before any compaction commit, 20s timeout).
  • Write boundary: the curator only sees the turn's user text plus the assistant's final text (skeleton when pre-compaction) — never raw tool output; secrets are redacted and injection / dangerous commands / oversized content / “drop-more-than-half” edits are rejected.
  • The Agent does not write memory: memory_write / memory_search / memory_list / memory_forget are retired; direct writes to MEMORY.md are intercepted and rejected — the Agent states durable facts in its answer instead.
  • When it reaches the model: every turn reads the file into session bootstrap — a saved change takes effect next turn (a one-time prefix miss), panel edits included.

/compact — Force Context Compression

Manually trigger v4 skeleton compaction, folding older rounds into a checkpoint to free token space:

  • Force mode: bypasses the 90% trigger line (an ineffective shrink is still rejected — no no-op checkpoints)
  • Deterministic skeleton: each folded round keeps its user question + final summary as two lines; tool calls/results collapse into count notes — zero LLM. The most recent 5 rounds stay verbatim; the zero-tool Compactor runs once only if the skeleton still overflows (deterministic line-truncation fallback otherwise)
  • Refreshes session bootstrap: the memory curator runs before compaction (folding what is about to be folded), then the bootstrap is re-rendered — new memory takes effect with the epoch
  • Use case: When approaching context limits or responses slow down, compress to restore smooth conversation

Configuration Entry Points

The "Config" entry in the desktop project header can:

  • Create/edit .CodePapr/AGENTS.md (generates a default template if none exists)
  • Create/edit/delete custom sub-agents (.CodePapr/agents/*.md)
  • Create/edit/enable/disable/delete Skills (.CodePapr/skills/**/SKILL.md)

Data Location Overview

PathPurpose
~/.codepapr/codepapr.sqliteApp-level settings, sessions, and cache statistics
~/.codepapr/lsp-tools/Managed LSP tool download cache (downloaded on first need, reused afterwards)
<workspace>/.CodePapr/project.sqliteProject-level state, chat history, cache statistics
<workspace>/.CodePapr/MEMORY.mdCross-session project memory (maintained by the memory curator; editable in the panel; injected into session bootstrap every turn)
<workspace>/.CodePapr/skillsProject-level skill files
<workspace>/.CodePapr/agentsProject-level sub-agent definitions
<workspace>/.CodePapr/commandsProject-level custom commands
<workspace>/.CodePapr/downloads/Default download directory for the Scout sub-agent
~/.codepapr/voices/Character reference audio files
~/.codepapr/gpt-sovits/GPT-SoVITS installation and pretrained models

Code Editing & Diff Mechanism

Search/Replace Diff (YOLO Diff)

CodePapr's automated modifications do not rely on standard Git diff line numbers. Multiple localized modifications are preferentially generated as Search/Replace blocks:

<<<<<<< SEARCH
Existing code already in the file
=======
Replacement new code
>>>>>>> REPLACE

Application Rules

  • SEARCH must exactly match content in the target file
  • If the same SEARCH matches multiple locations, it is rejected to prevent unintended changes
  • A single batch modification validates all files and all blocks first; if any block fails, no file is written
  • Line endings are compatible with LF / CRLF
  • Failure information is fed back to the Agent context, triggering a re-read of the original file and self-healing retry

Recommended Use Cases

  • Localized modifications across multiple files
  • Fixing tests, lint, or type errors where context precision must be maintained
  • Agent mode requiring a machine-parseable, verifiable, and rollback-friendly modification format

Not Recommended For

  • Creating new files or full file rewrites → use the write file tool
  • Changing only a very small localized block → regular patch is more direct

Skills System

What is a Skill

A Skill is the main Agent's reusable operations manual, suitable for codifying search strategies, troubleshooting workflows, release checklists, review manifests, and project-specific working methods. It does not create an independent sub-agent but serves as project-level context for the model to select on demand.

Skill File Format

Organized as directory packages, placed under .CodePapr/skills/**/SKILL.md. Each directory can contain assets/, references/, scripts/, and other resources.

---
name: search
description: Conduct verifiable searches using public web, official docs, and community resources
---

# Search Skill

When a task requires public information, current facts, third-party API usage, or error troubleshooting:

- Official docs first, then GitHub issues/PRs, then community answers.
- Use double quotes for exact error strings, e.g. "Cannot find module".
- Limit to specific sites using site:, e.g. site:developer.mozilla.org fetch abort.
- Include the library name, version, runtime environment, and key error codes together.

Skill Loading Mechanism

  • At runtime, only the name + description of user-enabled Skills are injected into stable context
  • The model decides autonomously whether a Skill is needed
  • Only after selection is skill called to read the full content
  • Enable status is saved in .CodePapr/project.sqlite

Built-in search Skill

The default search Skill includes common reference sources and methods:

  • Official Documentation: Microsoft Learn, OpenAI, MDN, Node.js, npm, PyPI, Rust, Tauri, Vite, React
  • Code & Issues: GitHub repositories, issues, pull requests
  • Community Resources: Stack Overflow, package manager pages, maintainer blogs
  • Search Methods: site: to scope to a domain, double quotes for exact errors, package name plus version number

Agents & Sub-agents

Built-in Sub-agents

CodePapr comes with three built-in sub-agents that the main Agent can dispatch via the task tool without additional configuration:

AgentPurposeModelTools
exploreRead-only code analysis: search project files, locate symbols, analyze dependenciesfastread, read_image, list, lsp, diagnostics, grep
scoutWeb search: find documentation, API references, latest resourcesfastwebsearch, webfetch, browser, read_image
mentorHigh-level architecture/algorithm/debugging guidance (no code writing, no tool usage)mentor*None

* Mentor uses the primary model by default; an independent mentor model can be enabled in settings (supports independent API Key, Base URL, and model selection; falls back to the main API Key when no dedicated key is configured).

Runtime-Internal Agents (never exposed via the task tool)

AgentPurposeModelTools
verifierGoal acceptance: read-only audit of whether the Worker truly achieved the goal — anti-completion-bias, anti-forgery (/goal)verifierModelTier (fast/primary/mentor)read, grep, glob, list
compactorSecond-level summary for compaction: merges the skeleton into one summary only when it still exceeds the budget (shared by between-turn / mid-loop / Goal / task sub-agents)compactionModel (fast/primary)None (pure reasoning)

All three internal agents are internal: true, invoked directly by the runtime: Verifier by the GoalRunner acceptance loop (dedicated budget: 6 tool rounds / 3-minute wall clock); Compactor by the compaction pipeline when the skeleton still overflows; Memory-curator by the memory pipeline at the delivery / pre-compaction checkpoints (its material never contains raw tool output). All three are zero-tool and get no skills/memory/project-graph injection (bootstrap isolation), with the sub-agent default 20-minute wall clock. In v4 the main compaction path is the deterministic skeleton (zero LLM); the Compactor runs only as a single second-level summary, falling back to deterministic line truncation when the fast tier is selected but the fast model is disabled — never recursion.

Custom Sub-agents

Declare a sub-agent in .CodePapr/agents/<name>.md with YAML frontmatter + body. The main agent can delegate subtasks to it. An agent with the same name will override the built-in definition.

---
description: reviewer is responsible for reviewing current changes, identifying risks, and providing minimal fix suggestions
mode: subagent
model: fast
temperature: 0.2
tools:
  read: true
  grep: true
  diagnostics: true
  git: true
  write: false
  exec: false
---

You are reviewer, a read-only code review sub-agent.

Responsibilities:
- Read the goal, relevant files, and current diff delegated by the main agent.
- Prioritize finding real bugs, behavioral regressions, missing edge-case handling, and absent verification.
- Provide minimal fix suggestions, indicating which files to modify and what verification commands to run.

Boundaries:
- Do not directly modify files by default.
- Do not repeatedly summarize irrelevant code style; only report findings that affect correctness, reliability, or maintainability.

Output Format:
1. Findings: List issues by severity
2. Suggested Fix: Provide the minimal fix direction
3. Verification: List recommended verification commands

Sub-agent Configuration Reference

  • model: Override model; options: fast (fast model) or a specific model name
  • temperature: Temperature parameter; optional numeric value
  • tools: Tool switches; defaults to inheriting all tools; declaring an empty object {} means no tools
  • The filename (without .md) is the sub-agent name; same name overrides built-in agents
  • Modify description to tell the main agent when to invoke it
  • Modify tools to control read/write/command permissions

Sub-task Mechanism (Two Approaches)

ApproachTriggerDescription
Orchestration-layer auto-decompositionSystem auto-decisionIn Agent mode, when a task contains execution verbs and is sufficiently complex, the LLM decides whether to break it into 2-5 sub-tasks for parallel/serial execution
Task tool active delegationAgent actively invokesThe main Agent explicitly calls the task tool during reasoning to delegate a sub-task to an independent sub-agent (including built-in and custom)

Sub-agent Runtime Model

  • Each sub-agent has an independent Session, ToolRegistry (filtered by tools), and Provider
  • Maximum nesting depth: 2 levels (sub-agents cannot delegate to other sub-agents)
  • Sub-agents can execute up to 50 internal tool rounds (main agent: 500)
  • Individual tool calls have a 90-second timeout — errors are returned to the LLM for autonomous decision
  • Each sub-agent has a 5-minute overall wall-clock timeout with automatic cancellation
  • Explore and Scout use the fast model; Mentor uses the independent mentor model or primary model
  • Custom prompts can be overridden in the Mentor tab of the settings panel

Difference from AGENTS.md

.CodePapr/AGENTS.md contains global project rules inherited by all modes and all sub-agents; custom Agents are dedicated sub-agents, only activated when the main Agent delegates sub-tasks via the task tool. The former is for writing "what all tasks must comply with," the latter for "who handles a certain type of task and which tools they can use."

Custom Commands

Built-in Commands

Commands support both --name (recommended) and /name (legacy compatibility) formats. A command's model field determines routing: undeclared uses the primary model, fast uses the fast model, and local commands cost zero tokens.

CommandFunctionModelExample
/helpList all commands and descriptionsLocal/help
/commandsAlias for /helpLocal/commands
/compactForce-compress current session context — deterministic skeleton checkpoint (zero LLM; one second-level summary only if the skeleton still overflows)Primary / Fast/compact
/undoUndo the last conversation reset (restore truncated messages and code snapshot)Local/undo
/goalAutonomous loop: Worker executes + Verifier validates, until condition is metPrimary/goal exec:npm test
/reviewReview current changes or specified scopePrimary/review src/App.tsx
/fixLocate and fix a specified issuePrimary/fix Login button not responding
/testAdd tests or run relevant testsPrimary/test src/utils/format.ts
/explainExplain a file, symbol, error, or implementationPrimary/explain handleSubmit function
/diagnoseDiagnose errors, slow operations, or abnormal behaviorPrimary/diagnose Page load exceeds 5 seconds
/refactorReorganize code while preserving behaviorPrimary/refactor src/components/Modal.tsx
/docUpdate documentation for changes or featuresPrimary/doc New refund endpoint
/newCreate new files, components, or features from scratch based on descriptionPrimary/new Create user password reset REST API
/optimizeAnalyze and fix performance bottlenecksPrimary/optimize src/pages/Dashboard.tsx
/buildBuild the project and diagnose/fix build errorsPrimary/build
/searchSearch codebase for patterns, usages, definitions, or referencesFast/search auth middleware
/lintRun linter and fix violationsFast/lint src/
/cleanClean up dead code, unused imports, and leftover debug statementsFast/clean src/utils/
/commitStage changes and generate a well-formed commit messageFast/commit
/summaryProvide a high-level overview of a file, module, or entire projectFast/summary src/core/

Custom Command Templates & Syntax

Declare reusable prompt templates in .CodePapr/commands/<name>.md to register slash commands /<name>:

Syntax / PlaceholderDescription
$ARGUMENTSAll arguments entered by user after the command
$1 $2 ...The Nth positional argument (supports quoted values)
@pathRead relative workspace file content and embed as an inline code block
!`cmd`Execute simple shell command and embed output (simple commands only, no compound operators)

Practical Template Examples

Example 1: Static Page & Rendering Logic Diagnosis (Zero Git Risk)

---
description: Diagnose index.html structure and visual logic
usage: /pagecheck [observed issue]
model: fast
---
Please help diagnose the page structure and visual logic of this static project.
Page entrypoint: @index.html
User question: $ARGUMENTS

Example 2: Dependency & Script Analysis

---
description: Analyze package.json dependencies and scripts
model: fast
---
Please answer user question based on root config:
Config: @package.json
Question: $ARGUMENTS

Example 3: Code Review & Lint Fix (Delegate to Subagent + Live Status)

---
description: Review and fix lint
agent: code-reviewer
---
Please review the changes for $ARGUMENTS and fix any lint issues.
See rules at @.CodePapr/AGENTS.md
Current status: !`git status -s`
Creation & Usage:
1. Visual UI: Click Project Config in the top toolbar → switch to Commands tab to create and edit commands easily.
2. Invoke: Type / in the chat input to bring up the command palette with ↑↓ navigation; type /command-name args to run. Type /help in chat to see all registered project commands.

App Mode & Plugin Generation

What is App Mode and .papr Apps

In CodePapr, App mode is not merely a code assistant — it is an on-demand interactive application factory. Simply describe what you need in natural language, and the Agent explores data, designs architecture, and builds ready-to-use .papr applications or desktop plugins in seconds, mounting them directly in the main window.

Two Artifact Forms: Fullscreen Apps vs. Desktop Plugins

Every .papr app declares its form via the kind field in manifest.json:

Artifact FormManifest DeclarationRuntime BehaviorTypical Use Cases
Fullscreen App (App) kind: "app" (default) Opens as an exclusive fullscreen view over the workbench, dominating the primary viewport. Supports background command processes. SQLite Database Explorer, 3D topology graphs, multi-panel dashboards, static site documentation previews
Desktop Plugin (Plugin) kind: "plugin" Renders as an in-window lightweight overlay (HUD), coexisting with the coding workbench. Always visible while you write code, freely draggable, dynamically resizable via papr.window, and easily pinned/unpinned in the App Dock. Real-time crypto/stock tickers, live architecture evolution boards, task progress widgets, scratchpads
Form Selection Guideline:
• When the user prompt includes words like "floating / plugin / widget / HUD / keep on the side while coding / live board", the Agent generates a kind: "plugin" plugin.
• Plugins cannot run background command processes and cannot use local: "write" project-write access, ensuring safety and lightweight operation.

.papr Source Structure & Mandatory Modularization

All apps and plugins are stored in .CodePapr/apps/<appId>/. To allow precise patching and continuous iteration by the Agent, CodePapr mandates modular file organization (native ES Modules, zero build tools, import statements must include .js extensions):

.CodePapr/apps/<appId>/
├── manifest.json       # App manifest: metadata, kind, surface, permissions, inbox contracts, agents
├── index.html          # Shell HTML: skeletal markup only, loads CSS & js/main.js, no giant monoliths
├── css/
│   └── theme.css       # Theming & styling: supports html[data-mode="dark"] & html[data-mode="light"]
├── js/
│   ├── main.js         # Entry module: initialization, DOM binding, and event listeners
│   ├── db.js           # Key-value storage wrapper (papr.db)
│   ├── ui.js           # View rendering, loading states, and animations
│   ├── api.js          # External HTTP fetch wrapper (papr.http, optional)
│   └── agent.js        # Multi-turn AI Agent wrapper (papr.agent.run, optional)
├── data/               # App-private sandbox filesystem storage (papr.fs, created at runtime)
└── db.sqlite           # papr.db data & inbox history (created at runtime)

Note: For lightweight plugins (kind: "plugin"), a 3-file layout (index.html + css/theme.css + js/main.js) is recommended until any single file exceeds ~200 lines.

Papr SDK Capabilities (window.papr)

Apps run inside a secure sandboxed iframe. Without installing npm packages, the runtime automatically injects the window.papr SDK:

SDK ModulePrimary APIsPermission RequirementsCapabilities & Details
papr.db get(key)
set(key, val)
delete(key)
keys()
No permissions required (always available) SQLite-backed persistent key-value storage isolated per app. Data persists across app restarts.
papr.agent.run run({ agent, task }, onProgress?) Follows local/network profile Invokes a multi-turn AI sub-agent directly within the app. Supports streaming events (tool-call-start, content-delta) and a 300s idle timeout.
papr.http get(url)
post(url, body)
request(opts)
network: true Safe public HTTP client with header whitelisting. Localhost and private intranet requests are blocked to prevent SSRF.
papr.fs readFile(path)
writeFile(path, data)
exists(path)
list()
delete(path)
No permissions required (app data dir) Dedicated sandbox filesystem restricted to the app's data/ folder. writeFile auto-creates parent folders; supports base64 binary assets.
papr.events on(channel, callback) No permissions required (always available) Real-time event bus. Subscribes to events pushed by the coding Agent via app_publish; returns an unsubscribe handler.
papr.window setSize({ width, height })
getBounds()
onBounds(cb)
No permissions required (kind: "plugin" only) Plugin viewport control. Dynamically resizes the overlay content box at runtime (host automatically adds the draggable titlebar).
papr.app.info info() No permissions required Retrieves app metadata: appId, name, version, local, network, and effective permissions.

Agent Push Mechanism (app_publish + inbox Contract)

In "Agent writes code in terminal → Plugin visualizes progress/architecture in real time" collaboration workflows, CodePapr provides a zero-overhead publish/subscribe system:

  1. Plugin Declares Contract: Declare inbox channels and minimal payload example in manifest.json.
  2. Agent Auto-Discovery: Enabled inbox plugins are automatically surfaced in the coding Agent's session context under "## Enabled plugins".
  3. Push from Any Mode: The coding Agent calls app_publish({ appId, channel, payload }) from any writable mode (Agent / Plan / App).
  4. Dual-Channel Persistence & Replay: Events are atomically appended to the app's db.sqlite (up to 200 events retained); delivered live via papr://event if mounted; when unmounted events are briefly queued (~30s) so a freshly opening instance still receives them live, while later launches replay history using papr.db.get("inbox:<channel>") (live and replay can overlap — dedupe by seq).

Security & Permission Isolation Model

manifest.json uses a Local Access (local) × Network Access (network) matrix:

Access AxisValueAllowed Capabilities & Tooling Scope
local "none" Pure compute sandbox: only papr.db and papr.fs private storage.
"read" Workspace read access: unlocks read-only Agent tools (read, grep, list, lsp).
"write" Workspace modification: unlocks Agent writing & execution (write, edit, patch, bash). Note: Plugins cannot use this level.
network false Strict offline sandbox: CSP blocks all external network requests.
true Network enabled: unlocks papr.http, Agent websearch / webfetch, and MCP services.

App Management Dock

Switch to the Apps tab on the right sidebar to browse all generated .papr apps and plugins:

  • Status Indicators: Green dot indicates "Ready/Pinned", labeled with a Plugin badge for overlay widgets.
  • Toolbar Actions:
    • Open / Pin / Unpin: Show floating overlay in the main window or hide it;
    • ▶ Run / ■ Stop: Manage lifecycle of apps running background server processes;
    • 🗑 Delete: Permanently delete app directory and runtime state;
    • ⤓ Export: Package app as a .zip for sharing and backup.
  • Settings Overrides: In Settings → App tab, configure default access for undeclared apps or narrow permissions per app.

Practical Example 1: Live Crypto Ticker Floating Plugin

Prompt: "Generate a lightweight floating crypto ticker plugin in the top-right corner, showing BTC/ETH prices every 10s with compact typography."

manifest.json Configuration:

{
  "spec": "papr/0.1",
  "name": "Crypto Ticker",
  "version": "1.0.0",
  "kind": "plugin",
  "surface": {
    "type": "overlay",
    "width": 300,
    "height": 180,
    "position": "top-right"
  },
  "local": "none",
  "network": true
}

js/main.js Logic:

async function fetchPrices() {
  try {
    const data = await window.papr.http.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd&include_24hr_change=true');
    render(data);
  } catch (err) {
    console.error('Ticker error:', err);
  }
}

fetchPrices();
setInterval(fetchPrices, 10000);

Practical Example 2: Architecture Evolution Board (Agent Push Supported)

Prompt: "Generate an architecture evolution board plugin that subscribes to the cards channel to receive live task nodes as you code."

manifest.json Configuration (with inbox contract):

{
  "spec": "papr/0.1",
  "name": "Architecture Board",
  "kind": "plugin",
  "surface": {
    "type": "overlay",
    "width": 360,
    "height": 260,
    "position": "bottom-right"
  },
  "local": "none",
  "network": false,
  "inbox": {
    "cards": {
      "description": "Push task progress & state change cards",
      "example": { "id": "task-1", "title": "Refactor Auth", "status": "done" }
    }
  }
}

js/main.js Subscription & History Replay:

// 1. Replay historical events on startup
const history = await window.papr.db.get('inbox:cards') || [];
history.forEach(evt => applyCard(evt.payload));

// 2. Listen to live Agent push events
window.papr.events.on('cards', (evt) => {
  applyCard(evt.payload);
});

Practical Example 3: Fullscreen SQLite Database Explorer (Full App)

Prompt: "Analyze the stats.sqlite database in this project and generate a fullscreen Database Explorer app with paginated table views and SQL query execution."

The Agent declares local: "read", modularly splits frontend components and SQL result tables, and mounts a full interactive dashboard in the workspace Apps panel.

Goal Autonomous Loop

What is the Goal Loop

/goal is a control command (same level as /compact) that starts a Worker + Evaluator dual-model autonomous loop. It transforms the AI coding assistant from a single-turn Q&A mode into a long-running autonomous agent that continues until a machine-verifiable condition is satisfied.

The core mechanism is not adding "keep working until done" to the prompt — it's an engineered self-play system:

  • Worker (primary model): has full tool permissions, responsible for planning, writing code, running tests
  • Verifier (read-only sub-agent: read/grep/glob/list): reads the Worker's execution transcript and can independently verify files, determines if success is being fabricated
  • Objective condition function: executes verification commands, uses exit codes and output matching for objective judgment

The three work together: condition function + Verifier anti-forgery = double insurance. Only when the condition is met AND the Verifier confirms the Worker didn't cheat is it judged SATISFIED.

Basic Usage

# Exit code 0 satisfies the condition
/goal exec:npm test

# Exit code 0 AND stdout matches regex
/goal exec:npm test match:"\d+ passed"

# Compound condition, all must pass
/goal exec:npm run lint && exec:npm test

# Natural language goal + verification condition (| separator)
/goal fix auth tests | exec:npm test

Condition Syntax

SyntaxDescription
exec:<command>Execute command, exit code must be 0
exec:<cmd> match:"<pattern>"Exit code 0 AND stdout matches regex pattern
exec:<cmd1> && exec:<cmd2>Compound condition, all clauses must pass
<goal> | exec:<cmd>Natural language goal + verification condition, separated by |
Key constraint: Conditions must be "machine-verifiable" (e.g. tests pass, exit code 0, lint clean), not subjective (e.g. "write a nice login page"). The read-only Verifier judges the transcript and spot-checks files, but only machine-verifiable conditions give hard guarantees.

How It Works

  1. Worker turn: the main Agent executes one round of work (read files, write code, run commands)
  2. Objective condition evaluation: the system automatically runs the verification command and gets exit code + output
  3. Verifier anti-forgery check: the read-only Verifier sub-agent (read/grep/glob/list) reads the Worker's execution transcript and independently verifies key claims with its tools, detecting completion bias like "claiming tests pass without actually running them"
  4. Judgment: condition met AND Verifier confirms → SATISFIED, loop ends; otherwise detailed feedback is injected into the next round
  5. Context rot mitigation: auto-compaction every 5 iterations through the same epoch commit as between-turn compaction (insert checkpoint, re-render and prime the bootstrap, rebuild the agent in place, await the single-transaction commit) — the Goal runtime context actually shrinks; state persisted to .CodePapr/goal-state.md

Safety Guardrails

LimitDefaultDescription
Max iterations20Maximum outer loop iterations, auto-stops when exceeded
Max wall clock30 minutesWall clock timeout, auto-stops
User interruptAnytime"Stop" button on GoalBanner
State persistenceEvery iterationWrites to .CodePapr/goal-state.md, prevents context rot

Configuration

Configure Goal loop parameters in the Advanced tab of the settings panel:

  • Max iterations: default 20, adjustable 1-100
  • Max wall clock: default 30 minutes, configured in minutes
  • Verifier model: default fast model (faster, cheaper), switchable to primary model (more accurate)
  • Verifier token limit: default 4000
  • Verifier temperature: default 0.1 (lower is more deterministic)

MCP Tool Integration

What is MCP

The Model Context Protocol (MCP) is an open protocol that allows Agents to extend their capabilities through external tool servers. CodePapr includes a built-in MCP host that can connect to multiple MCP servers simultaneously, exposing external tools to the main Agent for invocation.

Each MCP tool is registered in the form mcp__<serverId>__<toolName>, appearing alongside the 30 built-in tools in the ToolRegistry.

Three Transport Modes

TransportDescriptionUse Case
stdioSubprocess + stdin/stdout JSON-RPCLocal command-line MCP servers (npx / uvx / python, etc.)
sseServer-Sent EventsRemote HTTP MCP servers, unidirectional streaming
streamable-httpStreamable HTTPRemote HTTP MCP servers, bidirectional streaming

Per-MCP Server Fields

FieldTypeDescription
namestringDisplay name
categorysearch / database / customCategory; search replaces websearch routing when enabled
transportstdio / sse / streamable-httpTransport mode
command / argsstringstdio only: executable command and arguments (arguments support quoted grouping)
urlstringsse / streamable-http only: HTTP endpoint URL
envmulti-line KEY=valuestdio only: environment variables; not exposed to model context
headersmulti-line Header-Name: valuesse / streamable-http only: HTTP request headers, typically for authentication
allowedToolscomma-separated, supports * wildcardAllowlist; empty means allow all
deniedToolscomma-separated, supports * wildcardDenylist; higher priority than allowlist
permissionModeread-only / read-write / dangerousPermission tier; determines whether confirmation is required before invocation
requireConfirmationbooleanRequires confirmation for every invocation
timeoutSeconds5–600Per-tool invocation timeout

Preset Examples

The desktop provides three ready-to-use MCP servers by default (all disabled; must be manually enabled):

NameCategoryCommandPurpose
DuckDuckGo Search MCPsearchnpx -y duckduckgo-mcp-serverAPI-key-free web search
Postgres MCPdatabasenpx -y @modelcontextprotocol/server-postgres <DSN>SQL queries, schema discovery; write-disabled by default
SQLite MCPdatabaseuvx mcp-server-sqlite --db-path ./database.sqliteLocal SQLite database analysis

stdio Server Example

# Name
DuckDuckGo Search MCP

# Transport
stdio

# Command / Arguments
command: npx
args: -y duckduckgo-mcp-server

# Environment variables (one KEY=value per line)
env:
HTTP_PROXY=http://127.0.0.1:7890
USER_AGENT=CodePapr/0.1.0

# Tool filtering
allowedTools: duckduckgo_web_search

sse / streamable-http Server Example

# Name
Remote Knowledge Base

# Transport
streamable-http

# URL
url: https://example.com/mcp

# Headers (one Header-Name: value per line)
headers:
Authorization: Bearer your-token-here
X-API-Key: your-api-key

Permission Modes

  • read-only: Read-only tools, no confirmation required for invocation (suitable for search, queries)
  • read-write: Writable tools, used with requireConfirmation
  • dangerous: Dangerous tools (e.g., execute shell, delete data); strongly recommended to enable requireConfirmation

Tool Filtering

Control the subset of tools exposed by each server via allowedTools and deniedTools:

  • Supports * wildcards (e.g. describe*, list_*)
  • Comma-separated for multiple patterns
  • Denylist takes priority over allowlist
  • Typical scenario: Postgres MCP defaults to allowedTools=query,describe*,list* + deniedTools=delete*,drop*,truncate*,update*,insert*, ensuring read-only access

Global Switches

SettingDefaultDescription
enabledfalseMCP master switch; all MCP servers are disabled when off
exposeToolstrueWhether to expose MCP tools to the Agent; when off, MCP is only a background connection and does not appear in the tool list
resultMaxBytes200,000Maximum bytes per tool call result (1KB – 5MB)

Recommended Common MCP Servers

  • @modelcontextprotocol/server-filesystem: Restricted filesystem access
  • @modelcontextprotocol/server-postgres: Postgres database
  • @modelcontextprotocol/server-github: GitHub API
  • @modelcontextprotocol/server-slack: Slack integration
  • mcp-server-sqlite: SQLite database
  • duckduckgo-mcp-server: Free web search
Cache Impact: The enabled MCP server list enters the ImmutablePrefix tool definition hash. Adding/removing/modifying MCP servers will break the prefix cache, requiring cache rebuild on the next request. It is recommended to finalize MCP configuration before starting a long session.
Test Connection: The MCP settings panel provides a "Test" button, allowing you to connect to a server, list tools, and apply filter rules without entering a session, to confirm the configuration is correct before enabling.

System Architecture

Architecture Overview

User → React UI / Shared Agent Runtime │ Tauri command (thin client) ▼ JSON-RPC 2.0 ▼ codepapr-server (host process) ▼ codepapr-core (domain subsystems) fs · git · shell · lsp · db · mcp · web │ └─ JSON-RPC notification → Tauri event bus → UI

Package-Level Responsibilities

PackageRolePrimary Responsibility
@codepapr/typesShared protocol layerUnified message, request, response, tool, and statistics types
@codepapr/commonCommon infrastructureLogging, hashing, and general utilities
@codepapr/coreRuntime coreAgent, Session, ToolRegistry, cache partitioning, ProjectGraph, Prompt assembly
@codepapr/apiProvider adapter layerRequestBuilder, CacheValidator, provider implementations
@codepapr/editorEditor contractFramework-agnostic Monaco types, markers, navigation, and static check contracts
@codepapr/uiDesktop workbenchReact, Zustand, Tauri, WorkerBackedAgent; Tauri commands are thin JSON-RPC clients, while the host owns the main SQLite handles through codepapr-core::db

Host / Client Responsibilities

The Tauri desktop is not a monolithic backend: src-tauri keeps GUI-only capabilities and thin RPC proxies. File system, Git, Shell, LSP, database, MCP, Web, and other domain implementations live in codepapr-core and are exposed uniformly by codepapr-server over JSON-RPC.

  • src-tauri/src/commands.rs: Tauri commands that proxy UI requests to host.rs
  • src-tauri/src/host.rs: starts/connects to codepapr-server, sends JSON-RPC, and forwards notifications to the Tauri event bus
  • crates/codepapr-server: RPC routing, parameter validation, event broadcasting, and task queue
  • crates/codepapr-core: domain subsystems such as workspace_fs, git_operations, shell, lsp, db, mcp_host, and web
  • GUI-only exceptions: embedded/headless browser, TTS, Stronghold vault, file export, and the Papr App runtime remain client-owned

Desktop Agent Bridge

ChatPanel → agentStore.sendMessage() → WorkerBackedAgent.chat() ├─ Worker Thread: Agent.chat() → LLM └─ Main Thread: tool → Tauri command → JSON-RPC ↓ codepapr-server → codepapr-core subsystem ↓ JSON-RPC notification → Tauri event bus → UI

The desktop does not invoke the core Agent directly; instead, it offloads the LLM chat loop into a Web Worker via WorkerBackedAgent, ensuring long tasks do not block the UI.

Worker Crash Recovery & Streaming Snapshots

  • Crash capture: The main thread catches WorkerCrashError, automatically clears the current agent instance (next send creates a new Worker), and prepends "Agent Worker crashed." to the error message
  • Streaming snapshots: During streaming responses, approximately every 2 seconds (STREAM_SNAPSHOT_INTERVAL_MS), onStreamSnapshot is triggered to persist in-flight content to the project SQLite
  • Power-loss recovery: After a crash / forced quit / power loss, the next launch shows the conversation fragments written before the crash, preventing large chunks of progress from being lost

Tech Stack Overview

LayerTechnology
Frontend UIReact 18, TypeScript, Zustand 5, Monaco Editor, Tailwind CSS 3, Vite 8
Desktop FrameworkTauri 2 (Rust)
Rust Host / Clientcodepapr-server + codepapr-core (JSON-RPC, SQLite, tree-sitter, LSP, and other domain capabilities); thin Tauri client owns GUI-only capabilities
Agent OffloadWeb Workers
TestingVitest 4, Playwright (UI E2E)

LLM Prefix Cache

How a request is stacked (cache view)

The model does not get one blob. Full layering and memory flow: Context layering. Earlier bytes stay still so prefix cache works:

HoldsChanges whenCache
01 System coreSystem prompt, tools, params, AGENTS.mdFrozen for the sessionHit
02 Session bootstrapSkills catalog, memory section, long-term guidanceNext turn after MEMORY.md is savedUsually a hit
03 Session stateCheckpoint + retained recent turnsRewritten on compactionHit within an epoch
04 This turnCurrent user message + tool resultsAppend-onlyTail increment

Cache Hit Patterns

Multiple tool calls in the same user turn: [01][02][03][04 user + tools...] → bytes 01–03 stay still (hit); 04 onward is this turn’s increment Next user turn: [01][02][03][04 new user...] → 01–03 still hit (while MEMORY.md is unchanged) After MEMORY.md is saved (or after compaction): 02 (with the memory section) / 03 are rewritten; one miss, then hits accumulate again

Key Invariants

  • User-custom prompts go into session bootstrap, not each round's user prompt
  • Skills go into bootstrap, not the system prefix
  • The workspace path only appears in the system prompt, not duplicated in bootstrap
  • Custom guidance appears only once in bootstrap
  • Session bootstrap follows the per-turn promptKey: MEMORY.md / skills / file changes rebuild once on the next turn (save now, effective next turn), otherwise it keeps hitting
  • Per-turn dynamic content (date / diagnostics) is placed at the tail, not in the existing prefix

Cache-First Architecture: the Context Epoch Model

Prefix cache hits automatically by byte-exact prefix match (no explicit breakpoints). The first principle is: keep the prefix byte-stable (append-only) within an epoch; reset it deliberately only across epochs via compaction.

  • An epoch = a span within one agent lifetime during which the prefix stays byte-stable. Each tool-loop round appends the assistant message and tool results to the tail; the prefix is reused byte-for-byte → the multiple calls within a loop naturally hit the cache.
  • The epoch boundary = context compaction: when the context threshold is reached, history is summarized into a checkpoint + retained tail, starting a new epoch (a one-time miss, then stable hit accumulation resumes). This mirrors OpenCode's Context Epoch and Claude Code's auto-compact. The checkpoint is inserted at the retention boundary (not appended at the end); the recent tail after it stays verbatim (including tool-call↔result pairs — the boundary is chosen at UI-message granularity so no tool message is orphaned). In the effective context the checkpoint is emitted as a user turn, avoiding a leading/consecutive assistant after compaction for better cross-provider correctness.

Mid-Loop Overflow → Compaction

Context grows with tool results during the tool loop. Agent.chat estimates the context size before building each round's request; when the effective threshold is exceeded, it compacts (resetting the log into a new epoch) and continues:

  • Round-start check only: tool results are appended at the end of a round; the overflow they cause is caught at the next round's start — no LLM request is ever sent with an over-limit context; the task continues after compaction from "summary + recent tail".
  • No mid-tool-execution compaction: a round's multiple tool calls are executed atomically before compacting at the round boundary, preserving tool-call↔result pairing.
  • Anti-loop: repeated ineffective/failed compactions trip a circuit breaker for the turn; after a successful compaction the log is below the threshold, so retries do not oscillate.
  • Defense in depth: each tool result is first truncated to ~50KB (or spilled to disk with a preview), so per-round growth is bounded.

Pruning Is Retired (v4)

The old protection-window pruning layer was removed with v4: tool results now only exist inside the ≤5 most recent verbatim rounds — anything older is already folded by the skeleton, so separate pruning is meaningless. A single oversized tool output is bounded by the entry guardrails (tool-output truncation and artifact spillover, readable back via history_read_artifact). The trigger remains a single line: 90% of the context window.

Effective Context Threshold (single rule)

maxContextTokens declares the model input window (default 200K) and applies uniformly to DeepSeek, OpenAI-compatible, and Claude providers (no per-provider clamping). The compaction trigger line = window × 90% (constant COMPACT_TRIGGER_RATIO) — the same source for the main session, mid-loop, Goal, and task sub-agents; provider-measured usage and the estimate take the larger value, and genuinely over-limit requests still fall back to emergency compaction. A higher window → fewer compactions → higher hit rate (cache reads are cheap).

Prefix-Stability Guarantees

  • No per-request prefix mutation: v4 has no sliding pruning; history is only ever rewritten at epoch boundaries
  • Byte-identical rebuild serialization: object tool results use sortedStringify (matching the live path); empty assistant content is ''
  • Stable reasoning round-trip: reasoning_content is round-tripped based on "presence + model capability", decoupled from the per-request thinking toggle
  • Frozen TodoList digest: the current digest is frozen into the checkpoint at generation and reused on rebuild instead of re-rendered live
  • Frozen parameters: topP / temperature / maxTokens / thinkingEnabled are frozen in ImmutablePrefix; any change flips the hash

Known limitations: LLM prefix cache has a lifetime; after a long idle period the first call re-misses the whole prefix (independent of the client). Compaction is lossy — the higher the threshold, the more history a single compaction covers.

Language Intelligence & LSP

LSP Bridge Architecture

The desktop LSP uses a Tauri native host + stdio JSON-RPC architecture, managing language server subprocesses, stdin writes, stdout reader threads, and message queues via src-tauri/src/lsp.rs.

Supported Language Families (15)

LanguagePrimary LSP ServerTypeBuilt-in
TypeScript / JS / TSX / JSXtypescript-language-serverNode.js npmYes
HTMLvscode-html-language-serverNode.js npmYes
CSS / SCSS / LESSvscode-css-language-serverNode.js npmYes
JSON / JSONCvscode-json-language-serverNode.js npmYes
YAMLyaml-language-serverNode.js npmYes
PythonpyrightNode.js npmYes
ShellScriptbash-language-serverNode.js npmYes
C#csharp-ls / CodePapr.CSharp.Analyzer / omnisharp.NET binaryYes
Rustrust-analyzerNative binaryYes
JavaEclipse JDTLS + Temurin JRE 21Java binaryYes
C / C++clangd v22.1.6Native binaryYes
GogoplsNative binaryYes (best effort)
Swiftsourcekit-lsp (macOS Xcode toolchain)SystemNo
SQLsqlsNative binaryYes
MarkdownmarksmanNative binaryYes

C# LSP Priority Chain

C# has a multi-layer fallback mechanism for LSP:

  1. csharp-ls on system PATH or in ~/.dotnet/tools
  2. Release package built-in csharp-ls binary (generated/lsp-tools/csharp-ls/bin/)
  3. Built-in CodePapr.CSharp.Analyzer (custom Roslyn sidecar, supports cross-file and cross-ProjectReference resolution)
  4. dotnet run --project CodePapr.CSharp.Analyzer.csproj (development / source code fallback)
  5. omnisharp -lsp or OmniSharp -lsp on system PATH (static candidate only)
  6. Built-in tree-sitter symbol parsing (final fallback)

Managed Installation (Managed LSP)

The desktop manages on-demand installation of missing LSP tools at runtime:

  • Node-based (5 npm packages, providing 7 language services): typescript-language-server (TypeScript / JavaScript), vscode-langservers-extracted (HTML / CSS / JSON), yaml-language-server, pyright, bash-language-server — installed via npm using the built-in Node.js runtime v20.12.2
  • Binary-based (6): clangd v22.1.6, rust-analyzer, JDTLS + Temurin JRE 21, sqls, marksman, gopls — downloaded from official sources
  • C#: Installed via dotnet tool install -g csharp-ls, or uses the built-in Roslyn sidecar
  • Auto managed downloads can be disabled with CODEPAPR_DISABLE_MANAGED_LSP_DOWNLOAD=1

Tree-sitter Syntax Parsing (16 Languages)

Built-in tree-sitter syntax tree parsing used for ProjectGraph and fallback symbol extraction: TypeScript, JavaScript, Python, Rust, Java, Go, C++, Bash, C#, CSS, HTML, JSON, PHP, Ruby, Kotlin, Swift.

LSP Loading Strategy

  • No batch warm-up of LSP at workspace startup
  • The LSP for a file is asynchronously loaded only after the file is displayed
  • After generation/modification/save-to-disk, asynchronously refreshes diagnostics and symbol cache for the related file
  • The LSP backend caches full workspace diagnostics; cross-file errors are also detectable
  • The code area only shows hints when there are problems; stays clean when there are none
  • When upper-layer LSP is unavailable, falls back to built-in tree-sitter symbol parsing

Verification & Release

Verification Command Matrix

CommandScopeSuitable Scenario
npm run buildFull workspace buildAfter source changes, confirm artifacts can be generated
npm run testFull workspace testsDaily main regression
npm run test:e2e:uiPlaywright UI E2EChanges to desktop UI components, Toast, permissions, Code Review
npm run test:e2e:ui:installInstall Playwright ChromiumPreparation before first UI E2E run
npm run lintStatic analysisPre-commit quality gate
npm run auditSecurity auditBefore release or after dependency changes
npm run smoke:agent-toolsReal model tool smoke testChanges to tool selection, shell, browser interaction
npm run smoke:lsp-previewMulti-language LSP smoke testChanges to LSP hover, definition
npm run verifyMost comprehensive verificationBefore local release (includes cargo check)

Recommended Pre-commit Regression Order

npm run build
npm run test
npm run test:e2e
npm run test:e2e:ui
npm run verify

Browser dependencies must be installed before the first UI E2E run:

npm run test:e2e:ui:install

Desktop Release

# Development debugging
npm run debug

# Optimized desktop runtime (no packaging)
npm run release

# Generate installer (.dmg / .msi) and organize into Release/
npm run publish

Release Helper Scripts

  • macOS: ./publish-codepapr.command
  • Windows: publish-codepapr.cmd

Pre-release Checks

npm run release:prep
npm run publish:dry-run
Release Package Bundled Contents: The official desktop release package bundles the Node.js runtime v20.12.2 required for default LSP, 5 Node-based npm packages (typescript-language-server, vscode-langservers-extracted, yaml-language-server, pyright, bash-language-server, providing TypeScript / JavaScript / HTML / CSS / JSON / YAML / Python / ShellScript — 8 language services total), C# Roslyn sidecar + .NET SDK 10.0, JDTLS + Temurin JRE 21, clangd v22.1.6, rust-analyzer, sqls, marksman, and gopls. Users do not need to download these components separately for first-time use of default languages.

Typical Workflows

1. Understand First, Then Execute

Best when working with a repository for the first time or when requirements are unclear:

  1. Ask: Explain system structure, locate modules
  2. Plan: Output task checklist and verification plan
  3. Agent: Execute according to the checklist

2. Direct Fix

Best when you already know the target but don't want to manually search and fix:

Fix the incorrect cache statistics in packages/@codepapr/api.
First locate the statistics aggregation logic, then make a minimal fix, and finally run related tests.

3. Start Frontend and Preview In-App

Best for UI adjustments, page behavior verification, and preview integration:

  1. Let the Agent start a preview session or background command
  2. View the page in the in-app preview
  3. If you need to click pages, fill forms, or take screenshots, continue using browser tools

4. Persist Terminal Context for Sequential Operations

Best for scripts, REPL, interactive CLI, or multi-step shell workflows:

  1. Open a shell session
  2. Send commands continuously
  3. Proceed based on output
  4. Close the session when done

5. Review Historical Sessions and Costs

  • View the session list
  • View stats for a specific session (cache hits/misses/token usage)
  • Assess whether costs are reasonable against the current model settings

Cost & Model Selection

DeepSeek Model Reference

ModelContextMax OutputCache Hit InputCache Miss InputOutputConcurrency
deepseek-flash1M384K0.02 CNY/M tokens1 CNY/M tokens2 CNY/M tokens2500
deepseek-v4-pro1M384K0.025 CNY/M tokens3 CNY/M tokens6 CNY/M tokens500
Note: Prices are subject to change; always refer to the DeepSeek official pricing page as the final authority.

How to Choose in CodePapr

  • Primary model defaults to deepseek-v4-pro — used for Ask, Plan, Agent, and App main execution flow; App mode always uses the primary model for generation quality
  • Fast model defaults to deepseek-flash — used for context compression, sub-task planning, read-only lightweight sub-agents
  • Thinking effort (thinkingEffort) defaults to max (strongest reasoning); can be switched to high in the LLM settings tab

Cost Optimization Tips

  • Prefer cheaper models for Ask and lightweight analysis tasks
  • Use Plan before large changes to reduce ineffective execution rounds
  • Make task descriptions more specific to reduce the number of rounds the model spends searching and fixing
  • Keep system prompts and tool boundaries stable to maximize prefix cache hits

FAQ

1. Prompt says no API key after startup

First check whether the desktop settings have been saved, and whether the corresponding environment variables are set (DEEPSEEK_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY).

2. Installation or npm scripts won't run / not found

Confirm whether npm install and npm run build have been executed, and whether the current repository is under a OneDrive path causing .bin shim anomalies.

3. Agent encounters vite, tsc, eslint, or missing module errors

First suspect uninstalled dependencies or unbuilt local packages, rather than cloud sync or disk issues.

4. Browser tool unavailable

Usually because no detectable Chrome or Chromium-compatible browser is installed on the machine.

5. Tests still show old results after code changes

Many packages in this repository participate in tests or references through their respective dist entry points. After changing source files, if results look unchanged, first rebuild the affected packages, then run verification.

6. Build principles after modifying source code

Important: Modify source → build first → run affected tests → run broader verification. When results appear "not taking effect," first suspect the build wasn't applied, rather than suspecting a runtime anomaly.

7. How to use local models

In settings, you can connect to a local model provider (OpenAI-compatible endpoint) for offline or private deployment scenarios. With supported models, you can paste or drag images directly into the chat box as input.

8. Why does a popup appear when reading certain absolute paths

This is the desktop's external path permission mechanism. When the Agent attempts to read or list absolute paths outside the project, it requests your explicit authorization to ensure system files are not accessed without permission.

9. UI E2E tests won't run

First confirm whether Playwright browser dependencies have been installed:

npm run test:e2e:ui:install

UI E2E uses Chromium running in a mock environment without Tauri webview; real model configuration is not required.

Usage Tips

Beginners: First use Ask to understand the system → then Plan to see the scope of changes clearly → finally use Agent for actual execution. Need data visualization? Switch to App mode and generate interactive charts in one sentence.

Experienced users: Give clear goals directly in Agent mode → specify affected files and verification requirements → use the desktop to complete conversation, Git, preview, and browser integration.


CodePapr v0.1.0 · This tutorial is based on the project source code and documentation · Content is continuously updated