### Build and Run 1Code from Source Source: https://github.com/21st-dev/1code/blob/main/CONTRIBUTING.md Install dependencies, start a development server with hot reload, create a production build, or package the application for distribution. ```bash bun install bun run dev # Development with hot reload bun run build # Production build bun run package:mac # Create distributable ``` -------------------------------- ### Set up 1Code Development Environment Source: https://github.com/21st-dev/1code/blob/main/README.md Install dependencies and download agent binaries to start developing with 1Code. This command is for setting up a local development environment. ```bash bun install bun run claude:download # First time only bun run codex:download # First time only bun run dev ``` -------------------------------- ### Install Plugin Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Installs a plugin from a specified source (marketplace, URL, or local path). Returns plugin details. ```typescript install(input: { source: "marketplace" | "url" | "local" identifier: string // plugin name or URL or path }) => { id: string name: string version: string } ``` -------------------------------- ### Install 1Code from Source Source: https://github.com/21st-dev/1code/blob/main/README.md Follow these steps to build 1Code from source. Ensure you have Bun, Python 3.11, setuptools, and Xcode Command Line Tools installed. The agent binaries must be downloaded separately. ```bash # Prerequisites: Bun, Python 3.11, setuptools, Xcode Command Line Tools (macOS) bun install bun run claude:download # Download Claude binary (required!) bun run codex:download # Download Codex binary (required!) bun run build bun run package:mac # or package:win, package:linux ``` -------------------------------- ### Debugging First Install Issues Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Commands to simulate a fresh install by clearing app data, resetting protocol handlers, and clearing preferences. Use this to test auth flows and behavior for new users. ```bash # 1. Clear all app data (auth, database, settings) rm -rf ~/Library/Application\ Support/Agents\ Dev/ # 2. Reset macOS protocol handler registration (if testing deep links) /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user # 3. Clear app preferences defaults delete dev.21st.agents.dev # Dev mode defaults delete dev.21st.agents # Production # 4. Run in dev mode with clean state cd apps/desktop bun run dev ``` -------------------------------- ### Start Debug Server Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Starts the debug logging server. Run this command in your terminal. ```bash bun packages/debug/src/server.ts & ``` -------------------------------- ### Install Application Update Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Installs the downloaded update and restarts the application. This action will cause the application to close and relaunch. ```typescript desktopApi.installUpdate() // App will restart ``` -------------------------------- ### installUpdate Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Installs the downloaded update and restarts the application. ```APIDOC ## installUpdate ### Description Install and restart with downloaded update. ### Method `desktopApi.installUpdate() // App will restart` ``` -------------------------------- ### Backend Core Modules: tRPC Server Setup Source: https://github.com/21st-dev/1code/blob/main/_autodocs/01-overview.md Shows the core tRPC setup, including context and middleware configuration, and the combination of all routers into the main AppRouter. ```typescript // lib/trpc/index.ts - Core tRPC setup with context and middleware // lib/trpc/routers/index.ts - Combines all routers into AppRouter ``` -------------------------------- ### Worktree setup failures Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Handle events related to failures during worktree setup. ```APIDOC ## onWorktreeSetupFailed ### Description Registers a callback function to be executed when a worktree setup process fails. ### Method `SUBSCRIBE` (simulated) ### Endpoint `/events/worktree-setup-failed` (simulated) ### Parameters #### Callback - **callback** (function) - A function that takes data about the failure. - **data** (object) - **kind** (string) - The type of failure ('create-failed' or 'setup-failed'). - **message** (string) - A detailed error message. - **projectId** (string) - The ID of the project associated with the failure. ### Returns - **unsubscribe** (function) - A function to call to remove the event listener. ``` -------------------------------- ### Development and Build Commands Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Commands for starting the development server, compiling the application, and packaging for different platforms. ```bash # Development bun run dev # Start Electron with hot reload # Build bun run build # Compile app bun run package # Package for current platform (dir) bun run package:mac # Build macOS (DMG + ZIP) bun run package:win # Build Windows (NSIS + portable) bun run package:linux # Build Linux (AppImage + DEB) ``` -------------------------------- ### get Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Fetch a single project by ID. ```APIDOC ## get ### Description Fetch a single project by ID. ### Method Query ### Endpoint /projects/get ### Parameters #### Query Parameters - **id** (string) - Required - Project ID ### Returns - `Project | undefined` - Project object or undefined if not found ### Request Example ```typescript const project = await trpc.projects.get.query({ id: "proj_123" }) if (project) { console.log(project.name) } ``` ``` -------------------------------- ### WDYR Render Log Example Source: https://github.com/21st-dev/1code/blob/main/src/renderer/DEBUG-WDYR.md An example of a WDYR console log indicating a component re-render. It shows the component name, render count, and details about changed props, state, or hooks. ```text [WDYR] ComponentName render #3 { props: ['sortedSubChats'], state: false, hooks: false } ``` -------------------------------- ### Plugin Configuration Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Manages plugin enablement and configuration, including API keys for services like GitHub Copilot. Stored in ~/.1code/plugins.json. ```json { "plugins": [ { "id": "github-copilot", "enabled": true, "config": { "apiKey": "..." } } ] } ``` -------------------------------- ### List Plugins Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Lists installed plugins with their details, including version and enabled status. ```typescript list() => Array<{ id: string name: string description: string version: string enabled: boolean manifest: Record }> ``` -------------------------------- ### Worktree Config Router RunSetupCommand Procedure Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Executes a specific setup command within a given worktree path, returning the success status and any output or error. ```typescript runSetupCommand(input: { worktreePath: string command: string }) => { success: boolean output?: string error?: string } ``` -------------------------------- ### Worktree Config Router Procedures Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Handles worktree setup and command execution for project configuration. ```APIDOC ## getSetupCommands ### Description Retrieves the necessary shell commands to set up a worktree for a given project path. ### Method getSetupCommands ### Input - **projectPath** (string) - Required - The path to the project. ### Output - **commands** (string[]) - An array of shell commands to execute. - **shell** (string) - The recommended shell to use ('bash', 'zsh', or 'sh'). ## runSetupCommand ### Description Executes a single setup command within a specified worktree. ### Method runSetupCommand ### Input - **worktreePath** (string) - Required - The path to the worktree. - **command** (string) - Required - The command to run. ### Output - **success** (boolean) - Indicates if the command executed successfully. - **output** (string) - Optional - The output of the command. - **error** (string) - Optional - Any error message from the command. ``` -------------------------------- ### Example of RENAMED Requirement Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Demonstrates the format for renaming a requirement, specifying the 'FROM' and 'TO' states. ```markdown ## RENAMED Requirements - FROM: `### Requirement: Login` - TO: `### Requirement: User Authentication` ``` -------------------------------- ### Plugins Router Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Plugin discovery, installation, and lifecycle management. ```APIDOC ## Plugins Router Plugin discovery, installation, and lifecycle management. ### Procedures #### list ##### Method Signature ```typescript list() => Array<{ id: string name: string description: string version: string enabled: boolean manifest: Record }> ``` #### install ##### Method Signature ```typescript install(input: { source: "marketplace" | "url" | "local" identifier: string // plugin name or URL or path }) => { id: string name: string version: string } ``` #### uninstall ##### Method Signature ```typescript uninstall(input: { id: string }) => { success: boolean } ``` #### enable / disable ##### Method Signature ```typescript enable(input: { id: string }) => { success: boolean } disable(input: { id: string }) => { success: boolean } ``` #### getMcpServers ##### Method Signature ```typescript getMcpServers(input: { pluginId: string }) => Array<{ name: string command: string args: string[] status: string }> ``` ``` -------------------------------- ### Initialize Chat and Run Agent Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md This snippet demonstrates the process of initializing a chat session and running an agent. It covers getting or creating a project, setting up a chat with a worktree, and streaming messages with Claude. ```typescript // 1. Get or create project const project = await trpc.projects.openFolder.mutate() // 2. Create chat with worktree const chat = await trpc.chats.create.mutate({ projectId: project.id, useWorktree: true, baseBranch: "main" }) // 3. Create sub-chat for message stream const subChat = chat.subChats[0] // 4. Stream chat with Claude const unsub = trpc.claude.chat.subscribe( { subChatId: subChat.id, chatId: chat.id, prompt: "Fix the bug", cwd: chat.worktreePath, mode: "agent" }, { onData: (chunk) => { // Handle text, tool-use, results } } ) ``` -------------------------------- ### Start Claude SDK Session Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Explicitly starts a Claude SDK session. Typically called implicitly by the chat subscription, most users do not need to call this directly. ```typescript startSession(input: { subChatId: string token: string model: string baseUrl?: string maxThinkingTokens?: number }) => { sessionId: string messages: Message[] } ``` -------------------------------- ### startSession Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Explicitly starts a Claude SDK session. This is typically called implicitly by chat subscriptions but can be invoked directly when needed. ```APIDOC ## startSession ### Description Explicitly start a Claude SDK session (usually called implicitly by chat subscription). ### Method Mutation ### Endpoint `/claude/startSession` ### Parameters #### Request Body - **subChatId** (string) - Required - The ID of the sub-chat. - **token** (string) - Required - The authentication token. - **model** (string) - Required - The model to use for the session. - **baseUrl** (string) - Optional - The base URL for the Claude SDK. - **maxThinkingTokens** (number) - Optional - The maximum number of tokens for thinking. ### Response #### Success Response - **sessionId** (string) - The ID of the started session. - **messages** (Array) - The initial messages in the session. ``` -------------------------------- ### Get Approved Plugins Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Retrieves a list of approved plugin MCP servers. ```typescript getApprovedPlugins() => string[] ``` -------------------------------- ### Router Creation Pattern Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/02-trpc-setup.md Demonstrates the standard pattern for creating tRPC routers, including query, mutation, and subscription procedures with input validation using Zod. ```typescript import { z } from "zod" import { router, publicProcedure } from "../index" export const exampleRouter = router({ // Query: read-only get: publicProcedure .input(z.object({ id: z.string() })) .query(({ input }) => { return { id: input.id, value: 42 } }), // Mutation: write operations create: publicProcedure .input(z.object({ name: z.string() })) .mutation(async ({ input, ctx }) => { const window = ctx.getWindow?.() return { id: "new-id", name: input.name } }), // Subscription: streaming subscribe: publicProcedure .input(z.string()) .subscription(({ input }) => { return observable((emit) => { // Setup listeners return () => { // Cleanup } }) }), }) ``` -------------------------------- ### Environment Variables Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Defines common environment variables for application mode, analytics, authentication, and telemetry. These are typically set in a .env file. ```bash # Application mode NODE_ENV=development # "development" | "production" # Analytics FORCE_ANALYTICS=true # Force enable analytics in dev mode # OAuth & Authentication VITE_AUTH_PROVIDER_ID=your-provider-id # 21st.dev auth provider VITE_API_BASE_URL=https://api.21st.dev # API backend URL # Telemetry SENTRY_DSN=https://...@sentry.io/... # Sentry error tracking (optional) ``` -------------------------------- ### tRPC Performance Monitoring Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Example output showing tRPC query and mutation performance in milliseconds. Useful for identifying bottlenecks. ```text [tRPC] query projects.list - 42ms [tRPC] mutation chats.create - 1234ms ``` -------------------------------- ### get Source: https://github.com/21st-dev/1code/blob/main/_autodocs/04-chats-router.md Fetches a single chat along with its sub-chats and parent project information. ```APIDOC ## get ### Description Fetch a single chat with all its sub-chats and parent project. ### Method Query ### Parameters #### Query Parameters - **id** (string) - Required - Chat ID ### Returns Chat object with `subChats` array and `project` object, or `null` if not found ### Example ```typescript const chatWithContext = await trpc.chats.get.query({ id: "chat_123" }) if (chatWithContext) { console.log(chatWithContext.subChats) // All agent sessions console.log(chatWithContext.project) // Parent project } ``` ``` -------------------------------- ### Example of ADDED Requirement for Two-Factor Authentication Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Shows how to define a new requirement for Two-Factor Authentication, including a specific scenario. ```markdown ## ADDED Requirements ### Requirement: Two-Factor Authentication Users MUST provide a second factor during login. #### Scenario: OTP required - **WHEN** valid credentials are provided - **THEN** an OTP challenge is required ``` -------------------------------- ### Start Voice Recording Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Initiates voice recording using a specified device ID. Returns recording and stream IDs. ```typescript startRecording(input: { deviceId?: string }) => { recordingId: string streamId: string } ``` -------------------------------- ### Chat Creation Flow: Project and Chat Initialization Source: https://github.com/21st-dev/1code/blob/main/_autodocs/01-overview.md Describes the initial steps in creating a chat, starting with project selection and leading to the creation of a new chat record and worktree. ```text 1. User selects project → `projects.openFolder()` creates/retrieves Project 2. User creates chat → `chats.create()` initializes Chat record + worktree setup 3. Worktree established → Git isolated environment created 4. Sub-chat created → Initial SubChat record for agent session ``` -------------------------------- ### Router Input Validation Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Shows how to use Zod schemas for input validation, specifying required fields and constraints like minimum length. ```typescript .input(z.object({ id: z.string().uuid(), name: z.string().min(1).max(255) })) ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Provides essential commands for the development workflow, including recompiling TypeScript, starting the dev server, and enabling debug logging. Use `bun run build` for recompilation and `bun run dev` for hot-reloading. ```bash cd /workspace/home/1code bun run build # Recompile TypeScript bun run dev # Start dev server with hot reload ``` -------------------------------- ### Start and Listen to Server-Sent Events Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Use `streamFetch` to initiate a server-sent event stream and `onStreamChunk`/`onStreamDone` to process incoming data and completion. ```typescript const result = await desktopApi.streamFetch( "stream-123", // Unique stream ID "https://api.example.com/stream", { method: "POST", body: JSON.stringify({...}) } ) if (!result.ok) { console.error(result.error) } // 2. Listen for chunks const unsubChunk = desktopApi.onStreamChunk("stream-123", (chunk) => { const text = new TextDecoder().decode(chunk) console.log(text) }) // 3. Listen for completion const unsubDone = desktopApi.onStreamDone("stream-123", () => { console.log("Stream complete") unsubChunk() unsubDone() }) ``` -------------------------------- ### Get All MCP Configuration Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Retrieves all available MCP servers, including global, per-project, and plugin servers. Fetches tools with a 40s timeout per server and uses an in-memory cache. ```typescript getAllMcpConfig() => { groups: Array<{ groupName: string // "Global", "Plugin: ...", project name projectPath: string | null mcpServers: Array<{ name: string status: "connected" | "needs-auth" | "pending-approval" | "failed" tools: McpToolInfo[] needsAuth: boolean config: Record isApproved?: boolean // For plugin servers }> }> error?: string } ``` ```typescript const config = await trpc.claude.getAllMcpConfig.query() config.groups.forEach(group => { console.log(`${group.groupName}:`) group.mcpServers.forEach(server => { console.log(` ${server.name}: ${server.status} (${server.tools.length} tools)`) }) }) ``` -------------------------------- ### Development Build Commands Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Commands for building the application during development. `bun run dev` starts the server with hot reload, while `bun run build` compiles the code without packaging. ```bash bun run dev # Start with hot reload bun run build # Compile without packaging ``` -------------------------------- ### Example of ADDED Requirement for OTP Email Notification Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Illustrates the structure for adding a new requirement related to OTP email notifications. ```markdown ## ADDED Requirements ### Requirement: OTP Email Notification ... ``` -------------------------------- ### React tRPC Client Setup Source: https://github.com/21st-dev/1code/blob/main/_autodocs/02-trpc-setup.md Sets up the tRPC client for React applications using `@trpc/react-query`. It requires the AppRouter type for full type safety. ```typescript // src/renderer/lib/trpc.ts import { createTRPCReact } from "@trpc/react-query" import type { AppRouter } from "../../main/lib/trpc/routers" export const trpc = createTRPCReact() ``` -------------------------------- ### Git Command Escaping Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Illustrates safe execution of Git commands by escaping special characters in URLs and validating user input paths. ```typescript // Safe: shell special chars escaped execSync(`git clone "${sanitizedUrl}"`) // For user input validation const validatedPath = validatePathSafe(userInput) ``` -------------------------------- ### Example Usage of Claude Chat Subscription Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Demonstrates how to subscribe to the Claude chat service, handle incoming data chunks (text, tool-use, finish), manage errors, and optionally unsubscribe to abort the stream. ```typescript const unsubscribe = trpc.claude.chat.subscribe( { subChatId: "sub_123", chatId: "chat_123", prompt: "Fix the failing test", cwd: "/workspace/home/myproject", mode: "agent" }, { onData: (chunk) => { if (chunk.type === "text") { console.log(chunk.text) } else if (chunk.type === "tool-use") { console.log(`Tool: ${chunk.toolName}`) } else if (chunk.type === "finish") { console.log("Done") } }, onError: (err) => console.error(err), onComplete: () => console.log("Stream closed") } ) // To abort mid-stream unsubscribe() ``` -------------------------------- ### Project-Level MCP Server Configuration Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Configures project-specific MCP (Multi-Cloud Platform) servers, including GitHub API access and custom server setups. Stored in a .mcp.json file. ```json { "github": { "url": "https://api.github.com", "headers": { "Authorization": "Bearer ghp_..." }, "authType": "bearer" }, "custom-server": { "command": "/usr/local/bin/my-server", "args": ["--config", "/etc/server.conf"], "env": { "API_KEY": "secret" } } } ``` -------------------------------- ### Scan Installed VS Code Themes Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Use `scanVSCodeThemes` to retrieve a list of all installed VS Code themes on the system. ```typescript const themes = await desktopApi.scanVSCodeThemes() // Returns: Array<{ id, name, type: "light" | "dark", path, source }> ``` -------------------------------- ### Initialize OpenSpec Project Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md This command initializes a new OpenSpec project in the specified path. It sets up the necessary directory structure and configuration files. ```bash openspec init [path] ``` -------------------------------- ### Open Drizzle Studio Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Launches the Drizzle Studio web UI for inspecting and editing the database. The studio will be accessible at `localhost:5555`. ```bash bun run db:studio # Open Drizzle Studio (web UI) ``` -------------------------------- ### openFolder Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Opens native folder picker dialog and creates/returns a project. ```APIDOC ## openFolder ### Description Opens native folder picker dialog and creates/returns a project. ### Method Mutation ### Endpoint /projects/openFolder ### Parameters None ### Returns - `Project | null` - Created or updated project, or null if user cancelled dialog ### Behavior: 1. Shows native folder picker dialog (`openDirectory` + `createDirectory`) 2. Extracts git remote info from `.git/config` 3. Checks if project already exists by path 4. If exists: updates `updatedAt` and git info 5. If new: creates project with auto-generated ID 6. Tracks analytics event via `trackProjectOpened()` ### Dialog Options: - Title: "Select Project Folder" - Button: "Open Project" - Can create directories in dialog ### Request Example ```typescript const project = await trpc.projects.openFolder.mutate() if (project) { // Navigate to project } ``` ``` -------------------------------- ### create Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Create a project from a known path (programmatic, no dialog). ```APIDOC ## create ### Description Create a project from a known path (programmatic, no dialog). ### Method Mutation ### Endpoint /projects/create ### Parameters #### Request Body - **path** (string) - Required - Absolute folder path - **name** (string) - Optional - Display name (defaults to folder name) ### Returns - `Project` - Created or existing `Project` ### Behavior: 1. Checks if project already exists by path 2. Extracts git remote info 3. Creates project or returns existing ### Request Example ```typescript const project = await trpc.projects.create.mutate({ path: "/Users/me/myrepo", name: "My Repo" }) ``` ``` -------------------------------- ### Auto-update Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Manage application updates, including checking, downloading, and installing. ```APIDOC ## checkForUpdates ### Description Checks for available application updates. Can be forced to ignore cache. ### Method `GET` (simulated) ### Endpoint `/update/check` (simulated) ### Parameters #### Query Parameters - **force** (boolean) - Optional - If true, forces a check even if updates were recently checked. ### Response #### Success Response (200) - **updateInfo** (object | null) - Information about the available update, or null if no update is available. - **version** (string) - The version of the available update. - **releaseDate** (string) - The release date of the update. - **notes** (string) - Release notes for the update. ### Response Example ```json { "version": "1.1.0", "releaseDate": "2023-10-27T10:00:00Z", "notes": "Bug fixes and performance improvements." } ``` ## downloadUpdate ### Description Downloads the available application update. ### Method `POST` (simulated) ### Endpoint `/update/download` (simulated) ### Response #### Success Response (200) - **success** (boolean) - True if the download started successfully, false otherwise. ### Response Example ```json { "success": true } ``` ## installUpdate ### Description Installs the downloaded application update. This will restart the application. ### Method `POST` (simulated) ### Endpoint `/update/install` (simulated) ### Response #### Success Response (200) - **success** (boolean) - Indicates if the installation process was initiated. ### Response Example ```json { "success": true } ``` ## setUpdateChannel ### Description Sets the update channel for the application (e.g., 'latest' or 'beta'). ### Method `POST` (simulated) ### Endpoint `/update/channel` (simulated) ### Parameters #### Request Body - **channel** (string) - Required - The desired update channel ('latest' or 'beta'). ### Response #### Success Response (200) - **success** (boolean) - True if the channel was set successfully. ### Response Example ```json { "success": true } ``` ## getUpdateChannel ### Description Retrieves the current update channel the application is configured to use. ### Method `GET` (simulated) ### Endpoint `/update/channel` (simulated) ### Response #### Success Response (200) - **channel** (string) - The current update channel ('latest' or 'beta'). ### Response Example ```json { "channel": "latest" } ``` ``` -------------------------------- ### Release Commands Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Commands for building, signing, notarizing, and uploading a new version of the application. Use the full release command for a complete process or step-by-step commands for granular control. ```bash # Full release (build, sign, submit notarization, upload to CDN) bun run release # Or step by step: bun run build # Compile TypeScript bun run package:mac # Build & sign macOS app bun run dist:manifest # Generate latest-mac.yml manifests ./scripts/upload-release-wrangler.sh # Submit notarization & upload to R2 CDN ``` -------------------------------- ### Get MCP Servers Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Retrieves a list of MCP servers with their status. ```typescript getMcpServers() => Array<{ name: string url?: string command?: string status: "connected" | "needs-auth" | "failed" }> ``` -------------------------------- ### Perform Full Release Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Executes the complete release process, including building, signing, and uploading the application. Updates are distributed via `https://cdn.21st.dev/releases/desktop`. ```bash bun run release # Full release (build, sign, upload) ``` -------------------------------- ### scanVSCodeThemes Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Scans the local system to discover installed VS Code themes. ```APIDOC ## scanVSCodeThemes ### Description Discovers installed VS Code themes on the system. ### Method `desktopApi.scanVSCodeThemes()` ### Response #### Success Response - Returns an array of theme objects. Each object contains: - **id** (string) - The unique identifier for the theme. - **name** (string) - The display name of the theme. - **type** (string) - The theme type, either "light" or "dark". - **path** (string) - The file path to the theme's definition. - **source** (string) - The source of the theme (e.g., 'user', 'system'). ### Request Example ```typescript const themes = await desktopApi.scanVSCodeThemes() ``` ``` -------------------------------- ### Configuration: Environment Variables Source: https://github.com/21st-dev/1code/blob/main/_autodocs/01-overview.md Lists essential environment variables for configuring 1Code, including mode settings and analytics flags. ```text - NODE_ENV - Development or production mode - FORCE_ANALYTICS - Force enable analytics in dev - Various OAuth and API endpoints (managed by auth system) ``` -------------------------------- ### getLaunchDirectory Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Returns the launch directory from CLI arguments if the app was launched by passing a folder path. ```APIDOC ## getLaunchDirectory ### Description Returns the launch directory from CLI arguments (if the app was launched by passing a folder path). ### Method Query ### Endpoint /projects/getLaunchDirectory ### Parameters None ### Returns - `path?: string` - Absolute folder path if launched with one, else null - `null` - If app was launched normally without a target folder ### Request Example ```typescript const launchDir = await trpc.projects.getLaunchDirectory.query() if (launchDir?.path) { // User opened app by double-clicking a folder or via CLI } ``` ``` -------------------------------- ### Get Plugin MCP Servers Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Retrieves MCP servers associated with a specific plugin. ```typescript getMcpServers(input: { pluginId: string }) => Array<{ name: string command: string args: string[] status: string }> ``` -------------------------------- ### Open Folder and Create Project Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Opens a native folder picker dialog to create or update a project. Returns the created or updated Project object, or null if the user cancels the dialog. It extracts git remote info and handles existing projects. ```typescript const project = await trpc.projects.openFolder.mutate() if (project) { // Navigate to project } ``` -------------------------------- ### Close Application Window Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Use this function to close the application window. No specific setup is required. ```typescript await desktopApi.windowClose() ``` -------------------------------- ### resumeSession Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Checks if a previously started session can be resumed. Returns a boolean indicating resumability and an optional reason. ```APIDOC ## resumeSession ### Description Check if a session can be resumed. ### Method Query ### Endpoint `/claude/resumeSession` ### Parameters #### Request Body - **sessionId** (string) - Required - The ID of the session to check. ### Response #### Success Response - **canResume** (boolean) - True if the session can be resumed, false otherwise. - **reason** (string) - Optional - The reason why the session cannot be resumed. ``` -------------------------------- ### Worktree Config Router GetSetupCommands Procedure Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Retrieves the necessary shell commands and the appropriate shell for setting up a worktree at a given project path. ```typescript getSetupCommands(input: { projectPath: string }) => { commands: string[] shell: "bash" | "zsh" | "sh" } ``` -------------------------------- ### Sandbox Import Router List Procedure Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Lists available agent sessions in cloud sandboxes, including their ID, name, creation date, and status. ```typescript list() => Array<{ id: string name: string createdAt: string status: "active" | "completed" }> ``` -------------------------------- ### Configuration: Config Files Source: https://github.com/21st-dev/1code/blob/main/_autodocs/01-overview.md Lists key configuration files used by 1Code for managing servers, project settings, and database migrations. ```text - .claude/agents.json - Installed MCP servers - .claude.config.json - Project-level Claude settings - Drizzle migrations in `drizzle/` folder (packaged to `resources/migrations`) ``` -------------------------------- ### Router Error Handling Example Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Demonstrates how to throw a TRPCError with a specific code and message for error handling. ```typescript throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" }) ``` -------------------------------- ### Get Git Status Source: https://github.com/21st-dev/1code/blob/main/_autodocs/12-git-operations-router.md Queries the git status for a specified worktree. Requires the path to the Git repository. ```typescript status(input: { worktreePath: string }) => GitStatus ``` ```typescript const status = await trpc.changes.status.query({ worktreePath: "/workspace/worktrees/chat_123" }) console.log(`Current branch: ${status.branch}`) console.log(`${status.stagedCount} staged, ${status.unstagedCount} unstaged`) ``` -------------------------------- ### Clear Debug Logs Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Deletes all logs currently stored by the debug server. Use this to start with a clean slate. ```bash curl -X DELETE http://localhost:7799/logs ``` -------------------------------- ### Download Application Update Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Downloads the available application update in the background. Returns a boolean indicating if the download process was started. ```typescript const started = await desktopApi.downloadUpdate() ``` -------------------------------- ### Generate and Push Database Migrations Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Commands to manage database migrations. Use `bun run db:generate` to create new migration files based on schema changes and `bun run db:push` to apply them in development. ```bash bun run db:generate # Create migrations from schema changes bun run db:push # Apply migrations (dev only) ``` -------------------------------- ### Package for Distribution Source: https://github.com/21st-dev/1code/blob/main/_autodocs/00-index.md Commands to package the application for different operating systems. This prepares the final distribution files like DMG, ZIP, NSIS, portable, or AppImage. ```bash bun run package:mac # macOS (DMG + ZIP) bun run package:win # Windows (NSIS + portable) bun run package:linux # Linux (AppImage + DEB) ``` -------------------------------- ### newWindow Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Opens a new application window, optionally with a specific chat pre-loaded. ```APIDOC ## newWindow ### Description Open a new application window. ### Method `await desktopApi.newWindow({ chatId: "chat_123", // Optional: open chat in new window subChatId: "sub_456" // Optional: open sub-chat in new window })` ### Parameters #### Request Body - `chatId` (string) - Optional. The ID of the chat to open in the new window. - `subChatId` (string) - Optional. The ID of the sub-chat to open in the new window. ``` -------------------------------- ### Spec File Format: Incorrect Scenario Formatting Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Highlights incorrect markdown formatting for scenarios, showing examples that should be avoided. ```markdown - **Scenario: User login** ❌ **Scenario**: User login ❌ ### Scenario: User login ❌ ``` -------------------------------- ### List Specifications Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Use this command to list all existing specifications within the OpenSpec project. This is useful for understanding the current capabilities and identifying areas for modification. ```bash openspec list --specs ``` -------------------------------- ### Get Chat Details Source: https://github.com/21st-dev/1code/blob/main/_autodocs/04-chats-router.md Fetches a specific chat along with its sub-chats and parent project. Returns null if the chat is not found. ```typescript get(input: { id: string }) => { ...Chat subChats: SubChat[] project: Project } | null ``` ```typescript const chatWithContext = await trpc.chats.get.query({ id: "chat_123" }) if (chatWithContext) { console.log(chatWithContext.subChats) // All agent sessions console.log(chatWithContext.project) // Parent project } ``` -------------------------------- ### Git Types Source: https://github.com/21st-dev/1code/blob/main/_autodocs/07-types-and-schema.md Defines interfaces for Git-related information, including remote repository details, diff results, and worktree setup outcomes. ```typescript interface GitRemoteInfo { remoteUrl?: string provider?: "github" | "gitlab" | "bitbucket" owner?: string repo?: string } interface DiffResult { diff: string // Unified diff files: FileChange[] stats: { filesChanged: number additions: number deletions: number } } interface WorktreeSetupResult { success: boolean worktreePath?: string branch?: string baseBranch?: string error?: string errors?: string[] } ``` -------------------------------- ### createFolder Source: https://github.com/21st-dev/1code/blob/main/_autodocs/05-files-router.md Creates a new directory. The procedure supports creating parent directories if they do not exist. ```APIDOC ## createFolder ### Description Create a directory (with parents if needed). This procedure requires the absolute path of the directory to be created. ### Method Mutation ### Endpoint `/files/createFolder` ### Parameters #### Query Parameters - **path** (string) - Required - Absolute directory path ### Response #### Success Response (200) - **path** (string) - The absolute path of the created directory. ``` -------------------------------- ### Bulk Validation Mode Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md This command starts an interactive bulk validation mode for OpenSpec. It allows for efficient validation of multiple changes or specifications at once. ```bash openspec validate ``` -------------------------------- ### Get Active Terminal Session Count Source: https://github.com/21st-dev/1code/blob/main/_autodocs/06-terminal-router.md Counts the number of active terminal sessions for a given workspace. Useful for analytics and UI indicators. ```typescript getActiveSessionCount(input: { workspaceId: string }) => number ``` -------------------------------- ### Get Terminal Session Metadata Source: https://github.com/21st-dev/1code/blob/main/_autodocs/06-terminal-router.md Retrieves metadata for a specific terminal session using its pane ID. Returns null if the session is not found. ```typescript getSession(input: string) => TerminalSession | null ``` -------------------------------- ### Multi-window Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Manage multiple application windows and their states. ```APIDOC ## newWindow ### Description Opens a new application window. Optionally, it can be pre-focused on a specific chat. ### Method `POST` (simulated) ### Endpoint `/window/new` (simulated) ### Parameters #### Request Body - **chatId** (string) - Optional - The ID of the chat to focus on in the new window. - **subChatId** (string) - Optional - The ID of the sub-chat to focus on in the new window. ### Response #### Success Response (200) - **blocked** (boolean) - Indicates if the window creation was blocked (e.g., due to user settings or limits). ### Response Example ```json { "blocked": false } ``` ## setWindowTitle ### Description Sets the title of the current application window. ### Method `POST` (simulated) ### Endpoint `/window/set-title` (simulated) ### Parameters #### Request Body - **title** (string) - Required - The new title for the window. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. ### Response Example ```json { "success": true } ``` ## claimChat ### Description Claims ownership of a chat, preventing other windows from interacting with it. ### Method `POST` (simulated) ### Endpoint `/chat/claim` (simulated) ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat to claim. ### Response #### Success Response (200) - **ok** (boolean) - True if the claim was successful. - **ownerStableId** (string) - The stable ID of the current owner if the claim failed. ### Response Example ```json { "ok": true } ``` ## releaseChat ### Description Releases ownership of a chat, allowing other windows to interact with it. ### Method `POST` (simulated) ### Endpoint `/chat/release` (simulated) ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat to release. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. ### Response Example ```json { "success": true } ``` ## focusChatOwner ### Description Brings the window that owns the specified chat to the foreground. ### Method `POST` (simulated) ### Endpoint `/chat/focus-owner` (simulated) ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat whose owner window should be focused. ### Response #### Success Response (200) - **focused** (boolean) - True if the owner window was successfully focused, false otherwise. ### Response Example ```json { "focused": true } ``` ``` -------------------------------- ### Get File/Directory Metadata Source: https://github.com/21st-dev/1code/blob/main/_autodocs/05-files-router.md Retrieves metadata for a given file or directory path, including type, size, modification time, and symlink status. ```typescript stat(input: { path: string }) => { path: string type: "file" | "directory" size: number mtime: string // ISO 8601 isSymlink: boolean } ``` -------------------------------- ### Database Initialization Source: https://github.com/21st-dev/1code/blob/main/_autodocs/10-configuration.md Initializes the SQLite database connection and performs auto-migration on first run. Ensures a single database instance is used. ```typescript // src/main/lib/db/index.ts export function getDatabase(): BetterSqlite3Database { if (!db) { const filePath = path.join(getUserDataPath(), "data", "agents.db") // Auto-migrate on init db = buildDatabase(filePath) } return db } ``` -------------------------------- ### Get Single Project by ID Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Fetches a single project by its unique ID. Returns the Project object if found, otherwise returns undefined. ```typescript const project = await trpc.projects.get.query({ id: "proj_123" }) if (project) { console.log(project.name) } ``` -------------------------------- ### Create Folder Source: https://github.com/21st-dev/1code/blob/main/_autodocs/05-files-router.md Creates a new directory. Parent directories will be created automatically if they do not exist. Requires the absolute path for the new directory. ```typescript createFolder(input: { path: string }) => { path: string } ``` -------------------------------- ### Resume Claude SDK Session Source: https://github.com/21st-dev/1code/blob/main/_autodocs/11-claude-router.md Checks if a previously started session can be resumed. Returns whether the session is still valid for resumption and an optional reason. ```typescript resumeSession(input: { sessionId: string }) => { canResume: boolean reason?: string } ``` -------------------------------- ### Initialize Theme with JavaScript Source: https://github.com/21st-dev/1code/blob/main/src/renderer/index.html This IIFE sets the document's theme (light or dark) based on local storage or system preferences. It adds a class to the root element to apply the theme. ```javascript 1Code (function() { var stored = localStorage.getItem('theme'); var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; var theme = stored === 'light' ? 'light' : stored === 'dark' ? 'dark' : (prefersDark ? 'dark' : 'light'); document.documentElement.classList.add(theme); })(); ``` -------------------------------- ### Sandbox Import Router Procedures Source: https://github.com/21st-dev/1code/blob/main/_autodocs/13-other-routers.md Facilitates importing agent sessions from cloud sandboxes into local chats. ```APIDOC ## list ### Description Lists available agent sessions in cloud sandboxes. ### Method list ### Output - **Array of sandbox sessions**: Each session has `id` (string), `name` (string), `createdAt` (string), and `status` ('active' | 'completed'). ## import ### Description Imports a remote agent session from a sandbox into a local chat. ### Method import ### Input - **sandboxId** (string) - Required - The ID of the sandbox session to import. - **chatId** (string) - Required - The ID of the local chat to import into. ### Output - **success** (boolean) - Indicates if the import was successful. - **subChatId** (string) - Optional - The ID of the newly created sub-chat if the import was successful. ``` -------------------------------- ### Drizzle ORM Database Queries Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Example TypeScript code demonstrating how to query the projects and chats tables using Drizzle ORM and the SQLite database. ```typescript import { getDatabase, projects, chats } from "../lib/db" import { eq } from "drizzle-orm" const db = getDatabase() const allProjects = db.select().from(projects).all() const projectChats = db.select().from(chats).where(eq(chats.projectId, id)).all() ``` -------------------------------- ### Spec File Format: Correct Scenario Formatting Source: https://github.com/21st-dev/1code/blob/main/openspec/AGENTS.md Demonstrates the correct markdown formatting for scenarios within spec files, emphasizing the use of #### headers. ```markdown #### Scenario: User login success - **WHEN** valid credentials provided - **THEN** return JWT token ``` -------------------------------- ### Database Migration and Push Commands Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Commands for generating database migrations and pushing schema changes directly to the database during development. ```bash # Database (Drizzle + SQLite) bun run db:generate # Generate migrations from schema bun run db:push # Push schema directly (dev only) ``` -------------------------------- ### Sync to Public Source: https://github.com/21st-dev/1code/blob/main/CLAUDE.md Command to synchronize release files to the public repository. This is a final step in the release process. ```bash ./scripts/sync-to-public.sh ``` -------------------------------- ### Get Git Diff Source: https://github.com/21st-dev/1code/blob/main/_autodocs/12-git-operations-router.md Generates a unified diff for changes within a specified worktree. Optionally filters by base reference and specific file paths. ```typescript diff(input: { worktreePath: string baseRef?: string paths?: string[] }) => DiffResult ``` ```typescript const { diff, stats } = await trpc.changes.diff.query({ worktreePath: "/workspace/worktrees/chat_123" }) console.log(`${stats.filesChanged} files, +${stats.additions}/-${stats.deletions}`) console.log(diff) // Full unified diff ``` -------------------------------- ### Create Project Programmatically Source: https://github.com/21st-dev/1code/blob/main/_autodocs/03-projects-router.md Creates a new project from a known absolute folder path without using a dialog. An optional display name can be provided; otherwise, the folder name is used. Returns the created or existing Project. ```typescript const project = await trpc.projects.create.mutate({ path: "/Users/me/myrepo", name: "My Repo" }) ``` -------------------------------- ### Stashing and Applying Rollback Stashes Source: https://github.com/21st-dev/1code/blob/main/_autodocs/12-git-operations-router.md Demonstrates creating a stash before a rollback and later applying it to restore changes. Stashes are temporary and automatically cleaned up. ```typescript // Create stash before rollback const stashId = createRollbackStash(worktreePath) // Later, can restore if needed applyRollbackStash(worktreePath, stashId) ``` -------------------------------- ### Get Authenticated User and Status Source: https://github.com/21st-dev/1code/blob/main/_autodocs/08-desktop-api.md Retrieves information about the currently authenticated user, including their email and name. Also provides a boolean indicating if the user is authenticated. ```typescript const user = await desktopApi.getUser() if (user) { console.log(user.email, user.name) } const authed = await desktopApi.isAuthenticated() ```