chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,208 @@
|
||||
---
|
||||
name: cline-sdk
|
||||
description: Comprehensive Cline SDK skill for building AI agents. Covers the Agent runtime, ClineCore sessions, custom tools, plugins, events, LLM providers, scheduling, multi-agent teams, and production deployment. Use for any task involving @cline/sdk or its sub-packages.
|
||||
metadata:
|
||||
references: agent, clinecore
|
||||
---
|
||||
|
||||
# Cline SDK Skill
|
||||
|
||||
Consolidated skill for building AI agents with the Cline SDK. Use the decision trees below to find the right entry point and API surface, then load detailed references.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
Follow these rules in all Cline SDK code:
|
||||
|
||||
1. Install with `npm install @cline/sdk`. The `@cline/sdk` package re-exports everything from `@cline/core`, `@cline/agents`, `@cline/llms`, and `@cline/shared`.
|
||||
2. Requires Node.js 22 or later.
|
||||
3. Use `createTool()` from `@cline/sdk` (or `@cline/shared`) to define tools. Tool names must be `snake_case`.
|
||||
4. Return errors as structured data from tool `execute` functions. Throwing counts as a "mistake" against the agent's mistake limit.
|
||||
5. Use `lifecycle: { completesRun: true }` on tools that should end the agent loop (e.g. a "submit answer" tool).
|
||||
6. When using `ClineCore`, always call `dispose()` when done to clean up resources.
|
||||
7. The standalone `Agent` and `ClineCore` have different event systems. For `Agent`: use `agent.subscribe()` to get `AgentRuntimeEvent` types (text streaming is `"assistant-text-delta"`, result text is `result.outputText`). For `ClineCore`: use `cline.subscribe()` to get `CoreSessionEvent` types (text streaming is `"chunk"` with `payload.type === "text"`, result text is `result.text`). There is no top-level `onEvent` field on `AgentRuntimeConfig` -- use `agent.subscribe()` or `hooks.onEvent` instead. Do not use event types like `"content_update"` or `"content_start"` with `agent.subscribe()` -- those are internal legacy types from the ClineCore adapter layer.
|
||||
|
||||
## How to Use This Skill
|
||||
|
||||
### Reference File Structure
|
||||
|
||||
The two main API surfaces (`Agent` and `ClineCore`) follow a 4-file pattern. Cross-cutting concepts are single-file guides.
|
||||
|
||||
Each main API surface in `./references/<api>/` contains:
|
||||
|
||||
| File | Purpose | When to Read |
|
||||
|------|---------|--------------|
|
||||
| `REFERENCE.md` | Overview, when to use, quick start | Always read first |
|
||||
| `api.md` | Full API: classes, methods, config, types | Writing code |
|
||||
| `patterns.md` | Common patterns, best practices | Implementation guidance |
|
||||
| `gotchas.md` | Pitfalls, limitations, debugging | Troubleshooting |
|
||||
|
||||
Cross-cutting concepts in `./references/<concept>/` have `REFERENCE.md` as the entry point.
|
||||
|
||||
### Reading Order
|
||||
|
||||
1. Start with `REFERENCE.md` for your chosen API surface
|
||||
2. Then read additional files relevant to your task:
|
||||
- Writing agent code -> `api.md`
|
||||
- Common patterns -> `patterns.md`
|
||||
- Creating tools -> `tools/REFERENCE.md`
|
||||
- Adding plugins/hooks -> `plugins/REFERENCE.md`
|
||||
- Configuring LLM providers -> `providers/REFERENCE.md`
|
||||
- Streaming events -> `events/REFERENCE.md`
|
||||
- Deploying to production -> `production/REFERENCE.md`
|
||||
- Scheduling agents -> `scheduling/REFERENCE.md`
|
||||
- Multi-agent orchestration -> `multi-agent/REFERENCE.md`
|
||||
- Debugging -> `gotchas.md`
|
||||
|
||||
### Example Paths
|
||||
|
||||
```
|
||||
./references/agent/REFERENCE.md # Start here for lightweight agents
|
||||
./references/clinecore/REFERENCE.md # Start here for full runtime
|
||||
./references/agent/api.md # Agent class, config, methods
|
||||
./references/tools/REFERENCE.md # Creating and using tools
|
||||
./references/plugins/REFERENCE.md # Plugin system
|
||||
./references/providers/REFERENCE.md # LLM provider configuration
|
||||
```
|
||||
|
||||
## Quick Decision Trees
|
||||
|
||||
### "Which API surface should I use?"
|
||||
|
||||
```
|
||||
Which API?
|
||||
+-- I want a simple, stateless agent with custom tools
|
||||
| +-- agent/ (Agent class from @cline/agents)
|
||||
+-- I need session persistence, built-in tools, config discovery
|
||||
| +-- clinecore/ (ClineCore from @cline/core)
|
||||
+-- I want built-in file/shell/search/web tools
|
||||
| +-- clinecore/ (has built-in tools; Agent does not)
|
||||
+-- I want scheduled or recurring agents
|
||||
| +-- clinecore/ (automation API)
|
||||
+-- I need multi-process or multi-client session sharing
|
||||
| +-- clinecore/ (hub-backed runtime)
|
||||
+-- I'm building a browser-compatible agent
|
||||
| +-- agent/ (no Node.js dependencies)
|
||||
```
|
||||
|
||||
### "I need to create tools"
|
||||
|
||||
```
|
||||
Tools?
|
||||
+-- Define a custom tool with schema -> tools/REFERENCE.md
|
||||
+-- Use built-in tools (bash, editor, read_files) -> tools/REFERENCE.md (built-in section)
|
||||
+-- Control tool approval/policies -> tools/REFERENCE.md (policies section)
|
||||
+-- Tool that ends the agent loop -> tools/REFERENCE.md (completion tools)
|
||||
+-- Package tools as a reusable plugin -> plugins/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need to handle events"
|
||||
|
||||
```
|
||||
Events?
|
||||
+-- Stream text/reasoning in real time -> events/REFERENCE.md
|
||||
+-- Track token usage and costs -> events/REFERENCE.md
|
||||
+-- Watch tool calls -> events/REFERENCE.md
|
||||
+-- Detect completion/errors -> events/REFERENCE.md
|
||||
+-- Hook into lifecycle stages -> plugins/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need to configure a model provider"
|
||||
|
||||
```
|
||||
Providers?
|
||||
+-- Anthropic (Claude) -> providers/REFERENCE.md
|
||||
+-- OpenAI (GPT) -> providers/REFERENCE.md
|
||||
+-- Google (Gemini/Vertex) -> providers/REFERENCE.md
|
||||
+-- AWS Bedrock -> providers/REFERENCE.md
|
||||
+-- Mistral -> providers/REFERENCE.md
|
||||
+-- OpenAI-compatible (vLLM, Together, etc.) -> providers/REFERENCE.md
|
||||
+-- Custom/self-hosted provider -> providers/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need plugins or hooks"
|
||||
|
||||
```
|
||||
Plugins?
|
||||
+-- Package tools + hooks together -> plugins/REFERENCE.md
|
||||
+-- Observe tool calls (logging, metrics) -> plugins/REFERENCE.md
|
||||
+-- Intercept lifecycle events -> plugins/REFERENCE.md
|
||||
+-- Add system prompt rules -> plugins/REFERENCE.md
|
||||
+-- Distribute via npm/git -> plugins/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need multi-agent coordination"
|
||||
|
||||
```
|
||||
Multi-agent?
|
||||
+-- Spawn one-off background agents -> multi-agent/REFERENCE.md (sub-agents)
|
||||
+-- Persistent cross-session teams -> multi-agent/REFERENCE.md (teams)
|
||||
+-- Parent-child delegation -> multi-agent/REFERENCE.md (sub-agents)
|
||||
+-- Peer-to-peer task board -> multi-agent/REFERENCE.md (teams)
|
||||
```
|
||||
|
||||
### "I need scheduling or automation"
|
||||
|
||||
```
|
||||
Scheduling?
|
||||
+-- Recurring cron jobs -> scheduling/REFERENCE.md
|
||||
+-- One-off scheduled tasks -> scheduling/REFERENCE.md
|
||||
+-- Event-driven triggers -> scheduling/REFERENCE.md
|
||||
+-- CLI schedule management -> scheduling/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need to go to production"
|
||||
|
||||
```
|
||||
Production?
|
||||
+-- Error handling and status checks -> production/REFERENCE.md
|
||||
+-- Cost control and token limits -> production/REFERENCE.md
|
||||
+-- Observability (OpenTelemetry) -> production/REFERENCE.md
|
||||
+-- Security and sandboxing -> production/REFERENCE.md
|
||||
+-- Deployment patterns -> production/REFERENCE.md
|
||||
```
|
||||
|
||||
### Troubleshooting Index
|
||||
|
||||
- Agent loop not stopping -> `tools/REFERENCE.md` (completion tools)
|
||||
- Tool errors crashing the agent -> `agent/gotchas.md` or `clinecore/gotchas.md`
|
||||
- Provider auth failures -> `providers/REFERENCE.md`
|
||||
- Session not persisting -> `clinecore/gotchas.md`
|
||||
- Token usage too high -> `production/REFERENCE.md` (cost control)
|
||||
- Hub connection issues -> `clinecore/gotchas.md`
|
||||
- Plugin not loading -> `plugins/REFERENCE.md`
|
||||
- Events not firing -> `events/REFERENCE.md`
|
||||
|
||||
## Product Index
|
||||
|
||||
### API Surfaces
|
||||
| API | Entry File | Description |
|
||||
|-----|------------|-------------|
|
||||
| Agent | `./references/agent/REFERENCE.md` | Lightweight stateless agent loop |
|
||||
| ClineCore | `./references/clinecore/REFERENCE.md` | Full runtime with sessions, persistence, built-in tools |
|
||||
|
||||
### Cross-Cutting Concepts
|
||||
| Concept | Entry File | Description |
|
||||
|---------|------------|-------------|
|
||||
| Tools | `./references/tools/REFERENCE.md` | Built-in and custom tool creation |
|
||||
| Plugins | `./references/plugins/REFERENCE.md` | Extension system with hooks |
|
||||
| Events | `./references/events/REFERENCE.md` | Real-time streaming events |
|
||||
| Providers | `./references/providers/REFERENCE.md` | LLM provider configuration |
|
||||
| Production | `./references/production/REFERENCE.md` | Deployment, security, observability |
|
||||
| Scheduling | `./references/scheduling/REFERENCE.md` | Cron jobs and automation |
|
||||
| Multi-Agent | `./references/multi-agent/REFERENCE.md` | Teams and sub-agents |
|
||||
|
||||
### Package Map
|
||||
| Package | Purpose |
|
||||
|---------|---------|
|
||||
| `@cline/sdk` | Everything you need, install this one |
|
||||
| `@cline/core` | Sessions, persistence, built-in tools, config, hub |
|
||||
| `@cline/agents` | Stateless agent loop, tool orchestration, streaming |
|
||||
| `@cline/llms` | LLM provider gateway |
|
||||
| `@cline/shared` | Types, tool helpers, hook engine |
|
||||
|
||||
## Resources
|
||||
|
||||
Repository: https://github.com/cline/cline
|
||||
SDK Source: https://github.com/cline/cline/tree/main/sdk
|
||||
Documentation: https://docs.cline.bot/sdk/overview
|
||||
Discord: https://discord.gg/cline
|
||||
@@ -0,0 +1,107 @@
|
||||
# Agent Runtime
|
||||
|
||||
The `Agent` class (also exported as `AgentRuntime`) is the lightweight, stateless agent loop from `@cline/agents`. It handles the core iteration cycle: send messages to an LLM, execute tool calls, collect results, and repeat until the task is done.
|
||||
|
||||
## When to Use Agent
|
||||
|
||||
| Use Agent when... | Use ClineCore instead when... |
|
||||
|---|---|
|
||||
| You want a simple agent with custom tools | You need built-in tools (bash, editor, etc.) |
|
||||
| You want minimal dependencies | You need session persistence |
|
||||
| You need browser compatibility | You need config discovery from `.cline/` |
|
||||
| You're building a stateless worker | You need multi-process session sharing |
|
||||
| You want full control over the runtime | You want batteries-included setup |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
const result = await agent.run("What is the capital of France?")
|
||||
console.log(result.outputText)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
The Agent operates in a loop:
|
||||
1. Accept user input (string, message, or array of messages)
|
||||
2. Build turn context (system prompt, messages, tools)
|
||||
3. Call the LLM provider
|
||||
4. If the model returns tool calls, execute them and loop back to step 3
|
||||
5. If the model returns text without tool calls, the run completes
|
||||
6. Emit events throughout for streaming
|
||||
|
||||
The agent is stateless in the sense that it does not persist anything to disk. Conversation history is held in memory and can be accessed via `snapshot()`.
|
||||
|
||||
## Key APIs
|
||||
|
||||
- `new Agent(config)` or `createAgent(config)` - Create an agent
|
||||
- `agent.run(input)` - Start a run with user input
|
||||
- `agent.continue(input?)` - Continue an existing conversation
|
||||
- `agent.abort(reason?)` - Cancel an active run
|
||||
- `agent.subscribe(listener)` - Listen to streaming events
|
||||
- `agent.snapshot()` - Get current runtime state
|
||||
- `agent.restore(messages)` - Replace message history
|
||||
|
||||
See `api.md` for full API details.
|
||||
|
||||
## Multi-Turn Conversations
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
const first = await agent.run("What is 2 + 2?")
|
||||
console.log(first.outputText)
|
||||
|
||||
const second = await agent.continue("Now multiply that by 3")
|
||||
console.log(second.outputText)
|
||||
```
|
||||
|
||||
Use `agent.hasRun` to check if a run has already been executed, which determines whether to call `run()` or `continue()`.
|
||||
|
||||
## Event Streaming
|
||||
|
||||
Use `agent.subscribe()` to stream events in real time. Register the listener before calling `run()` to avoid missing early events.
|
||||
|
||||
There is no top-level `onEvent` field on the Agent config. For an async alternative, use `hooks.onEvent` (see `api.md` and `gotchas.md`).
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "assistant-text-delta") {
|
||||
process.stdout.write(event.text)
|
||||
}
|
||||
})
|
||||
|
||||
const result = await agent.run("What is the capital of France?")
|
||||
```
|
||||
|
||||
See `events/REFERENCE.md` for the full event type catalog.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- `api.md` - Full Agent API reference
|
||||
- `patterns.md` - Common patterns and best practices
|
||||
- `gotchas.md` - Pitfalls and debugging
|
||||
- `../tools/REFERENCE.md` - Creating custom tools
|
||||
- `../events/REFERENCE.md` - Event system details
|
||||
- `../providers/REFERENCE.md` - Provider configuration
|
||||
@@ -0,0 +1,231 @@
|
||||
# Agent API Reference
|
||||
|
||||
## Constructor
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
|
||||
const agent = new Agent(config: AgentRuntimeConfig)
|
||||
```
|
||||
|
||||
Also available via factory function:
|
||||
|
||||
```typescript
|
||||
import { createAgent } from "@cline/sdk"
|
||||
|
||||
const agent = createAgent(config)
|
||||
```
|
||||
|
||||
## AgentRuntimeConfig
|
||||
|
||||
Two config forms exist as a discriminated union:
|
||||
|
||||
### With Provider ID (recommended)
|
||||
|
||||
```typescript
|
||||
interface AgentRuntimeConfigWithProvider {
|
||||
providerId: string // e.g. "anthropic", "openai", "gemini"
|
||||
modelId: string // e.g. "claude-sonnet-4-6", "gpt-5.5"
|
||||
apiKey?: string // provider API key
|
||||
baseUrl?: string // custom endpoint
|
||||
headers?: Record<string, string>
|
||||
|
||||
systemPrompt?: string
|
||||
tools?: AgentTool[]
|
||||
initialMessages?: AgentMessage[]
|
||||
toolPolicies?: Record<string, ToolPolicy>
|
||||
hooks?: Partial<AgentRuntimeHooks>
|
||||
plugins?: AgentPlugin[]
|
||||
}
|
||||
```
|
||||
|
||||
### With Pre-built Model
|
||||
|
||||
```typescript
|
||||
interface AgentRuntimeConfigWithModel {
|
||||
model: AgentModel // pre-built model from gateway
|
||||
|
||||
systemPrompt?: string
|
||||
tools?: AgentTool[]
|
||||
initialMessages?: AgentMessage[]
|
||||
toolPolicies?: Record<string, ToolPolicy>
|
||||
hooks?: Partial<AgentRuntimeHooks>
|
||||
plugins?: AgentPlugin[]
|
||||
}
|
||||
```
|
||||
|
||||
Note: there is no top-level `onEvent` field on `AgentRuntimeConfig`. For event streaming, use `agent.subscribe()` or `hooks.onEvent` (see AgentRuntimeHooks below).
|
||||
|
||||
## Methods
|
||||
|
||||
### run(input)
|
||||
|
||||
Start the agent with user input. Returns when the agent loop completes.
|
||||
|
||||
```typescript
|
||||
const result: AgentRunResult = await agent.run("Build a REST API")
|
||||
```
|
||||
|
||||
Input can be a string, an `AgentMessage`, or an array of `AgentMessage[]`.
|
||||
|
||||
### continue(input?)
|
||||
|
||||
Continue an existing conversation with optional new input.
|
||||
|
||||
```typescript
|
||||
const result = await agent.continue("Now add authentication")
|
||||
```
|
||||
|
||||
### abort(reason?)
|
||||
|
||||
Cancel the currently active run.
|
||||
|
||||
```typescript
|
||||
agent.abort("User cancelled")
|
||||
```
|
||||
|
||||
### subscribe(listener)
|
||||
|
||||
Register a listener for streaming events.
|
||||
|
||||
```typescript
|
||||
const unsubscribe = agent.subscribe((event: AgentRuntimeEvent) => {
|
||||
// handle event
|
||||
})
|
||||
|
||||
// Later: stop listening
|
||||
unsubscribe()
|
||||
```
|
||||
|
||||
### snapshot()
|
||||
|
||||
Get the current runtime state including message history.
|
||||
|
||||
```typescript
|
||||
const state: AgentRuntimeStateSnapshot = agent.snapshot()
|
||||
```
|
||||
|
||||
### restore(messages)
|
||||
|
||||
Replace the agent's message history.
|
||||
|
||||
```typescript
|
||||
agent.restore(previousMessages)
|
||||
```
|
||||
|
||||
### hasRun
|
||||
|
||||
Boolean property indicating whether `run()` has been called at least once.
|
||||
|
||||
```typescript
|
||||
if (agent.hasRun) {
|
||||
await agent.continue(input)
|
||||
} else {
|
||||
await agent.run(input)
|
||||
}
|
||||
```
|
||||
|
||||
## AgentRunResult
|
||||
|
||||
Returned by `run()` and `continue()`.
|
||||
|
||||
```typescript
|
||||
interface AgentRunResult {
|
||||
agentId: string
|
||||
agentRole?: string
|
||||
runId: string
|
||||
status: "completed" | "aborted" | "failed"
|
||||
iterations: number
|
||||
outputText: string
|
||||
messages: readonly AgentMessage[]
|
||||
usage: AgentUsage
|
||||
error?: Error
|
||||
}
|
||||
```
|
||||
|
||||
### Status Values
|
||||
|
||||
- `"completed"` - Agent finished normally
|
||||
- `"aborted"` - Cancelled via `abort()`
|
||||
- `"failed"` - Unrecoverable error
|
||||
|
||||
## AgentMessage
|
||||
|
||||
```typescript
|
||||
interface AgentMessage {
|
||||
id: string
|
||||
role: "user" | "assistant" | "tool"
|
||||
content: AgentMessagePart[]
|
||||
createdAt: number
|
||||
metadata?: Record<string, unknown>
|
||||
modelInfo?: { id: string; provider: string; family?: string }
|
||||
metrics?: {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens?: number
|
||||
cacheWriteTokens?: number
|
||||
cost?: number
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## AgentUsage
|
||||
|
||||
```typescript
|
||||
interface AgentUsage {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
totalInputTokens: number
|
||||
totalOutputTokens: number
|
||||
totalCost?: number
|
||||
}
|
||||
```
|
||||
|
||||
## AgentRuntimeHooks
|
||||
|
||||
```typescript
|
||||
interface AgentRuntimeHooks {
|
||||
beforeRun?(context): AgentStopControl | undefined
|
||||
afterRun?(context): void
|
||||
beforeModel?(context): AgentBeforeModelResult | undefined
|
||||
afterModel?(context): AgentStopControl | undefined
|
||||
beforeTool?(context): AgentBeforeToolResult | undefined
|
||||
afterTool?(context): AgentAfterToolResult | undefined
|
||||
onEvent?(event: AgentRuntimeEvent): void | Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
Hooks can intercept and modify behavior at each stage. Return a stop control from `beforeRun`, `afterModel`, or `beforeTool` to halt the agent loop.
|
||||
|
||||
`hooks.onEvent` receives the same `AgentRuntimeEvent` types as `agent.subscribe()`, but hook callbacks are awaited (can be async), while `subscribe()` listeners are called synchronously. Use `subscribe()` for UI streaming and `hooks.onEvent` for async side effects like logging to an external service.
|
||||
|
||||
## AgentRuntimeStateSnapshot
|
||||
|
||||
```typescript
|
||||
interface AgentRuntimeStateSnapshot {
|
||||
messages: readonly AgentMessage[]
|
||||
usage: AgentUsage
|
||||
iterations: number
|
||||
status: string
|
||||
}
|
||||
```
|
||||
|
||||
## Factory: createAgentRuntime
|
||||
|
||||
Lower-level factory that returns the same `Agent` class:
|
||||
|
||||
```typescript
|
||||
import { createAgentRuntime } from "@cline/sdk"
|
||||
|
||||
const runtime = createAgentRuntime(config)
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `REFERENCE.md` - Overview and quick start
|
||||
- `patterns.md` - Common patterns
|
||||
- `../tools/REFERENCE.md` - Tool creation
|
||||
- `../events/REFERENCE.md` - Event types
|
||||
- `../providers/REFERENCE.md` - Provider setup
|
||||
@@ -0,0 +1,134 @@
|
||||
# Agent Gotchas
|
||||
|
||||
## Agent Loop Never Stops
|
||||
|
||||
If the agent keeps iterating without completing:
|
||||
|
||||
- Make sure at least one tool has `lifecycle: { completesRun: true }` if you want the agent to explicitly finish.
|
||||
- Without any tools, the agent will complete after the model returns text without tool calls.
|
||||
- If using tools, ensure the system prompt guides the model toward calling the completion tool when done.
|
||||
- Check that `completesRun` tools return successfully (not throwing errors).
|
||||
|
||||
## Tool Errors Count as Mistakes
|
||||
|
||||
When a tool's `execute` function throws an exception, the SDK counts it as a "mistake." After too many mistakes, the agent stops with a `mistake_limit` finish reason.
|
||||
|
||||
Instead, return errors as structured data:
|
||||
|
||||
```typescript
|
||||
// Bad: throwing
|
||||
execute: async (input) => {
|
||||
throw new Error("File not found")
|
||||
}
|
||||
|
||||
// Good: returning error data
|
||||
execute: async (input) => {
|
||||
return { error: "File not found", path: input.path }
|
||||
}
|
||||
```
|
||||
|
||||
## run() vs continue()
|
||||
|
||||
- Call `run()` for the first interaction. It sets up the conversation.
|
||||
- Call `continue()` for subsequent messages. It appends to the existing conversation.
|
||||
- Calling `run()` a second time resets the conversation history.
|
||||
- Use `agent.hasRun` to check which method to call.
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
`@cline/agents` (and by extension, the `Agent` class) is browser-safe with no Node.js dependencies. However, `@cline/core` and `ClineCore` require Node.js 22+. If you import from `@cline/sdk`, you get everything including the Node-only code. For browser usage, import directly from `@cline/agents`:
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/agents"
|
||||
```
|
||||
|
||||
## No Top-Level onEvent on Agent Config
|
||||
|
||||
`AgentRuntimeConfig` does not have a top-level `onEvent` field. Passing `onEvent` to `new Agent({ onEvent: ... })` has no effect. There are two ways to receive events:
|
||||
|
||||
```typescript
|
||||
// Option 1: subscribe() - synchronous, best for UI streaming
|
||||
const agent = new Agent({ ...config })
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "assistant-text-delta") {
|
||||
process.stdout.write(event.text)
|
||||
}
|
||||
})
|
||||
|
||||
// Option 2: hooks.onEvent - awaited, best for async side effects
|
||||
const agent = new Agent({
|
||||
...config,
|
||||
hooks: {
|
||||
onEvent: async (event) => {
|
||||
if (event.type === "assistant-text-delta") {
|
||||
await logToService(event.text)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Both receive the same `AgentRuntimeEvent` types. Prefer `subscribe()` for streaming UI.
|
||||
|
||||
## Event Listener Timing
|
||||
|
||||
Register event listeners via `subscribe()` before calling `run()`:
|
||||
|
||||
```typescript
|
||||
// Good: subscribe before run
|
||||
agent.subscribe(handler)
|
||||
const result = await agent.run(input)
|
||||
|
||||
// Bad: subscribing after run starts loses early events
|
||||
const promise = agent.run(input)
|
||||
agent.subscribe(handler) // may miss events
|
||||
```
|
||||
|
||||
## Tool Input Schema Matters
|
||||
|
||||
The model uses the tool's `inputSchema` to decide what arguments to pass. A vague or missing schema leads to incorrect tool calls.
|
||||
|
||||
- Use `z.enum()` for fixed value sets, not free-form strings
|
||||
- Describe every property with `.describe()` in Zod or `description` in JSON Schema
|
||||
- Include constraints (rate limits, max values) in the tool description
|
||||
|
||||
## Memory and Long Conversations
|
||||
|
||||
The Agent holds all messages in memory. For long-running conversations, memory usage grows with each turn. Consider:
|
||||
|
||||
- Using `ClineCore` with compaction for long sessions
|
||||
- Periodically creating a new agent with a summary of the conversation
|
||||
- Monitoring `result.usage.totalInputTokens` to track context growth
|
||||
|
||||
## Abort Signal Handling in Tools
|
||||
|
||||
Long-running tools should respect the abort signal:
|
||||
|
||||
```typescript
|
||||
execute: async (input, context) => {
|
||||
for (const item of items) {
|
||||
if (context.abortSignal?.aborted) {
|
||||
return { partial: results, aborted: true }
|
||||
}
|
||||
results.push(await process(item))
|
||||
}
|
||||
return { results }
|
||||
}
|
||||
```
|
||||
|
||||
## Provider API Key
|
||||
|
||||
If you get authentication errors, check:
|
||||
|
||||
- `apiKey` is set in the config or via environment variables
|
||||
- The key matches the `providerId` (e.g., Anthropic key for `providerId: "anthropic"`)
|
||||
- For OpenAI-compatible providers, both `apiKey` and `baseUrl` are set
|
||||
|
||||
See `../providers/REFERENCE.md` for provider-specific setup.
|
||||
|
||||
## See Also
|
||||
|
||||
- `api.md` - Full API reference
|
||||
- `patterns.md` - Common patterns
|
||||
- `../tools/REFERENCE.md` - Tool creation
|
||||
- `../clinecore/REFERENCE.md` - Use ClineCore for persistence
|
||||
@@ -0,0 +1,258 @@
|
||||
# Agent Patterns
|
||||
|
||||
## Interactive CLI Agent
|
||||
|
||||
A multi-turn conversational agent in the terminal with streaming output:
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
import * as readline from "node:readline"
|
||||
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
systemPrompt: "You are a helpful assistant. Keep responses concise.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "assistant-text-delta") {
|
||||
process.stdout.write(event.text)
|
||||
}
|
||||
})
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
})
|
||||
|
||||
function prompt(): void {
|
||||
rl.question("\nYou: ", async (input) => {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed || trimmed === "exit") {
|
||||
rl.close()
|
||||
return
|
||||
}
|
||||
|
||||
process.stdout.write("\nAssistant: ")
|
||||
|
||||
if (agent.hasRun) {
|
||||
await agent.continue(trimmed)
|
||||
} else {
|
||||
await agent.run(trimmed)
|
||||
}
|
||||
|
||||
process.stdout.write("\n")
|
||||
prompt()
|
||||
})
|
||||
}
|
||||
|
||||
prompt()
|
||||
```
|
||||
|
||||
## Conversational Agent (Slack Bot, Chat App)
|
||||
|
||||
Maintain per-thread agents with conversation memory:
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
|
||||
const agents = new Map<string, Agent>()
|
||||
|
||||
async function handleMessage(threadId: string, message: string) {
|
||||
let agent = agents.get(threadId)
|
||||
if (!agent) {
|
||||
agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "You are a concise assistant.",
|
||||
tools: [],
|
||||
})
|
||||
agents.set(threadId, agent)
|
||||
}
|
||||
|
||||
const result = agent.hasRun
|
||||
? await agent.continue(message)
|
||||
: await agent.run(message)
|
||||
|
||||
return result.outputText
|
||||
}
|
||||
```
|
||||
|
||||
## Streaming UI
|
||||
|
||||
Build a real-time UI by handling events via `subscribe()`:
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [myTool],
|
||||
})
|
||||
|
||||
agent.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "assistant-text-delta":
|
||||
ui.appendText(event.text)
|
||||
break
|
||||
case "assistant-message":
|
||||
ui.endText()
|
||||
break
|
||||
case "turn-started":
|
||||
ui.startTurn(event.iteration)
|
||||
break
|
||||
case "turn-finished":
|
||||
if (event.toolCallCount > 0) ui.showToolCount(event.toolCallCount)
|
||||
break
|
||||
case "usage-updated":
|
||||
ui.updateUsage(event.usage.inputTokens, event.usage.outputTokens)
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
const result = await agent.run("Hello!")
|
||||
```
|
||||
|
||||
## Structured Output via Completion Tool
|
||||
|
||||
Use a tool with `completesRun: true` to extract structured data:
|
||||
|
||||
```typescript
|
||||
import { Agent, createTool } from "@cline/sdk"
|
||||
import { z } from "zod"
|
||||
|
||||
const submitReview = createTool({
|
||||
name: "submit_review",
|
||||
description: "Submit the final code review with structured feedback.",
|
||||
inputSchema: z.object({
|
||||
summary: z.string(),
|
||||
issues: z.array(z.object({
|
||||
file: z.string(),
|
||||
line: z.number(),
|
||||
severity: z.enum(["error", "warning", "info"]),
|
||||
message: z.string(),
|
||||
})),
|
||||
approved: z.boolean(),
|
||||
}),
|
||||
lifecycle: { completesRun: true },
|
||||
execute: async (input) => input,
|
||||
})
|
||||
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "Review the code diff and submit structured feedback.",
|
||||
tools: [submitReview],
|
||||
})
|
||||
|
||||
const result = await agent.run(diffContent)
|
||||
const review = result.toolCalls.find(tc => tc.name === "submit_review")
|
||||
console.log(review?.output)
|
||||
```
|
||||
|
||||
## Agent with Abort/Timeout
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "Analyze this data.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
const timeout = setTimeout(() => agent.abort("Timeout"), 30_000)
|
||||
|
||||
try {
|
||||
const result = await agent.run(data)
|
||||
if (result.status === "aborted") {
|
||||
console.log("Agent was aborted")
|
||||
} else {
|
||||
console.log(result.outputText)
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
```
|
||||
|
||||
## Agent with Plugins
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
import type { AgentPlugin } from "@cline/sdk"
|
||||
|
||||
const loggingPlugin: AgentPlugin = {
|
||||
name: "logging",
|
||||
manifest: { capabilities: ["hooks"] },
|
||||
setup() {},
|
||||
hooks: {
|
||||
beforeTool({ toolCall }) {
|
||||
console.log(`Calling tool: ${toolCall.toolName}`)
|
||||
},
|
||||
afterRun({ result }) {
|
||||
console.log(`Completed in ${result.iterations} iterations`)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [myTool],
|
||||
plugins: [loggingPlugin],
|
||||
})
|
||||
```
|
||||
|
||||
## Restoring State Across Sessions
|
||||
|
||||
Save and restore agent state manually:
|
||||
|
||||
```typescript
|
||||
// Save state
|
||||
const snapshot = agent.snapshot()
|
||||
const serialized = JSON.stringify(snapshot.messages)
|
||||
|
||||
// Later: restore
|
||||
const agent2 = new Agent({ ...config })
|
||||
const messages = JSON.parse(serialized)
|
||||
agent2.restore(messages)
|
||||
const result = await agent2.continue("Continue where we left off")
|
||||
```
|
||||
|
||||
For automatic persistence, use `ClineCore` instead.
|
||||
|
||||
## Pre-Built Model via Gateway
|
||||
|
||||
For advanced provider configuration:
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
import { createGateway } from "@cline/llms"
|
||||
|
||||
const gateway = createGateway({
|
||||
providerConfigs: [
|
||||
{ providerId: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY },
|
||||
{ providerId: "openai", apiKey: process.env.OPENAI_API_KEY },
|
||||
],
|
||||
})
|
||||
|
||||
const model = gateway.createAgentModel({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-opus-4-7",
|
||||
})
|
||||
|
||||
const agent = new Agent({
|
||||
model,
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `api.md` - Full API reference
|
||||
- `gotchas.md` - Common pitfalls
|
||||
- `../tools/REFERENCE.md` - Creating tools
|
||||
- `../plugins/REFERENCE.md` - Plugin system
|
||||
@@ -0,0 +1,131 @@
|
||||
# ClineCore Runtime
|
||||
|
||||
`ClineCore` is the full-featured runtime from `@cline/core`. It wraps the `Agent` loop with session persistence, built-in tools (bash, editor, file reading, search, web fetch), config discovery, plugin loading, and optional hub-backed multi-process support.
|
||||
|
||||
## When to Use ClineCore
|
||||
|
||||
| Use ClineCore when... | Use Agent instead when... |
|
||||
|---|---|
|
||||
| You need built-in tools (bash, editor, etc.) | You only need custom tools |
|
||||
| You want session persistence to disk | Stateless is fine |
|
||||
| You need config discovery from `.cline/` dirs | You handle config yourself |
|
||||
| You want scheduled/automated agents | You don't need scheduling |
|
||||
| You need multi-client session sharing | Single-process is fine |
|
||||
| You're building a full application | You want minimal dependencies |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
const session = await cline.start({
|
||||
prompt: "Set up CI with GitHub Actions",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
cwd: "/path/to/project",
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(session.result?.text)
|
||||
await cline.dispose()
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Sessions
|
||||
|
||||
Every `cline.start()` call creates a session with a unique ID. Sessions persist their messages and metadata to SQLite. You can list, read, resume, and delete sessions.
|
||||
|
||||
### Built-in Tools
|
||||
|
||||
ClineCore provides these tools automatically when `enableTools: true`:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `bash` | Execute shell commands |
|
||||
| `editor` | Edit files |
|
||||
| `read_files` | Read file contents |
|
||||
| `apply_patch` | Apply unified diffs |
|
||||
| `search` | Search file contents and structure |
|
||||
| `fetch_web` | HTTP requests and web content |
|
||||
|
||||
### Config Discovery
|
||||
|
||||
ClineCore watches `.cline/` directories for:
|
||||
- Rules (system prompt additions)
|
||||
- Skills (domain knowledge)
|
||||
- Workflows (multi-step procedures)
|
||||
- Hooks (lifecycle logic)
|
||||
- Plugins (tool + hook bundles)
|
||||
- MCP servers (external tool providers)
|
||||
|
||||
### Backend Modes
|
||||
|
||||
| Mode | Description |
|
||||
|------|-------------|
|
||||
| `"auto"` (default) | Tries to connect to a local hub; falls back to in-process if unavailable |
|
||||
| `"local"` | In-process execution, local SQLite storage, no hub |
|
||||
| `"hub"` | Requires a compatible local WebSocket hub; fails if unavailable |
|
||||
| `"remote"` | Connects to an explicit remote hub endpoint |
|
||||
|
||||
The default mode is `"auto"`. For simple scripts and CLI tools, `"local"` avoids hub discovery overhead. Hub mode enables multi-client session sharing (e.g., a dashboard watching a running session from another process).
|
||||
|
||||
## Key APIs
|
||||
|
||||
- `ClineCore.create(options)` - Create and initialize
|
||||
- `cline.start(input)` - Start a new session
|
||||
- `cline.send({ sessionId, prompt })` - Send follow-up message
|
||||
- `cline.subscribe(listener)` - Listen to session events
|
||||
- `cline.list()` - List sessions
|
||||
- `cline.get(sessionId)` - Get session metadata
|
||||
- `cline.readMessages(sessionId)` - Read persisted messages
|
||||
- `cline.getAccumulatedUsage(sessionId)` - Token/cost totals
|
||||
- `cline.abort(sessionId)` - Abort a session
|
||||
- `cline.delete(sessionId)` - Delete a session
|
||||
- `cline.dispose()` - Clean up resources
|
||||
|
||||
See `api.md` for full API details.
|
||||
|
||||
## Event Streaming
|
||||
|
||||
`cline.subscribe()` emits `CoreSessionEvent` types. These are different from the `AgentRuntimeEvent` types emitted by the standalone `Agent` class -- see `../events/REFERENCE.md` for the full comparison.
|
||||
|
||||
```typescript
|
||||
cline.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "chunk":
|
||||
if (event.payload.type === "text") {
|
||||
process.stdout.write(event.payload.text)
|
||||
}
|
||||
break
|
||||
case "ended":
|
||||
console.log(`Session ended: ${event.payload.finishReason}`)
|
||||
break
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
ClineCore results use `AgentResult` with `.text` (not `.outputText` like the standalone Agent's `AgentRunResult`).
|
||||
|
||||
## Session Persistence
|
||||
|
||||
Sessions are stored at:
|
||||
```
|
||||
~/.cline/data/sessions/
|
||||
sessions.db # SQLite database
|
||||
[session-id].json # Message history
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- `api.md` - Full ClineCore API reference
|
||||
- `patterns.md` - Common patterns and best practices
|
||||
- `gotchas.md` - Pitfalls and debugging
|
||||
- `../tools/REFERENCE.md` - Custom tool creation
|
||||
- `../plugins/REFERENCE.md` - Plugin system
|
||||
- `../scheduling/REFERENCE.md` - Scheduled agents
|
||||
@@ -0,0 +1,304 @@
|
||||
# ClineCore API Reference
|
||||
|
||||
## Creating ClineCore
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create(options: ClineCoreOptions)
|
||||
```
|
||||
|
||||
### ClineCoreOptions
|
||||
|
||||
```typescript
|
||||
interface ClineCoreOptions {
|
||||
clientName: string // identifies your app
|
||||
distinctId?: string // user/instance identifier
|
||||
backendMode?: "auto" | "local" | "hub" | "remote"
|
||||
hub?: HubOptions
|
||||
remote?: RemoteOptions
|
||||
capabilities?: RuntimeCapabilities
|
||||
toolPolicies?: Record<string, ToolPolicy>
|
||||
automation?: boolean | ClineCoreAutomationOptions
|
||||
fetch?: typeof fetch
|
||||
}
|
||||
```
|
||||
|
||||
### RuntimeCapabilities
|
||||
|
||||
```typescript
|
||||
interface RuntimeCapabilities {
|
||||
requestToolApproval?: (request: ToolApprovalRequest) => Promise<ToolApprovalResult>
|
||||
// ... other capability callbacks
|
||||
}
|
||||
```
|
||||
|
||||
## Starting Sessions
|
||||
|
||||
### start(input)
|
||||
|
||||
```typescript
|
||||
const session = await cline.start(input: ClineCoreStartInput)
|
||||
```
|
||||
|
||||
Returns a `StartSessionResult`:
|
||||
|
||||
```typescript
|
||||
interface StartSessionResult {
|
||||
sessionId: string
|
||||
manifest: SessionManifest
|
||||
manifestPath: string
|
||||
messagesPath: string
|
||||
result?: AgentResult
|
||||
}
|
||||
```
|
||||
|
||||
### ClineCoreStartInput
|
||||
|
||||
```typescript
|
||||
interface ClineCoreStartInput {
|
||||
prompt: string
|
||||
config: CoreSessionConfig
|
||||
source?: string
|
||||
interactive?: boolean
|
||||
sessionMetadata?: Record<string, unknown>
|
||||
initialMessages?: AgentMessage[]
|
||||
toolPolicies?: Record<string, ToolPolicy>
|
||||
capabilities?: RuntimeCapabilities
|
||||
}
|
||||
```
|
||||
|
||||
### CoreSessionConfig
|
||||
|
||||
```typescript
|
||||
interface CoreSessionConfig {
|
||||
cwd?: string // working directory
|
||||
providerId: string // LLM provider
|
||||
modelId: string // model identifier
|
||||
apiKey?: string // provider API key
|
||||
systemPrompt?: string // custom system prompt
|
||||
tools?: readonly AgentTool[] // additional custom tools
|
||||
enableTools?: boolean // enable built-in tools
|
||||
hooks?: Partial<AgentRuntimeHooks> // runtime hooks
|
||||
extensions?: AgentPlugin[] // plugins loaded inline
|
||||
pluginPaths?: string[] // paths to plugin packages
|
||||
extensionLoading?: "isolated" | "direct"
|
||||
extensionContext?: { // context passed to plugin setup()
|
||||
workspace?: { rootPath: string; cwd: string }
|
||||
}
|
||||
checkpointConfig?: CoreCheckpointConfig
|
||||
compactionConfig?: CoreCompactionConfig
|
||||
telemetry?: ITelemetryService
|
||||
logger?: BasicLogger
|
||||
enableSpawnAgent?: boolean // enable sub-agent spawning
|
||||
enableAgentTeams?: boolean // enable team coordination
|
||||
teamName?: string // team identifier
|
||||
}
|
||||
```
|
||||
|
||||
`extensions` passes plugin objects directly. `pluginPaths` points to directories with `package.json` containing a `cline.plugins` field. Set `extensionContext.workspace` so plugins receive `ctx.workspaceInfo` in their `setup()` call -- without it, `ctx.workspaceInfo` is undefined.
|
||||
|
||||
## Follow-Up Messages
|
||||
|
||||
### send({ sessionId, prompt })
|
||||
|
||||
Send a follow-up message to an existing session:
|
||||
|
||||
```typescript
|
||||
const result = await cline.send({
|
||||
sessionId: session.sessionId,
|
||||
prompt: "Now add authentication",
|
||||
})
|
||||
```
|
||||
|
||||
Returns `AgentResult | undefined`.
|
||||
|
||||
## Event Subscription
|
||||
|
||||
### subscribe(listener, options?)
|
||||
|
||||
```typescript
|
||||
const unsubscribe = cline.subscribe(
|
||||
(event: CoreSessionEvent) => {
|
||||
// handle events
|
||||
},
|
||||
{ sessionId: "optional-filter" }
|
||||
)
|
||||
```
|
||||
|
||||
### CoreSessionEvent
|
||||
|
||||
```typescript
|
||||
type CoreSessionEvent =
|
||||
| { type: "chunk"; payload: SessionChunkEvent }
|
||||
| { type: "agent_event"; payload: { sessionId: string, event: AgentEvent } }
|
||||
| { type: "ended"; payload: SessionEndedEvent }
|
||||
| { type: "team_progress"; payload: SessionTeamProgressEvent }
|
||||
| { type: "status"; payload: { sessionId: string, status: string } }
|
||||
| { type: "hook"; payload: SessionToolEvent }
|
||||
```
|
||||
|
||||
## Session Management
|
||||
|
||||
### list(limit?, options?)
|
||||
|
||||
```typescript
|
||||
const sessions: SessionRecord[] = await cline.list(50)
|
||||
```
|
||||
|
||||
### get(sessionId)
|
||||
|
||||
```typescript
|
||||
const session: SessionRecord = await cline.get(sessionId)
|
||||
```
|
||||
|
||||
### readMessages(sessionId)
|
||||
|
||||
```typescript
|
||||
const messages: AgentMessage[] = await cline.readMessages(sessionId)
|
||||
```
|
||||
|
||||
### getAccumulatedUsage(sessionId)
|
||||
|
||||
```typescript
|
||||
const usage = await cline.getAccumulatedUsage(sessionId)
|
||||
// usage.usage - root agent only
|
||||
// usage.aggregateUsage - root + subagents/teammates
|
||||
```
|
||||
|
||||
### update(sessionId, updates)
|
||||
|
||||
```typescript
|
||||
await cline.update(sessionId, { title: "New title" })
|
||||
```
|
||||
|
||||
### abort(sessionId, reason?)
|
||||
|
||||
```typescript
|
||||
await cline.abort(sessionId, "User cancelled")
|
||||
```
|
||||
|
||||
### stop(sessionId)
|
||||
|
||||
```typescript
|
||||
await cline.stop(sessionId)
|
||||
```
|
||||
|
||||
### delete(sessionId)
|
||||
|
||||
```typescript
|
||||
await cline.delete(sessionId)
|
||||
```
|
||||
|
||||
### restore(input)
|
||||
|
||||
Restore a session from a checkpoint:
|
||||
|
||||
```typescript
|
||||
await cline.restore({ sessionId, checkpointId })
|
||||
```
|
||||
|
||||
### dispose(reason?)
|
||||
|
||||
Clean up all resources. Always call this when done:
|
||||
|
||||
```typescript
|
||||
await cline.dispose("Shutting down")
|
||||
```
|
||||
|
||||
## AgentResult
|
||||
|
||||
Returned by session operations:
|
||||
|
||||
```typescript
|
||||
interface AgentResult {
|
||||
text: string
|
||||
usage: LegacyAgentUsage
|
||||
messages: MessageWithMetadata[]
|
||||
toolCalls: ToolCallRecord[]
|
||||
iterations: number
|
||||
finishReason: "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"
|
||||
model: { id: string; provider: string; info?: ModelInfo }
|
||||
startedAt: Date
|
||||
endedAt: Date
|
||||
durationMs: number
|
||||
}
|
||||
```
|
||||
|
||||
## Tool Policies
|
||||
|
||||
Control tool access at the session level:
|
||||
|
||||
```typescript
|
||||
const session = await cline.start({
|
||||
prompt: "Review the code",
|
||||
config: { ... },
|
||||
toolPolicies: {
|
||||
read_files: { autoApprove: true },
|
||||
bash: { autoApprove: false },
|
||||
editor: { enabled: false },
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### ToolPolicy
|
||||
|
||||
```typescript
|
||||
interface ToolPolicy {
|
||||
enabled?: boolean // false = tool is hidden from the model
|
||||
autoApprove?: boolean // false = requires approval callback
|
||||
}
|
||||
```
|
||||
|
||||
## Interactive Approval
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
capabilities: {
|
||||
requestToolApproval: async (request) => {
|
||||
console.log(`Tool: ${request.toolName}, Input: ${JSON.stringify(request.input)}`)
|
||||
const approved = await askUser(`Allow ${request.toolName}?`)
|
||||
return { approved }
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Automation API
|
||||
|
||||
When `automation` is enabled in `ClineCore.create()`:
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
automation: true,
|
||||
})
|
||||
|
||||
// Access automation methods
|
||||
cline.automation.start()
|
||||
cline.automation.stop()
|
||||
cline.automation.reconcile(specs)
|
||||
cline.automation.ingestEvent(event)
|
||||
cline.automation.listEvents()
|
||||
cline.automation.listSpecs()
|
||||
cline.automation.listRuns()
|
||||
```
|
||||
|
||||
## Settings API
|
||||
|
||||
```typescript
|
||||
// Read settings
|
||||
const settings = await cline.settings.list()
|
||||
|
||||
// Toggle tools, plugins, MCP servers
|
||||
await cline.settings.toggle({ type: "tool", name: "bash", enabled: true })
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `REFERENCE.md` - Overview and quick start
|
||||
- `patterns.md` - Common patterns
|
||||
- `gotchas.md` - Pitfalls
|
||||
- `../tools/REFERENCE.md` - Tool creation
|
||||
- `../plugins/REFERENCE.md` - Plugin system
|
||||
@@ -0,0 +1,148 @@
|
||||
# ClineCore Gotchas
|
||||
|
||||
## Always Call dispose()
|
||||
|
||||
`ClineCore` holds resources (file watchers, database connections, hub connections). Failing to call `dispose()` can leave orphan processes and file locks.
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
try {
|
||||
// ... use cline
|
||||
} finally {
|
||||
await cline.dispose()
|
||||
}
|
||||
```
|
||||
|
||||
## Node.js 22 Required
|
||||
|
||||
ClineCore and `@cline/core` require Node.js 22 or later. If you're on an older version, you'll get runtime errors. Check with `node --version`.
|
||||
|
||||
## Session Config vs Global Config
|
||||
|
||||
Tool policies can be set at two levels:
|
||||
- Global: in `ClineCore.create({ toolPolicies })` -- applies to all sessions
|
||||
- Per-session: in `cline.start({ toolPolicies })` -- overrides global for that session
|
||||
|
||||
Per-session policies take precedence.
|
||||
|
||||
## enableTools Must Be Explicit
|
||||
|
||||
Built-in tools (bash, editor, read_files, etc.) are not available unless you set `enableTools: true` in the session config:
|
||||
|
||||
```typescript
|
||||
await cline.start({
|
||||
prompt: "Read package.json",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
enableTools: true, // required for built-in tools
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Without this, the agent only has access to custom tools you provide via `config.tools`.
|
||||
|
||||
## cwd Matters for Built-in Tools
|
||||
|
||||
Built-in tools like `bash`, `editor`, and `read_files` operate relative to `config.cwd`. If not set, they use the process working directory. Always set it explicitly for predictable behavior:
|
||||
|
||||
```typescript
|
||||
config: {
|
||||
cwd: "/absolute/path/to/project",
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Hub Startup Latency
|
||||
|
||||
With `backendMode: "auto"`, the first session may be slow if a hub daemon needs to be spawned. For immediate responsiveness:
|
||||
- Use `backendMode: "local"` for in-process execution (fastest startup)
|
||||
- Pre-warm the hub with `cline hub ensure` CLI command
|
||||
- Accept the one-time startup cost and let subsequent sessions reuse the hub
|
||||
|
||||
## Session Storage Location
|
||||
|
||||
Sessions are stored at `~/.cline/data/sessions/`. This includes:
|
||||
- `sessions.db` - SQLite database with session metadata
|
||||
- `[session-id].json` - Individual message history files
|
||||
|
||||
If you're running in a container or ephemeral environment, these paths may not persist across restarts.
|
||||
|
||||
## requestToolApproval Blocks Execution
|
||||
|
||||
When a tool policy has `autoApprove: false` and you provide a `requestToolApproval` callback, the agent loop blocks until your callback resolves. If your callback never resolves (e.g., waiting for user input that never comes), the session hangs.
|
||||
|
||||
For automated pipelines, either:
|
||||
- Set all tools to `autoApprove: true`
|
||||
- Implement a timeout in your approval callback
|
||||
|
||||
## Plugin Discovery Paths
|
||||
|
||||
ClineCore discovers plugins from:
|
||||
- Global: `~/.cline/plugins/`
|
||||
- Workspace: `.cline/plugins/`
|
||||
|
||||
For SDK consumers, pass plugins via `extensions: [plugin]` or `pluginPaths: ["./path"]` in the session config.
|
||||
|
||||
If a plugin isn't loading, verify:
|
||||
- The file is in one of the discovery directories, or passed via `extensions`/`pluginPaths`
|
||||
- The file exports a default plugin object with a non-empty `manifest.capabilities` array
|
||||
- Every `api.register*` call in `setup()` has a matching capability declared
|
||||
- If `hooks` is present on the plugin, `"hooks"` is in `capabilities`
|
||||
|
||||
## extensionContext.workspace Is Required for Plugins
|
||||
|
||||
If your plugins use `ctx.workspaceInfo` (e.g., to resolve workspace paths), you must set `extensionContext.workspace` in the session config. Without it, `ctx.workspaceInfo` is undefined:
|
||||
|
||||
```typescript
|
||||
await cline.start({
|
||||
config: {
|
||||
extensions: [myPlugin],
|
||||
extensionContext: {
|
||||
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
The CLI sets this automatically, but SDK consumers must set it explicitly.
|
||||
|
||||
## send() Requires an Active Session
|
||||
|
||||
`cline.send()` only works on sessions that are still active. If a session has already completed, `send()` may return `undefined` or fail. Check session status with `cline.get(sessionId)` first.
|
||||
|
||||
## Result May Be Undefined
|
||||
|
||||
`session.result` can be `undefined` if the session was started but hasn't completed yet (e.g., in a non-blocking hub mode). Check for this:
|
||||
|
||||
```typescript
|
||||
const session = await cline.start({ ... })
|
||||
if (session.result) {
|
||||
console.log(session.result.text)
|
||||
} else {
|
||||
console.log("Session started but not yet complete")
|
||||
}
|
||||
```
|
||||
|
||||
## Compaction and Long Sessions
|
||||
|
||||
For long-running sessions, message history grows and eventually exceeds the model's context window. ClineCore handles this via compaction, which summarizes older messages. Configure it via `compactionConfig`:
|
||||
|
||||
```typescript
|
||||
config: {
|
||||
compactionConfig: {
|
||||
strategy: "summarize",
|
||||
// ...
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The default strategy works for most cases, but extremely long sessions may benefit from tuning.
|
||||
|
||||
## See Also
|
||||
|
||||
- `api.md` - Full API reference
|
||||
- `patterns.md` - Common patterns
|
||||
- `../agent/gotchas.md` - Agent-level gotchas
|
||||
- `../tools/REFERENCE.md` - Tool troubleshooting
|
||||
- `../providers/REFERENCE.md` - Provider troubleshooting
|
||||
@@ -0,0 +1,279 @@
|
||||
# ClineCore Patterns
|
||||
|
||||
## Basic Session with Built-in Tools
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
const session = await cline.start({
|
||||
prompt: "Read package.json and summarize the dependencies",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
cwd: process.cwd(),
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(session.result?.text)
|
||||
await cline.dispose()
|
||||
```
|
||||
|
||||
## Streaming Session with UI Updates
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
cline.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "chunk":
|
||||
if (event.payload.type === "text") {
|
||||
ui.appendText(event.payload.text)
|
||||
}
|
||||
break
|
||||
case "ended":
|
||||
ui.showComplete(event.payload.finishReason)
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
await cline.start({
|
||||
prompt: "Refactor the auth module",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
cwd: "/path/to/project",
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Multi-Turn Session
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
const session = await cline.start({
|
||||
prompt: "Create a new Express server",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
cwd: "/path/to/project",
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Follow-up
|
||||
const result = await cline.send({
|
||||
sessionId: session.sessionId,
|
||||
prompt: "Now add a health check endpoint",
|
||||
})
|
||||
|
||||
console.log(result?.text)
|
||||
await cline.dispose()
|
||||
```
|
||||
|
||||
## Tiered Permission Model
|
||||
|
||||
Auto-approve reads, require approval for writes:
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
toolPolicies: {
|
||||
read_files: { autoApprove: true },
|
||||
search: { autoApprove: true },
|
||||
fetch_web: { autoApprove: true },
|
||||
bash: { autoApprove: false },
|
||||
editor: { autoApprove: false },
|
||||
apply_patch: { autoApprove: false },
|
||||
},
|
||||
capabilities: {
|
||||
requestToolApproval: async (request) => {
|
||||
const approved = await promptUser(
|
||||
`Allow ${request.toolName}?\n${JSON.stringify(request.input, null, 2)}`
|
||||
)
|
||||
return { approved }
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Custom Tools Alongside Built-ins
|
||||
|
||||
```typescript
|
||||
import { ClineCore, createTool } from "@cline/sdk"
|
||||
import { z } from "zod"
|
||||
|
||||
const deployTool = createTool({
|
||||
name: "deploy",
|
||||
description: "Deploy the application to the specified environment.",
|
||||
inputSchema: z.object({
|
||||
environment: z.enum(["staging", "production"]),
|
||||
}),
|
||||
execute: async (input) => {
|
||||
const result = await runDeployment(input.environment)
|
||||
return { url: result.url, status: "deployed" }
|
||||
},
|
||||
})
|
||||
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
await cline.start({
|
||||
prompt: "Deploy the app to staging",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
cwd: process.cwd(),
|
||||
enableTools: true,
|
||||
tools: [deployTool],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Session with Plugins
|
||||
|
||||
Load plugins inline with `extensions` and provide workspace context so plugins can access `ctx.workspaceInfo`:
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
import myPlugin from "./my-plugin"
|
||||
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
backendMode: "local",
|
||||
})
|
||||
|
||||
await cline.start({
|
||||
prompt: "Do the thing my plugin enables",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
cwd: process.cwd(),
|
||||
enableTools: true,
|
||||
extensions: [myPlugin],
|
||||
extensionContext: {
|
||||
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await cline.dispose()
|
||||
```
|
||||
|
||||
For directory-based plugin packages, use `pluginPaths` instead:
|
||||
|
||||
```typescript
|
||||
config: {
|
||||
pluginPaths: ["./my-cline-plugin"],
|
||||
extensionContext: {
|
||||
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
See `../plugins/REFERENCE.md` for the full plugin authoring guide.
|
||||
|
||||
## Session Listing and Replay
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
// List recent sessions
|
||||
const sessions = await cline.list(10)
|
||||
for (const session of sessions) {
|
||||
console.log(`${session.id}: ${session.title}`)
|
||||
}
|
||||
|
||||
// Read messages from a past session
|
||||
const messages = await cline.readMessages(sessions[0].id)
|
||||
for (const msg of messages) {
|
||||
console.log(`[${msg.role}] ${msg.content}`)
|
||||
}
|
||||
|
||||
// Check usage
|
||||
const usage = await cline.getAccumulatedUsage(sessions[0].id)
|
||||
console.log(`Total tokens: ${usage.aggregateUsage.totalInputTokens + usage.aggregateUsage.totalOutputTokens}`)
|
||||
```
|
||||
|
||||
## Graceful Shutdown
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
process.on("SIGTERM", async () => {
|
||||
await cline.dispose("SIGTERM received")
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
// Run sessions...
|
||||
```
|
||||
|
||||
## Stateless Worker Pattern
|
||||
|
||||
For request/response workloads (API endpoints, queue consumers):
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "worker",
|
||||
backendMode: "local",
|
||||
})
|
||||
|
||||
async function handleRequest(prompt: string, workspace: string) {
|
||||
const session = await cline.start({
|
||||
prompt,
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
cwd: workspace,
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
text: session.result?.text,
|
||||
usage: session.result?.usage,
|
||||
sessionId: session.sessionId,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Hub-Backed Multi-Client
|
||||
|
||||
Multiple clients can attach to the same session:
|
||||
|
||||
```typescript
|
||||
// Process 1: start session
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "backend",
|
||||
backendMode: "hub",
|
||||
})
|
||||
|
||||
const session = await cline.start({
|
||||
prompt: "Long running refactor task",
|
||||
config: { ... },
|
||||
})
|
||||
|
||||
// Process 2: attach and stream events
|
||||
const viewer = await ClineCore.create({
|
||||
clientName: "dashboard",
|
||||
backendMode: "hub",
|
||||
})
|
||||
|
||||
viewer.subscribe((event) => {
|
||||
dashboard.render(event)
|
||||
}, { sessionId: session.sessionId })
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `api.md` - Full API reference
|
||||
- `gotchas.md` - Common pitfalls
|
||||
- `../tools/REFERENCE.md` - Tool creation
|
||||
- `../plugins/REFERENCE.md` - Plugin system
|
||||
- `../scheduling/REFERENCE.md` - Scheduled agents
|
||||
@@ -0,0 +1,269 @@
|
||||
# Events
|
||||
|
||||
The Cline SDK has three event layers. Which one you use depends on whether you're working with the standalone `Agent` class or `ClineCore`.
|
||||
|
||||
## Which Events Do I Get?
|
||||
|
||||
| If you use... | You subscribe with... | You receive... | Text streaming event |
|
||||
|---|---|---|---|
|
||||
| Standalone `Agent` | `agent.subscribe()` | `AgentRuntimeEvent` | `assistant-text-delta` |
|
||||
| `ClineCore` | `cline.subscribe()` | `CoreSessionEvent` | `chunk` (with `payload.type === "text"`) |
|
||||
|
||||
These are different event types with different shapes. Do not mix them up.
|
||||
|
||||
## Layer 1: AgentRuntimeEvent (Standalone Agent)
|
||||
|
||||
Emitted by the `Agent` class via `agent.subscribe()`. This is what you get when using `new Agent(...)` directly. Every event includes a `snapshot` field with the current `AgentRuntimeStateSnapshot`.
|
||||
|
||||
### Run Lifecycle
|
||||
|
||||
```typescript
|
||||
{ type: "run-started", snapshot }
|
||||
{ type: "run-finished", snapshot, result: AgentRunResult }
|
||||
{ type: "run-failed", snapshot, error: Error }
|
||||
```
|
||||
|
||||
### Turns
|
||||
|
||||
```typescript
|
||||
{ type: "turn-started", snapshot, iteration: number }
|
||||
{ type: "turn-finished", snapshot, iteration: number, toolCallCount: number }
|
||||
```
|
||||
|
||||
### Text Streaming
|
||||
|
||||
```typescript
|
||||
// Streaming text delta (arrives as chunks during generation)
|
||||
{ type: "assistant-text-delta", snapshot, iteration: number, text: string, accumulatedText: string }
|
||||
|
||||
// Streaming reasoning delta (when model uses extended thinking)
|
||||
{ type: "assistant-reasoning-delta", snapshot, iteration: number, text: string }
|
||||
|
||||
// Complete assistant message after model finishes
|
||||
{ type: "assistant-message", snapshot, iteration: number, message: AgentMessage, finishReason: string }
|
||||
```
|
||||
|
||||
### Messages
|
||||
|
||||
```typescript
|
||||
// Fired when any message (user or assistant) is added to conversation history
|
||||
{ type: "message-added", snapshot, message: AgentMessage }
|
||||
```
|
||||
|
||||
### Tool Events
|
||||
|
||||
```typescript
|
||||
{ type: "tool-started", snapshot, toolCall: { toolName: string, toolCallId: string, input: unknown } }
|
||||
{ type: "tool-updated", snapshot, toolCall: { toolName: string, toolCallId: string }, update: string }
|
||||
{ type: "tool-finished", snapshot, toolCall: { toolName: string, toolCallId: string }, message: AgentMessage }
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: "usage-updated",
|
||||
snapshot,
|
||||
usage: {
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
cacheReadTokens?: number,
|
||||
cacheWriteTokens?: number,
|
||||
totalCost?: number,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Notices
|
||||
|
||||
```typescript
|
||||
{ type: "status-notice", snapshot, message: string, metadata?: Record<string, unknown> }
|
||||
```
|
||||
|
||||
### Subscribing
|
||||
|
||||
Use `agent.subscribe()`. Register the listener before calling `run()` to avoid missing early events.
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
|
||||
agent.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "assistant-text-delta":
|
||||
process.stdout.write(event.text)
|
||||
break
|
||||
case "tool-started":
|
||||
console.log(`\nUsing tool: ${event.toolCall.toolName}`)
|
||||
break
|
||||
case "usage-updated":
|
||||
console.log(`Cost: $${event.usage.totalCost?.toFixed(4)}`)
|
||||
break
|
||||
case "run-finished":
|
||||
console.log(`\nDone: ${event.result.status}`)
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
const result = await agent.run("Hello!")
|
||||
```
|
||||
|
||||
You can also receive events through hooks (these are awaited, so they can be async):
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
...config,
|
||||
hooks: {
|
||||
onEvent: async (event) => {
|
||||
// Same AgentRuntimeEvent types as subscribe()
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Layer 2: AgentEvent (ClineCore Internal)
|
||||
|
||||
When using `ClineCore`, a `RuntimeEventAdapter` translates Layer 1 events into a legacy format called `AgentEvent`. You do not interact with this layer directly -- it is projected into `CoreSessionEvent` for subscribers. The key mappings:
|
||||
|
||||
| AgentRuntimeEvent (Layer 1) | AgentEvent (Layer 2) |
|
||||
|---|---|
|
||||
| `turn-started` | `iteration_start` |
|
||||
| `turn-finished` | `iteration_end` |
|
||||
| `assistant-text-delta` | `content_start` (text) |
|
||||
| `assistant-message` | `content_end` (text) |
|
||||
| `tool-started` | `content_start` (tool) |
|
||||
| `tool-updated` | `content_update` (tool) |
|
||||
| `tool-finished` | `content_end` (tool) |
|
||||
| `usage-updated` | `usage` (with computed deltas) |
|
||||
| `run-finished` | `done` |
|
||||
| `run-failed` | `error` |
|
||||
| `run-started`, `message-added` | (suppressed, not emitted) |
|
||||
|
||||
This layer exists for backwards compatibility. If you see event types like `content_update` or `iteration_start` in other documentation, they refer to this layer, not to what `agent.subscribe()` emits.
|
||||
|
||||
## Layer 3: CoreSessionEvent (ClineCore Subscriber)
|
||||
|
||||
Emitted by `ClineCore` via `cline.subscribe()`. These are higher-level session events.
|
||||
|
||||
```typescript
|
||||
type CoreSessionEvent =
|
||||
| { type: "chunk"; payload: SessionChunkEvent }
|
||||
| { type: "agent_event"; payload: { sessionId: string, event: AgentEvent } }
|
||||
| { type: "ended"; payload: SessionEndedEvent }
|
||||
| { type: "team_progress"; payload: SessionTeamProgressEvent }
|
||||
| { type: "status"; payload: { sessionId: string, status: string } }
|
||||
| { type: "hook"; payload: SessionToolEvent }
|
||||
```
|
||||
|
||||
### SessionChunkEvent
|
||||
|
||||
```typescript
|
||||
interface SessionChunkEvent {
|
||||
type: "text" | "reasoning"
|
||||
text: string
|
||||
sessionId: string
|
||||
}
|
||||
```
|
||||
|
||||
### SessionEndedEvent
|
||||
|
||||
```typescript
|
||||
interface SessionEndedEvent {
|
||||
sessionId: string
|
||||
finishReason: "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"
|
||||
result?: AgentResult
|
||||
}
|
||||
```
|
||||
|
||||
### Subscribing
|
||||
|
||||
```typescript
|
||||
cline.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "chunk":
|
||||
if (event.payload.type === "text") {
|
||||
process.stdout.write(event.payload.text)
|
||||
}
|
||||
break
|
||||
case "ended":
|
||||
console.log(`Finished: ${event.payload.finishReason}`)
|
||||
break
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Filter by session:
|
||||
|
||||
```typescript
|
||||
cline.subscribe(handler, { sessionId: "specific-session-id" })
|
||||
```
|
||||
|
||||
## Hub Events (Layer 3b)
|
||||
|
||||
When ClineCore runs in hub mode (via `backendMode: "hub"` or `"auto"` when a hub is available), events are projected over WebSocket using `HubEventName` types like `assistant.delta`, `iteration.started`, `tool.started`, etc. You do not interact with these directly -- `cline.subscribe()` still gives you `CoreSessionEvent` regardless of backend mode.
|
||||
|
||||
## Result Type Differences
|
||||
|
||||
The standalone Agent and ClineCore return different result types:
|
||||
|
||||
| API | Result type | Text property |
|
||||
|---|---|---|
|
||||
| `agent.run()` | `AgentRunResult` | `result.outputText` |
|
||||
| `cline.start()` / `cline.send()` | `AgentResult` | `result.text` |
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Streaming Text (Standalone Agent)
|
||||
|
||||
```typescript
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "assistant-text-delta") {
|
||||
process.stdout.write(event.text)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Streaming Text (ClineCore)
|
||||
|
||||
```typescript
|
||||
cline.subscribe((event) => {
|
||||
if (event.type === "chunk" && event.payload.type === "text") {
|
||||
process.stdout.write(event.payload.text)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Usage Tracking (Standalone Agent)
|
||||
|
||||
```typescript
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "usage-updated" && event.usage.totalCost) {
|
||||
console.log(`Running cost: $${event.usage.totalCost.toFixed(4)}`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Tool Call Logging (Standalone Agent)
|
||||
|
||||
```typescript
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "tool-started") {
|
||||
console.log(`Tool started: ${event.toolCall.toolName}`)
|
||||
}
|
||||
if (event.type === "tool-finished") {
|
||||
console.log(`Tool finished: ${event.toolCall.toolName}`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `../agent/REFERENCE.md` - Agent runtime overview
|
||||
- `../clinecore/REFERENCE.md` - ClineCore session management
|
||||
- `../plugins/REFERENCE.md` - Plugin hooks for lifecycle events
|
||||
- `../production/REFERENCE.md` - Observability in production
|
||||
@@ -0,0 +1,157 @@
|
||||
# Multi-Agent Coordination
|
||||
|
||||
The Cline SDK supports two models for multi-agent work: sub-agents (parent-child) and teams (peer-to-peer).
|
||||
|
||||
## Sub-Agents vs Teams
|
||||
|
||||
| Feature | Sub-Agents | Teams |
|
||||
|---------|-----------|-------|
|
||||
| Enable with | `enableSpawnAgent: true` | `enableAgentTeams: true` |
|
||||
| Persistence | Session-scoped only | Across sessions |
|
||||
| Coordination | Parent-child hierarchy | Peer-to-peer |
|
||||
| Shared state | None | Task board, mailbox, mission log |
|
||||
| Best for | One-off delegation | Complex multi-session projects |
|
||||
|
||||
## Sub-Agents
|
||||
|
||||
Sub-agents are spawned by a parent agent during a run. They execute independently and report results back.
|
||||
|
||||
### Enabling Sub-Agents
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
await cline.start({
|
||||
prompt: "Refactor the auth module and update tests",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
enableSpawnAgent: true,
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
When `enableSpawnAgent` is true, the agent gets access to sub-agent tools:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `start_subagent` | Spawn a background agent with a task |
|
||||
| `message_subagent` | Send a message to a running sub-agent |
|
||||
| `handoff_to_agent` | Delegate the current task entirely |
|
||||
| `submit_and_exit` | Signal completion |
|
||||
|
||||
### How Sub-Agents Work
|
||||
|
||||
1. The parent agent decides a subtask can be delegated
|
||||
2. It calls `start_subagent` with a role, task description, and optionally a preset
|
||||
3. The sub-agent runs independently in the background
|
||||
4. The parent can check status or send follow-up messages
|
||||
5. Sub-agent results are available to the parent when complete
|
||||
|
||||
## Teams
|
||||
|
||||
Teams provide persistent, cross-session coordination between agents.
|
||||
|
||||
### Enabling Teams
|
||||
|
||||
```typescript
|
||||
await cline.start({
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
enableAgentTeams: true,
|
||||
teamName: "auth-sprint",
|
||||
enableTools: true,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Team Tools
|
||||
|
||||
When `enableAgentTeams` is true, the coordinator agent gets:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `team_spawn_teammate` | Create a new agent with a role and task |
|
||||
| `team_delegate_task` | Assign a task to an existing teammate |
|
||||
| `team_check_status` | Check on a delegated task's progress |
|
||||
| `team_get_result` | Get the completed result from a teammate |
|
||||
|
||||
### Team Persistence
|
||||
|
||||
Teams store shared state in:
|
||||
|
||||
```
|
||||
~/.cline/data/teams/[team-name]/
|
||||
task-board.json # task assignments and status
|
||||
mailbox.json # inter-agent messages
|
||||
mission-log.json # coordination log
|
||||
```
|
||||
|
||||
This state persists across sessions, so team members can pick up where they left off.
|
||||
|
||||
### CLI Team Access
|
||||
|
||||
```bash
|
||||
cline --team-name auth-sprint "Continue the auth refactor"
|
||||
```
|
||||
|
||||
## Choosing Between Sub-Agents and Teams
|
||||
|
||||
Use sub-agents when:
|
||||
- You need one-off parallel execution within a single session
|
||||
- Tasks are independent and don't need to communicate with each other
|
||||
- Results only matter to the parent agent
|
||||
|
||||
Use teams when:
|
||||
- Work spans multiple sessions over time
|
||||
- Agents need to coordinate and share progress
|
||||
- Tasks have dependencies between them
|
||||
- You want a persistent record of multi-agent collaboration
|
||||
|
||||
## Patterns
|
||||
|
||||
### Parallel Research with Sub-Agents
|
||||
|
||||
A parent agent spawns multiple sub-agents to research different topics simultaneously:
|
||||
|
||||
```typescript
|
||||
await cline.start({
|
||||
prompt: `Research these three topics in parallel:
|
||||
1. Current best practices for JWT auth
|
||||
2. OAuth 2.0 provider comparison
|
||||
3. Session management patterns
|
||||
Spawn a sub-agent for each topic, then synthesize the results.`,
|
||||
config: {
|
||||
enableSpawnAgent: true,
|
||||
enableTools: true,
|
||||
// ...
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Team Sprint
|
||||
|
||||
A coordinator manages a multi-session project:
|
||||
|
||||
```typescript
|
||||
await cline.start({
|
||||
prompt: `You are the coordinator for the auth-sprint team.
|
||||
Review the task board and delegate the next highest-priority task
|
||||
to a teammate. Check status on any in-progress tasks.`,
|
||||
config: {
|
||||
enableAgentTeams: true,
|
||||
teamName: "auth-sprint",
|
||||
enableTools: true,
|
||||
// ...
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `../clinecore/REFERENCE.md` - ClineCore runtime
|
||||
- `../clinecore/api.md` - Session config for teams
|
||||
- `../tools/REFERENCE.md` - Tool system
|
||||
- `../plugins/REFERENCE.md` - Plugin system
|
||||
@@ -0,0 +1,649 @@
|
||||
# Plugins
|
||||
|
||||
A Cline plugin is a TypeScript module that extends any agent built on the Cline SDK. The same plugin runs in the Cline CLI, VS Code and JetBrains extensions, and any custom app built on `@cline/core`.
|
||||
|
||||
A plugin can:
|
||||
|
||||
- Register tools the model can call.
|
||||
- Hook into the agent loop before/after runs, model calls, and tool calls.
|
||||
- Rewrite provider messages before they hit the model (custom compaction, redaction, context shaping).
|
||||
- Register slash commands, prompt rules, providers, and automation event types.
|
||||
|
||||
A plugin ships in one of two shapes:
|
||||
|
||||
1. Single-file plugin -- one `.ts` file that exports a default plugin object. Drop it in a discovery folder and it loads.
|
||||
2. Plugin package -- a directory with `package.json`, npm dependencies, and optionally bundled assets. Installable via `cline plugin install`.
|
||||
|
||||
Both shapes use the same plugin API.
|
||||
|
||||
## The Mental Model
|
||||
|
||||
When the host starts a session, it builds a registry of plugins and runs four phases:
|
||||
|
||||
1. resolve -- collect the plugin objects.
|
||||
2. validate -- check each plugin's `manifest`. Capabilities must be non-empty; declared hook stages must have matching handlers; if `hooks` is present, `"hooks"` must be in `capabilities`.
|
||||
3. setup -- call each plugin's `setup(api, ctx)` once. This is where you `registerTool`, `registerCommand`, etc.
|
||||
4. activate -- registry is frozen, the agent loop starts, and your hooks/tools are live.
|
||||
|
||||
Two invariants the registry enforces:
|
||||
|
||||
- Every contribution requires a matching capability. Calling `api.registerRule(...)` without `"rules"` in `manifest.capabilities` throws.
|
||||
- Capabilities and handlers must agree. Declaring `"hooks"` without a `hooks` object, or vice versa, fails validation.
|
||||
|
||||
After validation, registration is one-shot -- no dynamic register/unregister during the session.
|
||||
|
||||
## The Smallest Working Plugin
|
||||
|
||||
```typescript
|
||||
import type { AgentPlugin } from "@cline/core"
|
||||
import { createTool } from "@cline/core"
|
||||
|
||||
const plugin: AgentPlugin = {
|
||||
name: "hello-plugin",
|
||||
manifest: {
|
||||
capabilities: ["tools"],
|
||||
},
|
||||
setup(api, ctx) {
|
||||
api.registerTool(
|
||||
createTool({
|
||||
name: "say_hello",
|
||||
description: "Greet a person by name.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
},
|
||||
async execute({ name }: { name: string }) {
|
||||
return { greeting: `Hello, ${name}!` }
|
||||
},
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
export default plugin
|
||||
```
|
||||
|
||||
The agent will see `say_hello` as a callable tool.
|
||||
|
||||
## The Manifest
|
||||
|
||||
```typescript
|
||||
manifest: {
|
||||
capabilities: ["tools", "hooks"], // required, non-empty array
|
||||
paths?: string[], // optional, multi-entry packages
|
||||
providerIds?: string[], // optional, provider plugins
|
||||
modelIds?: string[], // optional, model plugins
|
||||
}
|
||||
```
|
||||
|
||||
### The Complete Capability List
|
||||
|
||||
| Capability | What It Unlocks in `api` |
|
||||
|-----------|--------------------------|
|
||||
| `"tools"` | `api.registerTool()` |
|
||||
| `"commands"` | `api.registerCommand()` (slash commands in chat surfaces) |
|
||||
| `"rules"` | `api.registerRule()` (string injected into the system prompt) |
|
||||
| `"messageBuilders"` | `api.registerMessageBuilder()` (rewrites provider-bound messages) |
|
||||
| `"providers"` | `api.registerProvider()` (custom model provider) |
|
||||
| `"automationEvents"` | `api.registerAutomationEventType()` and `ctx.automation?.ingestEvent()` |
|
||||
| `"hooks"` | The runtime `hooks` object on the plugin (lifecycle callbacks) |
|
||||
|
||||
You declare any combination -- most real plugins need 1-3 capabilities.
|
||||
|
||||
## setup(api, ctx) -- The Registration Phase
|
||||
|
||||
`setup()` runs once per session before the agent loop starts. Everything you register here is frozen for the lifetime of the session.
|
||||
|
||||
### The api Object
|
||||
|
||||
Each `register*` method requires the matching capability in your manifest:
|
||||
|
||||
```typescript
|
||||
api.registerTool(tool) // requires "tools"
|
||||
api.registerCommand({ name, description, handler }) // requires "commands"
|
||||
api.registerRule({ id, content, source }) // requires "rules"
|
||||
api.registerMessageBuilder({ name, build }) // requires "messageBuilders"
|
||||
api.registerProvider({ name, description }) // requires "providers"
|
||||
api.registerAutomationEventType({ eventType, source }) // requires "automationEvents"
|
||||
```
|
||||
|
||||
### The ctx Object -- Host-Provided Session Context
|
||||
|
||||
The second argument carries everything the host knows about the current session. All fields are optional, so feature-detect before using them -- the same plugin must work in hosts that supply less context (unit tests, sandboxed plugin processes).
|
||||
|
||||
```typescript
|
||||
ctx.session?.sessionId // string, stable core session id
|
||||
ctx.client?.name // host: "cline-cli", "cline-vscode", etc.
|
||||
ctx.user // authenticated user/org info, when available
|
||||
ctx.workspaceInfo // { rootPath, hint, latestGitBranchName,
|
||||
// latestGitCommitHash, associatedRemoteUrls }
|
||||
ctx.automation?.ingestEvent // emit normalized automation events
|
||||
ctx.logger?.log // structured logger scoped to this plugin
|
||||
ctx.telemetry // ITelemetryService, only present in-process
|
||||
```
|
||||
|
||||
Two rules about `ctx.workspaceInfo`:
|
||||
|
||||
1. Always prefer `ctx.workspaceInfo?.rootPath` over `process.cwd()`. The CLI may have been launched with `--cwd` without calling `chdir`, and VS Code workspaces don't share a single CWD. `workspaceInfo` is sourced from the session config and is always correct.
|
||||
2. Don't use `import.meta.url` tricks to find "the workspace". That gives you the plugin's own location, not the user's project.
|
||||
|
||||
### Persisting State Across Hooks
|
||||
|
||||
`setup()` runs first; hooks fire later. The simplest way to share state is module-level variables:
|
||||
|
||||
```typescript
|
||||
let sessionWorkspaceRoot: string | undefined
|
||||
let sessionBranch: string | undefined
|
||||
|
||||
const plugin: AgentPlugin = {
|
||||
name: "metrics",
|
||||
manifest: { capabilities: ["hooks"] },
|
||||
setup(api, ctx) {
|
||||
sessionWorkspaceRoot = ctx.workspaceInfo?.rootPath
|
||||
sessionBranch = ctx.workspaceInfo?.latestGitBranchName
|
||||
},
|
||||
hooks: {
|
||||
beforeTool({ toolCall, input }) {
|
||||
if (sessionBranch === "main" && toolCall.toolName === "run_commands") {
|
||||
// inspect input, optionally block
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
A single Node process may host multiple sessions concurrently. If your plugin will run in a multi-session host, key your state by `ctx.session?.sessionId`:
|
||||
|
||||
```typescript
|
||||
const stateBySession = new Map<string, MyState>()
|
||||
setup(api, ctx) {
|
||||
const id = ctx.session?.sessionId
|
||||
if (id) stateBySession.set(id, /* ... */)
|
||||
}
|
||||
```
|
||||
|
||||
## Runtime Hooks
|
||||
|
||||
Runtime hooks are typed in-process callbacks on the same hook layer the runtime uses internally. They run inside the agent loop with full type information -- no IPC, no JSON marshaling.
|
||||
|
||||
Declare `"hooks"` in `manifest.capabilities`, then add a `hooks` property:
|
||||
|
||||
```typescript
|
||||
const plugin: AgentPlugin = {
|
||||
name: "metrics",
|
||||
manifest: { capabilities: ["hooks"] },
|
||||
hooks: {
|
||||
beforeRun(ctx) { /* ... */ },
|
||||
beforeTool({ toolCall, input }) { /* ... */ },
|
||||
afterTool({ toolCall, result }) { /* ... */ },
|
||||
afterRun({ result }) { /* ... */ },
|
||||
onEvent(event) { /* ... */ },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### The Seven Hooks
|
||||
|
||||
| Hook | Fires | Can Stop the Loop? | Common Uses |
|
||||
|------|-------|--------------------|-------------|
|
||||
| `beforeRun` | Before the runtime loop starts | Yes | Greet, log, attach session metadata |
|
||||
| `afterRun` | After the runtime loop finishes (success, abort, or fail) | No | Notifications, metrics, persistent logs |
|
||||
| `beforeModel` | Before each model request | Yes (mutate req) | Inject context, last-mile prompt edits |
|
||||
| `afterModel` | After each model response, before tool execution | Yes | Block based on model output |
|
||||
| `beforeTool` | Before each tool execution | Yes (`{ stop }`) | Audit, redact, block dangerous tools |
|
||||
| `afterTool` | After each tool execution | Can replace result | Post-process, redact secrets in tool output |
|
||||
| `onEvent` | On every `AgentRuntimeEvent` emitted by the runtime | No | Streaming UIs, telemetry pipes |
|
||||
|
||||
### Stopping the Loop from a Hook
|
||||
|
||||
Several hooks return an optional control object. The most common pattern is `beforeTool` blocking a destructive tool call:
|
||||
|
||||
```typescript
|
||||
beforeTool({ toolCall, input }) {
|
||||
if (toolCall.toolName === "run_commands") {
|
||||
const { commands } = input as { commands?: string[] }
|
||||
if (sessionBranch === "main" && commands?.some(c => c.startsWith("git push"))) {
|
||||
return { stop: true, reason: "Blocked git push on protected branch" }
|
||||
}
|
||||
}
|
||||
return undefined // explicit "continue"
|
||||
}
|
||||
```
|
||||
|
||||
Returning `undefined` (or omitting `return`) lets execution continue normally.
|
||||
|
||||
### afterRun Semantics
|
||||
|
||||
`afterRun` fires for every terminal status -- `completed`, `aborted`, `failed`. If you only want to act on success:
|
||||
|
||||
```typescript
|
||||
afterRun({ result }) {
|
||||
if (result.status !== "completed") return
|
||||
// notify, log success metrics, etc.
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin Hooks vs File Hooks
|
||||
|
||||
The runtime supports two hook systems:
|
||||
|
||||
- File hooks -- external scripts in `.cline/hooks/` invoked with serialized JSON. Right for user/workspace-specific scripts that don't ship with code.
|
||||
- Plugin runtime hooks -- typed in-process callbacks. Right when the behavior belongs to a reusable extension and needs typed access to the runtime.
|
||||
|
||||
Core adapts file hooks onto the runtime hook layer, so you don't need both. If you're shipping a plugin, write it as runtime hooks.
|
||||
|
||||
## Message Builders
|
||||
|
||||
Message builders rewrite the provider-bound message list before the model call. They run after runtime messages are converted into SDK message blocks but before core's built-in safety builder.
|
||||
|
||||
Use them for:
|
||||
|
||||
- Custom compaction policies (replace middle history with a summary).
|
||||
- Redacting PII or secrets before they reach the provider.
|
||||
- Reshaping context for a specific model's strengths.
|
||||
|
||||
```typescript
|
||||
api.registerMessageBuilder({
|
||||
name: "summarize-middle-history",
|
||||
build(messages) {
|
||||
if (estimateTokens(messages) < THRESHOLD) return messages
|
||||
return [...prefix, summary, ...recent]
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Multiple builders run in registration order; the output of one is the input of the next.
|
||||
|
||||
When to use `beforeModel` instead: reach for the `beforeModel` hook only if you need the runtime snapshot or want to mutate the request object itself. Pure message rewrites belong in a builder.
|
||||
|
||||
## Automation Events
|
||||
|
||||
Plugins can declare normalized event types and emit them into Cline automation. Hosts that don't have automation enabled simply ignore both -- feature-detect `ctx.automation`.
|
||||
|
||||
```typescript
|
||||
manifest: { capabilities: ["automationEvents"] },
|
||||
|
||||
setup(api, ctx) {
|
||||
api.registerAutomationEventType({
|
||||
eventType: "github.pull_request.opened",
|
||||
source: "github",
|
||||
description: "A new GitHub PR was opened",
|
||||
attributesSchema: { /* JSON Schema for envelope.attributes */ },
|
||||
})
|
||||
|
||||
if (!ctx.automation) return // host has no automation
|
||||
ctx.automation.ingestEvent({
|
||||
eventId: "pr-1234",
|
||||
eventType: "github.pull_request.opened",
|
||||
source: "github",
|
||||
subject: "owner/repo#1234",
|
||||
occurredAt: new Date().toISOString(),
|
||||
attributes: { /* ... */ },
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Loading a Plugin
|
||||
|
||||
There are three ways a plugin gets into a session:
|
||||
|
||||
### Auto-Discovery (CLI)
|
||||
|
||||
The CLI scans these directories on startup:
|
||||
|
||||
- `<workspace>/.cline/plugins/` -- project-scoped plugins.
|
||||
- `~/.cline/plugins/` -- user-scoped plugins.
|
||||
|
||||
Drop a `.ts` or `.js` file in, run `cline`, done:
|
||||
|
||||
```bash
|
||||
mkdir -p .cline/plugins
|
||||
cp my-plugin.ts .cline/plugins/
|
||||
cline -i "do the thing my plugin enables"
|
||||
```
|
||||
|
||||
### Explicit extensions in SDK Config
|
||||
|
||||
When you build your own host with `ClineCore`, pass the plugin object directly:
|
||||
|
||||
```typescript
|
||||
import plugin from "./my-plugin"
|
||||
import { ClineCore } from "@cline/core"
|
||||
|
||||
const host = await ClineCore.create({ backendMode: "local" })
|
||||
await host.start({
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY ?? "",
|
||||
cwd: process.cwd(),
|
||||
enableTools: true,
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
extensions: [plugin],
|
||||
extensionContext: {
|
||||
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
|
||||
},
|
||||
},
|
||||
prompt: "...",
|
||||
interactive: false,
|
||||
})
|
||||
```
|
||||
|
||||
### pluginPaths for Directory-Based Plugins
|
||||
|
||||
When the plugin is a directory with `package.json`, point `pluginPaths` at the directory:
|
||||
|
||||
```typescript
|
||||
config: {
|
||||
pluginPaths: ["./path/to/my-plugin-package"],
|
||||
}
|
||||
```
|
||||
|
||||
Or install with the CLI:
|
||||
|
||||
```bash
|
||||
cline plugin install ./path/to/my-plugin-package
|
||||
cline plugin install @scope/my-cline-plugin # from npm
|
||||
cline plugin install --git github.com/owner/repo # from git
|
||||
```
|
||||
|
||||
## Single-File Plugin Template
|
||||
|
||||
Save as `my-plugin.ts`, drop in `.cline/plugins/`:
|
||||
|
||||
```typescript
|
||||
import { type AgentPlugin, ClineCore, createTool } from "@cline/core"
|
||||
|
||||
let sessionRoot: string | undefined
|
||||
|
||||
const plugin: AgentPlugin = {
|
||||
name: "my-plugin",
|
||||
manifest: {
|
||||
capabilities: ["tools", "hooks"],
|
||||
},
|
||||
|
||||
setup(api, ctx) {
|
||||
sessionRoot = ctx.workspaceInfo?.rootPath
|
||||
|
||||
api.registerTool(
|
||||
createTool({
|
||||
name: "do_thing",
|
||||
description: "Do the thing this plugin exists for.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { target: { type: "string" } },
|
||||
required: ["target"],
|
||||
},
|
||||
async execute(input) {
|
||||
const { target } = input as { target: string }
|
||||
return { ok: true, target, root: sessionRoot }
|
||||
},
|
||||
}),
|
||||
)
|
||||
},
|
||||
|
||||
hooks: {
|
||||
beforeRun() {
|
||||
console.log("[my-plugin] run started")
|
||||
},
|
||||
afterRun({ result }) {
|
||||
if (result.status !== "completed") return
|
||||
console.log(`[my-plugin] done in ${result.iterations} iteration(s)`)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
async function runDemo(): Promise<void> {
|
||||
const host = await ClineCore.create({ backendMode: "local" })
|
||||
try {
|
||||
const result = await host.start({
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY ?? "",
|
||||
cwd: process.cwd(),
|
||||
enableTools: true,
|
||||
systemPrompt: "You are a helpful assistant. Use tools when needed.",
|
||||
extensions: [plugin],
|
||||
extensionContext: {
|
||||
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
|
||||
},
|
||||
},
|
||||
prompt: "Use do_thing on the target 'world'.",
|
||||
interactive: false,
|
||||
})
|
||||
console.log(result.result?.text ?? "")
|
||||
} finally {
|
||||
await host.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
await runDemo()
|
||||
}
|
||||
|
||||
export { plugin, runDemo }
|
||||
export default plugin
|
||||
```
|
||||
|
||||
Copy it, rename the tool, swap in your logic. The `runDemo()` function lets you test with `ANTHROPIC_API_KEY=sk-... bun run my-plugin.ts`.
|
||||
|
||||
## Plugin Package
|
||||
|
||||
Use a plugin package when you need npm dependencies, multiple entry points, bundled assets, or npm/git distribution.
|
||||
|
||||
### Layout
|
||||
|
||||
```
|
||||
my-cline-plugin/
|
||||
+-- package.json
|
||||
+-- tsconfig.json (optional, for local typechecking)
|
||||
+-- index.ts (the plugin entry point)
|
||||
+-- README.md
|
||||
+-- assets/ (optional, bundled content)
|
||||
+-- templates/
|
||||
+-- schemas/
|
||||
```
|
||||
|
||||
### package.json -- The Discovery Contract
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "my-cline-plugin",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "What this plugin does, in one sentence.",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./index.ts"
|
||||
},
|
||||
"cline": {
|
||||
"plugins": [
|
||||
{
|
||||
"paths": ["./index.ts"],
|
||||
"capabilities": ["tools", "hooks"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@cline/core": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@cline/core": { "optional": true }
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.1.5"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key fields:
|
||||
|
||||
- `type: "module"` -- required. Cline plugins are ES modules.
|
||||
- `cline.plugins` -- the discovery contract. Array of entries, each with `paths` (entry files) and `capabilities` (pre-declared, validated before importing).
|
||||
- `peerDependencies` for `@cline/core` -- the host already provides it. Marking it optional lets you typecheck in isolation.
|
||||
|
||||
### Bundling Assets
|
||||
|
||||
Resolve asset paths with `import.meta.url`, not `process.cwd()`:
|
||||
|
||||
```typescript
|
||||
import { dirname, join } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { readFileSync, existsSync } from "node:fs"
|
||||
|
||||
const MODULE_DIR = dirname(fileURLToPath(import.meta.url))
|
||||
const TEMPLATES_DIR = join(MODULE_DIR, "assets", "templates")
|
||||
|
||||
function loadTemplate(name: string): string | undefined {
|
||||
const path = join(TEMPLATES_DIR, `${name}.md`)
|
||||
return existsSync(path) ? readFileSync(path, "utf8") : undefined
|
||||
}
|
||||
```
|
||||
|
||||
This is the only place `import.meta.url` is appropriate in a plugin -- locating files inside the plugin package. For workspace paths, always use `ctx.workspaceInfo?.rootPath`.
|
||||
|
||||
### The Override Pattern (Bundled / Global / Project)
|
||||
|
||||
A package can ship default assets and let users override them. The convention is a three-tier lookup, last write wins by `name`:
|
||||
|
||||
1. bundled -- files inside the plugin package (defaults shipped with the plugin).
|
||||
2. global -- files under `~/.cline/data/settings/<kind>/` (user overrides).
|
||||
3. project -- files under `<workspace>/.cline/<kind>/` (project overrides).
|
||||
|
||||
### Multiple Plugin Entries
|
||||
|
||||
If your package exposes more than one plugin, list each in `cline.plugins`:
|
||||
|
||||
```json
|
||||
"cline": {
|
||||
"plugins": [
|
||||
{ "paths": ["./tools-plugin.ts"], "capabilities": ["tools"] },
|
||||
{ "paths": ["./hooks-plugin.ts"], "capabilities": ["hooks"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each entry file should `export default` its own plugin object.
|
||||
|
||||
## Testing Your Plugin
|
||||
|
||||
### Unit Tests
|
||||
|
||||
The plugin object is plain data. Drive `setup()` against a minimal context and exercise tools directly:
|
||||
|
||||
```typescript
|
||||
import plugin from "../my-plugin"
|
||||
|
||||
const tools: unknown[] = []
|
||||
const api = {
|
||||
registerTool: (t: unknown) => tools.push(t),
|
||||
registerCommand: () => {},
|
||||
registerRule: () => {},
|
||||
registerMessageBuilder: () => {},
|
||||
registerProvider: () => {},
|
||||
registerAutomationEventType: () => {},
|
||||
}
|
||||
await plugin.setup?.(api as never, {
|
||||
workspaceInfo: { rootPath: "/tmp/fake-workspace" },
|
||||
})
|
||||
|
||||
// Now `tools` contains the registered tools -- call tool.execute(input, ctx)
|
||||
```
|
||||
|
||||
### End-to-End with runDemo()
|
||||
|
||||
Add a `runDemo()` in your plugin file (see the single-file template above) that boots a real `ClineCore` session:
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... bun run my-plugin.ts
|
||||
```
|
||||
|
||||
### CLI Smoke Test
|
||||
|
||||
```bash
|
||||
mkdir -p .cline/plugins
|
||||
cp my-plugin.ts .cline/plugins/
|
||||
cline -i "trigger something that exercises the plugin"
|
||||
```
|
||||
|
||||
For packages:
|
||||
|
||||
```bash
|
||||
cline plugin install ./my-cline-plugin
|
||||
cline -i "..."
|
||||
```
|
||||
|
||||
If the plugin fails validation or setup, the CLI prints a clear error and continues without it.
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
- "capabilities must be a non-empty array" -- you forgot `manifest.capabilities`, or it's `[]`.
|
||||
- "registerRule requires the 'rules' capability" -- capability/handler drift. Add `"rules"` to capabilities, or stop calling `registerRule`.
|
||||
- Tool not visible to the model -- check `enableTools: true` on the session config, and that you're declaring `"tools"` in capabilities.
|
||||
- `ctx.workspaceInfo` is undefined in SDK tests -- the host didn't pass `extensionContext.workspace`. In SDK code, set it explicitly (see the ClineCore loading example above).
|
||||
- State leaking across sessions -- module-level variables are shared across sessions in the same process. Key by `ctx.session?.sessionId` if your host runs multiple sessions concurrently.
|
||||
- `afterRun` firing on aborts -- guard with `if (result.status !== "completed") return`.
|
||||
- Heavy work in `setup()` -- `setup()` blocks session start. Defer expensive work into the first tool call or `beforeRun`.
|
||||
- Importing host internals -- only import from `@cline/core`. Reaching into host-specific packages (e.g. CLI internals) will break in non-CLI hosts.
|
||||
- Sandboxed plugins and `telemetry` -- telemetry is process-local. Feature-detect `ctx.telemetry` and expect it to be undefined in sandboxed plugin processes.
|
||||
- Resolving bundled assets -- use `import.meta.url` + `fileURLToPath` to find files inside your package; never `process.cwd()`. For workspace paths, do the opposite: use `ctx.workspaceInfo?.rootPath`, never `import.meta.url`.
|
||||
- Plugin name collisions -- `name` must be unique within a session. If two plugins share a name, validation fails. Namespace by package (`my-org-redactor`, not `redactor`).
|
||||
|
||||
## Decision Guide -- Which Extension Point?
|
||||
|
||||
| You want to... | Use |
|
||||
|----------------|-----|
|
||||
| Give the model a new capability | `registerTool` |
|
||||
| Add a slash command in chat surfaces | `registerCommand` |
|
||||
| Inject text into the system prompt | `registerRule` |
|
||||
| Rewrite messages before they hit the provider | `registerMessageBuilder` |
|
||||
| Add a custom model provider | `registerProvider` |
|
||||
| Emit normalized cron/webhook events | `registerAutomationEventType` + `ctx.automation` |
|
||||
| Observe or steer the agent loop | `hooks.*` |
|
||||
| Block a dangerous tool call | `hooks.beforeTool` returning `{ stop: true }` |
|
||||
| Notify on completion | `hooks.afterRun` (gate on `status === "completed"`) |
|
||||
| Tweak each model request | `hooks.beforeModel` |
|
||||
| Stream events to a UI | `hooks.onEvent` |
|
||||
| Ship reusable templates with the plugin | Bundle assets next to `index.ts`, resolve via `import.meta.url` |
|
||||
| Let users override defaults globally or per-project | Three-tier lookup: bundled / global / project |
|
||||
|
||||
## Pre-Ship Checklist
|
||||
|
||||
- `manifest.capabilities` is a non-empty array.
|
||||
- Every `api.register*` call has a matching capability declared.
|
||||
- If `hooks` is present, `"hooks"` is in `capabilities`.
|
||||
- `ctx.workspaceInfo?.rootPath` is used for workspace paths (not `process.cwd()`).
|
||||
- Optional `ctx` fields are feature-detected.
|
||||
- Tool names are snake_case verbs; descriptions are written for the model.
|
||||
- Tool inputs have JSON Schema with `required` set.
|
||||
- `afterRun` handlers gate on `result.status === "completed"` if they only want successes.
|
||||
- State that must not leak between concurrent sessions is keyed by `ctx.session?.sessionId`.
|
||||
- (Package) `package.json` has `type: "module"`, `cline.plugins`, and `@cline/core` as an optional peer dep.
|
||||
- (Package) Bundled assets resolved via `import.meta.url`, not `process.cwd()`.
|
||||
- Smoke test: drop the plugin into `.cline/plugins/` (or `cline plugin install`), run `cline -i "..."`, watch it work.
|
||||
|
||||
## Plugin Examples from SDK
|
||||
|
||||
The SDK repo includes these example plugins:
|
||||
|
||||
| Plugin | Description |
|
||||
|--------|-------------|
|
||||
| `weather-metrics.ts` | Tool registration + lifecycle metrics |
|
||||
| `mac-notify.ts` | macOS Notification Center alerts |
|
||||
| `custom-compaction.ts` | Custom message compaction via message builders |
|
||||
| `background-terminal.ts` | Detached shell job management |
|
||||
| `automation-events.ts` | Plugin-emitted automation events |
|
||||
| `gitignore-read-files-guard.ts` | File access policy enforcement via beforeTool |
|
||||
| `web-search.ts` | Web search via Exa API |
|
||||
| `typescript-lsp/` | TypeScript Language Service tools (plugin package) |
|
||||
| `agents-squad/` | Multi-agent team orchestration (plugin package) |
|
||||
|
||||
## See Also
|
||||
|
||||
- `../tools/REFERENCE.md` - Tool creation
|
||||
- `../events/REFERENCE.md` - Event system
|
||||
- `../agent/REFERENCE.md` - Using plugins with Agent
|
||||
- `../clinecore/REFERENCE.md` - Using plugins with ClineCore
|
||||
@@ -0,0 +1,253 @@
|
||||
# Going to Production
|
||||
|
||||
Guidelines for deploying Cline SDK agents in production environments.
|
||||
|
||||
## Error Handling
|
||||
|
||||
Always check the result status:
|
||||
|
||||
```typescript
|
||||
const result = await agent.run(input)
|
||||
|
||||
switch (result.status) {
|
||||
case "completed":
|
||||
console.log("Success:", result.outputText)
|
||||
break
|
||||
case "aborted":
|
||||
console.log("Cancelled:", result.error?.message)
|
||||
break
|
||||
case "failed":
|
||||
console.error("Failed:", result.error)
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
For ClineCore, check `finishReason`:
|
||||
|
||||
```typescript
|
||||
const session = await cline.start({ ... })
|
||||
|
||||
switch (session.result?.finishReason) {
|
||||
case "completed":
|
||||
// normal completion
|
||||
break
|
||||
case "max_iterations":
|
||||
// agent hit iteration limit
|
||||
break
|
||||
case "aborted":
|
||||
// manually cancelled
|
||||
break
|
||||
case "mistake_limit":
|
||||
// too many tool errors
|
||||
break
|
||||
case "error":
|
||||
// unrecoverable error
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
## Cost Control
|
||||
|
||||
### Token Limits
|
||||
|
||||
Set maximum tokens per turn and iteration limits:
|
||||
|
||||
```typescript
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
maxTokensPerTurn: 4096,
|
||||
maxIterations: 10,
|
||||
tools: [...],
|
||||
})
|
||||
```
|
||||
|
||||
### Model Selection
|
||||
|
||||
Use cheaper models for simple tasks:
|
||||
|
||||
```typescript
|
||||
// Simple classification or formatting
|
||||
{ providerId: "anthropic", modelId: "claude-haiku-4-5" }
|
||||
|
||||
// Complex reasoning and code generation
|
||||
{ providerId: "anthropic", modelId: "claude-sonnet-4-6" }
|
||||
|
||||
// Hardest tasks requiring deep reasoning
|
||||
{ providerId: "anthropic", modelId: "claude-opus-4-7" }
|
||||
```
|
||||
|
||||
### Usage Tracking
|
||||
|
||||
Monitor spending in real time:
|
||||
|
||||
```typescript
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "usage-updated" && event.usage.totalCost) {
|
||||
if (event.usage.totalCost > MAX_BUDGET) {
|
||||
agent.abort("Budget exceeded")
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Observability
|
||||
|
||||
### OpenTelemetry Integration
|
||||
|
||||
The SDK supports OpenTelemetry for traces, metrics, and logs:
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
// OpenTelemetry config is picked up from environment
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_SERVICE_NAME, etc.
|
||||
})
|
||||
```
|
||||
|
||||
### Structured Logging
|
||||
|
||||
Use the `BasicLogger` interface for injectable logging:
|
||||
|
||||
```typescript
|
||||
import type { BasicLogger } from "@cline/sdk"
|
||||
|
||||
const logger: BasicLogger = {
|
||||
debug: (msg, meta) => console.debug(msg, meta),
|
||||
log: (msg, meta) => console.log(msg, meta),
|
||||
error: (msg, meta) => console.error(msg, meta),
|
||||
}
|
||||
|
||||
await cline.start({
|
||||
config: {
|
||||
logger,
|
||||
// ...
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Custom Metrics via Plugins
|
||||
|
||||
```typescript
|
||||
const metricsPlugin: AgentPlugin = {
|
||||
name: "metrics",
|
||||
manifest: { capabilities: ["hooks"] },
|
||||
setup() {},
|
||||
hooks: {
|
||||
beforeRun() {
|
||||
metrics.increment("agent.runs.started")
|
||||
},
|
||||
afterRun({ result }) {
|
||||
metrics.increment("agent.runs.completed")
|
||||
metrics.histogram("agent.iterations", result.iterations)
|
||||
metrics.histogram("agent.tokens.output", result.usage.outputTokens)
|
||||
},
|
||||
beforeTool({ toolCall }) {
|
||||
metrics.increment(`agent.tools.${toolCall.toolName}`)
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
### Sandbox Tool Execution
|
||||
|
||||
Validate tool inputs to prevent path traversal and injection:
|
||||
|
||||
```typescript
|
||||
execute: async (input) => {
|
||||
const safePath = path.resolve(WORKSPACE_ROOT, input.path)
|
||||
if (!safePath.startsWith(WORKSPACE_ROOT)) {
|
||||
return { error: "Path traversal attempt blocked" }
|
||||
}
|
||||
return await readFile(safePath, "utf-8")
|
||||
}
|
||||
```
|
||||
|
||||
### API Key Management
|
||||
|
||||
- Use environment variables, never hardcode keys
|
||||
- Rotate keys regularly
|
||||
- Use different keys for development and production
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY, // never a literal string
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Policy Hardening
|
||||
|
||||
Disable tools you don't need and require approval for dangerous ones:
|
||||
|
||||
```typescript
|
||||
toolPolicies: {
|
||||
read_files: { autoApprove: true },
|
||||
search: { autoApprove: true },
|
||||
bash: { autoApprove: false }, // require approval
|
||||
editor: { autoApprove: false },
|
||||
apply_patch: { autoApprove: false },
|
||||
fetch_web: { enabled: false }, // disable entirely
|
||||
}
|
||||
```
|
||||
|
||||
## Deployment Patterns
|
||||
|
||||
### Stateless Worker
|
||||
|
||||
For request/response workloads (API endpoints, queue consumers):
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "worker",
|
||||
backendMode: "local",
|
||||
})
|
||||
|
||||
app.post("/agent", async (req, res) => {
|
||||
const session = await cline.start({
|
||||
prompt: req.body.prompt,
|
||||
config: { ... },
|
||||
})
|
||||
res.json({ text: session.result?.text, usage: session.result?.usage })
|
||||
})
|
||||
```
|
||||
|
||||
### Persistent Service
|
||||
|
||||
For long-running services with session management:
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "service",
|
||||
backendMode: "hub",
|
||||
})
|
||||
|
||||
process.on("SIGTERM", async () => {
|
||||
await cline.dispose("SIGTERM")
|
||||
process.exit(0)
|
||||
})
|
||||
```
|
||||
|
||||
### Scheduled Automation
|
||||
|
||||
See `../scheduling/REFERENCE.md` for recurring agent tasks.
|
||||
|
||||
## Retry and Resilience
|
||||
|
||||
- Tool `execute` functions support `retryable: true` (default) and `maxRetries: 3` (default)
|
||||
- Provider API calls are retried automatically on transient failures
|
||||
- Use `timeoutMs` on tools to prevent hanging
|
||||
- Monitor `mistake_limit` finish reason to detect systematic tool failures
|
||||
|
||||
## See Also
|
||||
|
||||
- `../agent/REFERENCE.md` - Agent overview
|
||||
- `../clinecore/REFERENCE.md` - ClineCore overview
|
||||
- `../tools/REFERENCE.md` - Tool configuration
|
||||
- `../plugins/REFERENCE.md` - Metrics plugins
|
||||
- `../scheduling/REFERENCE.md` - Scheduled agents
|
||||
@@ -0,0 +1,257 @@
|
||||
# Model Providers
|
||||
|
||||
The Cline SDK supports every major LLM provider out of the box via `@cline/llms`.
|
||||
|
||||
## Supported Providers
|
||||
|
||||
| Provider ID | Models |
|
||||
|-------------|--------|
|
||||
| `"anthropic"` | Claude Opus 4.7, Sonnet 4.6, Haiku 4.5 |
|
||||
| `"openai"` | GPT-5.5, GPT-5.3 Codex |
|
||||
| `"gemini"` | Gemini 3.1 Pro Preview, Gemini 3 Flash Preview |
|
||||
| `"vertex"` | Google models via Vertex AI |
|
||||
| `"bedrock"` | Claude, Llama via AWS Bedrock |
|
||||
| `"mistral"` | Mistral Large, Codestral |
|
||||
| `"openai-compatible"` | vLLM, Together, Fireworks, Groq, etc. |
|
||||
|
||||
## Basic Configuration
|
||||
|
||||
### With Agent
|
||||
|
||||
```typescript
|
||||
import { Agent } from "@cline/sdk"
|
||||
|
||||
const agent = new Agent({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
systemPrompt: "You are a helpful assistant.",
|
||||
tools: [],
|
||||
})
|
||||
```
|
||||
|
||||
### With ClineCore
|
||||
|
||||
```typescript
|
||||
import { ClineCore } from "@cline/sdk"
|
||||
|
||||
const cline = await ClineCore.create({ clientName: "my-app" })
|
||||
|
||||
await cline.start({
|
||||
prompt: "Hello",
|
||||
config: {
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Provider-Specific Configuration
|
||||
|
||||
### Anthropic
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-opus-4-7", // or "claude-sonnet-4-6", "claude-haiku-4-5"
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
}
|
||||
```
|
||||
|
||||
### OpenAI
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "openai",
|
||||
modelId: "gpt-5.5",
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
}
|
||||
```
|
||||
|
||||
### Google (Gemini)
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "gemini",
|
||||
modelId: "gemini-3.1-pro-preview",
|
||||
apiKey: process.env.GOOGLE_API_KEY,
|
||||
}
|
||||
```
|
||||
|
||||
### Google (Vertex AI)
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "vertex",
|
||||
modelId: "gemini-3.1-pro-preview",
|
||||
// Uses application default credentials or service account
|
||||
}
|
||||
```
|
||||
|
||||
### AWS Bedrock
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "bedrock",
|
||||
modelId: "anthropic.claude-sonnet-4-6",
|
||||
// Uses AWS credential chain (env vars, config file, IAM role)
|
||||
// Set AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
|
||||
}
|
||||
```
|
||||
|
||||
### Mistral
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "mistral",
|
||||
modelId: "mistral-large-latest",
|
||||
apiKey: process.env.MISTRAL_API_KEY,
|
||||
}
|
||||
```
|
||||
|
||||
### OpenAI-Compatible
|
||||
|
||||
For any provider with an OpenAI-compatible API:
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "openai-compatible",
|
||||
modelId: "my-model",
|
||||
apiKey: process.env.API_KEY,
|
||||
baseUrl: "https://api.together.xyz/v1",
|
||||
}
|
||||
```
|
||||
|
||||
Works with: vLLM, Together AI, Fireworks, Groq, Ollama, LiteLLM, etc.
|
||||
|
||||
## Custom Base URL
|
||||
|
||||
Override the API endpoint for any provider:
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
apiKey: process.env.API_KEY,
|
||||
baseUrl: "https://my-proxy.example.com/v1",
|
||||
}
|
||||
```
|
||||
|
||||
## Custom Headers
|
||||
|
||||
Pass additional headers to API requests:
|
||||
|
||||
```typescript
|
||||
{
|
||||
providerId: "openai",
|
||||
modelId: "gpt-5.5",
|
||||
apiKey: process.env.API_KEY,
|
||||
headers: {
|
||||
"X-Custom-Header": "value",
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Gateway API
|
||||
|
||||
For advanced multi-provider setups, use the Gateway directly:
|
||||
|
||||
```typescript
|
||||
import { createGateway, DefaultGateway } from "@cline/llms"
|
||||
|
||||
const gateway = createGateway({
|
||||
providerConfigs: [
|
||||
{ providerId: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY },
|
||||
{ providerId: "openai", apiKey: process.env.OPENAI_API_KEY },
|
||||
],
|
||||
})
|
||||
|
||||
// Create a model for a specific provider
|
||||
const model = gateway.createAgentModel({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-opus-4-7",
|
||||
})
|
||||
|
||||
// Use with Agent
|
||||
const agent = new Agent({ model, systemPrompt: "...", tools: [] })
|
||||
```
|
||||
|
||||
### Gateway Methods
|
||||
|
||||
```typescript
|
||||
gateway.registerProvider(registration) // add a custom provider
|
||||
gateway.configureProvider(config) // update provider settings
|
||||
gateway.listProviders() // list available providers
|
||||
gateway.listModels(providerId?) // list available models
|
||||
gateway.createAgentModel(selection) // create model for agent
|
||||
gateway.stream(request) // raw streaming (AsyncIterable)
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Query and register providers programmatically:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
getAllProviders,
|
||||
getProviderIds,
|
||||
getProvider,
|
||||
getModelsForProvider,
|
||||
registerProvider,
|
||||
registerModel,
|
||||
createHandler,
|
||||
} from "@cline/llms"
|
||||
|
||||
// List all registered providers
|
||||
const providers = getAllProviders()
|
||||
|
||||
// Get models for a provider
|
||||
const models = getModelsForProvider("anthropic")
|
||||
|
||||
// Register a custom provider
|
||||
registerProvider({
|
||||
id: "my-provider",
|
||||
name: "My Custom Provider",
|
||||
handler: createHandler({ ... }),
|
||||
})
|
||||
```
|
||||
|
||||
## Model Metadata
|
||||
|
||||
Access model info (context window, pricing, capabilities):
|
||||
|
||||
```typescript
|
||||
import { getModelsForProvider } from "@cline/llms"
|
||||
|
||||
const models = getModelsForProvider("anthropic")
|
||||
for (const model of models) {
|
||||
console.log(`${model.id}: context=${model.contextWindow}, input=$${model.inputPrice}/MTok`)
|
||||
}
|
||||
```
|
||||
|
||||
## Cost Tracking
|
||||
|
||||
Track per-request and cumulative costs:
|
||||
|
||||
```typescript
|
||||
// Via events
|
||||
agent.subscribe((event) => {
|
||||
if (event.type === "usage-updated") {
|
||||
console.log(`Cost: $${event.usage.totalCost?.toFixed(4)}`)
|
||||
}
|
||||
})
|
||||
|
||||
// Via result
|
||||
const result = await agent.run("...")
|
||||
console.log(`Total cost: $${result.usage.totalCost?.toFixed(4)}`)
|
||||
|
||||
// Via ClineCore accumulated usage
|
||||
const usage = await cline.getAccumulatedUsage(sessionId)
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- `../agent/REFERENCE.md` - Using providers with Agent
|
||||
- `../clinecore/REFERENCE.md` - Using providers with ClineCore
|
||||
- `../production/REFERENCE.md` - Cost control in production
|
||||
@@ -0,0 +1,227 @@
|
||||
# Scheduling and Automation
|
||||
|
||||
The Cline SDK supports scheduled, one-off, and event-driven agent execution through the automation subsystem in `@cline/core`.
|
||||
|
||||
## Overview
|
||||
|
||||
Three trigger types:
|
||||
|
||||
| Trigger | Description |
|
||||
|---------|-------------|
|
||||
| `schedule` | Recurring jobs via cron expressions |
|
||||
| `one_off` | Single execution tasks |
|
||||
| `event` | Triggered by external events (GitHub, Linear, custom) |
|
||||
|
||||
## CLI Schedule Management
|
||||
|
||||
```bash
|
||||
# Create a recurring schedule
|
||||
cline schedule create "Daily standup" \
|
||||
--cron "0 9 * * MON-FRI" \
|
||||
--prompt "Summarize open PRs and blockers" \
|
||||
--workspace /path/to/project \
|
||||
--model anthropic/claude-sonnet-4-6
|
||||
|
||||
# List schedules
|
||||
cline schedule list
|
||||
|
||||
# Trigger a schedule immediately
|
||||
cline schedule trigger <schedule-id>
|
||||
|
||||
# Pause/resume
|
||||
cline schedule pause <schedule-id>
|
||||
cline schedule resume <schedule-id>
|
||||
|
||||
# Delete
|
||||
cline schedule delete <schedule-id>
|
||||
|
||||
# View past executions
|
||||
cline schedule executions <schedule-id>
|
||||
```
|
||||
|
||||
## Cron Expressions
|
||||
|
||||
| Expression | Meaning |
|
||||
|-----------|---------|
|
||||
| `0 9 * * MON-FRI` | 9 AM weekdays |
|
||||
| `0 */6 * * *` | Every 6 hours |
|
||||
| `0 8 * * MON` | Mondays at 8 AM |
|
||||
| `*/30 * * * *` | Every 30 minutes |
|
||||
| `0 0 1 * *` | First of every month |
|
||||
|
||||
## File-Based Specs
|
||||
|
||||
Create Markdown files in `~/.cline/cron/` (global) or `.cline/cron/` (workspace):
|
||||
|
||||
### Recurring Schedule
|
||||
|
||||
```markdown
|
||||
---
|
||||
trigger: schedule
|
||||
schedule: "0 9 * * MON-FRI"
|
||||
timezone: America/New_York
|
||||
mode: exclusive
|
||||
prompt: "Check for dependency updates and create PRs for any outdated packages."
|
||||
modelSelection:
|
||||
providerId: anthropic
|
||||
modelId: claude-sonnet-4-6
|
||||
tools:
|
||||
enabled: true
|
||||
---
|
||||
|
||||
Additional context or instructions for the agent go in the body.
|
||||
```
|
||||
|
||||
### One-Off Task
|
||||
|
||||
```markdown
|
||||
---
|
||||
trigger: one_off
|
||||
prompt: "Generate a comprehensive test coverage report."
|
||||
modelSelection:
|
||||
providerId: anthropic
|
||||
modelId: claude-sonnet-4-6
|
||||
---
|
||||
```
|
||||
|
||||
### Event-Driven
|
||||
|
||||
```markdown
|
||||
---
|
||||
trigger: event
|
||||
eventType: github.pull_request.opened
|
||||
filters:
|
||||
repository: myorg/myrepo
|
||||
debounceMs: 5000
|
||||
cooldownMs: 60000
|
||||
prompt: "Review the PR for security issues and code quality."
|
||||
modelSelection:
|
||||
providerId: anthropic
|
||||
modelId: claude-sonnet-4-6
|
||||
---
|
||||
```
|
||||
|
||||
## CronSpec Types
|
||||
|
||||
```typescript
|
||||
interface CronScheduleSpec {
|
||||
trigger: "schedule"
|
||||
schedule: string // cron expression
|
||||
timezone?: string
|
||||
mode?: "exclusive" | "concurrent"
|
||||
prompt: string
|
||||
modelSelection?: { providerId: string; modelId?: string }
|
||||
extensionLoading?: "isolated" | "direct"
|
||||
configExtensions?: RuntimeConfigExtensionKind[]
|
||||
tools?: { enabled?: boolean; names?: string[] }
|
||||
}
|
||||
|
||||
interface CronOneOffSpec {
|
||||
trigger: "one_off"
|
||||
prompt: string
|
||||
modelSelection?: { providerId: string; modelId?: string }
|
||||
}
|
||||
|
||||
interface CronEventSpec {
|
||||
trigger: "event"
|
||||
eventType: string // e.g., "github.pull_request.opened"
|
||||
filters?: Record<string, unknown>
|
||||
debounceMs?: number
|
||||
cooldownMs?: number
|
||||
prompt: string
|
||||
modelSelection?: { providerId: string; modelId?: string }
|
||||
}
|
||||
```
|
||||
|
||||
## Programmatic Automation API
|
||||
|
||||
```typescript
|
||||
const cline = await ClineCore.create({
|
||||
clientName: "my-app",
|
||||
automation: true,
|
||||
})
|
||||
|
||||
// Start automation service
|
||||
cline.automation.start()
|
||||
|
||||
// Ingest an external event
|
||||
cline.automation.ingestEvent({
|
||||
eventId: "evt-123",
|
||||
eventType: "github.pull_request.opened",
|
||||
source: "github",
|
||||
timestamp: Date.now(),
|
||||
payload: { pr: { number: 42, title: "..." } },
|
||||
})
|
||||
|
||||
// List specs, runs, events
|
||||
const specs = await cline.automation.listSpecs()
|
||||
const runs = await cline.automation.listRuns()
|
||||
const events = await cline.automation.listEvents()
|
||||
|
||||
// Reconcile specs from directory
|
||||
await cline.automation.reconcile(specDirectory)
|
||||
|
||||
// Stop automation
|
||||
cline.automation.stop()
|
||||
```
|
||||
|
||||
## Event Ingestion from Plugins
|
||||
|
||||
Plugins can declare and emit automation events:
|
||||
|
||||
```typescript
|
||||
const webhookPlugin: AgentPlugin = {
|
||||
name: "webhook-events",
|
||||
manifest: { capabilities: ["automationEvents"] },
|
||||
setup(api) {
|
||||
api.registerAutomationEventType({
|
||||
type: "webhook.received",
|
||||
description: "External webhook received",
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Submit events via the plugin context:
|
||||
|
||||
```typescript
|
||||
ctx.automation.ingestEvent({
|
||||
eventId: "evt-456",
|
||||
eventType: "webhook.received",
|
||||
source: "custom",
|
||||
timestamp: Date.now(),
|
||||
payload: { ... },
|
||||
})
|
||||
```
|
||||
|
||||
## Concurrency Control
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `"exclusive"` | Skip if previous run still active |
|
||||
| `"concurrent"` | Allow overlapping runs |
|
||||
|
||||
## Run Reports
|
||||
|
||||
Each completed run writes a Markdown report to `.cline/cron/reports/<run-id>.md` with:
|
||||
- Run metadata (spec, trigger, timing)
|
||||
- Summary of agent output
|
||||
- Usage (tokens, cost)
|
||||
- Tool calls made
|
||||
- Trigger event context (for event-driven runs)
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Daily standup summaries
|
||||
- Automated dependency update checks
|
||||
- PR review on open
|
||||
- Codebase health reports
|
||||
- Scheduled security scans
|
||||
- Event-driven CI/CD workflows
|
||||
|
||||
## See Also
|
||||
|
||||
- `../clinecore/REFERENCE.md` - ClineCore runtime
|
||||
- `../clinecore/api.md` - Automation API details
|
||||
- `../plugins/REFERENCE.md` - Plugin events
|
||||
- `../production/REFERENCE.md` - Production deployment
|
||||
@@ -0,0 +1,259 @@
|
||||
# Tools
|
||||
|
||||
Tools are how agents interact with the world. The Cline SDK supports both built-in tools (via ClineCore) and custom tools you define yourself.
|
||||
|
||||
## Creating Custom Tools
|
||||
|
||||
Use `createTool()` from `@cline/sdk` (or `@cline/shared`):
|
||||
|
||||
```typescript
|
||||
import { createTool } from "@cline/sdk"
|
||||
|
||||
const myTool = createTool({
|
||||
name: "search_issues",
|
||||
description: "Search GitHub issues by query. Returns up to 10 results.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: { type: "string", description: "Search query" },
|
||||
state: { type: "string", enum: ["open", "closed", "all"] },
|
||||
},
|
||||
required: ["query"],
|
||||
},
|
||||
execute: async (input) => {
|
||||
const issues = await github.searchIssues(input.query, input.state)
|
||||
return { issues, count: issues.length }
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### With Zod Schema
|
||||
|
||||
```typescript
|
||||
import { createTool } from "@cline/sdk"
|
||||
import { z } from "zod"
|
||||
|
||||
const deployTool = createTool({
|
||||
name: "deploy",
|
||||
description: "Deploy the app to the specified environment.",
|
||||
inputSchema: z.object({
|
||||
environment: z.enum(["staging", "production"]).describe("Target environment"),
|
||||
version: z.string().optional().describe("Version tag, defaults to latest"),
|
||||
}),
|
||||
execute: async (input) => {
|
||||
const result = await deploy(input.environment, input.version)
|
||||
return { url: result.url, status: "deployed" }
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Tool Config Options
|
||||
|
||||
```typescript
|
||||
createTool({
|
||||
name: string, // snake_case, unique per agent
|
||||
description: string, // what the tool does (model reads this)
|
||||
inputSchema: JSONSchema | ZodSchema, // input validation
|
||||
execute: async (input, context, onChange?) => output,
|
||||
timeoutMs?: number, // default: 30000
|
||||
retryable?: boolean, // default: true
|
||||
maxRetries?: number, // default: 3
|
||||
lifecycle?: {
|
||||
completesRun?: boolean // true = ends agent loop on success
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### AgentToolContext
|
||||
|
||||
The second argument to `execute` provides runtime context:
|
||||
|
||||
```typescript
|
||||
interface AgentToolContext {
|
||||
agentId: string
|
||||
conversationId: string
|
||||
iteration: number
|
||||
abortSignal?: AbortSignal
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
```
|
||||
|
||||
## Tool Naming Rules
|
||||
|
||||
- Names must be `snake_case` (e.g., `search_issues`, `deploy_app`)
|
||||
- Names must be unique within a single agent's tool set
|
||||
- Choose descriptive names since the model uses them to decide which tool to call
|
||||
|
||||
## Tool Descriptions Matter
|
||||
|
||||
The model reads the tool description to decide when and how to use it. Write clear, specific descriptions:
|
||||
|
||||
```typescript
|
||||
// Bad: vague
|
||||
description: "Does deployment stuff"
|
||||
|
||||
// Good: specific with constraints
|
||||
description: "Deploy the application to staging or production. " +
|
||||
"Staging deployments are immediate. Production requires a passing CI build. " +
|
||||
"Returns the deployment URL and status."
|
||||
```
|
||||
|
||||
Include constraints, rate limits, and expected behavior in the description.
|
||||
|
||||
## Error Handling in Tools
|
||||
|
||||
Return errors as structured data instead of throwing:
|
||||
|
||||
```typescript
|
||||
// Good: return error data
|
||||
execute: async (input) => {
|
||||
const file = await readFile(input.path).catch(() => null)
|
||||
if (!file) {
|
||||
return { error: "File not found", path: input.path }
|
||||
}
|
||||
return { content: file }
|
||||
}
|
||||
```
|
||||
|
||||
Thrown exceptions count as "mistakes" against the agent's mistake limit. Returned error data lets the agent adjust its approach.
|
||||
|
||||
## Completion Tools
|
||||
|
||||
Tools with `lifecycle: { completesRun: true }` end the agent loop when they execute successfully:
|
||||
|
||||
```typescript
|
||||
const submitAnswer = createTool({
|
||||
name: "submit_answer",
|
||||
description: "Submit the final answer and end the task.",
|
||||
inputSchema: z.object({
|
||||
answer: z.string(),
|
||||
confidence: z.number().min(0).max(1),
|
||||
}),
|
||||
lifecycle: { completesRun: true },
|
||||
execute: async (input) => input,
|
||||
})
|
||||
```
|
||||
|
||||
The model sees the tool result and the run ends. Access the output via `result.toolCalls`.
|
||||
|
||||
## Built-in Tools (ClineCore Only)
|
||||
|
||||
When using `ClineCore` with `enableTools: true`, these tools are available automatically:
|
||||
|
||||
| Tool | Name | What It Does |
|
||||
|------|------|-------------|
|
||||
| Shell | `bash` | Execute shell commands in the session workspace |
|
||||
| Editor | `editor` | Create and edit files |
|
||||
| Read | `read_files` | Read file contents |
|
||||
| Patch | `apply_patch` | Apply unified diffs to files |
|
||||
| Search | `search` | Search file contents and directory structure |
|
||||
| Web | `fetch_web` | Fetch web content via HTTP |
|
||||
|
||||
Built-in tools respect the `cwd` setting in `CoreSessionConfig`.
|
||||
|
||||
## Tool Policies
|
||||
|
||||
Control which tools are available and whether they require approval:
|
||||
|
||||
```typescript
|
||||
// In Agent config
|
||||
const agent = new Agent({
|
||||
tools: [toolA, toolB, toolC],
|
||||
toolPolicies: {
|
||||
tool_a: { autoApprove: true }, // runs without asking
|
||||
tool_b: { autoApprove: false }, // requires approval
|
||||
tool_c: { enabled: false }, // hidden from model
|
||||
},
|
||||
})
|
||||
|
||||
// In ClineCore session
|
||||
await cline.start({
|
||||
prompt: "...",
|
||||
config: { ... },
|
||||
toolPolicies: {
|
||||
bash: { autoApprove: true },
|
||||
editor: { autoApprove: false },
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Policy Options
|
||||
|
||||
| Policy | Effect |
|
||||
|--------|--------|
|
||||
| `{ autoApprove: true }` | Tool runs without approval |
|
||||
| `{ autoApprove: false }` | Triggers approval callback before running |
|
||||
| `{ enabled: false }` | Tool is hidden from the model entirely |
|
||||
| No policy set | Defaults to enabled and auto-approved |
|
||||
|
||||
## Abort Signal in Long-Running Tools
|
||||
|
||||
Respect the abort signal for tools that take a long time:
|
||||
|
||||
```typescript
|
||||
execute: async (input, context) => {
|
||||
const results = []
|
||||
for (const item of input.items) {
|
||||
if (context.abortSignal?.aborted) {
|
||||
return { results, aborted: true, processed: results.length }
|
||||
}
|
||||
results.push(await processItem(item))
|
||||
}
|
||||
return { results, processed: results.length }
|
||||
}
|
||||
```
|
||||
|
||||
## Streaming Tool Output
|
||||
|
||||
Use the `onChange` callback (third argument) to stream partial results:
|
||||
|
||||
```typescript
|
||||
execute: async (input, context, onChange) => {
|
||||
let progress = 0
|
||||
for (const step of steps) {
|
||||
progress++
|
||||
onChange?.(`Processing step ${progress}/${steps.length}...`)
|
||||
await processStep(step)
|
||||
}
|
||||
return { completed: true }
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Tools
|
||||
|
||||
Tools are plain async functions, so they're straightforward to test:
|
||||
|
||||
```typescript
|
||||
import { describe, it, expect } from "vitest"
|
||||
|
||||
describe("deploy tool", () => {
|
||||
it("deploys to staging", async () => {
|
||||
const context = { agentId: "test", conversationId: "test", iteration: 1 }
|
||||
const result = await deployTool.execute({ environment: "staging" }, context)
|
||||
expect(result.status).toBe("deployed")
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## MCP Tool Integration
|
||||
|
||||
ClineCore can connect to MCP (Model Context Protocol) servers for additional tools. Configure in `.cline/mcp-servers.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"servers": {
|
||||
"my-server": {
|
||||
"command": "node",
|
||||
"args": ["./mcp-server.js"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
MCP tools appear alongside built-in and custom tools automatically.
|
||||
|
||||
## See Also
|
||||
|
||||
- `../agent/REFERENCE.md` - Using tools with Agent
|
||||
- `../clinecore/REFERENCE.md` - Using tools with ClineCore
|
||||
- `../plugins/REFERENCE.md` - Packaging tools as plugins
|
||||
@@ -0,0 +1,211 @@
|
||||
---
|
||||
name: create-pull-request
|
||||
description: Create a GitHub pull request following project conventions. Use when the user asks to create a PR, submit changes for review, or open a pull request. Handles commit analysis, branch management, PR template usage, and PR creation using the gh CLI tool.
|
||||
---
|
||||
|
||||
# Create Pull Request
|
||||
|
||||
This skill guides you through creating a well-structured GitHub pull request that follows project conventions and best practices.
|
||||
|
||||
## Prerequisites Check
|
||||
|
||||
Before proceeding, verify the following:
|
||||
|
||||
### 1. Check if `gh` CLI is installed
|
||||
|
||||
```bash
|
||||
gh --version
|
||||
```
|
||||
|
||||
If not installed, inform the user:
|
||||
> The GitHub CLI (`gh`) is required but not installed. Please install it:
|
||||
> - macOS: `brew install gh`
|
||||
> - Other: https://cli.github.com/
|
||||
|
||||
### 2. Check if authenticated with GitHub
|
||||
|
||||
```bash
|
||||
gh auth status
|
||||
```
|
||||
|
||||
If not authenticated, guide the user to run `gh auth login`.
|
||||
|
||||
### 3. Verify clean working directory
|
||||
|
||||
```bash
|
||||
git status
|
||||
```
|
||||
|
||||
If there are uncommitted changes, ask the user whether to:
|
||||
- Commit them as part of this PR
|
||||
- Stash them temporarily
|
||||
- Discard them (with caution)
|
||||
|
||||
## Gather Context
|
||||
|
||||
### 1. Identify the current branch
|
||||
|
||||
```bash
|
||||
git branch --show-current
|
||||
```
|
||||
|
||||
Ensure you're not on `main` or `master`. If so, ask the user to create or switch to a feature branch.
|
||||
|
||||
### 2. Find the base branch
|
||||
|
||||
```bash
|
||||
git remote show origin | grep "HEAD branch"
|
||||
```
|
||||
|
||||
This is typically `main` or `master`.
|
||||
|
||||
### 3. Analyze recent commits relevant to this PR
|
||||
|
||||
```bash
|
||||
git log origin/main..HEAD --oneline --no-decorate
|
||||
```
|
||||
|
||||
Review these commits to understand:
|
||||
- What changes are being introduced
|
||||
- The scope of the PR (single feature/fix or multiple changes)
|
||||
- Whether commits should be squashed or reorganized
|
||||
|
||||
### 4. Review the diff
|
||||
|
||||
```bash
|
||||
git diff origin/main..HEAD --stat
|
||||
```
|
||||
|
||||
This shows which files changed and helps identify the type of change.
|
||||
|
||||
## Information Gathering
|
||||
|
||||
Before creating the PR, you need the following information. Check if it can be inferred from:
|
||||
- Commit messages
|
||||
- Branch name (e.g., `fix/issue-123`, `feature/new-login`)
|
||||
- Changed files and their content
|
||||
|
||||
If any critical information is missing, use `ask_followup_question` to ask the user:
|
||||
|
||||
### Required Information
|
||||
|
||||
1. **Related Issue Number**: Look for patterns like `#123`, `fixes #123`, or `closes #123` in commit messages
|
||||
2. **Description**: What problem does this solve? Why were these changes made?
|
||||
3. **Type of Change**: Bug fix, new feature, breaking change, refactor, cosmetic, documentation, or workflow
|
||||
4. **Test Procedure**: How was this tested? What could break?
|
||||
|
||||
### Example clarifying question
|
||||
|
||||
If the issue number is not found:
|
||||
> I couldn't find a related issue number in the commit messages or branch name. What GitHub issue does this PR address? (Enter the issue number, e.g., "123" or "N/A" for small fixes)
|
||||
|
||||
## Git Best Practices
|
||||
|
||||
Before creating the PR, consider these best practices:
|
||||
|
||||
### Commit Hygiene
|
||||
|
||||
1. **Atomic commits**: Each commit should represent a single logical change
|
||||
2. **Clear commit messages**: Follow conventional commit format when possible
|
||||
3. **No merge commits**: Prefer rebasing over merging to keep history clean
|
||||
|
||||
### Branch Management
|
||||
|
||||
1. **Rebase on latest main** (if needed):
|
||||
```bash
|
||||
git fetch origin
|
||||
git rebase origin/main
|
||||
```
|
||||
|
||||
2. **Squash if appropriate**: If there are many small "WIP" commits, consider interactive rebase:
|
||||
```bash
|
||||
git rebase -i origin/main
|
||||
```
|
||||
Only suggest this if commits appear messy and the user is comfortable with rebasing.
|
||||
|
||||
### Push Changes
|
||||
|
||||
Ensure all commits are pushed:
|
||||
```bash
|
||||
git push origin HEAD
|
||||
```
|
||||
|
||||
If the branch was rebased, you may need:
|
||||
```bash
|
||||
git push origin HEAD --force-with-lease
|
||||
```
|
||||
|
||||
## Create the Pull Request
|
||||
|
||||
**IMPORTANT**: Read and use the PR template at `.github/pull_request_template.md`. The PR body format must **strictly match** the template structure. Do not deviate from the template format.
|
||||
|
||||
When filling out the template:
|
||||
- Replace `#XXXX` with the actual issue number, or keep as `#XXXX` if no issue exists (for small fixes)
|
||||
- Fill in all sections with relevant information gathered from commits and context
|
||||
- Mark the appropriate "Type of Change" checkbox(es)
|
||||
- Complete the "Pre-flight Checklist" items that apply
|
||||
|
||||
### Create PR with gh CLI
|
||||
|
||||
**Use a temporary file for the PR body** to avoid shell escaping issues, newline problems, and other command-line flakiness:
|
||||
|
||||
1. Write the PR body to a temporary file:
|
||||
```
|
||||
/tmp/pr-body.md
|
||||
```
|
||||
|
||||
2. Create the PR using the file:
|
||||
```bash
|
||||
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main
|
||||
```
|
||||
|
||||
3. Clean up the temporary file:
|
||||
```bash
|
||||
rm /tmp/pr-body.md
|
||||
```
|
||||
|
||||
For draft PRs:
|
||||
```bash
|
||||
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main --draft
|
||||
```
|
||||
|
||||
**Why use a file?** Passing complex markdown with newlines, special characters, and checkboxes directly via `--body` is error-prone. The `--body-file` flag handles all content reliably.
|
||||
|
||||
## Post-Creation
|
||||
|
||||
After creating the PR:
|
||||
|
||||
1. **Display the PR URL** so the user can review it
|
||||
2. **Remind about CI checks**: Tests and linting will run automatically
|
||||
3. **Suggest next steps**:
|
||||
- Add reviewers if needed: `gh pr edit --add-reviewer USERNAME`
|
||||
- Add labels if needed: `gh pr edit --add-label "bug"`
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **No commits ahead of main**: The branch has no changes to submit
|
||||
- Ask if the user meant to work on a different branch
|
||||
|
||||
2. **Branch not pushed**: Remote doesn't have the branch
|
||||
- Push the branch first: `git push -u origin HEAD`
|
||||
|
||||
3. **PR already exists**: A PR for this branch already exists
|
||||
- Show the existing PR: `gh pr view`
|
||||
- Ask if they want to update it instead
|
||||
|
||||
4. **Merge conflicts**: Branch conflicts with base
|
||||
- Guide user through resolving conflicts or rebasing
|
||||
|
||||
## Summary Checklist
|
||||
|
||||
Before finalizing, ensure:
|
||||
- [ ] `gh` CLI is installed and authenticated
|
||||
- [ ] Working directory is clean
|
||||
- [ ] All commits are pushed
|
||||
- [ ] Branch is up-to-date with base branch
|
||||
- [ ] Related issue number is identified, or placeholder is used
|
||||
- [ ] PR description follows the template exactly
|
||||
- [ ] Appropriate type of change is selected
|
||||
- [ ] Pre-flight checklist items are addressed
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
name: opentui
|
||||
description: Comprehensive OpenTUI skill for building terminal user interfaces. Covers the core imperative API, React reconciler, and Solid reconciler. Use for any TUI development task including components, layout, keyboard handling, animations, and testing.
|
||||
metadata:
|
||||
references: core, react, solid
|
||||
---
|
||||
|
||||
# OpenTUI Platform Skill
|
||||
|
||||
Consolidated skill for building terminal user interfaces with OpenTUI. Use decision trees below to find the right framework and components, then load detailed references.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
**Follow these rules in all OpenTUI code:**
|
||||
|
||||
1. **Use `create-tui` for new projects.** See framework `REFERENCE.md` quick starts.
|
||||
2. **`create-tui` options must come before arguments.** `bunx create-tui -t react my-app` works, `bunx create-tui my-app -t react` does NOT.
|
||||
3. **Never call `process.exit()` directly.** Use `renderer.destroy()` (see `core/gotchas.md`).
|
||||
4. **Text styling requires nested tags in React/Solid.** Use modifier elements, not props (see `components/text-display.md`).
|
||||
|
||||
## How to Use This Skill
|
||||
|
||||
### Reference File Structure
|
||||
|
||||
Framework references follow a 5-file pattern. Cross-cutting concepts are single-file guides.
|
||||
|
||||
Each framework in `./references/<framework>/` contains:
|
||||
|
||||
| File | Purpose | When to Read |
|
||||
|------|---------|--------------|
|
||||
| `REFERENCE.md` | Overview, when to use, quick start | **Always read first** |
|
||||
| `api.md` | Runtime API, components, hooks | Writing code |
|
||||
| `configuration.md` | Setup, tsconfig, bundling | Configuring a project |
|
||||
| `patterns.md` | Common patterns, best practices | Implementation guidance |
|
||||
| `gotchas.md` | Pitfalls, limitations, debugging | Troubleshooting |
|
||||
|
||||
Cross-cutting concepts in `./references/<concept>/` have `REFERENCE.md` as the entry point.
|
||||
|
||||
### Reading Order
|
||||
|
||||
1. Start with `REFERENCE.md` for your chosen framework
|
||||
2. Then read additional files relevant to your task:
|
||||
- Building components -> `api.md` + `components/<category>.md`
|
||||
- Setting up project -> `configuration.md`
|
||||
- Layout/positioning -> `layout/REFERENCE.md`
|
||||
- Keyboard/input handling -> `keyboard/REFERENCE.md`
|
||||
- Animations -> `animation/REFERENCE.md`
|
||||
- Troubleshooting -> `gotchas.md` + `testing/REFERENCE.md`
|
||||
|
||||
### Example Paths
|
||||
|
||||
```
|
||||
./references/react/REFERENCE.md # Start here for React
|
||||
./references/react/api.md # React components and hooks
|
||||
./references/solid/configuration.md # Solid project setup
|
||||
./references/components/inputs.md # Input, Textarea, Select docs
|
||||
./references/core/gotchas.md # Core debugging tips
|
||||
```
|
||||
|
||||
### Runtime Notes
|
||||
|
||||
OpenTUI runs on Bun and uses Zig for native builds. Read `./references/core/gotchas.md` for runtime requirements and build guidance.
|
||||
|
||||
## Quick Decision Trees
|
||||
|
||||
### "Which framework should I use?"
|
||||
|
||||
```
|
||||
Which framework?
|
||||
├─ I want full control, maximum performance, no framework overhead
|
||||
│ └─ core/ (imperative API)
|
||||
├─ I know React, want familiar component patterns
|
||||
│ └─ react/ (React reconciler)
|
||||
├─ I want fine-grained reactivity, optimal re-renders
|
||||
│ └─ solid/ (Solid reconciler)
|
||||
└─ I'm building a library/framework on top of OpenTUI
|
||||
└─ core/ (imperative API)
|
||||
```
|
||||
|
||||
### "I need to display content"
|
||||
|
||||
```
|
||||
Display content?
|
||||
├─ Plain or styled text -> components/text-display.md
|
||||
├─ Container with borders/background -> components/containers.md
|
||||
├─ Scrollable content area -> components/containers.md (scrollbox)
|
||||
├─ ASCII art banner/title -> components/text-display.md (ascii-font)
|
||||
├─ Data table with borders/wrapping -> components/code-diff.md (TextTable)
|
||||
├─ Code with syntax highlighting -> components/code-diff.md
|
||||
├─ Diff viewer (unified/split) -> components/code-diff.md
|
||||
├─ Line numbers with diagnostics -> components/code-diff.md
|
||||
└─ Markdown content (streaming) -> components/code-diff.md (markdown)
|
||||
```
|
||||
|
||||
### "I need user input"
|
||||
|
||||
```
|
||||
User input?
|
||||
├─ Single-line text field -> components/inputs.md (input)
|
||||
├─ Multi-line text editor -> components/inputs.md (textarea)
|
||||
├─ Select from a list (vertical) -> components/inputs.md (select)
|
||||
├─ Tab-based selection (horizontal) -> components/inputs.md (tab-select)
|
||||
└─ Custom keyboard shortcuts -> keyboard/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need layout/positioning"
|
||||
|
||||
```
|
||||
Layout?
|
||||
├─ Flexbox-style layouts (row, column, wrap) -> layout/REFERENCE.md
|
||||
├─ Absolute positioning -> layout/patterns.md
|
||||
├─ Responsive to terminal size -> layout/patterns.md
|
||||
├─ Centering content -> layout/patterns.md
|
||||
└─ Complex nested layouts -> layout/patterns.md
|
||||
```
|
||||
|
||||
### "I need animations"
|
||||
|
||||
```
|
||||
Animations?
|
||||
├─ Timeline-based animations -> animation/REFERENCE.md
|
||||
├─ Easing functions -> animation/REFERENCE.md
|
||||
├─ Property transitions -> animation/REFERENCE.md
|
||||
└─ Looping animations -> animation/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need to handle input"
|
||||
|
||||
```
|
||||
Input handling?
|
||||
├─ Keyboard events (keypress, release) -> keyboard/REFERENCE.md
|
||||
├─ Focus management -> keyboard/REFERENCE.md
|
||||
├─ Paste events -> keyboard/REFERENCE.md
|
||||
├─ Mouse events -> components/containers.md
|
||||
├─ Text selection & copy-on-select -> keyboard/REFERENCE.md (selection)
|
||||
└─ Clipboard (OSC 52) -> keyboard/REFERENCE.md (clipboard)
|
||||
```
|
||||
|
||||
### "I need to test my TUI"
|
||||
|
||||
```
|
||||
Testing?
|
||||
├─ Snapshot testing -> testing/REFERENCE.md
|
||||
├─ Interaction testing -> testing/REFERENCE.md
|
||||
├─ Test renderer setup -> testing/REFERENCE.md
|
||||
└─ Debugging tests -> testing/REFERENCE.md
|
||||
```
|
||||
|
||||
### "I need to debug/troubleshoot"
|
||||
|
||||
```
|
||||
Troubleshooting?
|
||||
├─ Runtime errors, crashes -> <framework>/gotchas.md
|
||||
├─ Layout issues -> layout/REFERENCE.md + layout/patterns.md
|
||||
├─ Input/focus issues -> keyboard/REFERENCE.md
|
||||
└─ Repro + regression tests -> testing/REFERENCE.md
|
||||
```
|
||||
|
||||
### Troubleshooting Index
|
||||
|
||||
- Terminal cleanup, crashes -> `core/gotchas.md`
|
||||
- Text styling not applying -> `components/text-display.md`
|
||||
- Input focus/shortcuts -> `keyboard/REFERENCE.md`
|
||||
- Layout misalignment -> `layout/REFERENCE.md`
|
||||
- Flaky snapshots -> `testing/REFERENCE.md`
|
||||
|
||||
For component naming differences and text modifiers, see `components/REFERENCE.md`.
|
||||
|
||||
## Product Index
|
||||
|
||||
### Frameworks
|
||||
| Framework | Entry File | Description |
|
||||
|-----------|------------|-------------|
|
||||
| Core | `./references/core/REFERENCE.md` | Imperative API, all primitives |
|
||||
| React | `./references/react/REFERENCE.md` | React reconciler for declarative TUI |
|
||||
| Solid | `./references/solid/REFERENCE.md` | SolidJS reconciler for declarative TUI |
|
||||
|
||||
### Cross-Cutting Concepts
|
||||
| Concept | Entry File | Description |
|
||||
|---------|------------|-------------|
|
||||
| Layout | `./references/layout/REFERENCE.md` | Yoga/Flexbox layout system |
|
||||
| Components | `./references/components/REFERENCE.md` | Component reference by category |
|
||||
| Keyboard | `./references/keyboard/REFERENCE.md` | Keyboard input handling |
|
||||
| Animation | `./references/animation/REFERENCE.md` | Timeline-based animations |
|
||||
| Testing | `./references/testing/REFERENCE.md` | Test renderer and snapshots |
|
||||
|
||||
### Component Categories
|
||||
| Category | Entry File | Components |
|
||||
|----------|------------|------------|
|
||||
| Text & Display | `./references/components/text-display.md` | text, ascii-font, styled text |
|
||||
| Containers | `./references/components/containers.md` | box, scrollbox, borders |
|
||||
| Inputs | `./references/components/inputs.md` | input, textarea, select, tab-select |
|
||||
| Code & Diff | `./references/components/code-diff.md` | code, line-number, diff, markdown, text-table |
|
||||
|
||||
## Resources
|
||||
|
||||
**Repository**: https://github.com/anomalyco/opentui
|
||||
**Core Docs**: https://github.com/anomalyco/opentui/tree/main/packages/core/docs
|
||||
**Examples**: https://github.com/anomalyco/opentui/tree/main/packages/core/src/examples
|
||||
**Awesome List**: https://github.com/msmps/awesome-opentui
|
||||
@@ -0,0 +1,431 @@
|
||||
# Animation System
|
||||
|
||||
OpenTUI provides a timeline-based animation system for smooth property transitions.
|
||||
|
||||
## Overview
|
||||
|
||||
Animations in OpenTUI use:
|
||||
- **Timeline**: Orchestrates multiple animations
|
||||
- **Animation Engine**: Manages timelines and rendering
|
||||
- **Easing Functions**: Control animation curves
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this reference when you need timeline-driven animations, easing curves, or progressive transitions.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### React
|
||||
|
||||
```tsx
|
||||
import { useTimeline } from "@opentui/react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
function AnimatedBox() {
|
||||
const [width, setWidth] = useState(0)
|
||||
|
||||
const timeline = useTimeline({
|
||||
duration: 2000,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ width: 0 },
|
||||
{
|
||||
width: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].width))
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<box
|
||||
width={width}
|
||||
height={3}
|
||||
backgroundColor="#6a5acd"
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Solid
|
||||
|
||||
```tsx
|
||||
import { useTimeline } from "@opentui/solid"
|
||||
import { createSignal, onMount } from "solid-js"
|
||||
|
||||
function AnimatedBox() {
|
||||
const [width, setWidth] = createSignal(0)
|
||||
|
||||
const timeline = useTimeline({
|
||||
duration: 2000,
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
timeline.add(
|
||||
{ width: 0 },
|
||||
{
|
||||
width: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].width))
|
||||
},
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
<box
|
||||
width={width()}
|
||||
height={3}
|
||||
backgroundColor="#6a5acd"
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Core
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, Timeline, engine } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
engine.attach(renderer)
|
||||
|
||||
const timeline = new Timeline({
|
||||
duration: 2000,
|
||||
autoplay: true,
|
||||
})
|
||||
|
||||
timeline.add(
|
||||
{ x: 0 },
|
||||
{
|
||||
x: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
box.setLeft(Math.round(anim.targets[0].x))
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
engine.addTimeline(timeline)
|
||||
```
|
||||
|
||||
## Timeline Options
|
||||
|
||||
```typescript
|
||||
const timeline = useTimeline({
|
||||
duration: 2000, // Total duration in ms
|
||||
loop: false, // Loop the timeline
|
||||
autoplay: true, // Start automatically
|
||||
onComplete: () => {}, // Called when timeline completes
|
||||
onPause: () => {}, // Called when timeline pauses
|
||||
})
|
||||
```
|
||||
|
||||
## Timeline Methods
|
||||
|
||||
```typescript
|
||||
// Add animation
|
||||
timeline.add(target, properties, startTime?)
|
||||
|
||||
// Control playback
|
||||
timeline.play() // Start/resume
|
||||
timeline.pause() // Pause
|
||||
timeline.restart() // Restart from beginning
|
||||
|
||||
// State
|
||||
timeline.progress // Current progress (0-1)
|
||||
timeline.duration // Total duration
|
||||
```
|
||||
|
||||
## Animation Properties
|
||||
|
||||
```typescript
|
||||
timeline.add(
|
||||
{ value: 0 }, // Target object with initial values
|
||||
{
|
||||
value: 100, // Final value
|
||||
duration: 1000, // Animation duration in ms
|
||||
ease: "linear", // Easing function
|
||||
delay: 0, // Delay before starting
|
||||
onUpdate: (anim) => {
|
||||
// Called each frame
|
||||
const current = anim.targets[0].value
|
||||
},
|
||||
onComplete: () => {
|
||||
// Called when this animation completes
|
||||
},
|
||||
},
|
||||
0 // Start time in timeline (optional)
|
||||
)
|
||||
```
|
||||
|
||||
## Easing Functions
|
||||
|
||||
Available easing functions:
|
||||
|
||||
### Linear
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `linear` | Constant speed |
|
||||
|
||||
### Quad (Power of 2)
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInQuad` | Slow start |
|
||||
| `easeOutQuad` | Slow end |
|
||||
| `easeInOutQuad` | Slow start and end |
|
||||
|
||||
### Cubic (Power of 3)
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInCubic` | Slower start |
|
||||
| `easeOutCubic` | Slower end |
|
||||
| `easeInOutCubic` | Slower start and end |
|
||||
|
||||
### Quart (Power of 4)
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInQuart` | Even slower start |
|
||||
| `easeOutQuart` | Even slower end |
|
||||
| `easeInOutQuart` | Even slower start and end |
|
||||
|
||||
### Expo (Exponential)
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInExpo` | Exponential start |
|
||||
| `easeOutExpo` | Exponential end |
|
||||
| `easeInOutExpo` | Exponential start and end |
|
||||
|
||||
### Back (Overshoot)
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInBack` | Pull back, then forward |
|
||||
| `easeOutBack` | Overshoot, then settle |
|
||||
| `easeInOutBack` | Both |
|
||||
|
||||
### Elastic
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInElastic` | Elastic start |
|
||||
| `easeOutElastic` | Elastic end (bouncy) |
|
||||
| `easeInOutElastic` | Both |
|
||||
|
||||
### Bounce
|
||||
|
||||
| Name | Description |
|
||||
|------|-------------|
|
||||
| `easeInBounce` | Bounce at start |
|
||||
| `easeOutBounce` | Bounce at end |
|
||||
| `easeInOutBounce` | Both |
|
||||
|
||||
## Patterns
|
||||
|
||||
### Progress Bar
|
||||
|
||||
```tsx
|
||||
function ProgressBar({ progress }: { progress: number }) {
|
||||
const [width, setWidth] = useState(0)
|
||||
const maxWidth = 50
|
||||
|
||||
const timeline = useTimeline()
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ value: width },
|
||||
{
|
||||
value: (progress / 100) * maxWidth,
|
||||
duration: 300,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].value))
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [progress])
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text>Progress: {progress}%</text>
|
||||
<box width={maxWidth} height={1} backgroundColor="#333">
|
||||
<box width={width} height={1} backgroundColor="#00FF00" />
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Fade In
|
||||
|
||||
```tsx
|
||||
function FadeIn({ children }) {
|
||||
const [opacity, setOpacity] = useState(0)
|
||||
|
||||
const timeline = useTimeline()
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ opacity: 0 },
|
||||
{
|
||||
opacity: 1,
|
||||
duration: 500,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setOpacity(anim.targets[0].opacity)
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<box style={{ opacity }}>
|
||||
{children}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Looping Animation
|
||||
|
||||
```tsx
|
||||
function Spinner() {
|
||||
const [frame, setFrame] = useState(0)
|
||||
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setFrame(f => (f + 1) % frames.length)
|
||||
}, 80)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
return <text>{frames[frame]} Loading...</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Staggered Animation
|
||||
|
||||
```tsx
|
||||
function StaggeredList({ items }) {
|
||||
const [visibleCount, setVisibleCount] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let count = 0
|
||||
const interval = setInterval(() => {
|
||||
count++
|
||||
setVisibleCount(count)
|
||||
if (count >= items.length) {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, 100)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [items.length])
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
{items.slice(0, visibleCount).map((item, i) => (
|
||||
<text key={i}>{item}</text>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Slide In
|
||||
|
||||
```tsx
|
||||
function SlideIn({ children, from = "left" }) {
|
||||
const [offset, setOffset] = useState(from === "left" ? -20 : 20)
|
||||
|
||||
const timeline = useTimeline()
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ offset: from === "left" ? -20 : 20 },
|
||||
{
|
||||
offset: 0,
|
||||
duration: 300,
|
||||
ease: "easeOutCubic",
|
||||
onUpdate: (anim) => {
|
||||
setOffset(Math.round(anim.targets[0].offset))
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<box position="relative" left={offset}>
|
||||
{children}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Tips
|
||||
|
||||
### Batch Updates
|
||||
|
||||
Timeline automatically batches updates within the render loop.
|
||||
|
||||
### Use Integer Values
|
||||
|
||||
Round animated values for character-based positioning:
|
||||
|
||||
```typescript
|
||||
onUpdate: (anim) => {
|
||||
setX(Math.round(anim.targets[0].x))
|
||||
}
|
||||
```
|
||||
|
||||
### Clean Up Timelines
|
||||
|
||||
Hooks automatically clean up, but for core:
|
||||
|
||||
```typescript
|
||||
// When done with timeline
|
||||
engine.removeTimeline(timeline)
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Terminal Refresh Rate
|
||||
|
||||
Terminal UIs typically refresh at 60 FPS max. Very fast animations may appear choppy.
|
||||
|
||||
### Character Grid
|
||||
|
||||
Animations are constrained to character cells. Sub-pixel positioning isn't possible.
|
||||
|
||||
### Cleanup in Effects
|
||||
|
||||
Always clean up intervals and timelines:
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
const interval = setInterval(...)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [React API](../react/api.md) - `useTimeline` hook reference
|
||||
- [Solid API](../solid/api.md) - `useTimeline` hook reference
|
||||
- [Core API](../core/api.md) - `AnimationEngine` and `Timeline` classes
|
||||
- [Layout Patterns](../layout/patterns.md) - Animated positioning and transitions
|
||||
@@ -0,0 +1,144 @@
|
||||
# OpenTUI Components
|
||||
|
||||
Reference for all OpenTUI components, organized by category. Components are available in all three frameworks (Core, React, Solid) with slight API differences.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this reference when you need to find the right component category or compare naming across Core, React, and Solid.
|
||||
|
||||
## Component Categories
|
||||
|
||||
| Category | Components | File |
|
||||
|----------|------------|------|
|
||||
| Text & Display | text, ascii-font, styled text | [text-display.md](./text-display.md) |
|
||||
| Containers | box, scrollbox, borders | [containers.md](./containers.md) |
|
||||
| Inputs | input, textarea, select, tab-select | [inputs.md](./inputs.md) |
|
||||
| Code & Diff | code, line-number, diff, markdown, text-table | [code-diff.md](./code-diff.md) |
|
||||
|
||||
## Component Chooser
|
||||
|
||||
```
|
||||
Need a component?
|
||||
├─ Styled text or ASCII art -> text-display.md
|
||||
├─ Containers, borders, scrolling -> containers.md
|
||||
├─ Forms or input controls -> inputs.md
|
||||
└─ Code blocks, diffs, line numbers, markdown -> code-diff.md
|
||||
```
|
||||
|
||||
## Component Naming
|
||||
|
||||
Components have different names across frameworks:
|
||||
|
||||
| Concept | Core (Class) | React (JSX) | Solid (JSX) |
|
||||
|---------|--------------|-------------|-------------|
|
||||
| Text | `TextRenderable` | `<text>` | `<text>` |
|
||||
| Box | `BoxRenderable` | `<box>` | `<box>` |
|
||||
| ScrollBox | `ScrollBoxRenderable` | `<scrollbox>` | `<scrollbox>` |
|
||||
| Input | `InputRenderable` | `<input>` | `<input>` |
|
||||
| Textarea | `TextareaRenderable` | `<textarea>` | `<textarea>` |
|
||||
| Select | `SelectRenderable` | `<select>` | `<select>` |
|
||||
| Tab Select | `TabSelectRenderable` | `<tab-select>` | `<tab_select>` |
|
||||
| ASCII Font | `ASCIIFontRenderable` | `<ascii-font>` | `<ascii_font>` |
|
||||
| Code | `CodeRenderable` | `<code>` | `<code>` |
|
||||
| Line Number | `LineNumberRenderable` | `<line-number>` | `<line_number>` |
|
||||
| Diff | `DiffRenderable` | `<diff>` | `<diff>` |
|
||||
| Markdown | `MarkdownRenderable` | `<markdown>` | `<markdown>` |
|
||||
| TextTable | `TextTableRenderable` | N/A (Core only) | N/A (Core only) |
|
||||
|
||||
**Note**: Solid uses underscores (`tab_select`) while React uses hyphens (`tab-select`). `TextTableRenderable` is used internally by `MarkdownRenderable` for table rendering and is also available as a standalone Core component.
|
||||
|
||||
## Common Properties
|
||||
|
||||
All components share these layout properties (see [Layout](../layout/REFERENCE.md)):
|
||||
|
||||
```tsx
|
||||
// Positioning
|
||||
position="relative" | "absolute"
|
||||
left, top, right, bottom
|
||||
|
||||
// Dimensions
|
||||
width, height
|
||||
minWidth, maxWidth, minHeight, maxHeight
|
||||
|
||||
// Flexbox
|
||||
flexDirection, flexGrow, flexShrink, flexBasis
|
||||
justifyContent, alignItems, alignSelf
|
||||
flexWrap, gap
|
||||
|
||||
// Spacing
|
||||
padding, paddingTop, paddingRight, paddingBottom, paddingLeft
|
||||
paddingX, paddingY // Axis shorthand (horizontal/vertical)
|
||||
margin, marginTop, marginRight, marginBottom, marginLeft
|
||||
marginX, marginY // Axis shorthand (horizontal/vertical)
|
||||
|
||||
// Display
|
||||
display="flex" | "none"
|
||||
overflow="visible" | "hidden" | "scroll"
|
||||
zIndex
|
||||
```
|
||||
|
||||
## Quick Examples
|
||||
|
||||
### Core (Imperative)
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, TextRenderable, BoxRenderable } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
const box = new BoxRenderable(renderer, {
|
||||
id: "container",
|
||||
border: true,
|
||||
padding: 2,
|
||||
})
|
||||
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: "greeting",
|
||||
content: "Hello!",
|
||||
fg: "#00FF00",
|
||||
})
|
||||
|
||||
box.add(text)
|
||||
renderer.root.add(box)
|
||||
```
|
||||
|
||||
### React
|
||||
|
||||
```tsx
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
import { createRoot } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<box border padding={2}>
|
||||
<text fg="#00FF00">Hello!</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
createRoot(renderer).render(<App />)
|
||||
```
|
||||
|
||||
### Solid
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<box border padding={2}>
|
||||
<text fg="#00FF00">Hello!</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
render(() => <App />)
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [Core API](../core/api.md) - Imperative component classes
|
||||
- [React API](../react/api.md) - React component props
|
||||
- [Solid API](../solid/api.md) - Solid component props
|
||||
- [Layout](../layout/REFERENCE.md) - Layout system details
|
||||
@@ -0,0 +1,672 @@
|
||||
# Code & Diff Components
|
||||
|
||||
Components for displaying code with syntax highlighting and diffs in OpenTUI.
|
||||
|
||||
## Code Component
|
||||
|
||||
Display syntax-highlighted code blocks.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<code
|
||||
code={`function hello() {
|
||||
console.log("Hello, World!");
|
||||
}`}
|
||||
language="typescript"
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="javascript"
|
||||
/>
|
||||
|
||||
// Core
|
||||
const codeBlock = new CodeRenderable(renderer, {
|
||||
id: "code",
|
||||
code: sourceCode,
|
||||
language: "typescript",
|
||||
})
|
||||
```
|
||||
|
||||
### Supported Languages
|
||||
|
||||
OpenTUI uses Tree-sitter for syntax highlighting. Common languages:
|
||||
- `typescript`, `javascript`
|
||||
- `python`
|
||||
- `rust`
|
||||
- `go`
|
||||
- `json`
|
||||
- `html`, `css`
|
||||
- `markdown`
|
||||
- `bash`, `shell`
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
backgroundColor="#1a1a2e"
|
||||
showLineNumbers
|
||||
/>
|
||||
```
|
||||
|
||||
### onHighlight Callback
|
||||
|
||||
Intercept and modify syntax highlights before rendering:
|
||||
|
||||
```tsx
|
||||
// Core
|
||||
const codeBlock = new CodeRenderable(renderer, {
|
||||
id: "code",
|
||||
code: sourceCode,
|
||||
language: "typescript",
|
||||
onHighlight: (highlights, context) => {
|
||||
// Add custom highlights
|
||||
highlights.push([10, 20, "custom.error", {}])
|
||||
return highlights
|
||||
},
|
||||
})
|
||||
|
||||
// React/Solid
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
onHighlight={(highlights, context) => {
|
||||
// context: { content, filetype, syntaxStyle }
|
||||
// Modify and return highlights array
|
||||
return highlights.filter(h => h[2] !== "comment")
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
**Callback signature:**
|
||||
- `highlights: SimpleHighlight[]` - Array of `[start, end, scope, metadata]`
|
||||
- `context: { content, filetype, syntaxStyle }` - Highlighting context
|
||||
- Return modified highlights array or `undefined` to use original
|
||||
|
||||
Supports async callbacks for fetching additional highlight data.
|
||||
|
||||
### onChunks Callback
|
||||
|
||||
Post-process rendered text chunks after syntax highlighting. Runs after `onHighlight` and receives fully resolved chunks:
|
||||
|
||||
```tsx
|
||||
// Core
|
||||
const codeBlock = new CodeRenderable(renderer, {
|
||||
id: "code",
|
||||
code: sourceCode,
|
||||
language: "typescript",
|
||||
onChunks: (chunks, context) => {
|
||||
// Transform chunks (e.g., add link detection)
|
||||
return chunks
|
||||
},
|
||||
})
|
||||
|
||||
// React/Solid
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
onChunks={(chunks, context) => {
|
||||
// context: { content, filetype, syntaxStyle, highlights }
|
||||
return chunks
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Link Detection Utility
|
||||
|
||||
Auto-detect URLs in code and add clickable hyperlinks:
|
||||
|
||||
```typescript
|
||||
import { detectLinks } from "@opentui/core"
|
||||
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
onChunks={(chunks, context) => detectLinks(chunks, context)}
|
||||
/>
|
||||
```
|
||||
|
||||
`detectLinks` examines Tree-sitter highlights to find URL tokens and sets `chunk.link` on matching chunks. Supports async usage.
|
||||
|
||||
## TextTable Component
|
||||
|
||||
Render data tables with borders, word wrapping, and selection support.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```typescript
|
||||
// Core
|
||||
import { TextTableRenderable, type TextTableContent } from "@opentui/core"
|
||||
|
||||
const content: TextTableContent = [
|
||||
[[ { text: "Name" } ], [ { text: "Age" } ], [ { text: "Role" } ]],
|
||||
[[ { text: "Alice" } ], [ { text: "30" } ], [ { text: "Engineer" } ]],
|
||||
[[ { text: "Bob" } ], [ { text: "25" } ], [ { text: "Designer" } ]],
|
||||
]
|
||||
|
||||
const table = new TextTableRenderable(renderer, {
|
||||
id: "table",
|
||||
content,
|
||||
wrapMode: "word", // "none" | "char" | "word"
|
||||
columnWidthMode: "content", // "content" | "fill"
|
||||
cellPadding: 0,
|
||||
border: true,
|
||||
outerBorder: true,
|
||||
borderStyle: "single", // single | double | rounded | bold
|
||||
selectable: true, // Allow text selection
|
||||
columnFitter: "balanced", // "proportional" | "balanced"
|
||||
})
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `content` | `TextTableContent` | - | 2D array of cell content |
|
||||
| `wrapMode` | `"none" \| "char" \| "word"` | `"none"` | Text wrapping in cells |
|
||||
| `columnWidthMode` | `"content" \| "fill"` | `"content"` | Column sizing strategy |
|
||||
| `cellPadding` | `number` | `0` | Padding inside cells |
|
||||
| `border` | `boolean` | `true` | Show inner borders |
|
||||
| `outerBorder` | `boolean` | `true` | Show outer borders |
|
||||
| `borderStyle` | `string` | `"single"` | Border style |
|
||||
| `borderColor` | `string \| RGBA` | - | Border color |
|
||||
| `selectable` | `boolean` | `false` | Allow text selection |
|
||||
| `columnFitter` | `"proportional" \| "balanced"` | `"proportional"` | Column width distribution |
|
||||
|
||||
### Cell Content Format
|
||||
|
||||
Each cell is an array of styled text chunks:
|
||||
|
||||
```typescript
|
||||
type TextTableCellContent = { text: string; fg?: RGBA; bg?: RGBA }[]
|
||||
type TextTableContent = TextTableCellContent[][] // rows -> cells -> chunks
|
||||
```
|
||||
|
||||
### Selection
|
||||
|
||||
```typescript
|
||||
table.getSelectedText() // Get selected text
|
||||
table.hasSelection() // Check if text is selected
|
||||
```
|
||||
|
||||
Columnar selection is supported: dragging vertically within a single column selects only that column's content.
|
||||
|
||||
## Line Number Component
|
||||
|
||||
Code display with line numbers, highlighting, and diagnostics.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
/>
|
||||
|
||||
// Solid (note underscore)
|
||||
<line_number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
/>
|
||||
|
||||
// Core
|
||||
const codeView = new LineNumberRenderable(renderer, {
|
||||
id: "code-view",
|
||||
code: sourceCode,
|
||||
language: "typescript",
|
||||
})
|
||||
```
|
||||
|
||||
### Line Number Options
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
startLine={1} // Starting line number
|
||||
showLineNumbers={true} // Display line numbers
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<line_number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
startLine={1}
|
||||
showLineNumbers={true}
|
||||
/>
|
||||
```
|
||||
|
||||
### Line Highlighting
|
||||
|
||||
Highlight specific lines:
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
highlightedLines={[5, 10, 15]} // Highlight these lines
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<line_number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
highlightedLines={[5, 10, 15]}
|
||||
/>
|
||||
```
|
||||
|
||||
### Diagnostics
|
||||
|
||||
Show errors, warnings, and info on specific lines:
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
diagnostics={[
|
||||
{ line: 3, severity: "error", message: "Unexpected token" },
|
||||
{ line: 7, severity: "warning", message: "Unused variable" },
|
||||
{ line: 12, severity: "info", message: "Consider using const" },
|
||||
]}
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<line_number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
diagnostics={[
|
||||
{ line: 3, severity: "error", message: "Unexpected token" },
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
**Diagnostic severity levels:**
|
||||
- `error` - Red indicator
|
||||
- `warning` - Yellow indicator
|
||||
- `info` - Blue indicator
|
||||
- `hint` - Gray indicator
|
||||
|
||||
### Diff Highlighting
|
||||
|
||||
Show added/removed lines:
|
||||
|
||||
```tsx
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
addedLines={[5, 6, 7]} // Green background
|
||||
removedLines={[10, 11]} // Red background
|
||||
/>
|
||||
```
|
||||
|
||||
## Diff Component
|
||||
|
||||
Unified or split diff viewer with syntax highlighting.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<diff
|
||||
oldCode={originalCode}
|
||||
newCode={modifiedCode}
|
||||
language="typescript"
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<diff
|
||||
oldCode={originalCode}
|
||||
newCode={modifiedCode}
|
||||
language="typescript"
|
||||
/>
|
||||
|
||||
// Core
|
||||
const diffView = new DiffRenderable(renderer, {
|
||||
id: "diff",
|
||||
oldCode: originalCode,
|
||||
newCode: modifiedCode,
|
||||
language: "typescript",
|
||||
})
|
||||
```
|
||||
|
||||
### Display Modes
|
||||
|
||||
```tsx
|
||||
// Unified diff (default)
|
||||
<diff
|
||||
oldCode={old}
|
||||
newCode={new}
|
||||
mode="unified"
|
||||
/>
|
||||
|
||||
// Split/side-by-side diff
|
||||
<diff
|
||||
oldCode={old}
|
||||
newCode={new}
|
||||
mode="split"
|
||||
/>
|
||||
```
|
||||
|
||||
### Synchronized Scrolling (Split View)
|
||||
|
||||
In split view, enable synchronized scrolling between left and right panes:
|
||||
|
||||
```tsx
|
||||
// React/Solid
|
||||
<diff
|
||||
oldCode={old}
|
||||
newCode={new}
|
||||
mode="split"
|
||||
syncScroll // Scrolling one pane syncs the other
|
||||
/>
|
||||
|
||||
// Core
|
||||
const diffView = new DiffRenderable(renderer, {
|
||||
id: "diff",
|
||||
diff: unifiedDiff,
|
||||
view: "split",
|
||||
syncScroll: true,
|
||||
})
|
||||
|
||||
// Toggle at runtime
|
||||
diffView.syncScroll = true
|
||||
diffView.syncScroll = false
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
```tsx
|
||||
<diff
|
||||
oldCode={originalCode}
|
||||
newCode={modifiedCode}
|
||||
language="typescript"
|
||||
mode="unified"
|
||||
showLineNumbers
|
||||
context={3} // Lines of context around changes
|
||||
/>
|
||||
```
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
<diff
|
||||
oldCode={old}
|
||||
newCode={new}
|
||||
addedLineColor="#2d4f2d" // Background for added lines
|
||||
removedLineColor="#4f2d2d" // Background for removed lines
|
||||
unchangedLineColor="transparent"
|
||||
/>
|
||||
```
|
||||
|
||||
### Line Highlighting API (Core)
|
||||
|
||||
Programmatically highlight specific lines in a diff:
|
||||
|
||||
```typescript
|
||||
// Set a single line's color
|
||||
diffView.setLineColor(5, "#2d4f2d")
|
||||
diffView.setLineColor(5, { gutter: "#333", content: "#2d4f2d" })
|
||||
|
||||
// Clear a single line's color
|
||||
diffView.clearLineColor(5)
|
||||
|
||||
// Set multiple lines at once
|
||||
diffView.setLineColors(new Map([
|
||||
[1, "#2d4f2d"],
|
||||
[2, "#4f2d2d"],
|
||||
]))
|
||||
|
||||
// Highlight a range
|
||||
diffView.highlightLines(10, 20, "#2d4f2d")
|
||||
diffView.clearHighlightLines(10, 20)
|
||||
|
||||
// Clear all line colors
|
||||
diffView.clearAllLineColors()
|
||||
```
|
||||
|
||||
The `LineNumberRenderable` also supports programmatic highlighting:
|
||||
|
||||
```typescript
|
||||
lineNumberView.highlightLines(5, 10, "#2d4f2d")
|
||||
lineNumberView.clearHighlightLines(5, 10)
|
||||
```
|
||||
```
|
||||
|
||||
## Markdown Component
|
||||
|
||||
Render markdown content with syntax highlighting for code blocks.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<markdown
|
||||
content={markdownText}
|
||||
syntaxStyle={mySyntaxStyle}
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<markdown
|
||||
content={markdownText}
|
||||
syntaxStyle={mySyntaxStyle}
|
||||
/>
|
||||
|
||||
// Core
|
||||
import { MarkdownRenderable } from "@opentui/core"
|
||||
|
||||
const md = new MarkdownRenderable(renderer, {
|
||||
id: "markdown",
|
||||
content: "# Hello\n\nThis is **markdown**.",
|
||||
syntaxStyle: mySyntaxStyle,
|
||||
})
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
```tsx
|
||||
<markdown
|
||||
content={markdownText}
|
||||
syntaxStyle={syntaxStyle}
|
||||
treeSitterClient={client} // Optional: custom tree-sitter client
|
||||
conceal={true} // Hide markdown syntax characters
|
||||
streaming={true} // Enable streaming mode for incremental updates
|
||||
tableOptions={{ // Customize markdown table rendering
|
||||
widthMode: "full", // "content" | "full"
|
||||
wrapMode: "word", // "none" | "char" | "word"
|
||||
cellPadding: 0,
|
||||
borders: true,
|
||||
outerBorder: true,
|
||||
borderStyle: "single",
|
||||
borderColor: "#555",
|
||||
selectable: true, // Tables are selectable by default
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Custom Node Rendering
|
||||
|
||||
```tsx
|
||||
// Core
|
||||
const md = new MarkdownRenderable(renderer, {
|
||||
id: "markdown",
|
||||
content: "# Custom Heading",
|
||||
syntaxStyle,
|
||||
renderNode: (node, ctx, defaultRender) => {
|
||||
if (node.type === "heading") {
|
||||
// Return custom renderable for headings
|
||||
return new TextRenderable(ctx, {
|
||||
content: `>> ${node.content} <<`,
|
||||
})
|
||||
}
|
||||
return null // Use default rendering
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Streaming Mode
|
||||
|
||||
For real-time content like LLM output:
|
||||
|
||||
```tsx
|
||||
const [content, setContent] = useState("")
|
||||
|
||||
// Append text as it arrives
|
||||
useEffect(() => {
|
||||
llmStream.on("token", (token) => {
|
||||
setContent(c => c + token)
|
||||
})
|
||||
}, [])
|
||||
|
||||
<markdown
|
||||
content={content}
|
||||
syntaxStyle={syntaxStyle}
|
||||
streaming={true} // Optimizes for incremental updates
|
||||
/>
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
### Code Editor
|
||||
|
||||
```tsx
|
||||
function CodeEditor() {
|
||||
const [code, setCode] = useState(`function hello() {
|
||||
console.log("Hello!");
|
||||
}`)
|
||||
|
||||
return (
|
||||
<box flexDirection="column" height="100%">
|
||||
<box height={1}>
|
||||
<text>editor.ts</text>
|
||||
</box>
|
||||
<textarea
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
language="typescript"
|
||||
showLineNumbers
|
||||
flexGrow={1}
|
||||
focused
|
||||
/>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Code Review
|
||||
|
||||
```tsx
|
||||
function CodeReview({ oldCode, newCode }) {
|
||||
return (
|
||||
<box flexDirection="column" height="100%">
|
||||
<box height={1} backgroundColor="#333">
|
||||
<text>Changes in src/utils.ts</text>
|
||||
</box>
|
||||
<diff
|
||||
oldCode={oldCode}
|
||||
newCode={newCode}
|
||||
language="typescript"
|
||||
mode="split"
|
||||
showLineNumbers
|
||||
/>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Syntax-Highlighted Preview
|
||||
|
||||
```tsx
|
||||
function MarkdownPreview({ content }) {
|
||||
// Extract code blocks from markdown
|
||||
const codeBlocks = extractCodeBlocks(content)
|
||||
|
||||
return (
|
||||
<scrollbox height={20}>
|
||||
{codeBlocks.map((block, i) => (
|
||||
<box key={i} marginBottom={1}>
|
||||
<code
|
||||
code={block.code}
|
||||
language={block.language}
|
||||
/>
|
||||
</box>
|
||||
))}
|
||||
</scrollbox>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Error Display
|
||||
|
||||
```tsx
|
||||
function ErrorView({ errors, code }) {
|
||||
const diagnostics = errors.map(err => ({
|
||||
line: err.line,
|
||||
severity: "error",
|
||||
message: err.message,
|
||||
}))
|
||||
|
||||
return (
|
||||
<line-number
|
||||
code={code}
|
||||
language="typescript"
|
||||
diagnostics={diagnostics}
|
||||
highlightedLines={errors.map(e => e.line)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Solid Uses Underscores
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<line-number />
|
||||
|
||||
// Solid
|
||||
<line_number />
|
||||
```
|
||||
|
||||
### Language Required for Highlighting
|
||||
|
||||
```tsx
|
||||
// No highlighting (plain text)
|
||||
<code code={text} />
|
||||
|
||||
// With highlighting
|
||||
<code code={text} language="typescript" />
|
||||
```
|
||||
|
||||
### Large Files
|
||||
|
||||
For very large files, consider:
|
||||
- Pagination or virtual scrolling
|
||||
- Loading only visible portion
|
||||
- Using `scrollbox` wrapper
|
||||
|
||||
```tsx
|
||||
<scrollbox height={30}>
|
||||
<line-number
|
||||
code={largeFile}
|
||||
language="typescript"
|
||||
/>
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Tree-sitter Loading
|
||||
|
||||
Syntax highlighting requires Tree-sitter grammars. If highlighting isn't working:
|
||||
|
||||
1. Check the language is supported
|
||||
2. Verify grammars are installed
|
||||
3. Check `OTUI_TREE_SITTER_WORKER_PATH` if using custom path
|
||||
@@ -0,0 +1,417 @@
|
||||
# Container Components
|
||||
|
||||
Components for grouping and organizing content in OpenTUI.
|
||||
|
||||
## Box Component
|
||||
|
||||
The primary container component with borders, backgrounds, and layout capabilities.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React/Solid
|
||||
<box>
|
||||
<text>Content inside box</text>
|
||||
</box>
|
||||
|
||||
// Core
|
||||
const box = new BoxRenderable(renderer, {
|
||||
id: "container",
|
||||
})
|
||||
box.add(child)
|
||||
```
|
||||
|
||||
### Borders
|
||||
|
||||
```tsx
|
||||
<box border>
|
||||
Simple border
|
||||
</box>
|
||||
|
||||
<box
|
||||
border
|
||||
borderStyle="single" // single | double | rounded | bold | none
|
||||
borderColor="#FFFFFF"
|
||||
>
|
||||
Styled border
|
||||
</box>
|
||||
|
||||
// Individual borders
|
||||
<box
|
||||
borderTop
|
||||
borderBottom
|
||||
borderLeft={false}
|
||||
borderRight={false}
|
||||
>
|
||||
Top and bottom only
|
||||
</box>
|
||||
```
|
||||
|
||||
**Border Styles:**
|
||||
|
||||
| Style | Appearance |
|
||||
|-------|------------|
|
||||
| `single` | `┌─┐│ │└─┘` |
|
||||
| `double` | `╔═╗║ ║╚═╝` |
|
||||
| `rounded` | `╭─╮│ │╰─╯` |
|
||||
| `bold` | `┏━┓┃ ┃┗━┛` |
|
||||
|
||||
### Title
|
||||
|
||||
```tsx
|
||||
<box
|
||||
border
|
||||
title="Settings"
|
||||
titleAlignment="center" // left | center | right
|
||||
>
|
||||
Panel content
|
||||
</box>
|
||||
```
|
||||
|
||||
### Background
|
||||
|
||||
```tsx
|
||||
<box backgroundColor="#1a1a2e">
|
||||
Dark background
|
||||
</box>
|
||||
|
||||
<box backgroundColor="transparent">
|
||||
No background
|
||||
</box>
|
||||
```
|
||||
|
||||
### Layout
|
||||
|
||||
Boxes are flex containers by default:
|
||||
|
||||
```tsx
|
||||
<box
|
||||
flexDirection="row" // row | column | row-reverse | column-reverse
|
||||
justifyContent="center" // flex-start | flex-end | center | space-between | space-around
|
||||
alignItems="center" // flex-start | flex-end | center | stretch | baseline
|
||||
gap={2} // Space between children
|
||||
>
|
||||
<text>Item 1</text>
|
||||
<text>Item 2</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Spacing
|
||||
|
||||
```tsx
|
||||
<box
|
||||
padding={2} // All sides
|
||||
paddingTop={1}
|
||||
paddingRight={2}
|
||||
paddingBottom={1}
|
||||
paddingLeft={2}
|
||||
paddingX={2} // Horizontal (left + right)
|
||||
paddingY={1} // Vertical (top + bottom)
|
||||
margin={1}
|
||||
marginTop={1}
|
||||
marginX={2} // Horizontal (left + right)
|
||||
marginY={1} // Vertical (top + bottom)
|
||||
>
|
||||
Spaced content
|
||||
</box>
|
||||
```
|
||||
|
||||
### Dimensions
|
||||
|
||||
```tsx
|
||||
<box
|
||||
width={40} // Fixed width
|
||||
height={10} // Fixed height
|
||||
width="50%" // Percentage of parent
|
||||
minWidth={20} // Minimum width
|
||||
maxWidth={80} // Maximum width
|
||||
flexGrow={1} // Grow to fill space
|
||||
>
|
||||
Sized box
|
||||
</box>
|
||||
```
|
||||
|
||||
### Mouse Events
|
||||
|
||||
```tsx
|
||||
<box
|
||||
onMouseDown={(event) => {
|
||||
console.log("Clicked at:", event.x, event.y)
|
||||
}}
|
||||
onMouseUp={(event) => {}}
|
||||
onMouseMove={(event) => {}}
|
||||
>
|
||||
Clickable box
|
||||
</box>
|
||||
```
|
||||
|
||||
### Focusable Boxes
|
||||
|
||||
By default, Box elements are not focusable. Set the `focusable` prop to enable focus behavior:
|
||||
|
||||
```tsx
|
||||
// Make a box focusable - it can receive focus via mouse click
|
||||
<box focusable border>
|
||||
<text>Click to focus</text>
|
||||
</box>
|
||||
|
||||
// Controlled focus state
|
||||
const [focused, setFocused] = useState(false)
|
||||
|
||||
<box
|
||||
focusable
|
||||
focused={focused}
|
||||
border
|
||||
borderColor={focused ? "#00ff00" : "#888"}
|
||||
>
|
||||
<text>{focused ? "Focused!" : "Not focused"}</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
When a focusable Box is clicked, focus bubbles up from the click target to the nearest focusable parent. Use `event.preventDefault()` in `onMouseDown` to prevent auto-focus.
|
||||
|
||||
## ScrollBox Component
|
||||
|
||||
A scrollable container for content that exceeds the viewport.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<scrollbox height={10}>
|
||||
{items.map((item, i) => (
|
||||
<text key={i}>{item}</text>
|
||||
))}
|
||||
</scrollbox>
|
||||
|
||||
// Solid
|
||||
<scrollbox height={10}>
|
||||
<For each={items()}>
|
||||
{(item) => <text>{item}</text>}
|
||||
</For>
|
||||
</scrollbox>
|
||||
|
||||
// Core
|
||||
const scrollbox = new ScrollBoxRenderable(renderer, {
|
||||
id: "list",
|
||||
height: 10,
|
||||
})
|
||||
items.forEach(item => {
|
||||
scrollbox.add(new TextRenderable(renderer, { content: item }))
|
||||
})
|
||||
```
|
||||
|
||||
### Focus for Keyboard Scrolling
|
||||
|
||||
```tsx
|
||||
<scrollbox focused height={20}>
|
||||
{/* Use arrow keys to scroll */}
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Scrollbar Styling
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<scrollbox
|
||||
style={{
|
||||
rootOptions: {
|
||||
backgroundColor: "#24283b",
|
||||
},
|
||||
wrapperOptions: {
|
||||
backgroundColor: "#1f2335",
|
||||
},
|
||||
viewportOptions: {
|
||||
backgroundColor: "#1a1b26",
|
||||
},
|
||||
contentOptions: {
|
||||
backgroundColor: "#16161e",
|
||||
},
|
||||
scrollbarOptions: {
|
||||
showArrows: true,
|
||||
trackOptions: {
|
||||
foregroundColor: "#7aa2f7",
|
||||
backgroundColor: "#414868",
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Scroll Position (Core)
|
||||
|
||||
```typescript
|
||||
const scrollbox = new ScrollBoxRenderable(renderer, {
|
||||
id: "list",
|
||||
height: 20,
|
||||
})
|
||||
|
||||
// Scroll programmatically
|
||||
scrollbox.scrollTo(0) // Scroll to top
|
||||
scrollbox.scrollTo(100) // Scroll to position
|
||||
scrollbox.scrollBy(10) // Scroll relative
|
||||
scrollbox.scrollToBottom() // Scroll to end
|
||||
|
||||
// Scroll a child into view (nearest alignment)
|
||||
scrollbox.scrollChildIntoView("child-id") // Searches descendants by ID
|
||||
```
|
||||
|
||||
`scrollChildIntoView(childId)` scrolls the minimum amount needed to make the identified descendant visible. It mirrors `Element.scrollIntoView({ block: "nearest" })` from the CSSOM View spec. Works with nested descendants and handles both horizontal and vertical scrolling.
|
||||
|
||||
## Composition Patterns
|
||||
|
||||
### Card Component
|
||||
|
||||
```tsx
|
||||
function Card({ title, children }) {
|
||||
return (
|
||||
<box
|
||||
border
|
||||
borderStyle="rounded"
|
||||
padding={2}
|
||||
marginBottom={1}
|
||||
>
|
||||
{title && (
|
||||
<text fg="#00FFFF" bold>
|
||||
{title}
|
||||
</text>
|
||||
)}
|
||||
<box marginTop={title ? 1 : 0}>
|
||||
{children}
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Panel Component
|
||||
|
||||
```tsx
|
||||
function Panel({ title, children, width = 40 }) {
|
||||
return (
|
||||
<box
|
||||
border
|
||||
borderStyle="double"
|
||||
width={width}
|
||||
backgroundColor="#1a1a2e"
|
||||
>
|
||||
{title && (
|
||||
<box
|
||||
borderBottom
|
||||
padding={1}
|
||||
backgroundColor="#2a2a4e"
|
||||
>
|
||||
<text bold>{title}</text>
|
||||
</box>
|
||||
)}
|
||||
<box padding={2}>
|
||||
{children}
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### List Container
|
||||
|
||||
```tsx
|
||||
function List({ items, renderItem }) {
|
||||
return (
|
||||
<scrollbox height={15} focused>
|
||||
{items.map((item, i) => (
|
||||
<box
|
||||
key={i}
|
||||
padding={1}
|
||||
backgroundColor={i % 2 === 0 ? "#222" : "#333"}
|
||||
>
|
||||
{renderItem(item, i)}
|
||||
</box>
|
||||
))}
|
||||
</scrollbox>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Nesting Containers
|
||||
|
||||
```tsx
|
||||
<box flexDirection="column" height="100%">
|
||||
{/* Header */}
|
||||
<box height={3} border>
|
||||
<text>Header</text>
|
||||
</box>
|
||||
|
||||
{/* Main area with sidebar */}
|
||||
<box flexDirection="row" flexGrow={1}>
|
||||
<box width={20} border>
|
||||
<text>Sidebar</text>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
<scrollbox height="100%">
|
||||
{/* Scrollable content */}
|
||||
</scrollbox>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
{/* Footer */}
|
||||
<box height={1}>
|
||||
<text>Footer</text>
|
||||
</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Percentage Dimensions Need Parent Size
|
||||
|
||||
```tsx
|
||||
// WRONG - parent has no explicit size
|
||||
<box>
|
||||
<box width="50%">Won't work</box>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box width="100%">
|
||||
<box width="50%">Works</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### FlexGrow Needs Sized Parent
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<box>
|
||||
<box flexGrow={1}>Won't grow</box>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box height="100%">
|
||||
<box flexGrow={1}>Will grow</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### ScrollBox Needs Height
|
||||
|
||||
```tsx
|
||||
// WRONG - no height constraint
|
||||
<scrollbox>
|
||||
{items}
|
||||
</scrollbox>
|
||||
|
||||
// CORRECT
|
||||
<scrollbox height={20}>
|
||||
{items}
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Borders Add to Size
|
||||
|
||||
Borders take up space inside the box:
|
||||
|
||||
```tsx
|
||||
<box width={10} border>
|
||||
{/* Inner content area is 8 chars (10 - 2 for borders) */}
|
||||
</box>
|
||||
```
|
||||
@@ -0,0 +1,531 @@
|
||||
# Input Components
|
||||
|
||||
Components for user input in OpenTUI.
|
||||
|
||||
## Input Component
|
||||
|
||||
Single-line text input field.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<input
|
||||
value={value}
|
||||
onChange={(newValue) => setValue(newValue)}
|
||||
placeholder="Enter text..."
|
||||
focused
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<input
|
||||
value={value()}
|
||||
onInput={(newValue) => setValue(newValue)}
|
||||
placeholder="Enter text..."
|
||||
focused
|
||||
/>
|
||||
|
||||
// Core
|
||||
const input = new InputRenderable(renderer, {
|
||||
id: "name",
|
||||
placeholder: "Enter text...",
|
||||
})
|
||||
input.on(InputRenderableEvents.CHANGE, (value) => {
|
||||
console.log("Value:", value)
|
||||
})
|
||||
input.focus()
|
||||
```
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
<input
|
||||
width={30}
|
||||
backgroundColor="#1a1a1a"
|
||||
textColor="#FFFFFF"
|
||||
cursorColor="#00FF00"
|
||||
focusedBackgroundColor="#2a2a2a"
|
||||
placeholderColor="#666666"
|
||||
/>
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<input
|
||||
onChange={(value) => console.log("Changed:", value)}
|
||||
onFocus={() => console.log("Focused")}
|
||||
onBlur={() => console.log("Blurred")}
|
||||
/>
|
||||
|
||||
// Core
|
||||
input.on(InputRenderableEvents.CHANGE, (value) => {})
|
||||
input.on(InputRenderableEvents.FOCUS, () => {})
|
||||
input.on(InputRenderableEvents.BLUR, () => {})
|
||||
```
|
||||
|
||||
### Controlled Input
|
||||
|
||||
```tsx
|
||||
// React
|
||||
function ControlledInput() {
|
||||
const [value, setValue] = useState("")
|
||||
|
||||
return (
|
||||
<input
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
focused
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Solid
|
||||
function ControlledInput() {
|
||||
const [value, setValue] = createSignal("")
|
||||
|
||||
return (
|
||||
<input
|
||||
value={value()}
|
||||
onInput={setValue}
|
||||
focused
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Textarea Component
|
||||
|
||||
Multi-line text input field.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(newText) => setText(newText)}
|
||||
placeholder="Enter multiple lines..."
|
||||
width={40}
|
||||
height={10}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<textarea
|
||||
value={text()}
|
||||
onInput={(newText) => setText(newText)}
|
||||
placeholder="Enter multiple lines..."
|
||||
width={40}
|
||||
height={10}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Core
|
||||
const textarea = new TextareaRenderable(renderer, {
|
||||
id: "editor",
|
||||
width: 40,
|
||||
height: 10,
|
||||
placeholder: "Enter text...",
|
||||
})
|
||||
```
|
||||
|
||||
### Features
|
||||
|
||||
```tsx
|
||||
<textarea
|
||||
showLineNumbers // Display line numbers
|
||||
wrapText // Wrap long lines
|
||||
readOnly // Disable editing
|
||||
tabSize={2} // Tab character width
|
||||
/>
|
||||
```
|
||||
|
||||
### Syntax Highlighting
|
||||
|
||||
```tsx
|
||||
<textarea
|
||||
language="typescript"
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
/>
|
||||
```
|
||||
|
||||
## Select Component
|
||||
|
||||
List selection for choosing from options.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<select
|
||||
options={[
|
||||
{ name: "Option 1", description: "First option", value: "1" },
|
||||
{ name: "Option 2", description: "Second option", value: "2" },
|
||||
{ name: "Option 3", description: "Third option", value: "3" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
console.log("Selected:", option.name) // Called when Enter is pressed
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<select
|
||||
options={[
|
||||
{ name: "Option 1", description: "First option", value: "1" },
|
||||
{ name: "Option 2", description: "Second option", value: "2" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
console.log("Selected:", option.name) // Called when Enter is pressed
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Core
|
||||
const select = new SelectRenderable(renderer, {
|
||||
id: "menu",
|
||||
options: [
|
||||
{ name: "Option 1", description: "First option", value: "1" },
|
||||
{ name: "Option 2", description: "Second option", value: "2" },
|
||||
],
|
||||
})
|
||||
select.on(SelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
console.log("Selected:", option.name) // Called when Enter is pressed
|
||||
})
|
||||
select.focus()
|
||||
```
|
||||
|
||||
### Option Format
|
||||
|
||||
```typescript
|
||||
interface SelectOption {
|
||||
name: string // Display text
|
||||
description?: string // Optional description shown below
|
||||
value?: any // Associated value
|
||||
}
|
||||
```
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
<select
|
||||
height={8} // Visible height
|
||||
selectedIndex={0} // Initially selected
|
||||
showScrollIndicator // Show scroll arrows
|
||||
selectedBackgroundColor="#333"
|
||||
selectedTextColor="#fff"
|
||||
highlightBackgroundColor="#444"
|
||||
/>
|
||||
```
|
||||
|
||||
### Navigation
|
||||
|
||||
Default keybindings:
|
||||
- `Up` / `k` - Move up
|
||||
- `Down` / `j` - Move down
|
||||
- `Enter` - Select item
|
||||
|
||||
### Events
|
||||
|
||||
**Important**: `onSelect` and `onChange` serve different purposes:
|
||||
|
||||
| Event | Trigger | Use Case |
|
||||
|-------|---------|----------|
|
||||
| `onSelect` | **Enter key pressed** - user confirms selection | Perform action with selected item |
|
||||
| `onChange` | **Arrow keys** - user navigates list | Preview, update UI as user browses |
|
||||
|
||||
```tsx
|
||||
// React/Solid
|
||||
<select
|
||||
onSelect={(index, option) => {
|
||||
// Called when Enter is pressed - selection confirmed
|
||||
console.log("User selected:", option.name)
|
||||
performAction(option)
|
||||
}}
|
||||
onChange={(index, option) => {
|
||||
// Called when navigating with arrow keys
|
||||
console.log("Browsing:", option.name)
|
||||
showPreview(option)
|
||||
}}
|
||||
/>
|
||||
|
||||
// Core
|
||||
select.on(SelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
// Called when Enter is pressed
|
||||
})
|
||||
select.on(SelectRenderableEvents.SELECTION_CHANGED, (index, option) => {
|
||||
// Called when navigating with arrow keys
|
||||
})
|
||||
```
|
||||
|
||||
## Tab Select Component
|
||||
|
||||
Horizontal tab-based selection.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<tab-select
|
||||
options={[
|
||||
{ name: "Home", description: "Dashboard view" },
|
||||
{ name: "Settings", description: "Configuration" },
|
||||
{ name: "Help", description: "Documentation" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
console.log("Tab selected:", option.name) // Called when Enter is pressed
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Solid (note underscore)
|
||||
<tab_select
|
||||
options={[
|
||||
{ name: "Home", description: "Dashboard view" },
|
||||
{ name: "Settings", description: "Configuration" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
console.log("Tab selected:", option.name) // Called when Enter is pressed
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
|
||||
// Core
|
||||
const tabs = new TabSelectRenderable(renderer, {
|
||||
id: "tabs",
|
||||
options: [...],
|
||||
tabWidth: 20,
|
||||
})
|
||||
tabs.on(TabSelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
console.log("Tab selected:", option.name) // Called when Enter is pressed
|
||||
})
|
||||
tabs.focus()
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
Same pattern as Select - `onSelect` for Enter key, `onChange` for navigation:
|
||||
|
||||
```tsx
|
||||
<tab-select
|
||||
onSelect={(index, option) => {
|
||||
// Called when Enter is pressed - switch to tab
|
||||
setActiveTab(index)
|
||||
}}
|
||||
onChange={(index, option) => {
|
||||
// Called when navigating with arrow keys
|
||||
showTabPreview(option)
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<tab-select
|
||||
tabWidth={20} // Width of each tab
|
||||
selectedIndex={0} // Initially selected tab
|
||||
/>
|
||||
|
||||
// Solid
|
||||
<tab_select
|
||||
tabWidth={20}
|
||||
selectedIndex={0}
|
||||
/>
|
||||
```
|
||||
|
||||
### Navigation
|
||||
|
||||
Default keybindings:
|
||||
- `Left` / `[` - Previous tab
|
||||
- `Right` / `]` - Next tab
|
||||
- `Enter` - Select tab
|
||||
|
||||
## Focus Management
|
||||
|
||||
### Single Focused Input
|
||||
|
||||
```tsx
|
||||
function SingleInput() {
|
||||
return <input placeholder="I'm focused" focused />
|
||||
}
|
||||
```
|
||||
|
||||
### Multiple Inputs with Focus State
|
||||
|
||||
```tsx
|
||||
// React
|
||||
function Form() {
|
||||
const [focusIndex, setFocusIndex] = useState(0)
|
||||
const fields = ["name", "email", "message"]
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "tab") {
|
||||
setFocusIndex(i => (i + 1) % fields.length)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
{fields.map((field, i) => (
|
||||
<input
|
||||
key={field}
|
||||
placeholder={`Enter ${field}`}
|
||||
focused={i === focusIndex}
|
||||
/>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Focus Methods (Core)
|
||||
|
||||
```typescript
|
||||
input.focus() // Give focus
|
||||
input.blur() // Remove focus
|
||||
input.isFocused() // Check focus state
|
||||
```
|
||||
|
||||
## Form Patterns
|
||||
|
||||
### Login Form
|
||||
|
||||
```tsx
|
||||
function LoginForm() {
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [focusField, setFocusField] = useState<"username" | "password">("username")
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "tab") {
|
||||
setFocusField(f => f === "username" ? "password" : "username")
|
||||
}
|
||||
if (key.name === "enter") {
|
||||
handleLogin()
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1} border padding={2}>
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text>Username:</text>
|
||||
<input
|
||||
value={username}
|
||||
onChange={setUsername}
|
||||
focused={focusField === "username"}
|
||||
width={20}
|
||||
/>
|
||||
</box>
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text>Password:</text>
|
||||
<input
|
||||
value={password}
|
||||
onChange={setPassword}
|
||||
focused={focusField === "password"}
|
||||
width={20}
|
||||
/>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Search with Results
|
||||
|
||||
```tsx
|
||||
function SearchableList({ items, onItemSelected }) {
|
||||
const [query, setQuery] = useState("")
|
||||
const [focusSearch, setFocusSearch] = useState(true)
|
||||
const [preview, setPreview] = useState(null)
|
||||
|
||||
const filtered = items.filter(item =>
|
||||
item.toLowerCase().includes(query.toLowerCase())
|
||||
)
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "tab") {
|
||||
setFocusSearch(f => !f)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<input
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Search..."
|
||||
focused={focusSearch}
|
||||
/>
|
||||
<select
|
||||
options={filtered.map(item => ({ name: item }))}
|
||||
focused={!focusSearch}
|
||||
height={10}
|
||||
onSelect={(index, option) => {
|
||||
// Enter pressed - confirm selection
|
||||
onItemSelected(option)
|
||||
}}
|
||||
onChange={(index, option) => {
|
||||
// Navigating - show preview
|
||||
setPreview(option)
|
||||
}}
|
||||
/>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Focus Required
|
||||
|
||||
Inputs must be focused to receive keyboard input:
|
||||
|
||||
```tsx
|
||||
// WRONG - won't receive input
|
||||
<input placeholder="Type here" />
|
||||
|
||||
// CORRECT
|
||||
<input placeholder="Type here" focused />
|
||||
```
|
||||
|
||||
### Select Options Format
|
||||
|
||||
Options must be objects with `name` property:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<select options={["a", "b", "c"]} />
|
||||
|
||||
// CORRECT
|
||||
<select options={[
|
||||
{ name: "A", description: "Option A" },
|
||||
{ name: "B", description: "Option B" },
|
||||
]} />
|
||||
```
|
||||
|
||||
### Solid Uses Underscores
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<tab-select />
|
||||
|
||||
// Solid
|
||||
<tab_select />
|
||||
```
|
||||
|
||||
### Value vs onInput (Solid)
|
||||
|
||||
Solid uses `onInput` instead of `onChange`:
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<input value={value} onChange={setValue} />
|
||||
|
||||
// Solid
|
||||
<input value={value()} onInput={setValue} />
|
||||
```
|
||||
@@ -0,0 +1,386 @@
|
||||
# Text & Display Components
|
||||
|
||||
Components for displaying text content in OpenTUI.
|
||||
|
||||
## Text Component
|
||||
|
||||
The primary component for displaying styled text.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React/Solid
|
||||
<text>Hello, World!</text>
|
||||
|
||||
// With content prop
|
||||
<text content="Hello, World!" />
|
||||
|
||||
// Core
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: "greeting",
|
||||
content: "Hello, World!",
|
||||
})
|
||||
```
|
||||
|
||||
### Styling (React/Solid)
|
||||
|
||||
For React and Solid, use **nested modifier tags** for text styling:
|
||||
|
||||
```tsx
|
||||
<text fg="#FFFFFF" bg="#000000">
|
||||
<strong>Bold</strong>, <em>italic</em>, and <u>underlined</u>
|
||||
</text>
|
||||
```
|
||||
|
||||
> **Important**: Do NOT use `bold`, `italic`, `underline`, `dim`, `strikethrough` as props on `<text>` — they don't work. Always use nested tags like `<strong>`, `<em>`, `<u>`, or `<span>` with styling.
|
||||
|
||||
### Styling (Core) - Text Attributes
|
||||
|
||||
```typescript
|
||||
import { TextRenderable, TextAttributes } from "@opentui/core"
|
||||
|
||||
const text = new TextRenderable(renderer, {
|
||||
content: "Styled",
|
||||
attributes: TextAttributes.BOLD | TextAttributes.UNDERLINE,
|
||||
})
|
||||
```
|
||||
|
||||
**Available attributes:**
|
||||
- `TextAttributes.BOLD`
|
||||
- `TextAttributes.DIM`
|
||||
- `TextAttributes.ITALIC`
|
||||
- `TextAttributes.UNDERLINE`
|
||||
- `TextAttributes.BLINK`
|
||||
- `TextAttributes.INVERSE`
|
||||
- `TextAttributes.HIDDEN`
|
||||
- `TextAttributes.STRIKETHROUGH`
|
||||
|
||||
### Text Selection
|
||||
|
||||
```tsx
|
||||
<text selectable>
|
||||
This text can be selected by the user
|
||||
</text>
|
||||
|
||||
<text selectable={false}>
|
||||
This text cannot be selected
|
||||
</text>
|
||||
```
|
||||
|
||||
For copy-on-selection and the full selection API, see `keyboard/REFERENCE.md` (selection).
|
||||
|
||||
## Text Modifiers
|
||||
|
||||
Inline styling elements that must be used inside `<text>`:
|
||||
|
||||
### Span
|
||||
|
||||
Inline styled text:
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
Normal text with <span fg="red">red text</span> inline
|
||||
</text>
|
||||
```
|
||||
|
||||
### Bold/Strong
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<strong>Bold text</strong>
|
||||
<b>Also bold</b>
|
||||
</text>
|
||||
```
|
||||
|
||||
### Italic/Emphasis
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<em>Italic text</em>
|
||||
<i>Also italic</i>
|
||||
</text>
|
||||
```
|
||||
|
||||
### Underline
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<u>Underlined text</u>
|
||||
</text>
|
||||
```
|
||||
|
||||
### Line Break
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
Line one
|
||||
<br />
|
||||
Line two
|
||||
</text>
|
||||
```
|
||||
|
||||
### Link
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
Visit <a href="https://example.com">our website</a>
|
||||
</text>
|
||||
```
|
||||
|
||||
### Combined Modifiers
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<span fg="#00FF00">
|
||||
<strong>Bold green</strong>
|
||||
</span>
|
||||
and
|
||||
<span fg="#FF0000">
|
||||
<em><u>italic underlined red</u></em>
|
||||
</span>
|
||||
</text>
|
||||
```
|
||||
|
||||
## Styled Text Template (Core)
|
||||
|
||||
The `t` template literal for complex styling:
|
||||
|
||||
```typescript
|
||||
import { t, bold, italic, underline, fg, bg, dim } from "@opentui/core"
|
||||
|
||||
const styled = t`
|
||||
${bold("Bold")} and ${italic("italic")} text.
|
||||
${fg("#FF0000")("Red text")} with ${bg("#0000FF")("blue background")}.
|
||||
${dim("Dimmed")} and ${underline("underlined")}.
|
||||
`
|
||||
|
||||
const text = new TextRenderable(renderer, {
|
||||
content: styled,
|
||||
})
|
||||
```
|
||||
|
||||
### Style Functions
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `bold(text)` | Bold text |
|
||||
| `italic(text)` | Italic text |
|
||||
| `underline(text)` | Underlined text |
|
||||
| `dim(text)` | Dimmed text |
|
||||
| `strikethrough(text)` | Strikethrough text |
|
||||
| `fg(color)(text)` | Set foreground color |
|
||||
| `bg(color)(text)` | Set background color |
|
||||
|
||||
## ASCII Font Component
|
||||
|
||||
Display large ASCII art text banners.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<ascii-font text="TITLE" font="tiny" />
|
||||
|
||||
// Solid
|
||||
<ascii_font text="TITLE" font="tiny" />
|
||||
|
||||
// Core
|
||||
const title = new ASCIIFontRenderable(renderer, {
|
||||
id: "title",
|
||||
text: "TITLE",
|
||||
font: "tiny",
|
||||
})
|
||||
```
|
||||
|
||||
### Available Fonts
|
||||
|
||||
| Font | Description |
|
||||
|------|-------------|
|
||||
| `tiny` | Compact ASCII font |
|
||||
| `block` | Block-style letters |
|
||||
| `slick` | Sleek modern style |
|
||||
| `shade` | Shaded 3D effect |
|
||||
|
||||
### Styling
|
||||
|
||||
```tsx
|
||||
// React
|
||||
<ascii-font
|
||||
text="HELLO"
|
||||
font="block"
|
||||
color="#00FF00"
|
||||
/>
|
||||
|
||||
// Core
|
||||
import { RGBA } from "@opentui/core"
|
||||
|
||||
const title = new ASCIIFontRenderable(renderer, {
|
||||
text: "HELLO",
|
||||
font: "block",
|
||||
color: RGBA.fromHex("#00FF00"),
|
||||
})
|
||||
```
|
||||
|
||||
### Example Output
|
||||
|
||||
```
|
||||
Font: tiny
|
||||
╭─╮╭─╮╭─╮╭╮╭╮╭─╮╶╮╶ ╶╮
|
||||
│ ││─┘├┤ │╰╯││ │ │
|
||||
╰─╯╵ ╰─╯╵ ╵╰─╯╶╯╶╰─╯
|
||||
|
||||
Font: block
|
||||
█▀▀█ █▀▀█ █▀▀ █▀▀▄
|
||||
█ █ █▀▀▀ █▀▀ █ █
|
||||
▀▀▀▀ ▀ ▀▀▀ ▀ ▀
|
||||
```
|
||||
|
||||
## Colors
|
||||
|
||||
### Color Formats
|
||||
|
||||
```tsx
|
||||
// Hex colors
|
||||
<text fg="#FF0000">Red</text>
|
||||
<text fg="#F00">Short hex</text>
|
||||
|
||||
// Named colors
|
||||
<text fg="red">Red</text>
|
||||
<text fg="blue">Blue</text>
|
||||
|
||||
// Transparent
|
||||
<text bg="transparent">No background</text>
|
||||
```
|
||||
|
||||
### RGBA Class
|
||||
|
||||
The `RGBA` class from `@opentui/core` can be used in **all frameworks** (Core, React, Solid) for programmatic color manipulation:
|
||||
|
||||
```typescript
|
||||
import { RGBA } from "@opentui/core"
|
||||
|
||||
// From hex string (most common)
|
||||
const red = RGBA.fromHex("#FF0000")
|
||||
const shortHex = RGBA.fromHex("#F00") // Short form supported
|
||||
|
||||
// From integers (0-255 range for each channel)
|
||||
const green = RGBA.fromInts(0, 255, 0, 255) // r, g, b, a
|
||||
const semiGreen = RGBA.fromInts(0, 255, 0, 128) // 50% transparent
|
||||
|
||||
// From normalized floats (0.0-1.0 range)
|
||||
const blue = RGBA.fromValues(0.0, 0.0, 1.0, 1.0) // r, g, b, a
|
||||
const overlay = RGBA.fromValues(0.1, 0.1, 0.1, 0.7) // Dark semi-transparent
|
||||
|
||||
// Common use cases
|
||||
const backgroundColor = RGBA.fromHex("#1a1a2e")
|
||||
const textColor = RGBA.fromHex("#FFFFFF")
|
||||
const borderColor = RGBA.fromInts(122, 162, 247, 255) // Tokyo Night blue
|
||||
const shadowColor = RGBA.fromValues(0.0, 0.0, 0.0, 0.5) // 50% black
|
||||
```
|
||||
|
||||
**When to use each method:**
|
||||
- `fromHex()` - When working with design specs or CSS colors
|
||||
- `fromInts()` - When you have 8-bit color values (0-255)
|
||||
- `fromValues()` - When doing color math or interpolation (normalized 0.0-1.0)
|
||||
|
||||
### Using RGBA in React/Solid
|
||||
|
||||
```tsx
|
||||
// React or Solid - RGBA works with color props
|
||||
import { RGBA } from "@opentui/core"
|
||||
|
||||
const primaryColor = RGBA.fromHex("#7aa2f7")
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<box backgroundColor={primaryColor} borderColor={primaryColor}>
|
||||
<text fg={RGBA.fromHex("#c0caf5")}>Styled with RGBA</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Most props that accept color strings (`"#FF0000"`, `"red"`) also accept `RGBA` objects directly.
|
||||
|
||||
## Text Wrapping
|
||||
|
||||
Text wraps based on parent container:
|
||||
|
||||
```tsx
|
||||
<box width={40}>
|
||||
<text>
|
||||
This long text will wrap when it reaches the edge of the
|
||||
40-character wide parent container.
|
||||
</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Dynamic Content
|
||||
|
||||
### React
|
||||
|
||||
```tsx
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0)
|
||||
return <text>Count: {count}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Solid
|
||||
|
||||
```tsx
|
||||
function Counter() {
|
||||
const [count, setCount] = createSignal(0)
|
||||
return <text>Count: {count()}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Core
|
||||
|
||||
```typescript
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: "counter",
|
||||
content: "Count: 0",
|
||||
})
|
||||
|
||||
// Update later
|
||||
text.setContent("Count: 1")
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Text Modifiers Outside Text
|
||||
|
||||
```tsx
|
||||
// WRONG - modifiers only work inside <text>
|
||||
<box>
|
||||
<strong>Won't work</strong>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box>
|
||||
<text>
|
||||
<strong>This works</strong>
|
||||
</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Empty Text
|
||||
|
||||
```tsx
|
||||
// May cause layout issues
|
||||
<text></text>
|
||||
|
||||
// Better - use space or conditional
|
||||
<text>{content || " "}</text>
|
||||
```
|
||||
|
||||
### Color Format
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<text fg="FF0000">Missing #</text>
|
||||
|
||||
// CORRECT
|
||||
<text fg="#FF0000">With #</text>
|
||||
```
|
||||
@@ -0,0 +1,145 @@
|
||||
# OpenTUI Core (@opentui/core)
|
||||
|
||||
The foundational library for building terminal user interfaces. Provides an imperative API with all primitives, giving you maximum control over rendering, state, and behavior.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTUI Core runs on Bun with native Zig bindings for performance-critical operations:
|
||||
- **Renderer**: Manages terminal output, input events, and the rendering loop
|
||||
- **Renderables**: Hierarchical UI building blocks with Yoga layout
|
||||
- **Constructs**: Declarative wrappers for composing Renderables
|
||||
- **FrameBuffer**: Low-level 2D rendering surface for custom graphics
|
||||
|
||||
## When to Use Core
|
||||
|
||||
Use the core imperative API when:
|
||||
- Building a library or framework on top of OpenTUI
|
||||
- Need maximum control over rendering and state
|
||||
- Want smallest possible bundle size (no React/Solid runtime)
|
||||
- Building performance-critical applications
|
||||
- Integrating with existing imperative codebases
|
||||
|
||||
## When NOT to Use Core
|
||||
|
||||
| Scenario | Use Instead |
|
||||
|----------|-------------|
|
||||
| Familiar with React patterns | `@opentui/react` |
|
||||
| Want fine-grained reactivity | `@opentui/solid` |
|
||||
| Building typical applications | React or Solid reconciler |
|
||||
| Rapid prototyping | React or Solid reconciler |
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Using create-tui (Recommended)
|
||||
|
||||
```bash
|
||||
bunx create-tui@latest -t core my-app
|
||||
cd my-app
|
||||
bun run src/index.ts
|
||||
```
|
||||
|
||||
The CLI creates the `my-app` directory for you - it must **not already exist**.
|
||||
|
||||
**Agent guidance**: Always use autonomous mode with `-t <template>` flag. Never use interactive mode (`bunx create-tui@latest my-app` without `-t`) as it requires user prompts that agents cannot respond to.
|
||||
|
||||
### Manual Setup
|
||||
|
||||
```bash
|
||||
mkdir my-tui && cd my-tui
|
||||
bun init
|
||||
bun install @opentui/core
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, TextRenderable, BoxRenderable } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
// Create a box container
|
||||
const container = new BoxRenderable(renderer, {
|
||||
id: "container",
|
||||
width: 40,
|
||||
height: 10,
|
||||
border: true,
|
||||
borderStyle: "rounded",
|
||||
padding: 1,
|
||||
})
|
||||
|
||||
// Create text inside the box
|
||||
const greeting = new TextRenderable(renderer, {
|
||||
id: "greeting",
|
||||
content: "Hello, OpenTUI!",
|
||||
fg: "#00FF00",
|
||||
})
|
||||
|
||||
// Compose the tree
|
||||
container.add(greeting)
|
||||
renderer.root.add(container)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Renderer
|
||||
|
||||
The `CliRenderer` orchestrates everything:
|
||||
- Manages the terminal viewport and alternate screen
|
||||
- Handles input events (keyboard, mouse, paste)
|
||||
- Runs the rendering loop (configurable FPS)
|
||||
- Provides the root node for the renderable tree
|
||||
|
||||
### Renderables vs Constructs
|
||||
|
||||
| Renderables (Imperative) | Constructs (Declarative) |
|
||||
|--------------------------|--------------------------|
|
||||
| `new TextRenderable(renderer, {...})` | `Text({...})` |
|
||||
| Requires renderer at creation | Creates VNode, instantiated later |
|
||||
| Direct mutation via methods | Chained calls recorded, replayed on instantiation |
|
||||
| Full control | Cleaner composition |
|
||||
|
||||
### Storage Options
|
||||
|
||||
Renderables can be composed in two ways:
|
||||
1. **Imperative**: Create instances, call `.add()` to compose
|
||||
2. **Declarative (Constructs)**: Create VNodes, pass children as arguments
|
||||
|
||||
## Essential Commands
|
||||
|
||||
```bash
|
||||
bun install @opentui/core # Install
|
||||
bun run src/index.ts # Run directly (no build needed)
|
||||
bun test # Run tests
|
||||
```
|
||||
|
||||
## Runtime Requirements
|
||||
|
||||
OpenTUI runs on Bun and uses Zig for native builds.
|
||||
|
||||
```bash
|
||||
# Package management
|
||||
bun install @opentui/core
|
||||
|
||||
# Running
|
||||
bun run src/index.ts
|
||||
bun test
|
||||
|
||||
# Building (only needed for native code changes)
|
||||
bun run build
|
||||
```
|
||||
|
||||
**Zig** is required for building native components.
|
||||
|
||||
## In This Reference
|
||||
|
||||
- [Configuration](./configuration.md) - Renderer options, environment variables
|
||||
- [API](./api.md) - Renderer, Renderables, types, utilities
|
||||
- [Patterns](./patterns.md) - Composition, events, state management
|
||||
- [Gotchas](./gotchas.md) - Common issues, debugging, limitations
|
||||
|
||||
## See Also
|
||||
|
||||
- [React](../react/REFERENCE.md) - React reconciler for declarative TUI
|
||||
- [Solid](../solid/REFERENCE.md) - Solid reconciler for declarative TUI
|
||||
- [Layout](../layout/REFERENCE.md) - Yoga/Flexbox layout system
|
||||
- [Components](../components/REFERENCE.md) - Component reference by category
|
||||
- [Keyboard](../keyboard/REFERENCE.md) - Input handling and shortcuts
|
||||
- [Testing](../testing/REFERENCE.md) - Test renderer and snapshots
|
||||
@@ -0,0 +1,543 @@
|
||||
# Core API Reference
|
||||
|
||||
## Renderer
|
||||
|
||||
### createCliRenderer(config?)
|
||||
|
||||
Creates and initializes the CLI renderer.
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, type CliRendererConfig } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
targetFPS: 60, // Target frames per second
|
||||
exitOnCtrlC: true, // Exit process on Ctrl+C
|
||||
consoleOptions: { // Debug console overlay
|
||||
position: ConsolePosition.BOTTOM,
|
||||
sizePercent: 30,
|
||||
startInDebugMode: false,
|
||||
},
|
||||
onDestroy: () => {}, // Cleanup callback
|
||||
})
|
||||
```
|
||||
|
||||
### CliRenderer Instance
|
||||
|
||||
```typescript
|
||||
renderer.root // Root renderable node
|
||||
renderer.width // Terminal width in columns
|
||||
renderer.height // Terminal height in rows
|
||||
renderer.keyInput // Keyboard event emitter
|
||||
renderer.console // Console overlay controller
|
||||
|
||||
renderer.start() // Start render loop
|
||||
renderer.stop() // Stop render loop
|
||||
renderer.destroy() // Cleanup and exit alternate screen
|
||||
renderer.requestRender() // Request a re-render
|
||||
|
||||
renderer.setCursorStyle(options) // Set cursor style
|
||||
renderer.setCursorColor(color) // Set cursor color
|
||||
renderer.setMousePointer(style) // Set mouse pointer shape
|
||||
```
|
||||
|
||||
### Cursor & Mouse Pointer
|
||||
|
||||
```typescript
|
||||
import { type CursorStyleOptions, type MousePointerStyle } from "@opentui/core"
|
||||
|
||||
// Set cursor style (options object)
|
||||
renderer.setCursorStyle({
|
||||
style: "block", // "block" | "line" | "underline" | "default"
|
||||
blinking: true, // Cursor blink
|
||||
color: RGBA.fromHex("#FF0000"), // Cursor color
|
||||
cursor: "pointer", // Mouse pointer shape
|
||||
})
|
||||
|
||||
// Set mouse pointer shape (OSC 22)
|
||||
renderer.setMousePointer("pointer")
|
||||
// Available: "default" | "pointer" | "text" | "crosshair" | "move" | "not-allowed"
|
||||
```
|
||||
|
||||
### Renderer Events
|
||||
|
||||
```typescript
|
||||
renderer.on("resize", (width, height) => {}) // Terminal resized
|
||||
renderer.on("focus", () => {}) // Terminal window gained focus
|
||||
renderer.on("blur", () => {}) // Terminal window lost focus
|
||||
renderer.on("theme_mode", (mode) => {}) // "dark" | "light"
|
||||
renderer.on("capabilities", (caps) => {}) // Terminal capabilities detected
|
||||
renderer.on("selection", (selection) => {}) // Text selection finished (mouse-up)
|
||||
renderer.on("destroy", () => {}) // Renderer destroyed
|
||||
renderer.on("memory:snapshot", (snapshot) => {}) // Memory snapshot
|
||||
renderer.on("debugOverlay:toggle", () => {}) // Debug overlay toggled
|
||||
```
|
||||
|
||||
### Console Overlay
|
||||
|
||||
```typescript
|
||||
renderer.console.show() // Show console overlay
|
||||
renderer.console.hide() // Hide console overlay
|
||||
renderer.console.toggle() // Toggle visibility/focus
|
||||
renderer.console.clear() // Clear console contents
|
||||
```
|
||||
|
||||
## Renderables
|
||||
|
||||
All renderables extend the base `Renderable` class and share common properties.
|
||||
|
||||
### Common Properties
|
||||
|
||||
```typescript
|
||||
interface CommonProps {
|
||||
id?: string // Unique identifier
|
||||
|
||||
// Positioning
|
||||
position?: "relative" | "absolute"
|
||||
left?: number | string
|
||||
top?: number | string
|
||||
right?: number | string
|
||||
bottom?: number | string
|
||||
|
||||
// Dimensions
|
||||
width?: number | string | "auto"
|
||||
height?: number | string | "auto"
|
||||
minWidth?: number
|
||||
minHeight?: number
|
||||
maxWidth?: number
|
||||
maxHeight?: number
|
||||
|
||||
// Flexbox
|
||||
flexDirection?: "row" | "column" | "row-reverse" | "column-reverse"
|
||||
flexGrow?: number
|
||||
flexShrink?: number
|
||||
flexBasis?: number | string
|
||||
flexWrap?: "nowrap" | "wrap" | "wrap-reverse"
|
||||
justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly"
|
||||
alignItems?: "flex-start" | "flex-end" | "center" | "stretch" | "baseline"
|
||||
alignSelf?: "auto" | "flex-start" | "flex-end" | "center" | "stretch" | "baseline"
|
||||
alignContent?: "flex-start" | "flex-end" | "center" | "stretch" | "space-between" | "space-around"
|
||||
|
||||
// Spacing
|
||||
padding?: number
|
||||
paddingTop?: number
|
||||
paddingRight?: number
|
||||
paddingBottom?: number
|
||||
paddingLeft?: number
|
||||
margin?: number
|
||||
marginTop?: number
|
||||
marginRight?: number
|
||||
marginBottom?: number
|
||||
marginLeft?: number
|
||||
gap?: number
|
||||
|
||||
// Display
|
||||
display?: "flex" | "none"
|
||||
overflow?: "visible" | "hidden" | "scroll"
|
||||
zIndex?: number
|
||||
}
|
||||
```
|
||||
|
||||
### Renderable Methods
|
||||
|
||||
```typescript
|
||||
renderable.add(child) // Add child renderable
|
||||
renderable.remove(child) // Remove child renderable
|
||||
renderable.getRenderable(id) // Find child by ID
|
||||
renderable.focus() // Focus this renderable
|
||||
renderable.blur() // Remove focus
|
||||
renderable.destroy() // Destroy and cleanup
|
||||
|
||||
renderable.on(event, handler) // Add event listener
|
||||
renderable.off(event, handler) // Remove event listener
|
||||
renderable.emit(event, ...args) // Emit event
|
||||
```
|
||||
|
||||
### TextRenderable
|
||||
|
||||
Display styled text content.
|
||||
|
||||
```typescript
|
||||
import { TextRenderable, TextAttributes, t, bold, fg, underline } from "@opentui/core"
|
||||
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: "text",
|
||||
content: "Hello World",
|
||||
fg: "#FFFFFF", // Foreground color
|
||||
bg: "#000000", // Background color
|
||||
attributes: TextAttributes.BOLD | TextAttributes.UNDERLINE,
|
||||
selectable: true, // Allow text selection
|
||||
})
|
||||
|
||||
// Styled text with template literals
|
||||
const styled = new TextRenderable(renderer, {
|
||||
content: t`${bold("Bold")} and ${fg("#FF0000")(underline("red underlined"))}`,
|
||||
})
|
||||
```
|
||||
|
||||
**TextAttributes flags:**
|
||||
- `TextAttributes.BOLD`
|
||||
- `TextAttributes.DIM`
|
||||
- `TextAttributes.ITALIC`
|
||||
- `TextAttributes.UNDERLINE`
|
||||
- `TextAttributes.BLINK`
|
||||
- `TextAttributes.INVERSE`
|
||||
- `TextAttributes.HIDDEN`
|
||||
- `TextAttributes.STRIKETHROUGH`
|
||||
|
||||
### BoxRenderable
|
||||
|
||||
Container with borders and layout.
|
||||
|
||||
```typescript
|
||||
import { BoxRenderable } from "@opentui/core"
|
||||
|
||||
const box = new BoxRenderable(renderer, {
|
||||
id: "box",
|
||||
width: 40,
|
||||
height: 10,
|
||||
backgroundColor: "#1a1a2e",
|
||||
border: true,
|
||||
borderStyle: "single" | "double" | "rounded" | "bold" | "none",
|
||||
borderColor: "#FFFFFF",
|
||||
title: "Panel Title",
|
||||
titleAlignment: "left" | "center" | "right",
|
||||
onMouseDown: (event) => {},
|
||||
onMouseUp: (event) => {},
|
||||
onMouseMove: (event) => {},
|
||||
})
|
||||
```
|
||||
|
||||
### InputRenderable
|
||||
|
||||
Single-line text input.
|
||||
|
||||
```typescript
|
||||
import { InputRenderable, InputRenderableEvents } from "@opentui/core"
|
||||
|
||||
const input = new InputRenderable(renderer, {
|
||||
id: "input",
|
||||
width: 30,
|
||||
placeholder: "Enter text...",
|
||||
value: "", // Initial value
|
||||
backgroundColor: "#1a1a1a",
|
||||
textColor: "#FFFFFF",
|
||||
cursorColor: "#00FF00",
|
||||
focusedBackgroundColor: "#2a2a2a",
|
||||
})
|
||||
|
||||
input.on(InputRenderableEvents.CHANGE, (value: string) => {
|
||||
console.log("Value:", value)
|
||||
})
|
||||
|
||||
input.focus() // Must be focused to receive input
|
||||
```
|
||||
|
||||
### SelectRenderable
|
||||
|
||||
List selection component.
|
||||
|
||||
```typescript
|
||||
import { SelectRenderable, SelectRenderableEvents } from "@opentui/core"
|
||||
|
||||
const select = new SelectRenderable(renderer, {
|
||||
id: "select",
|
||||
width: 30,
|
||||
height: 10,
|
||||
options: [
|
||||
{ name: "Option 1", description: "First option", value: "1" },
|
||||
{ name: "Option 2", description: "Second option", value: "2" },
|
||||
],
|
||||
selectedIndex: 0,
|
||||
})
|
||||
|
||||
// Called when Enter is pressed - selection confirmed
|
||||
select.on(SelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
console.log("Selected:", option.name)
|
||||
performAction(option)
|
||||
})
|
||||
|
||||
// Called when navigating with arrow keys
|
||||
select.on(SelectRenderableEvents.SELECTION_CHANGED, (index, option) => {
|
||||
console.log("Browsing:", option.name)
|
||||
showPreview(option)
|
||||
})
|
||||
|
||||
select.focus() // Navigate with up/down/j/k, select with enter
|
||||
```
|
||||
|
||||
**Event distinction:**
|
||||
- `ITEM_SELECTED` - Enter key pressed, user confirms selection
|
||||
- `SELECTION_CHANGED` - Arrow keys, user navigating/browsing options
|
||||
|
||||
### TabSelectRenderable
|
||||
|
||||
Horizontal tab selection.
|
||||
|
||||
```typescript
|
||||
import { TabSelectRenderable, TabSelectRenderableEvents } from "@opentui/core"
|
||||
|
||||
const tabs = new TabSelectRenderable(renderer, {
|
||||
id: "tabs",
|
||||
width: 60,
|
||||
options: [
|
||||
{ name: "Home", description: "Dashboard" },
|
||||
{ name: "Settings", description: "Configuration" },
|
||||
],
|
||||
tabWidth: 20,
|
||||
})
|
||||
|
||||
// Called when Enter is pressed - tab selected
|
||||
tabs.on(TabSelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
console.log("Tab selected:", option.name)
|
||||
switchToTab(index)
|
||||
})
|
||||
|
||||
// Called when navigating with arrow keys
|
||||
tabs.on(TabSelectRenderableEvents.SELECTION_CHANGED, (index, option) => {
|
||||
console.log("Browsing tab:", option.name)
|
||||
})
|
||||
|
||||
tabs.focus() // Navigate with left/right/[/], select with enter
|
||||
```
|
||||
|
||||
**Event distinction** (same as SelectRenderable):
|
||||
- `ITEM_SELECTED` - Enter key pressed, user confirms tab
|
||||
- `SELECTION_CHANGED` - Arrow keys, user navigating tabs
|
||||
|
||||
### ScrollBoxRenderable
|
||||
|
||||
Scrollable container.
|
||||
|
||||
```typescript
|
||||
import { ScrollBoxRenderable } from "@opentui/core"
|
||||
|
||||
const scrollbox = new ScrollBoxRenderable(renderer, {
|
||||
id: "scrollbox",
|
||||
width: 40,
|
||||
height: 20,
|
||||
showScrollbar: true,
|
||||
scrollbarOptions: {
|
||||
showArrows: true,
|
||||
trackOptions: {
|
||||
foregroundColor: "#7aa2f7",
|
||||
backgroundColor: "#414868",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Add content that exceeds viewport
|
||||
for (let i = 0; i < 100; i++) {
|
||||
scrollbox.add(new TextRenderable(renderer, {
|
||||
id: `line-${i}`,
|
||||
content: `Line ${i}`,
|
||||
}))
|
||||
}
|
||||
|
||||
scrollbox.focus() // Scroll with arrow keys
|
||||
```
|
||||
|
||||
### ASCIIFontRenderable
|
||||
|
||||
ASCII art text.
|
||||
|
||||
```typescript
|
||||
import { ASCIIFontRenderable, RGBA } from "@opentui/core"
|
||||
|
||||
const title = new ASCIIFontRenderable(renderer, {
|
||||
id: "title",
|
||||
text: "OPENTUI",
|
||||
font: "tiny" | "block" | "slick" | "shade",
|
||||
color: RGBA.fromHex("#FFFFFF"),
|
||||
})
|
||||
```
|
||||
|
||||
### FrameBufferRenderable
|
||||
|
||||
Low-level 2D rendering surface.
|
||||
|
||||
```typescript
|
||||
import { FrameBufferRenderable, RGBA } from "@opentui/core"
|
||||
|
||||
const canvas = new FrameBufferRenderable(renderer, {
|
||||
id: "canvas",
|
||||
width: 50,
|
||||
height: 20,
|
||||
})
|
||||
|
||||
// Direct pixel manipulation
|
||||
canvas.frameBuffer.fillRect(10, 5, 20, 8, RGBA.fromHex("#FF0000"))
|
||||
canvas.frameBuffer.drawText("Custom", 12, 7, RGBA.fromHex("#FFFFFF"))
|
||||
canvas.frameBuffer.setCell(x, y, char, fg, bg)
|
||||
```
|
||||
|
||||
## Constructs (VNode API)
|
||||
|
||||
Declarative wrappers that create VNodes instead of direct instances.
|
||||
|
||||
```typescript
|
||||
import { Text, Box, Input, Select, instantiate, delegate } from "@opentui/core"
|
||||
|
||||
// Create VNode tree
|
||||
const ui = Box(
|
||||
{ border: true, padding: 1 },
|
||||
Text({ content: "Hello" }),
|
||||
Input({ placeholder: "Type here..." }),
|
||||
)
|
||||
|
||||
// Instantiate onto renderer
|
||||
renderer.root.add(ui)
|
||||
|
||||
// Delegate focus to nested element
|
||||
const form = delegate(
|
||||
{ focus: "email-input" },
|
||||
Box(
|
||||
{},
|
||||
Text({ content: "Email:" }),
|
||||
Input({ id: "email-input", placeholder: "you@example.com" }),
|
||||
),
|
||||
)
|
||||
form.focus() // Focuses the input, not the box
|
||||
```
|
||||
|
||||
## Colors (RGBA)
|
||||
|
||||
The `RGBA` class is exported from `@opentui/core` but works across **all frameworks** (Core, React, Solid). Use it for programmatic color manipulation.
|
||||
|
||||
### Creating Colors
|
||||
|
||||
```typescript
|
||||
import { RGBA, parseColor } from "@opentui/core"
|
||||
|
||||
// From hex string (most common)
|
||||
RGBA.fromHex("#FF0000") // Full hex
|
||||
RGBA.fromHex("#F00") // Short hex
|
||||
|
||||
// From integers (0-255 range)
|
||||
RGBA.fromInts(255, 0, 0, 255) // r, g, b, a - fully opaque red
|
||||
RGBA.fromInts(255, 0, 0, 128) // 50% transparent red
|
||||
RGBA.fromInts(0, 0, 0, 0) // Fully transparent
|
||||
|
||||
// From normalized floats (0.0-1.0 range)
|
||||
RGBA.fromValues(1.0, 0.0, 0.0, 1.0) // Fully opaque red
|
||||
RGBA.fromValues(0.1, 0.1, 0.1, 0.7) // Dark gray, 70% opaque
|
||||
RGBA.fromValues(0.0, 0.5, 1.0, 1.0) // Light blue
|
||||
```
|
||||
|
||||
### Common Color Patterns
|
||||
|
||||
```typescript
|
||||
// Theme colors
|
||||
const primary = RGBA.fromHex("#7aa2f7") // Tokyo Night blue
|
||||
const background = RGBA.fromHex("#1a1a2e")
|
||||
const foreground = RGBA.fromHex("#c0caf5")
|
||||
const error = RGBA.fromHex("#f7768e")
|
||||
|
||||
// Overlays and shadows
|
||||
const modalOverlay = RGBA.fromValues(0.0, 0.0, 0.0, 0.5) // 50% black
|
||||
const shadow = RGBA.fromInts(0, 0, 0, 77) // 30% black
|
||||
|
||||
// Borders
|
||||
const activeBorder = RGBA.fromHex("#7aa2f7")
|
||||
const inactiveBorder = RGBA.fromInts(65, 72, 104, 255)
|
||||
```
|
||||
|
||||
### parseColor Utility
|
||||
|
||||
```typescript
|
||||
// Accepts multiple formats
|
||||
parseColor("#FF0000") // Hex string
|
||||
parseColor("red") // CSS color name
|
||||
parseColor("transparent") // Special values
|
||||
parseColor(RGBA.fromHex("#F00")) // Pass-through RGBA objects
|
||||
```
|
||||
|
||||
### When to Use Each Method
|
||||
|
||||
| Method | Use When |
|
||||
|--------|----------|
|
||||
| `fromHex()` | Working with design specs, CSS colors, config files |
|
||||
| `fromInts()` | You have 8-bit values (0-255), common in graphics |
|
||||
| `fromValues()` | Doing color interpolation, animations, math |
|
||||
| `parseColor()` | Accepting user input or config that could be any format |
|
||||
|
||||
### Using RGBA in React/Solid
|
||||
|
||||
```tsx
|
||||
// Import from @opentui/core, use in any framework
|
||||
import { RGBA } from "@opentui/core"
|
||||
|
||||
// React or Solid component
|
||||
function ThemedBox() {
|
||||
const bg = RGBA.fromHex("#1a1a2e")
|
||||
const border = RGBA.fromInts(122, 162, 247, 255)
|
||||
|
||||
return (
|
||||
<box backgroundColor={bg} borderColor={border} border>
|
||||
<text fg={RGBA.fromHex("#c0caf5")}>Works everywhere!</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Color props in React/Solid accept both string formats (`"#FF0000"`, `"red"`) and `RGBA` objects.
|
||||
|
||||
## Keyboard Input
|
||||
|
||||
```typescript
|
||||
import { type KeyEvent } from "@opentui/core"
|
||||
|
||||
renderer.keyInput.on("keypress", (key: KeyEvent) => {
|
||||
console.log(key.name) // "a", "escape", "f1", etc.
|
||||
console.log(key.sequence) // Raw escape sequence
|
||||
console.log(key.ctrl) // Ctrl held
|
||||
console.log(key.shift) // Shift held
|
||||
console.log(key.meta) // Alt held
|
||||
console.log(key.option) // Option held (macOS)
|
||||
console.log(key.eventType) // "press" | "release" | "repeat"
|
||||
})
|
||||
|
||||
renderer.keyInput.on("paste", (event: PasteEvent) => {
|
||||
const text = decodePasteBytes(event.bytes)
|
||||
console.log("Pasted:", text)
|
||||
})
|
||||
```
|
||||
|
||||
## Animation Timeline
|
||||
|
||||
```typescript
|
||||
import { Timeline, engine } from "@opentui/core"
|
||||
|
||||
const timeline = new Timeline({
|
||||
duration: 2000,
|
||||
loop: false,
|
||||
autoplay: true,
|
||||
})
|
||||
|
||||
timeline.add(
|
||||
{ width: 0 },
|
||||
{
|
||||
width: 50,
|
||||
duration: 1000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
box.setWidth(anim.targets[0].width)
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
engine.attach(renderer)
|
||||
engine.addTimeline(timeline)
|
||||
```
|
||||
|
||||
## Type Exports
|
||||
|
||||
```typescript
|
||||
import type {
|
||||
CliRenderer,
|
||||
CliRendererConfig,
|
||||
RenderContext,
|
||||
KeyEvent,
|
||||
Renderable,
|
||||
// ... and more
|
||||
} from "@opentui/core"
|
||||
```
|
||||
@@ -0,0 +1,168 @@
|
||||
# Core Configuration
|
||||
|
||||
## Renderer Configuration
|
||||
|
||||
### createCliRenderer Options
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, ConsolePosition } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
// Rendering
|
||||
targetFPS: 60, // Target frames per second (default: 60)
|
||||
|
||||
// Behavior
|
||||
exitOnCtrlC: true, // Exit on Ctrl+C (default: true)
|
||||
|
||||
// Console overlay
|
||||
consoleOptions: {
|
||||
position: ConsolePosition.BOTTOM, // BOTTOM | TOP | LEFT | RIGHT
|
||||
sizePercent: 30, // Percentage of screen
|
||||
colorInfo: "#00FFFF",
|
||||
colorWarn: "#FFFF00",
|
||||
colorError: "#FF0000",
|
||||
colorDebug: "#888888",
|
||||
startInDebugMode: false,
|
||||
},
|
||||
|
||||
// Lifecycle
|
||||
onDestroy: () => {
|
||||
// Cleanup callback
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
OpenTUI respects several environment variables for configuration and debugging.
|
||||
|
||||
### Debug & Development
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `OTUI_DEBUG` | boolean | false | Enable debug mode, capture raw input |
|
||||
| `OTUI_DEBUG_FFI` | boolean | false | Debug logging for FFI bindings |
|
||||
| `OTUI_TRACE_FFI` | boolean | false | Tracing for FFI bindings |
|
||||
| `OTUI_SHOW_STATS` | boolean | false | Show debug overlay at startup |
|
||||
| `OTUI_DUMP_CAPTURES` | boolean | false | Dump captured output on exit |
|
||||
|
||||
### Console
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `OTUI_USE_CONSOLE` | boolean | true | Enable console capture |
|
||||
| `SHOW_CONSOLE` | boolean | false | Show console at startup |
|
||||
|
||||
### Rendering
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `OTUI_NO_NATIVE_RENDER` | boolean | false | Disable ANSI output (for debugging) |
|
||||
| `OTUI_USE_ALTERNATE_SCREEN` | boolean | true | Use alternate screen buffer |
|
||||
| `OTUI_OVERRIDE_STDOUT` | boolean | true | Override stdout stream |
|
||||
|
||||
### Terminal Capabilities
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `OPENTUI_NO_GRAPHICS` | boolean | false | Disable Kitty graphics protocol |
|
||||
| `OPENTUI_FORCE_UNICODE` | boolean | false | Force Mode 2026 Unicode support |
|
||||
| `OPENTUI_FORCE_WCWIDTH` | boolean | false | Use wcwidth for character width |
|
||||
| `OPENTUI_FORCE_NOZWJ` | boolean | false | Disable ZWJ emoji joining |
|
||||
| `OPENTUI_FORCE_EXPLICIT_WIDTH` | string | - | Force explicit width ("true"/"false") |
|
||||
|
||||
### Tree-sitter (Syntax Highlighting)
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `OTUI_TS_STYLE_WARN` | boolean | false | Warn on missing syntax styles |
|
||||
| `OTUI_TREE_SITTER_WORKER_PATH` | string | "" | Custom tree-sitter worker path |
|
||||
|
||||
### XDG Paths
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|----------|------|---------|-------------|
|
||||
| `XDG_CONFIG_HOME` | string | "" | User config directory |
|
||||
| `XDG_DATA_HOME` | string | "" | User data directory |
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Development Mode
|
||||
|
||||
```bash
|
||||
# Show debug overlay and console
|
||||
OTUI_SHOW_STATS=true SHOW_CONSOLE=true bun run src/index.ts
|
||||
|
||||
# Debug FFI issues
|
||||
OTUI_DEBUG_FFI=true OTUI_TRACE_FFI=true bun run src/index.ts
|
||||
|
||||
# Disable native rendering for testing
|
||||
OTUI_NO_NATIVE_RENDER=true bun run src/index.ts
|
||||
```
|
||||
|
||||
### Terminal Compatibility
|
||||
|
||||
```bash
|
||||
# Force wcwidth for problematic terminals
|
||||
OPENTUI_FORCE_WCWIDTH=true bun run src/index.ts
|
||||
|
||||
# Disable graphics for SSH sessions
|
||||
OPENTUI_NO_GRAPHICS=true bun run src/index.ts
|
||||
```
|
||||
|
||||
## Project Setup
|
||||
|
||||
### package.json
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "my-tui-app",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "bun run src/index.ts",
|
||||
"dev": "bun --watch run src/index.ts",
|
||||
"test": "bun test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opentui/core": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"typescript": "latest"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["bun-types"]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: OpenTUI uses `NodeNext` module resolution. All internal imports use `.js` extensions. If you use `bundler` resolution, imports still work but `NodeNext` is recommended for compatibility.
|
||||
|
||||
## Building Native Code
|
||||
|
||||
Native code changes require rebuilding:
|
||||
|
||||
```bash
|
||||
# From repo root (if developing OpenTUI itself)
|
||||
bun run build
|
||||
|
||||
# Zig is required for native compilation
|
||||
# Install: https://ziglang.org/learn/getting-started/
|
||||
```
|
||||
|
||||
**Note**: TypeScript changes do NOT require building. Bun runs TypeScript directly.
|
||||
@@ -0,0 +1,393 @@
|
||||
# Core Gotchas
|
||||
|
||||
## Runtime Environment
|
||||
|
||||
### Use Bun, Not Node.js
|
||||
|
||||
OpenTUI is built for Bun. Always use Bun commands:
|
||||
|
||||
```bash
|
||||
# CORRECT
|
||||
bun install @opentui/core
|
||||
bun run src/index.ts
|
||||
bun test
|
||||
|
||||
# WRONG
|
||||
npm install @opentui/core
|
||||
node src/index.ts
|
||||
npx jest
|
||||
```
|
||||
|
||||
### Bun APIs to Use
|
||||
|
||||
Prefer Bun's built-in APIs for your application code:
|
||||
|
||||
```typescript
|
||||
// CORRECT - Bun APIs
|
||||
Bun.serve({ ... }) // Instead of express
|
||||
Bun.$`ls -la` // Instead of execa
|
||||
import { Database } from "bun:sqlite" // Instead of better-sqlite3
|
||||
|
||||
// WRONG - Node.js patterns
|
||||
import express from "express"
|
||||
```
|
||||
|
||||
> **Note**: OpenTUI itself uses `node:fs` internally for file I/O (for broader compatibility), but your application code should still prefer Bun APIs where available.
|
||||
|
||||
### Avoid process.exit()
|
||||
|
||||
**Never use `process.exit()` directly** - it prevents proper terminal cleanup and can leave the terminal in a broken state (alternate screen mode, raw input mode, etc.).
|
||||
|
||||
```typescript
|
||||
// WRONG - Terminal may be left in broken state
|
||||
if (error) {
|
||||
console.error("Fatal error")
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// CORRECT - Use renderer.destroy() for cleanup
|
||||
if (error) {
|
||||
console.error("Fatal error")
|
||||
await renderer.destroy()
|
||||
process.exit(1) // Only after destroy
|
||||
}
|
||||
|
||||
// BETTER - Let destroy handle exit
|
||||
const renderer = await createCliRenderer({
|
||||
exitOnCtrlC: true, // Handles Ctrl+C properly
|
||||
})
|
||||
|
||||
// For programmatic exit
|
||||
renderer.destroy() // Cleans up and exits
|
||||
```
|
||||
|
||||
`renderer.destroy()` restores the terminal to its original state before exiting.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Bun auto-loads `.env` files. Don't use dotenv:
|
||||
|
||||
```typescript
|
||||
// CORRECT
|
||||
const apiKey = process.env.API_KEY
|
||||
|
||||
// WRONG
|
||||
import dotenv from "dotenv"
|
||||
dotenv.config()
|
||||
```
|
||||
|
||||
## Debugging TUIs
|
||||
|
||||
### Cannot See console.log Output
|
||||
|
||||
OpenTUI captures console output for the debug overlay. You can't see logs in the terminal while the TUI is running.
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. **Use the console overlay:**
|
||||
```typescript
|
||||
const renderer = await createCliRenderer()
|
||||
renderer.console.show()
|
||||
console.log("This appears in the overlay")
|
||||
```
|
||||
|
||||
2. **Toggle with keyboard:**
|
||||
```typescript
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.name === "f12") {
|
||||
renderer.console.toggle()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
3. **Write to a file:**
|
||||
```typescript
|
||||
import { appendFileSync } from "node:fs"
|
||||
function debugLog(msg: string) {
|
||||
appendFileSync("debug.log", `${new Date().toISOString()} ${msg}\n`)
|
||||
}
|
||||
```
|
||||
|
||||
4. **Disable console capture:**
|
||||
```bash
|
||||
OTUI_USE_CONSOLE=false bun run src/index.ts
|
||||
```
|
||||
|
||||
### Reproduce Issues in Tests
|
||||
|
||||
Don't guess at bugs. Create a reproducible test:
|
||||
|
||||
```typescript
|
||||
import { test, expect } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
|
||||
test("reproduces the issue", async () => {
|
||||
const { renderer, snapshot } = await createTestRenderer({
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
// Setup that reproduces the bug
|
||||
const box = new BoxRenderable(renderer, { ... })
|
||||
renderer.root.add(box)
|
||||
|
||||
// Verify with snapshot
|
||||
expect(snapshot()).toMatchSnapshot()
|
||||
})
|
||||
```
|
||||
|
||||
## Focus Management
|
||||
|
||||
### Components Must Be Focused
|
||||
|
||||
Input components only receive keyboard input when focused:
|
||||
|
||||
```typescript
|
||||
const input = new InputRenderable(renderer, {
|
||||
id: "input",
|
||||
placeholder: "Type here...",
|
||||
})
|
||||
|
||||
renderer.root.add(input)
|
||||
|
||||
// WRONG - input won't receive keystrokes
|
||||
// (no focus call)
|
||||
|
||||
// CORRECT
|
||||
input.focus()
|
||||
```
|
||||
|
||||
### Focus in Nested Components
|
||||
|
||||
When a component is inside a container, focus the component directly:
|
||||
|
||||
```typescript
|
||||
const container = new BoxRenderable(renderer, { id: "container" })
|
||||
const input = new InputRenderable(renderer, { id: "input" })
|
||||
container.add(input)
|
||||
renderer.root.add(container)
|
||||
|
||||
// WRONG
|
||||
container.focus()
|
||||
|
||||
// CORRECT
|
||||
input.focus()
|
||||
|
||||
// Or use getRenderable
|
||||
container.getRenderable("input")?.focus()
|
||||
|
||||
// Or use delegate (constructs)
|
||||
const form = delegate(
|
||||
{ focus: "input" },
|
||||
Box({}, Input({ id: "input" })),
|
||||
)
|
||||
form.focus() // Routes to the input
|
||||
```
|
||||
|
||||
## Build Requirements
|
||||
|
||||
### Zig is Required
|
||||
|
||||
Native code compilation requires Zig:
|
||||
|
||||
```bash
|
||||
# Install Zig first
|
||||
# macOS
|
||||
brew install zig
|
||||
|
||||
# Linux
|
||||
# Download from https://ziglang.org/download/
|
||||
|
||||
# Then build
|
||||
bun run build
|
||||
```
|
||||
|
||||
### When to Build
|
||||
|
||||
- **TypeScript changes**: NO build needed (Bun runs TS directly)
|
||||
- **Native code changes**: Build required
|
||||
|
||||
```bash
|
||||
# Only needed when changing native (Zig) code
|
||||
cd packages/core
|
||||
bun run build
|
||||
```
|
||||
|
||||
## Common Errors
|
||||
|
||||
### "Cannot read properties of undefined"
|
||||
|
||||
Usually means a renderable wasn't added to the tree:
|
||||
|
||||
```typescript
|
||||
// WRONG - not added to tree
|
||||
const text = new TextRenderable(renderer, { content: "Hello" })
|
||||
// text.someMethod() // May fail
|
||||
|
||||
// CORRECT
|
||||
const text = new TextRenderable(renderer, { content: "Hello" })
|
||||
renderer.root.add(text)
|
||||
text.someMethod()
|
||||
```
|
||||
|
||||
### Layout Not Updating
|
||||
|
||||
Yoga layout is calculated lazily. Force a recalculation:
|
||||
|
||||
```typescript
|
||||
// After changing layout properties
|
||||
box.setWidth(newWidth)
|
||||
renderer.requestRender()
|
||||
```
|
||||
|
||||
### Text Overflow/Clipping
|
||||
|
||||
Text doesn't wrap by default. Set explicit width:
|
||||
|
||||
```typescript
|
||||
// May overflow
|
||||
const text = new TextRenderable(renderer, {
|
||||
content: "Very long text that might overflow the terminal...",
|
||||
})
|
||||
|
||||
// Contained within width
|
||||
const text = new TextRenderable(renderer, {
|
||||
content: "Very long text that might overflow the terminal...",
|
||||
width: 40, // Will clip or wrap based on parent
|
||||
})
|
||||
```
|
||||
|
||||
### Colors Not Showing
|
||||
|
||||
Check terminal capability and color format:
|
||||
|
||||
```typescript
|
||||
// CORRECT formats
|
||||
fg: "#FF0000" // Hex
|
||||
fg: "red" // CSS color name
|
||||
fg: RGBA.fromHex("#FF0000")
|
||||
|
||||
// WRONG
|
||||
fg: "FF0000" // Missing #
|
||||
fg: 0xFF0000 // Number (not supported)
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
### Avoid Frequent Re-renders
|
||||
|
||||
Batch updates when possible:
|
||||
|
||||
```typescript
|
||||
// WRONG - multiple render calls
|
||||
item1.setContent("...")
|
||||
item2.setContent("...")
|
||||
item3.setContent("...")
|
||||
|
||||
// BETTER - single render after all updates
|
||||
// (OpenTUI batches automatically, but be mindful)
|
||||
items.forEach((item, i) => {
|
||||
item.setContent(data[i])
|
||||
})
|
||||
```
|
||||
|
||||
### Minimize Tree Depth
|
||||
|
||||
Deep nesting impacts layout calculation:
|
||||
|
||||
```typescript
|
||||
// Avoid unnecessary wrappers
|
||||
// WRONG
|
||||
Box({}, Box({}, Box({}, Text({ content: "Hello" }))))
|
||||
|
||||
// CORRECT
|
||||
Box({}, Text({ content: "Hello" }))
|
||||
```
|
||||
|
||||
### Use display: none
|
||||
|
||||
Hide elements instead of removing/re-adding:
|
||||
|
||||
```typescript
|
||||
// For toggling visibility
|
||||
element.setDisplay("none") // Hidden
|
||||
element.setDisplay("flex") // Visible
|
||||
|
||||
// Instead of
|
||||
parent.remove(element)
|
||||
parent.add(element)
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Runner
|
||||
|
||||
Use Bun's test runner:
|
||||
|
||||
```typescript
|
||||
import { test, expect, beforeEach, afterEach } from "bun:test"
|
||||
|
||||
test("my test", () => {
|
||||
expect(1 + 1).toBe(2)
|
||||
})
|
||||
```
|
||||
|
||||
### Test from Package Directories
|
||||
|
||||
Run tests from the specific package directory:
|
||||
|
||||
```bash
|
||||
# CORRECT
|
||||
cd packages/core
|
||||
bun test
|
||||
|
||||
# For native tests
|
||||
cd packages/core
|
||||
bun run test:native
|
||||
```
|
||||
|
||||
### Filter Tests
|
||||
|
||||
```bash
|
||||
# Bun test filter
|
||||
bun test --filter "component name"
|
||||
|
||||
# Native test filter
|
||||
bun run test:native -Dtest-filter="test name"
|
||||
```
|
||||
|
||||
## Keyboard Handling
|
||||
|
||||
### Key Names
|
||||
|
||||
Common key names for `KeyEvent.name`:
|
||||
|
||||
```typescript
|
||||
// Letters/numbers
|
||||
"a", "b", ..., "z"
|
||||
"1", "2", ..., "0"
|
||||
|
||||
// Special keys
|
||||
"escape", "enter", "return", "tab", "backspace", "delete"
|
||||
"up", "down", "left", "right"
|
||||
"home", "end", "pageup", "pagedown"
|
||||
"f1", "f2", ..., "f12"
|
||||
"space"
|
||||
|
||||
// Modifiers (check boolean properties)
|
||||
key.ctrl // Ctrl held
|
||||
key.shift // Shift held
|
||||
key.meta // Alt held
|
||||
key.option // Option held (macOS)
|
||||
```
|
||||
|
||||
### Key Event Types
|
||||
|
||||
```typescript
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
// eventType: "press" | "release" | "repeat"
|
||||
if (key.eventType === "repeat") {
|
||||
// Key being held down
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,449 @@
|
||||
# Core Patterns
|
||||
|
||||
## Composition Patterns
|
||||
|
||||
### Imperative Composition
|
||||
|
||||
Create renderables and compose with `.add()`:
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, BoxRenderable, TextRenderable } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
// Create parent
|
||||
const container = new BoxRenderable(renderer, {
|
||||
id: "container",
|
||||
flexDirection: "column",
|
||||
padding: 1,
|
||||
})
|
||||
|
||||
// Create children
|
||||
const header = new TextRenderable(renderer, {
|
||||
id: "header",
|
||||
content: "Header",
|
||||
fg: "#00FF00",
|
||||
})
|
||||
|
||||
const body = new TextRenderable(renderer, {
|
||||
id: "body",
|
||||
content: "Body content",
|
||||
})
|
||||
|
||||
// Compose tree
|
||||
container.add(header)
|
||||
container.add(body)
|
||||
renderer.root.add(container)
|
||||
```
|
||||
|
||||
### Declarative Composition (Constructs)
|
||||
|
||||
Use VNode functions for cleaner composition:
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, Box, Text, Input, delegate } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
// Compose as function calls
|
||||
const ui = Box(
|
||||
{ flexDirection: "column", padding: 1 },
|
||||
Text({ content: "Header", fg: "#00FF00" }),
|
||||
Box(
|
||||
{ flexDirection: "row", gap: 2 },
|
||||
Text({ content: "Name:" }),
|
||||
Input({ id: "name", placeholder: "Enter name..." }),
|
||||
),
|
||||
)
|
||||
|
||||
renderer.root.add(ui)
|
||||
```
|
||||
|
||||
### Reusable Components
|
||||
|
||||
Create factory functions for reusable UI pieces:
|
||||
|
||||
```typescript
|
||||
// Imperative factory
|
||||
function createLabeledInput(
|
||||
renderer: RenderContext,
|
||||
props: { id: string; label: string; placeholder: string }
|
||||
) {
|
||||
const container = new BoxRenderable(renderer, {
|
||||
id: `${props.id}-container`,
|
||||
flexDirection: "row",
|
||||
gap: 1,
|
||||
})
|
||||
|
||||
container.add(new TextRenderable(renderer, {
|
||||
id: `${props.id}-label`,
|
||||
content: props.label,
|
||||
}))
|
||||
|
||||
container.add(new InputRenderable(renderer, {
|
||||
id: `${props.id}-input`,
|
||||
placeholder: props.placeholder,
|
||||
width: 20,
|
||||
}))
|
||||
|
||||
return container
|
||||
}
|
||||
|
||||
// Declarative factory
|
||||
function LabeledInput(props: { id: string; label: string; placeholder: string }) {
|
||||
return delegate(
|
||||
{ focus: `${props.id}-input` },
|
||||
Box(
|
||||
{ flexDirection: "row", gap: 1 },
|
||||
Text({ content: props.label }),
|
||||
Input({
|
||||
id: `${props.id}-input`,
|
||||
placeholder: props.placeholder,
|
||||
width: 20,
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Focus Delegation
|
||||
|
||||
Route focus calls to nested elements:
|
||||
|
||||
```typescript
|
||||
import { delegate, Box, Input, Text } from "@opentui/core"
|
||||
|
||||
const form = delegate(
|
||||
{
|
||||
focus: "email-input", // Route .focus() to this child
|
||||
blur: "email-input", // Route .blur() to this child
|
||||
},
|
||||
Box(
|
||||
{ border: true, padding: 1 },
|
||||
Text({ content: "Email:" }),
|
||||
Input({ id: "email-input", placeholder: "you@example.com" }),
|
||||
),
|
||||
)
|
||||
|
||||
// This focuses the input inside, not the box
|
||||
form.focus()
|
||||
```
|
||||
|
||||
## Event Handling
|
||||
|
||||
### Keyboard Events
|
||||
|
||||
```typescript
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
// Global keyboard handler
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (key.ctrl && key.name === "c") {
|
||||
// Ctrl+C handling (if exitOnCtrlC is false)
|
||||
}
|
||||
|
||||
if (key.name === "tab") {
|
||||
// Tab navigation
|
||||
focusNext()
|
||||
}
|
||||
})
|
||||
|
||||
// Paste events
|
||||
renderer.keyInput.on("paste", (event) => {
|
||||
const text = decodePasteBytes(event.bytes)
|
||||
currentInput?.setValue(currentInput.value + text)
|
||||
})
|
||||
```
|
||||
|
||||
### Component Events
|
||||
|
||||
```typescript
|
||||
import { InputRenderable, InputRenderableEvents } from "@opentui/core"
|
||||
|
||||
const input = new InputRenderable(renderer, {
|
||||
id: "search",
|
||||
placeholder: "Search...",
|
||||
})
|
||||
|
||||
input.on(InputRenderableEvents.CHANGE, (value) => {
|
||||
performSearch(value)
|
||||
})
|
||||
|
||||
// Select events
|
||||
const select = new SelectRenderable(renderer, {
|
||||
id: "menu",
|
||||
options: [...],
|
||||
})
|
||||
|
||||
select.on(SelectRenderableEvents.ITEM_SELECTED, (index, option) => {
|
||||
handleSelection(option)
|
||||
})
|
||||
|
||||
select.on(SelectRenderableEvents.SELECTION_CHANGED, (index, option) => {
|
||||
showPreview(option)
|
||||
})
|
||||
```
|
||||
|
||||
### Mouse Events
|
||||
|
||||
```typescript
|
||||
const button = new BoxRenderable(renderer, {
|
||||
id: "button",
|
||||
border: true,
|
||||
onMouseDown: (event) => {
|
||||
button.setBackgroundColor("#444444")
|
||||
},
|
||||
onMouseUp: (event) => {
|
||||
button.setBackgroundColor("#222222")
|
||||
handleClick()
|
||||
},
|
||||
onMouseMove: (event) => {
|
||||
// Hover effect
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
### Local State
|
||||
|
||||
Manage state in closures or objects:
|
||||
|
||||
```typescript
|
||||
// Closure-based state
|
||||
function createCounter(renderer: RenderContext) {
|
||||
let count = 0
|
||||
|
||||
const display = new TextRenderable(renderer, {
|
||||
id: "count",
|
||||
content: `Count: ${count}`,
|
||||
})
|
||||
|
||||
const increment = () => {
|
||||
count++
|
||||
display.setContent(`Count: ${count}`)
|
||||
}
|
||||
|
||||
return { display, increment }
|
||||
}
|
||||
|
||||
// Class-based state
|
||||
class CounterWidget {
|
||||
private count = 0
|
||||
private display: TextRenderable
|
||||
|
||||
constructor(renderer: RenderContext) {
|
||||
this.display = new TextRenderable(renderer, {
|
||||
id: "count",
|
||||
content: this.formatCount(),
|
||||
})
|
||||
}
|
||||
|
||||
private formatCount() {
|
||||
return `Count: ${this.count}`
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.count++
|
||||
this.display.setContent(this.formatCount())
|
||||
}
|
||||
|
||||
getRenderable() {
|
||||
return this.display
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Focus Management
|
||||
|
||||
Track and manage focus across components:
|
||||
|
||||
```typescript
|
||||
class FocusManager {
|
||||
private focusables: Renderable[] = []
|
||||
private currentIndex = 0
|
||||
|
||||
register(renderable: Renderable) {
|
||||
this.focusables.push(renderable)
|
||||
}
|
||||
|
||||
focusNext() {
|
||||
this.focusables[this.currentIndex]?.blur()
|
||||
this.currentIndex = (this.currentIndex + 1) % this.focusables.length
|
||||
this.focusables[this.currentIndex]?.focus()
|
||||
}
|
||||
|
||||
focusPrevious() {
|
||||
this.focusables[this.currentIndex]?.blur()
|
||||
this.currentIndex = (this.currentIndex - 1 + this.focusables.length) % this.focusables.length
|
||||
this.focusables[this.currentIndex]?.focus()
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const focusManager = new FocusManager()
|
||||
focusManager.register(input1)
|
||||
focusManager.register(input2)
|
||||
focusManager.register(select1)
|
||||
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.name === "tab") {
|
||||
key.shift ? focusManager.focusPrevious() : focusManager.focusNext()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Lifecycle Patterns
|
||||
|
||||
### Cleanup
|
||||
|
||||
Always clean up resources:
|
||||
|
||||
```typescript
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
// Track intervals/timeouts
|
||||
const intervals: Timer[] = []
|
||||
|
||||
intervals.push(setInterval(() => {
|
||||
updateClock()
|
||||
}, 1000))
|
||||
|
||||
// Cleanup on exit
|
||||
process.on("SIGINT", () => {
|
||||
intervals.forEach(clearInterval)
|
||||
renderer.destroy()
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
// Or use onDestroy callback
|
||||
const renderer = await createCliRenderer({
|
||||
onDestroy: () => {
|
||||
intervals.forEach(clearInterval)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Dynamic Updates
|
||||
|
||||
Update UI based on external data:
|
||||
|
||||
```typescript
|
||||
async function createDashboard(renderer: RenderContext) {
|
||||
const statsText = new TextRenderable(renderer, {
|
||||
id: "stats",
|
||||
content: "Loading...",
|
||||
})
|
||||
|
||||
// Poll for updates
|
||||
const updateStats = async () => {
|
||||
const data = await fetchStats()
|
||||
statsText.setContent(`CPU: ${data.cpu}% | Memory: ${data.memory}%`)
|
||||
}
|
||||
|
||||
// Initial load
|
||||
await updateStats()
|
||||
|
||||
// Periodic updates
|
||||
setInterval(updateStats, 5000)
|
||||
|
||||
return statsText
|
||||
}
|
||||
```
|
||||
|
||||
## Layout Patterns
|
||||
|
||||
### Responsive Layout
|
||||
|
||||
Adapt to terminal size:
|
||||
|
||||
```typescript
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
const mainPanel = new BoxRenderable(renderer, {
|
||||
id: "main",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
flexDirection: renderer.width > 80 ? "row" : "column",
|
||||
})
|
||||
|
||||
// Listen for resize
|
||||
process.stdout.on("resize", () => {
|
||||
mainPanel.setFlexDirection(renderer.width > 80 ? "row" : "column")
|
||||
})
|
||||
```
|
||||
|
||||
### Split Panels
|
||||
|
||||
```typescript
|
||||
function createSplitView(renderer: RenderContext, ratio = 0.3) {
|
||||
const container = new BoxRenderable(renderer, {
|
||||
id: "split",
|
||||
flexDirection: "row",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
})
|
||||
|
||||
const left = new BoxRenderable(renderer, {
|
||||
id: "left",
|
||||
width: `${ratio * 100}%`,
|
||||
border: true,
|
||||
})
|
||||
|
||||
const right = new BoxRenderable(renderer, {
|
||||
id: "right",
|
||||
flexGrow: 1,
|
||||
border: true,
|
||||
})
|
||||
|
||||
container.add(left)
|
||||
container.add(right)
|
||||
|
||||
return { container, left, right }
|
||||
}
|
||||
```
|
||||
|
||||
## Debugging Patterns
|
||||
|
||||
### Console Overlay
|
||||
|
||||
Use the built-in console for debugging:
|
||||
|
||||
```typescript
|
||||
const renderer = await createCliRenderer({
|
||||
consoleOptions: {
|
||||
startInDebugMode: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Show console
|
||||
renderer.console.show()
|
||||
|
||||
// All console methods work
|
||||
console.log("Debug info")
|
||||
console.warn("Warning")
|
||||
console.error("Error")
|
||||
|
||||
// Toggle with keyboard
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.name === "f12") {
|
||||
renderer.console.toggle()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### State Inspection
|
||||
|
||||
```typescript
|
||||
function debugState(label: string, state: unknown) {
|
||||
console.log(`[${label}]`, JSON.stringify(state, null, 2))
|
||||
}
|
||||
|
||||
// In your update logic
|
||||
debugState("form", { name: nameInput.value, email: emailInput.value })
|
||||
```
|
||||
@@ -0,0 +1,617 @@
|
||||
# Keyboard Input Handling
|
||||
|
||||
How to handle keyboard input in OpenTUI applications.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTUI provides keyboard input handling through:
|
||||
- **Core**: `renderer.keyInput` EventEmitter
|
||||
- **React**: `useKeyboard()` hook
|
||||
- **Solid**: `useKeyboard()` hook
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this reference when you need keyboard shortcuts, focus-aware input handling, or custom keybindings.
|
||||
|
||||
## KeyEvent Object
|
||||
|
||||
All keyboard handlers receive a `KeyEvent` object:
|
||||
|
||||
```typescript
|
||||
interface KeyEvent {
|
||||
name: string // Key name: "a", "escape", "f1", etc.
|
||||
sequence: string // Raw escape sequence
|
||||
ctrl: boolean // Ctrl modifier held
|
||||
shift: boolean // Shift modifier held
|
||||
meta: boolean // Alt modifier held
|
||||
option: boolean // Option modifier held (macOS)
|
||||
eventType: "press" | "release" | "repeat"
|
||||
repeated: boolean // Key is being held (repeat event)
|
||||
}
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Core
|
||||
|
||||
```typescript
|
||||
import { createCliRenderer, type KeyEvent } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
|
||||
renderer.keyInput.on("keypress", (key: KeyEvent) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
if (key.ctrl && key.name === "s") {
|
||||
saveDocument()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### React
|
||||
|
||||
```tsx
|
||||
import { useKeyboard, useRenderer } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
return <text>Press ESC to exit</text>
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Solid
|
||||
|
||||
```tsx
|
||||
import { useKeyboard, useRenderer } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
return <text>Press ESC to exit</text>
|
||||
}
|
||||
```
|
||||
|
||||
## Key Names
|
||||
|
||||
### Alphabetic Keys
|
||||
|
||||
Lowercase: `a`, `b`, `c`, ... `z`
|
||||
|
||||
With Shift: Check `key.shift && key.name === "a"` for uppercase
|
||||
|
||||
### Numeric Keys
|
||||
|
||||
`0`, `1`, `2`, ... `9`
|
||||
|
||||
### Function Keys
|
||||
|
||||
`f1`, `f2`, `f3`, ... `f12`
|
||||
|
||||
### Special Keys
|
||||
|
||||
| Key Name | Description |
|
||||
|----------|-------------|
|
||||
| `escape` | Escape key |
|
||||
| `enter` | Enter/Return |
|
||||
| `return` | Enter/Return (alias) |
|
||||
| `tab` | Tab key |
|
||||
| `backspace` | Backspace |
|
||||
| `delete` | Delete key |
|
||||
| `space` | Spacebar |
|
||||
|
||||
### Arrow Keys
|
||||
|
||||
| Key Name | Description |
|
||||
|----------|-------------|
|
||||
| `up` | Up arrow |
|
||||
| `down` | Down arrow |
|
||||
| `left` | Left arrow |
|
||||
| `right` | Right arrow |
|
||||
|
||||
### Navigation Keys
|
||||
|
||||
| Key Name | Description |
|
||||
|----------|-------------|
|
||||
| `home` | Home key |
|
||||
| `end` | End key |
|
||||
| `pageup` | Page Up |
|
||||
| `pagedown` | Page Down |
|
||||
| `insert` | Insert key |
|
||||
|
||||
## Modifier Keys
|
||||
|
||||
Check modifier properties on `KeyEvent`:
|
||||
|
||||
```typescript
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.ctrl && key.name === "c") {
|
||||
// Ctrl+C
|
||||
}
|
||||
|
||||
if (key.shift && key.name === "tab") {
|
||||
// Shift+Tab
|
||||
}
|
||||
|
||||
if (key.meta && key.name === "s") {
|
||||
// Alt+S (meta = Alt on most systems)
|
||||
}
|
||||
|
||||
if (key.option && key.name === "a") {
|
||||
// Option+A (macOS)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Modifier Combinations
|
||||
|
||||
```typescript
|
||||
// Ctrl+Shift+S
|
||||
if (key.ctrl && key.shift && key.name === "s") {
|
||||
saveAs()
|
||||
}
|
||||
|
||||
// Ctrl+Alt+Delete (careful with system shortcuts!)
|
||||
if (key.ctrl && key.meta && key.name === "delete") {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Event Types
|
||||
|
||||
### Press Events (Default)
|
||||
|
||||
Normal key press:
|
||||
|
||||
```typescript
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.eventType === "press") {
|
||||
// Initial key press
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Repeat Events
|
||||
|
||||
Key held down:
|
||||
|
||||
```typescript
|
||||
renderer.keyInput.on("keypress", (key) => {
|
||||
if (key.eventType === "repeat" || key.repeated) {
|
||||
// Key is being held
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Release Events
|
||||
|
||||
Key released (opt-in):
|
||||
|
||||
```tsx
|
||||
// React
|
||||
useKeyboard(
|
||||
(key) => {
|
||||
if (key.eventType === "release") {
|
||||
// Key released
|
||||
}
|
||||
},
|
||||
{ release: true } // Enable release events
|
||||
)
|
||||
|
||||
// Solid
|
||||
useKeyboard(
|
||||
(key) => {
|
||||
if (key.eventType === "release") {
|
||||
// Key released
|
||||
}
|
||||
},
|
||||
{ release: true }
|
||||
)
|
||||
```
|
||||
|
||||
## Patterns
|
||||
|
||||
### Navigation Menu
|
||||
|
||||
```tsx
|
||||
function Menu() {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0)
|
||||
const items = ["Home", "Settings", "Help", "Quit"]
|
||||
|
||||
useKeyboard((key) => {
|
||||
switch (key.name) {
|
||||
case "up":
|
||||
case "k":
|
||||
setSelectedIndex(i => Math.max(0, i - 1))
|
||||
break
|
||||
case "down":
|
||||
case "j":
|
||||
setSelectedIndex(i => Math.min(items.length - 1, i + 1))
|
||||
break
|
||||
case "enter":
|
||||
handleSelect(items[selectedIndex])
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
{items.map((item, i) => (
|
||||
<text
|
||||
key={item}
|
||||
fg={i === selectedIndex ? "#00FF00" : "#FFFFFF"}
|
||||
>
|
||||
{i === selectedIndex ? "> " : " "}{item}
|
||||
</text>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Modal Escape
|
||||
|
||||
```tsx
|
||||
function Modal({ onClose, children }) {
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
onClose()
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box border padding={2}>
|
||||
{children}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Vim-style Modes
|
||||
|
||||
```tsx
|
||||
function Editor() {
|
||||
const [mode, setMode] = useState<"normal" | "insert">("normal")
|
||||
const [content, setContent] = useState("")
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (mode === "normal") {
|
||||
switch (key.name) {
|
||||
case "i":
|
||||
setMode("insert")
|
||||
break
|
||||
case "escape":
|
||||
// Already in normal mode
|
||||
break
|
||||
case "j":
|
||||
moveCursorDown()
|
||||
break
|
||||
case "k":
|
||||
moveCursorUp()
|
||||
break
|
||||
}
|
||||
} else if (mode === "insert") {
|
||||
if (key.name === "escape") {
|
||||
setMode("normal")
|
||||
}
|
||||
// Input component handles text in insert mode
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text>Mode: {mode}</text>
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
focused={mode === "insert"}
|
||||
/>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Game Controls
|
||||
|
||||
```tsx
|
||||
function Game() {
|
||||
const [pressed, setPressed] = useState(new Set<string>())
|
||||
|
||||
useKeyboard(
|
||||
(key) => {
|
||||
setPressed(keys => {
|
||||
const newKeys = new Set(keys)
|
||||
if (key.eventType === "release") {
|
||||
newKeys.delete(key.name)
|
||||
} else {
|
||||
newKeys.add(key.name)
|
||||
}
|
||||
return newKeys
|
||||
})
|
||||
},
|
||||
{ release: true }
|
||||
)
|
||||
|
||||
// Game logic uses pressed set
|
||||
useEffect(() => {
|
||||
if (pressed.has("up") || pressed.has("w")) {
|
||||
moveUp()
|
||||
}
|
||||
if (pressed.has("down") || pressed.has("s")) {
|
||||
moveDown()
|
||||
}
|
||||
}, [pressed])
|
||||
|
||||
return <text>WASD or arrows to move</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Keyboard Shortcuts Help
|
||||
|
||||
```tsx
|
||||
function ShortcutsHelp() {
|
||||
const shortcuts = [
|
||||
{ keys: "Ctrl+S", action: "Save" },
|
||||
{ keys: "Ctrl+Q", action: "Quit" },
|
||||
{ keys: "Ctrl+F", action: "Find" },
|
||||
{ keys: "Tab", action: "Next field" },
|
||||
{ keys: "Shift+Tab", action: "Previous field" },
|
||||
]
|
||||
|
||||
return (
|
||||
<box border title="Keyboard Shortcuts" padding={1}>
|
||||
{shortcuts.map(({ keys, action }) => (
|
||||
<box key={keys} flexDirection="row">
|
||||
<text width={15} fg="#00FFFF">{keys}</text>
|
||||
<text>{action}</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Paste Events
|
||||
|
||||
Handle pasted content. Paste events deliver raw bytes, not decoded text.
|
||||
|
||||
### PasteEvent Object
|
||||
|
||||
```typescript
|
||||
import { type PasteEvent } from "@opentui/core"
|
||||
|
||||
interface PasteEvent {
|
||||
type: "paste" // Always "paste"
|
||||
bytes: Uint8Array // Raw pasted bytes
|
||||
metadata?: PasteMetadata // Optional metadata
|
||||
preventDefault(): void // Prevent default paste handling
|
||||
defaultPrevented: boolean // Whether preventDefault was called
|
||||
}
|
||||
|
||||
interface PasteMetadata {
|
||||
mimeType?: string // MIME type if available
|
||||
kind?: PasteKind // Paste kind
|
||||
}
|
||||
```
|
||||
|
||||
### Decoding Paste Bytes
|
||||
|
||||
Use `decodePasteBytes` to convert raw bytes to a string, and `stripAnsiSequences` to remove ANSI escape codes:
|
||||
|
||||
```typescript
|
||||
import { decodePasteBytes, stripAnsiSequences } from "@opentui/core"
|
||||
|
||||
const text = decodePasteBytes(event.bytes) // Decode UTF-8
|
||||
const clean = stripAnsiSequences(decodePasteBytes(event.bytes)) // Decode + strip ANSI
|
||||
```
|
||||
|
||||
### Core
|
||||
|
||||
```typescript
|
||||
import { type PasteEvent, decodePasteBytes } from "@opentui/core"
|
||||
|
||||
renderer.keyInput.on("paste", (event: PasteEvent) => {
|
||||
const text = decodePasteBytes(event.bytes)
|
||||
console.log("Pasted:", text)
|
||||
})
|
||||
```
|
||||
|
||||
### Solid
|
||||
|
||||
Solid provides a dedicated `usePaste` hook:
|
||||
|
||||
```tsx
|
||||
import { usePaste } from "@opentui/solid"
|
||||
import { decodePasteBytes } from "@opentui/core"
|
||||
|
||||
function App() {
|
||||
usePaste((event) => {
|
||||
const text = decodePasteBytes(event.bytes)
|
||||
console.log("Pasted:", text)
|
||||
})
|
||||
|
||||
return <text>Paste something</text>
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: `usePaste` is **Solid-only**. React does not have this hook - handle paste via the Core event emitter or input component's `onChange`.
|
||||
|
||||
## Text Selection
|
||||
|
||||
Text selection is renderer-managed. The renderer owns a single `Selection` object, walks the renderable tree to find selectable children, and emits a `"selection"` event when the user finishes selecting (mouse-up). The `Selection` object aggregates text from all selected renderables automatically.
|
||||
|
||||
### Making Renderables Selectable
|
||||
|
||||
A renderable must have `selectable` set to `true` to participate in selection. Text-based renderables (`TextRenderable`, `TextareaRenderable`, `ASCIIFontRenderable`, `TextTableRenderable`) support this:
|
||||
|
||||
```tsx
|
||||
// React / Solid
|
||||
<text selectable>This text can be selected</text>
|
||||
|
||||
// Core
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: "label",
|
||||
content: "This text can be selected",
|
||||
selectable: true,
|
||||
})
|
||||
```
|
||||
|
||||
### Copy-on-Selection (Core)
|
||||
|
||||
Listen to the renderer's `"selection"` event. The `Selection` object's `getSelectedText()` returns text aggregated from all selected renderables in reading order:
|
||||
|
||||
```typescript
|
||||
import type { Selection } from "@opentui/core"
|
||||
|
||||
renderer.on("selection", (selection: Selection) => {
|
||||
const text = selection.getSelectedText()
|
||||
if (text) {
|
||||
renderer.copyToClipboardOSC52(text)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
> **Important**: Call `selection.getSelectedText()` on the `Selection` object from the event -- not `renderer.root.getSelectedText()`. Individual renderables only return their own selected text. The `Selection` object aggregates across the tree.
|
||||
|
||||
### Copy-on-Selection (Solid)
|
||||
|
||||
```tsx
|
||||
import { useSelectionHandler } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
useSelectionHandler((selection) => {
|
||||
const text = selection.getSelectedText()
|
||||
if (text) {
|
||||
renderer.copyToClipboardOSC52(text)
|
||||
}
|
||||
})
|
||||
|
||||
return <text selectable>Select this text</text>
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: `useSelectionHandler` is **Solid-only**. React does not have this hook -- use the Core `renderer.on("selection", ...)` event.
|
||||
|
||||
### Selection Object
|
||||
|
||||
The `Selection` object passed to the event callback:
|
||||
|
||||
```typescript
|
||||
selection.getSelectedText() // Aggregated text from all selected renderables
|
||||
selection.bounds // { startX, startY, endX, endY } bounding rect
|
||||
selection.selectedRenderables // Renderable[] with active selections
|
||||
selection.isActive // Whether selection is still active
|
||||
```
|
||||
|
||||
Individual renderables also expose:
|
||||
|
||||
```typescript
|
||||
renderable.hasSelection() // Does this renderable have selected text?
|
||||
renderable.getSelectedText() // Selected text in this renderable only
|
||||
```
|
||||
|
||||
### How Selection Traversal Works
|
||||
|
||||
When the user drags to select, the renderer:
|
||||
1. Identifies the selection container (common ancestor of start and end points)
|
||||
2. Walks all `selectable` descendants within the selection bounds
|
||||
3. Calls `onSelectionChanged(selection)` on each, which computes local selection
|
||||
4. Tracks which renderables have active selections in `selection.selectedRenderables`
|
||||
|
||||
This means selection works across multiple renderables. Dragging across two `<text selectable>` elements selects text in both, and `selection.getSelectedText()` joins them with newlines.
|
||||
|
||||
## Clipboard API (OSC 52)
|
||||
|
||||
Copy text to the system clipboard using OSC 52 escape sequences. Works over SSH and in most modern terminal emulators.
|
||||
|
||||
```typescript
|
||||
// Copy to clipboard
|
||||
const success = renderer.copyToClipboardOSC52("text to copy")
|
||||
|
||||
// Check if OSC 52 is supported
|
||||
if (renderer.isOsc52Supported()) {
|
||||
renderer.copyToClipboardOSC52("Hello!")
|
||||
}
|
||||
|
||||
// Clear clipboard
|
||||
renderer.clearClipboardOSC52()
|
||||
|
||||
// Target specific clipboard (X11)
|
||||
import { ClipboardTarget } from "@opentui/core"
|
||||
renderer.copyToClipboardOSC52("text", ClipboardTarget.Primary) // X11 primary
|
||||
renderer.copyToClipboardOSC52("text", ClipboardTarget.Clipboard) // System clipboard (default)
|
||||
```
|
||||
|
||||
## Focus and Input Components
|
||||
|
||||
Input components (`<input>`, `<textarea>`, `<select>`) capture keyboard events when focused:
|
||||
|
||||
```tsx
|
||||
<input focused /> // Receives keyboard input
|
||||
|
||||
// Global useKeyboard still fires, but input consumes characters
|
||||
```
|
||||
|
||||
To prevent conflicts, check if an input is focused before handling global shortcuts:
|
||||
|
||||
```tsx
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
const [inputFocused, setInputFocused] = useState(false)
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (inputFocused) return // Let input handle it
|
||||
|
||||
// Global shortcuts
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<input
|
||||
focused={inputFocused}
|
||||
onFocus={() => setInputFocused(true)}
|
||||
onBlur={() => setInputFocused(false)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Terminal Limitations
|
||||
|
||||
Some key combinations are captured by the terminal or OS:
|
||||
- `Ctrl+C` often sends SIGINT (use `exitOnCtrlC: false` to handle)
|
||||
- `Ctrl+Z` suspends the process
|
||||
- Some function keys may be intercepted
|
||||
|
||||
### SSH and Remote Sessions
|
||||
|
||||
Key detection may vary over SSH. Test on target environments.
|
||||
|
||||
### Multiple Handlers
|
||||
|
||||
Multiple `useKeyboard` calls all receive events. Coordinate handlers to prevent conflicts.
|
||||
|
||||
## See Also
|
||||
|
||||
- [React API](../react/api.md) - `useKeyboard` hook reference
|
||||
- [Solid API](../solid/api.md) - `useKeyboard` hook reference
|
||||
- [Input Components](../components/inputs.md) - Focus management with input, textarea, select
|
||||
- [Testing](../testing/REFERENCE.md) - Simulating key presses in tests
|
||||
@@ -0,0 +1,337 @@
|
||||
# OpenTUI Layout System
|
||||
|
||||
OpenTUI uses the Yoga layout engine, providing CSS Flexbox-like capabilities for positioning and sizing components in the terminal.
|
||||
|
||||
## Overview
|
||||
|
||||
Key concepts:
|
||||
- **Flexbox model**: Familiar CSS Flexbox properties
|
||||
- **Yoga engine**: Facebook's cross-platform layout engine
|
||||
- **Terminal units**: Dimensions are in character cells (columns x rows)
|
||||
- **Percentage support**: Relative sizing based on parent
|
||||
|
||||
## Flex Container Properties
|
||||
|
||||
### flexDirection
|
||||
|
||||
Controls the main axis direction:
|
||||
|
||||
```tsx
|
||||
// Row (default) - children flow horizontally
|
||||
<box flexDirection="row">
|
||||
<text>1</text>
|
||||
<text>2</text>
|
||||
<text>3</text>
|
||||
</box>
|
||||
// Output: 1 2 3
|
||||
|
||||
// Column - children flow vertically
|
||||
<box flexDirection="column">
|
||||
<text>1</text>
|
||||
<text>2</text>
|
||||
<text>3</text>
|
||||
</box>
|
||||
// Output:
|
||||
// 1
|
||||
// 2
|
||||
// 3
|
||||
|
||||
// Reverse variants
|
||||
<box flexDirection="row-reverse">...</box> // 3 2 1
|
||||
<box flexDirection="column-reverse">...</box> // Bottom to top
|
||||
```
|
||||
|
||||
### justifyContent
|
||||
|
||||
Aligns children along the main axis:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" width={40} justifyContent="flex-start">
|
||||
{/* Children at start (left for row) */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" width={40} justifyContent="flex-end">
|
||||
{/* Children at end (right for row) */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" width={40} justifyContent="center">
|
||||
{/* Children centered */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" width={40} justifyContent="space-between">
|
||||
{/* First at start, last at end, rest evenly distributed */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" width={40} justifyContent="space-around">
|
||||
{/* Equal space around each child */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" width={40} justifyContent="space-evenly">
|
||||
{/* Equal space between all children and edges */}
|
||||
</box>
|
||||
```
|
||||
|
||||
### alignItems
|
||||
|
||||
Aligns children along the cross axis:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" height={10} alignItems="flex-start">
|
||||
{/* Children at top */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" height={10} alignItems="flex-end">
|
||||
{/* Children at bottom */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" height={10} alignItems="center">
|
||||
{/* Children vertically centered */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" height={10} alignItems="stretch">
|
||||
{/* Children stretch to fill height */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" height={10} alignItems="baseline">
|
||||
{/* Children aligned by text baseline */}
|
||||
</box>
|
||||
```
|
||||
|
||||
### flexWrap
|
||||
|
||||
Controls whether children wrap to new lines:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" flexWrap="nowrap" width={20}>
|
||||
{/* Children overflow (default) */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" flexWrap="wrap" width={20}>
|
||||
{/* Children wrap to next row */}
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" flexWrap="wrap-reverse" width={20}>
|
||||
{/* Children wrap upward */}
|
||||
</box>
|
||||
```
|
||||
|
||||
### gap
|
||||
|
||||
Space between children:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" gap={2}>
|
||||
<text>A</text>
|
||||
<text>B</text>
|
||||
<text>C</text>
|
||||
</box>
|
||||
// Output: A B C (2 spaces between)
|
||||
```
|
||||
|
||||
## Flex Item Properties
|
||||
|
||||
### flexGrow
|
||||
|
||||
How much a child should grow relative to siblings:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" width={30}>
|
||||
<box flexGrow={1}><text>1</text></box>
|
||||
<box flexGrow={2}><text>2</text></box>
|
||||
<box flexGrow={1}><text>1</text></box>
|
||||
</box>
|
||||
// Widths: 7.5 | 15 | 7.5 (1:2:1 ratio)
|
||||
```
|
||||
|
||||
### flexShrink
|
||||
|
||||
How much a child should shrink when space is limited:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" width={20}>
|
||||
<box width={15} flexShrink={1}><text>Shrinks</text></box>
|
||||
<box width={15} flexShrink={0}><text>Fixed</text></box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### flexBasis
|
||||
|
||||
Initial size before growing/shrinking:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row">
|
||||
<box flexBasis={20} flexGrow={1}>Starts at 20, can grow</box>
|
||||
<box flexBasis="50%">Half of parent</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### alignSelf
|
||||
|
||||
Override parent's alignItems for this child:
|
||||
|
||||
```tsx
|
||||
<box flexDirection="row" height={10} alignItems="center">
|
||||
<text>Centered</text>
|
||||
<text alignSelf="flex-start">Top</text>
|
||||
<text alignSelf="flex-end">Bottom</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Dimensions
|
||||
|
||||
### Fixed Dimensions
|
||||
|
||||
```tsx
|
||||
<box width={40} height={10}>
|
||||
{/* Exactly 40 columns by 10 rows */}
|
||||
</box>
|
||||
```
|
||||
|
||||
### Percentage Dimensions
|
||||
|
||||
Parent must have explicit size:
|
||||
|
||||
```tsx
|
||||
<box width="100%" height="100%">
|
||||
<box width="50%" height="50%">
|
||||
{/* Half of parent */}
|
||||
</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Min/Max Constraints
|
||||
|
||||
```tsx
|
||||
<box
|
||||
minWidth={20}
|
||||
maxWidth={60}
|
||||
minHeight={5}
|
||||
maxHeight={20}
|
||||
>
|
||||
{/* Constrained sizing */}
|
||||
</box>
|
||||
```
|
||||
|
||||
## Spacing
|
||||
|
||||
### Padding (inside)
|
||||
|
||||
```tsx
|
||||
// All sides
|
||||
<box padding={2}>Content</box>
|
||||
|
||||
// Individual sides
|
||||
<box
|
||||
paddingTop={1}
|
||||
paddingRight={2}
|
||||
paddingBottom={1}
|
||||
paddingLeft={2}
|
||||
>
|
||||
Content
|
||||
</box>
|
||||
```
|
||||
|
||||
### Margin (outside)
|
||||
|
||||
```tsx
|
||||
// All sides
|
||||
<box margin={1}>Content</box>
|
||||
|
||||
// Individual sides
|
||||
<box
|
||||
marginTop={1}
|
||||
marginRight={2}
|
||||
marginBottom={1}
|
||||
marginLeft={2}
|
||||
>
|
||||
Content
|
||||
</box>
|
||||
```
|
||||
|
||||
## Positioning
|
||||
|
||||
### Relative (default)
|
||||
|
||||
Element flows in normal document order:
|
||||
|
||||
```tsx
|
||||
<box position="relative">
|
||||
{/* Normal flow */}
|
||||
</box>
|
||||
```
|
||||
|
||||
### Absolute
|
||||
|
||||
Element positioned relative to nearest positioned ancestor:
|
||||
|
||||
```tsx
|
||||
<box position="relative" width="100%" height="100%">
|
||||
<box
|
||||
position="absolute"
|
||||
left={10}
|
||||
top={5}
|
||||
width={20}
|
||||
height={5}
|
||||
>
|
||||
Positioned at (10, 5)
|
||||
</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Position Properties
|
||||
|
||||
```tsx
|
||||
<box
|
||||
position="absolute"
|
||||
left={10} // From left edge
|
||||
top={5} // From top edge
|
||||
right={10} // From right edge
|
||||
bottom={5} // From bottom edge
|
||||
>
|
||||
Content
|
||||
</box>
|
||||
```
|
||||
|
||||
## Display
|
||||
|
||||
### Visibility Control
|
||||
|
||||
```tsx
|
||||
// Visible (default)
|
||||
<box display="flex">Visible</box>
|
||||
|
||||
// Hidden (removed from layout)
|
||||
<box display="none">Hidden</box>
|
||||
```
|
||||
|
||||
## Overflow
|
||||
|
||||
```tsx
|
||||
<box overflow="visible">
|
||||
{/* Content can extend beyond bounds (default) */}
|
||||
</box>
|
||||
|
||||
<box overflow="hidden">
|
||||
{/* Content clipped at bounds */}
|
||||
</box>
|
||||
|
||||
<box overflow="scroll">
|
||||
{/* Scrollable when content exceeds bounds */}
|
||||
</box>
|
||||
```
|
||||
|
||||
## Z-Index
|
||||
|
||||
Control stacking order for overlapping elements:
|
||||
|
||||
```tsx
|
||||
<box position="relative">
|
||||
<box position="absolute" zIndex={1}>Behind</box>
|
||||
<box position="absolute" zIndex={2}>In front</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [Layout Patterns](./patterns.md) - Common layout recipes
|
||||
- [Components/Containers](../components/containers.md) - Box and ScrollBox details
|
||||
@@ -0,0 +1,444 @@
|
||||
# Layout Patterns
|
||||
|
||||
Common layout recipes for terminal user interfaces.
|
||||
|
||||
## Full-Screen App
|
||||
|
||||
Fill the entire terminal:
|
||||
|
||||
```tsx
|
||||
function App() {
|
||||
return (
|
||||
<box width="100%" height="100%">
|
||||
{/* Content fills terminal */}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Header/Content/Footer
|
||||
|
||||
Classic app layout:
|
||||
|
||||
```tsx
|
||||
function AppLayout() {
|
||||
return (
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
{/* Header - fixed height */}
|
||||
<box height={3} borderStyle="single" borderBottom>
|
||||
<text>Header</text>
|
||||
</box>
|
||||
|
||||
{/* Content - fills remaining space */}
|
||||
<box flexGrow={1}>
|
||||
<text>Main Content</text>
|
||||
</box>
|
||||
|
||||
{/* Footer - fixed height */}
|
||||
<box height={1}>
|
||||
<text>Status: Ready</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Sidebar Layout
|
||||
|
||||
```tsx
|
||||
function SidebarLayout() {
|
||||
return (
|
||||
<box flexDirection="row" width="100%" height="100%">
|
||||
{/* Sidebar - fixed width */}
|
||||
<box width={25} borderStyle="single" borderRight>
|
||||
<text>Sidebar</text>
|
||||
</box>
|
||||
|
||||
{/* Main - fills remaining space */}
|
||||
<box flexGrow={1}>
|
||||
<text>Main Content</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Resizable Sidebar
|
||||
|
||||
Responsive based on terminal width:
|
||||
|
||||
```tsx
|
||||
function ResponsiveSidebar() {
|
||||
const dims = useTerminalDimensions() // React: useTerminalDimensions()
|
||||
const showSidebar = dims.width > 60
|
||||
const sidebarWidth = Math.min(30, Math.floor(dims.width * 0.3))
|
||||
|
||||
return (
|
||||
<box flexDirection="row" width="100%" height="100%">
|
||||
{showSidebar && (
|
||||
<box width={sidebarWidth} border>
|
||||
<text>Sidebar</text>
|
||||
</box>
|
||||
)}
|
||||
<box flexGrow={1}>
|
||||
<text>Main</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Centered Content
|
||||
|
||||
### Horizontally Centered
|
||||
|
||||
```tsx
|
||||
<box width="100%" justifyContent="center">
|
||||
<box width={40}>
|
||||
<text>Centered horizontally</text>
|
||||
</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Vertically Centered
|
||||
|
||||
```tsx
|
||||
<box height="100%" alignItems="center">
|
||||
<text>Centered vertically</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Both Axes
|
||||
|
||||
```tsx
|
||||
<box
|
||||
width="100%"
|
||||
height="100%"
|
||||
justifyContent="center"
|
||||
alignItems="center"
|
||||
>
|
||||
<box width={40} height={10} border>
|
||||
<text>Centered both ways</text>
|
||||
</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Modal/Dialog
|
||||
|
||||
Centered overlay:
|
||||
|
||||
```tsx
|
||||
function Modal({ children, visible }) {
|
||||
if (!visible) return null
|
||||
|
||||
return (
|
||||
<box
|
||||
position="absolute"
|
||||
left={0}
|
||||
top={0}
|
||||
width="100%"
|
||||
height="100%"
|
||||
justifyContent="center"
|
||||
alignItems="center"
|
||||
backgroundColor="rgba(0,0,0,0.5)"
|
||||
>
|
||||
<box
|
||||
width={50}
|
||||
height={15}
|
||||
border
|
||||
borderStyle="double"
|
||||
backgroundColor="#1a1a2e"
|
||||
padding={2}
|
||||
>
|
||||
{children}
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Grid Layout
|
||||
|
||||
Using flexWrap:
|
||||
|
||||
```tsx
|
||||
function Grid({ items, columns = 3 }) {
|
||||
const itemWidth = `${Math.floor(100 / columns)}%`
|
||||
|
||||
return (
|
||||
<box flexDirection="row" flexWrap="wrap" width="100%">
|
||||
{items.map((item, i) => (
|
||||
<box key={i} width={itemWidth} padding={1}>
|
||||
<text>{item}</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Split Panels
|
||||
|
||||
### Horizontal Split
|
||||
|
||||
```tsx
|
||||
function HorizontalSplit({ ratio = 0.5 }) {
|
||||
return (
|
||||
<box flexDirection="row" width="100%" height="100%">
|
||||
<box width={`${ratio * 100}%`} border>
|
||||
<text>Left Panel</text>
|
||||
</box>
|
||||
<box flexGrow={1} border>
|
||||
<text>Right Panel</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Vertical Split
|
||||
|
||||
```tsx
|
||||
function VerticalSplit({ ratio = 0.5 }) {
|
||||
return (
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
<box height={`${ratio * 100}%`} border>
|
||||
<text>Top Panel</text>
|
||||
</box>
|
||||
<box flexGrow={1} border>
|
||||
<text>Bottom Panel</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Form Layout
|
||||
|
||||
Label + Input pairs:
|
||||
|
||||
```tsx
|
||||
function FormField({ label, children }) {
|
||||
return (
|
||||
<box flexDirection="row" marginBottom={1}>
|
||||
<box width={15}>
|
||||
<text>{label}:</text>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
{children}
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
function LoginForm() {
|
||||
return (
|
||||
<box flexDirection="column" padding={2} border width={50}>
|
||||
<FormField label="Username">
|
||||
<input placeholder="Enter username" />
|
||||
</FormField>
|
||||
<FormField label="Password">
|
||||
<input placeholder="Enter password" />
|
||||
</FormField>
|
||||
<box marginTop={2} justifyContent="flex-end">
|
||||
<box border padding={1}>
|
||||
<text>Login</text>
|
||||
</box>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Navigation Tabs
|
||||
|
||||
```tsx
|
||||
function TabBar({ tabs, activeIndex, onSelect }) {
|
||||
return (
|
||||
<box flexDirection="row" borderBottom>
|
||||
{tabs.map((tab, i) => (
|
||||
<box
|
||||
key={i}
|
||||
padding={1}
|
||||
backgroundColor={i === activeIndex ? "#333" : "transparent"}
|
||||
onMouseDown={() => onSelect(i)}
|
||||
>
|
||||
<text fg={i === activeIndex ? "#fff" : "#888"}>
|
||||
{tab}
|
||||
</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Sticky Footer
|
||||
|
||||
Footer always at bottom:
|
||||
|
||||
```tsx
|
||||
function StickyFooterLayout() {
|
||||
return (
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
{/* Content area */}
|
||||
<box flexGrow={1} flexDirection="column">
|
||||
{/* Your content here */}
|
||||
<text>Content that might be short</text>
|
||||
</box>
|
||||
|
||||
{/* Footer pushed to bottom */}
|
||||
<box height={1}>
|
||||
<text fg="#888">Press ? for help | q to quit</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Absolute Positioning Overlay
|
||||
|
||||
Tooltip or popup:
|
||||
|
||||
```tsx
|
||||
function Tooltip({ x, y, children }) {
|
||||
return (
|
||||
<box
|
||||
position="absolute"
|
||||
left={x}
|
||||
top={y}
|
||||
border
|
||||
backgroundColor="#333"
|
||||
padding={1}
|
||||
zIndex={100}
|
||||
>
|
||||
{children}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Responsive Breakpoints
|
||||
|
||||
Different layouts based on terminal size:
|
||||
|
||||
```tsx
|
||||
function ResponsiveApp() {
|
||||
const { width, height } = useTerminalDimensions()
|
||||
|
||||
// Define breakpoints
|
||||
const isSmall = width < 60
|
||||
const isMedium = width >= 60 && width < 100
|
||||
const isLarge = width >= 100
|
||||
|
||||
if (isSmall) {
|
||||
// Mobile-like: stacked layout
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<Navigation />
|
||||
<Content />
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMedium) {
|
||||
// Tablet-like: sidebar + content
|
||||
return (
|
||||
<box flexDirection="row">
|
||||
<box width={20}><Navigation /></box>
|
||||
<box flexGrow={1}><Content /></box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
// Large: full layout
|
||||
return (
|
||||
<box flexDirection="row">
|
||||
<box width={25}><Navigation /></box>
|
||||
<box flexGrow={1}><Content /></box>
|
||||
<box width={30}><Sidebar /></box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Equal Height Columns
|
||||
|
||||
```tsx
|
||||
function EqualColumns() {
|
||||
return (
|
||||
<box flexDirection="row" alignItems="stretch" height={20}>
|
||||
<box flexGrow={1} border>
|
||||
<text>Short content</text>
|
||||
</box>
|
||||
<box flexGrow={1} border>
|
||||
<text>
|
||||
Longer content that
|
||||
spans multiple lines
|
||||
and takes up space
|
||||
</text>
|
||||
</box>
|
||||
<box flexGrow={1} border>
|
||||
<text>Medium content</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Spacing Utilities
|
||||
|
||||
Consistent spacing patterns:
|
||||
|
||||
```tsx
|
||||
// Spacer component
|
||||
function Spacer({ size = 1 }) {
|
||||
return <box height={size} width={size} />
|
||||
}
|
||||
|
||||
// Divider component
|
||||
function Divider() {
|
||||
return <box height={1} width="100%" backgroundColor="#333" />
|
||||
}
|
||||
|
||||
// Usage
|
||||
<box flexDirection="column">
|
||||
<text>Section 1</text>
|
||||
<Spacer size={2} />
|
||||
<Divider />
|
||||
<Spacer size={2} />
|
||||
<text>Section 2</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Axis Shorthand Props
|
||||
|
||||
Use `paddingX`/`paddingY` and `marginX`/`marginY` for horizontal/vertical spacing:
|
||||
|
||||
```tsx
|
||||
// Horizontal padding (left + right)
|
||||
<box paddingX={4}>
|
||||
<text>4 chars padding left and right</text>
|
||||
</box>
|
||||
|
||||
// Vertical padding (top + bottom)
|
||||
<box paddingY={2}>
|
||||
<text>2 lines padding top and bottom</text>
|
||||
</box>
|
||||
|
||||
// Horizontal margin for centering-like effect
|
||||
<box marginX={10}>
|
||||
<text>Indented content</text>
|
||||
</box>
|
||||
|
||||
// Combined for card-like spacing
|
||||
<box paddingX={3} paddingY={1} marginY={1} border>
|
||||
<text>Nicely spaced card</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
These are shorthand for:
|
||||
- `paddingX={n}` = `paddingLeft={n}` + `paddingRight={n}`
|
||||
- `paddingY={n}` = `paddingTop={n}` + `paddingBottom={n}`
|
||||
- `marginX={n}` = `marginLeft={n}` + `marginRight={n}`
|
||||
- `marginY={n}` = `marginTop={n}` + `marginBottom={n}`
|
||||
@@ -0,0 +1,174 @@
|
||||
# OpenTUI React (@opentui/react)
|
||||
|
||||
A React reconciler for building terminal user interfaces with familiar React patterns. Write TUIs using JSX, hooks, and component composition.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTUI React provides:
|
||||
- **Custom reconciler**: React components render to OpenTUI renderables
|
||||
- **JSX intrinsics**: `<text>`, `<box>`, `<input>`, etc.
|
||||
- **Hooks**: `useKeyboard`, `useRenderer`, `useTimeline`, etc.
|
||||
- **Full React compatibility**: useState, useEffect, context, and more
|
||||
|
||||
## When to Use React
|
||||
|
||||
Use the React reconciler when:
|
||||
- You're familiar with React patterns
|
||||
- You want declarative UI composition
|
||||
- You need React's ecosystem (context, state management libraries)
|
||||
- Building applications with complex state
|
||||
- Team knows React already
|
||||
|
||||
## When NOT to Use React
|
||||
|
||||
| Scenario | Use Instead |
|
||||
|----------|-------------|
|
||||
| Maximum performance critical | `@opentui/core` (imperative) |
|
||||
| Fine-grained reactivity | `@opentui/solid` |
|
||||
| Smallest bundle size | `@opentui/core` |
|
||||
| Building a framework/library | `@opentui/core` |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
bunx create-tui@latest -t react my-app
|
||||
cd my-app
|
||||
bun run src/index.tsx
|
||||
```
|
||||
|
||||
The CLI creates the `my-app` directory for you - it must **not already exist**.
|
||||
|
||||
**Agent guidance**: Always use autonomous mode with `-t <template>` flag. Never use interactive mode (`bunx create-tui@latest my-app` without `-t`) as it requires user prompts that agents cannot respond to.
|
||||
|
||||
Or manual setup:
|
||||
|
||||
```bash
|
||||
mkdir my-tui && cd my-tui
|
||||
bun init
|
||||
bun install @opentui/react @opentui/core react
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
import { createRoot } from "@opentui/react"
|
||||
import { useState } from "react"
|
||||
|
||||
function App() {
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
return (
|
||||
<box border padding={2}>
|
||||
<text>Count: {count}</text>
|
||||
<box
|
||||
border
|
||||
onMouseDown={() => setCount(c => c + 1)}
|
||||
>
|
||||
<text>Click me!</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
createRoot(renderer).render(<App />)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### JSX Elements
|
||||
|
||||
React maps JSX intrinsic elements to OpenTUI renderables:
|
||||
|
||||
```tsx
|
||||
// These are not HTML elements!
|
||||
<text>Hello</text> // TextRenderable
|
||||
<box border>Content</box> // BoxRenderable
|
||||
<input placeholder="..." /> // InputRenderable
|
||||
<select options={[...]} /> // SelectRenderable
|
||||
```
|
||||
|
||||
### Text Modifiers
|
||||
|
||||
Inside `<text>`, use modifier elements:
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<strong>Bold</strong>, <em>italic</em>, and <u>underlined</u>
|
||||
<span fg="red">Colored text</span>
|
||||
<br />
|
||||
New line with <a href="https://example.com">link</a>
|
||||
</text>
|
||||
```
|
||||
|
||||
### Styling
|
||||
|
||||
Two approaches to styling:
|
||||
|
||||
```tsx
|
||||
// Direct props
|
||||
<box backgroundColor="blue" padding={2} border>
|
||||
<text fg="#00FF00">Green text</text>
|
||||
</box>
|
||||
|
||||
// Style prop
|
||||
<box style={{ backgroundColor: "blue", padding: 2, border: true }}>
|
||||
<text style={{ fg: "#00FF00" }}>Green text</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Available Components
|
||||
|
||||
### Layout & Display
|
||||
- `<text>` - Styled text content
|
||||
- `<box>` - Container with borders and layout
|
||||
- `<scrollbox>` - Scrollable container
|
||||
- `<ascii-font>` - ASCII art text
|
||||
|
||||
### Input
|
||||
- `<input>` - Single-line text input
|
||||
- `<textarea>` - Multi-line text input
|
||||
- `<select>` - List selection
|
||||
- `<tab-select>` - Tab-based selection
|
||||
|
||||
### Code & Diff
|
||||
- `<code>` - Syntax-highlighted code
|
||||
- `<line-number>` - Code with line numbers
|
||||
- `<diff>` - Unified or split diff viewer
|
||||
|
||||
### Text Modifiers (inside `<text>`)
|
||||
- `<span>` - Inline styled text
|
||||
- `<strong>`, `<b>` - Bold
|
||||
- `<em>`, `<i>` - Italic
|
||||
- `<u>` - Underline
|
||||
- `<br>` - Line break
|
||||
- `<a>` - Link
|
||||
|
||||
## Essential Hooks
|
||||
|
||||
```tsx
|
||||
import {
|
||||
useRenderer,
|
||||
useKeyboard,
|
||||
useOnResize,
|
||||
useTerminalDimensions,
|
||||
useTimeline,
|
||||
} from "@opentui/react"
|
||||
```
|
||||
|
||||
See [API Reference](./api.md) for detailed hook documentation.
|
||||
|
||||
## In This Reference
|
||||
|
||||
- [Configuration](./configuration.md) - Project setup, tsconfig, bundling
|
||||
- [API](./api.md) - Components, hooks, createRoot
|
||||
- [Patterns](./patterns.md) - State management, keyboard handling, forms
|
||||
- [Gotchas](./gotchas.md) - Common issues, debugging, limitations
|
||||
|
||||
## See Also
|
||||
|
||||
- [Core](../core/REFERENCE.md) - Underlying imperative API
|
||||
- [Solid](../solid/REFERENCE.md) - Alternative declarative approach
|
||||
- [Components](../components/REFERENCE.md) - Component reference by category
|
||||
- [Layout](../layout/REFERENCE.md) - Flexbox layout system
|
||||
- [Keyboard](../keyboard/REFERENCE.md) - Input handling and shortcuts
|
||||
- [Testing](../testing/REFERENCE.md) - Test renderer and snapshots
|
||||
@@ -0,0 +1,436 @@
|
||||
# React API Reference
|
||||
|
||||
## Rendering
|
||||
|
||||
### createRoot(renderer)
|
||||
|
||||
Creates a React root for rendering.
|
||||
|
||||
```tsx
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
import { createRoot } from "@opentui/react"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
exitOnCtrlC: false, // Handle Ctrl+C yourself
|
||||
})
|
||||
|
||||
const root = createRoot(renderer)
|
||||
root.render(<App />)
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
### useRenderer()
|
||||
|
||||
Access the OpenTUI renderer instance.
|
||||
|
||||
```tsx
|
||||
import { useRenderer } from "@opentui/react"
|
||||
import { useEffect } from "react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useEffect(() => {
|
||||
// Access renderer properties
|
||||
console.log(`Terminal: ${renderer.width}x${renderer.height}`)
|
||||
|
||||
// Show debug console
|
||||
renderer.console.show()
|
||||
|
||||
// Access theme mode (dark/light based on terminal settings)
|
||||
console.log(`Theme: ${renderer.themeMode}`) // "dark" | "light" | null
|
||||
}, [renderer])
|
||||
|
||||
return <text>Hello</text>
|
||||
}
|
||||
|
||||
// Listen for theme mode changes
|
||||
function ThemedApp() {
|
||||
const renderer = useRenderer()
|
||||
const [theme, setTheme] = useState(renderer.themeMode ?? "dark")
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (mode: "dark" | "light") => setTheme(mode)
|
||||
renderer.on("theme_mode", handler)
|
||||
return () => renderer.off("theme_mode", handler)
|
||||
}, [renderer])
|
||||
|
||||
return (
|
||||
<box backgroundColor={theme === "dark" ? "#1a1a2e" : "#ffffff"}>
|
||||
<text fg={theme === "dark" ? "#fff" : "#000"}>
|
||||
Current theme: {theme}
|
||||
</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### useKeyboard(handler, options?)
|
||||
|
||||
Handle keyboard events.
|
||||
|
||||
```tsx
|
||||
import { useKeyboard, useRenderer } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy() // Never use process.exit() directly!
|
||||
}
|
||||
if (key.ctrl && key.name === "s") {
|
||||
saveDocument()
|
||||
}
|
||||
})
|
||||
|
||||
return <text>Press ESC to exit</text>
|
||||
}
|
||||
|
||||
// With release events
|
||||
function GameControls() {
|
||||
const [pressed, setPressed] = useState(new Set<string>())
|
||||
|
||||
useKeyboard(
|
||||
(event) => {
|
||||
setPressed(keys => {
|
||||
const newKeys = new Set(keys)
|
||||
if (event.eventType === "release") {
|
||||
newKeys.delete(event.name)
|
||||
} else {
|
||||
newKeys.add(event.name)
|
||||
}
|
||||
return newKeys
|
||||
})
|
||||
},
|
||||
{ release: true } // Include release events
|
||||
)
|
||||
|
||||
return <text>Pressed: {Array.from(pressed).join(", ")}</text>
|
||||
}
|
||||
```
|
||||
|
||||
**Options:**
|
||||
- `release?: boolean` - Include key release events (default: false)
|
||||
|
||||
**KeyEvent properties:**
|
||||
- `name: string` - Key name ("a", "escape", "f1", etc.)
|
||||
- `sequence: string` - Raw escape sequence
|
||||
- `ctrl: boolean` - Ctrl modifier
|
||||
- `shift: boolean` - Shift modifier
|
||||
- `meta: boolean` - Alt modifier
|
||||
- `option: boolean` - Option modifier (macOS)
|
||||
- `eventType: "press" | "release" | "repeat"`
|
||||
- `repeated: boolean` - Key is being held
|
||||
|
||||
### useOnResize(callback)
|
||||
|
||||
Handle terminal resize events.
|
||||
|
||||
```tsx
|
||||
import { useOnResize } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
useOnResize((width, height) => {
|
||||
console.log(`Resized to ${width}x${height}`)
|
||||
})
|
||||
|
||||
return <text>Resize the terminal</text>
|
||||
}
|
||||
```
|
||||
|
||||
### useTerminalDimensions()
|
||||
|
||||
Get reactive terminal dimensions.
|
||||
|
||||
```tsx
|
||||
import { useTerminalDimensions } from "@opentui/react"
|
||||
|
||||
function ResponsiveLayout() {
|
||||
const { width, height } = useTerminalDimensions()
|
||||
|
||||
return (
|
||||
<box flexDirection={width > 80 ? "row" : "column"}>
|
||||
<box flexGrow={1}>
|
||||
<text>Width: {width}</text>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
<text>Height: {height}</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### useTimeline(options?)
|
||||
|
||||
Create animations with the timeline system.
|
||||
|
||||
```tsx
|
||||
import { useTimeline } from "@opentui/react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
function AnimatedBox() {
|
||||
const [width, setWidth] = useState(0)
|
||||
|
||||
const timeline = useTimeline({
|
||||
duration: 2000,
|
||||
loop: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ width: 0 },
|
||||
{
|
||||
width: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].width))
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [timeline])
|
||||
|
||||
return <box style={{ width, height: 3, backgroundColor: "#6a5acd" }} />
|
||||
}
|
||||
```
|
||||
|
||||
**Options:**
|
||||
- `duration?: number` - Default duration (ms)
|
||||
- `loop?: boolean` - Loop the timeline
|
||||
- `autoplay?: boolean` - Auto-start (default: true)
|
||||
- `onComplete?: () => void` - Completion callback
|
||||
- `onPause?: () => void` - Pause callback
|
||||
|
||||
**Timeline methods:**
|
||||
- `add(target, properties, startTime?)` - Add animation
|
||||
- `play()` - Start playback
|
||||
- `pause()` - Pause playback
|
||||
- `restart()` - Restart from beginning
|
||||
|
||||
## Components
|
||||
|
||||
### Text Component
|
||||
|
||||
```tsx
|
||||
<text
|
||||
content="Hello" // Or use children
|
||||
fg="#FFFFFF" // Foreground color
|
||||
bg="#000000" // Background color
|
||||
selectable={true} // Allow text selection
|
||||
>
|
||||
{/* Use nested modifier tags for styling */}
|
||||
<span fg="red">Red</span>
|
||||
<strong>Bold</strong>
|
||||
<em>Italic</em>
|
||||
<u>Underline</u>
|
||||
<br />
|
||||
<a href="https://...">Link</a>
|
||||
</text>
|
||||
```
|
||||
|
||||
> **Note**: Do NOT use `bold`, `italic`, `underline` as props on `<text>`. Use nested modifier tags like `<strong>`, `<em>`, `<u>` instead.
|
||||
|
||||
### Box Component
|
||||
|
||||
```tsx
|
||||
<box
|
||||
// Borders
|
||||
border // Enable border
|
||||
borderStyle="single" // single | double | rounded | bold
|
||||
borderColor="#FFFFFF"
|
||||
title="Title"
|
||||
titleAlignment="center" // left | center | right
|
||||
|
||||
// Colors
|
||||
backgroundColor="#1a1a2e"
|
||||
|
||||
// Layout (see layout/REFERENCE.md)
|
||||
flexDirection="row"
|
||||
justifyContent="center"
|
||||
alignItems="center"
|
||||
gap={2}
|
||||
|
||||
// Spacing
|
||||
padding={2}
|
||||
paddingTop={1}
|
||||
paddingX={2} // Horizontal (left + right)
|
||||
paddingY={1} // Vertical (top + bottom)
|
||||
margin={1}
|
||||
marginX={2} // Horizontal (left + right)
|
||||
marginY={1} // Vertical (top + bottom)
|
||||
|
||||
// Dimensions
|
||||
width={40}
|
||||
height={10}
|
||||
flexGrow={1}
|
||||
|
||||
// Focus
|
||||
focusable // Allow box to receive focus
|
||||
focused={isFocused} // Controlled focus state
|
||||
|
||||
// Events
|
||||
onMouseDown={(e) => {}}
|
||||
onMouseUp={(e) => {}}
|
||||
onMouseMove={(e) => {}}
|
||||
>
|
||||
{children}
|
||||
</box>
|
||||
```
|
||||
|
||||
### Scrollbox Component
|
||||
|
||||
```tsx
|
||||
<scrollbox
|
||||
focused // Enable keyboard scrolling
|
||||
style={{
|
||||
rootOptions: { backgroundColor: "#24283b" },
|
||||
wrapperOptions: { backgroundColor: "#1f2335" },
|
||||
viewportOptions: { backgroundColor: "#1a1b26" },
|
||||
contentOptions: { backgroundColor: "#16161e" },
|
||||
scrollbarOptions: {
|
||||
showArrows: true,
|
||||
trackOptions: {
|
||||
foregroundColor: "#7aa2f7",
|
||||
backgroundColor: "#414868",
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
{/* Scrollable content */}
|
||||
{items.map((item, i) => (
|
||||
<box key={i}>
|
||||
<text>{item}</text>
|
||||
</box>
|
||||
))}
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Input Component
|
||||
|
||||
```tsx
|
||||
<input
|
||||
value={value}
|
||||
onChange={(newValue) => setValue(newValue)}
|
||||
placeholder="Enter text..."
|
||||
focused // Start focused
|
||||
width={30}
|
||||
backgroundColor="#1a1a1a"
|
||||
textColor="#FFFFFF"
|
||||
cursorColor="#00FF00"
|
||||
focusedBackgroundColor="#2a2a2a"
|
||||
/>
|
||||
```
|
||||
|
||||
### Textarea Component
|
||||
|
||||
```tsx
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(newValue) => setText(newValue)}
|
||||
placeholder="Enter multiple lines..."
|
||||
focused
|
||||
width={40}
|
||||
height={10}
|
||||
showLineNumbers
|
||||
wrapText
|
||||
/>
|
||||
```
|
||||
|
||||
### Select Component
|
||||
|
||||
```tsx
|
||||
<select
|
||||
options={[
|
||||
{ name: "Option 1", description: "First option", value: "1" },
|
||||
{ name: "Option 2", description: "Second option", value: "2" },
|
||||
]}
|
||||
onChange={(index, option) => setSelected(option)}
|
||||
selectedIndex={0}
|
||||
focused
|
||||
showScrollIndicator
|
||||
height={8}
|
||||
/>
|
||||
```
|
||||
|
||||
### Tab Select Component
|
||||
|
||||
```tsx
|
||||
<tab-select
|
||||
options={[
|
||||
{ name: "Home", description: "Dashboard" },
|
||||
{ name: "Settings", description: "Configuration" },
|
||||
]}
|
||||
onChange={(index, option) => setTab(option)}
|
||||
tabWidth={20}
|
||||
focused
|
||||
/>
|
||||
```
|
||||
|
||||
### ASCII Font Component
|
||||
|
||||
```tsx
|
||||
<ascii-font
|
||||
text="TITLE"
|
||||
font="tiny" // tiny | block | slick | shade
|
||||
color="#FFFFFF"
|
||||
/>
|
||||
```
|
||||
|
||||
### Code Component
|
||||
|
||||
```tsx
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
showLineNumbers
|
||||
highlightLines={[1, 5, 10]}
|
||||
/>
|
||||
```
|
||||
|
||||
### Line Number Component
|
||||
|
||||
```tsx
|
||||
<line-number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
startLine={1}
|
||||
highlightedLines={[5]}
|
||||
diagnostics={[
|
||||
{ line: 3, severity: "error", message: "Syntax error" }
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
### Diff Component
|
||||
|
||||
```tsx
|
||||
<diff
|
||||
oldCode={originalCode}
|
||||
newCode={modifiedCode}
|
||||
language="typescript"
|
||||
mode="unified" // unified | split
|
||||
syncScroll // Sync scroll between split view panes
|
||||
showLineNumbers
|
||||
/>
|
||||
```
|
||||
|
||||
## Type Exports
|
||||
|
||||
```tsx
|
||||
import type {
|
||||
// Component props
|
||||
TextProps,
|
||||
BoxProps,
|
||||
InputProps,
|
||||
SelectProps,
|
||||
|
||||
// Hook types
|
||||
KeyEvent,
|
||||
|
||||
// From core
|
||||
CliRenderer,
|
||||
} from "@opentui/react"
|
||||
```
|
||||
@@ -0,0 +1,302 @@
|
||||
# React Configuration
|
||||
|
||||
## Project Setup
|
||||
|
||||
### Quick Start
|
||||
|
||||
```bash
|
||||
bunx create-tui@latest -t react my-app
|
||||
cd my-app && bun install
|
||||
```
|
||||
|
||||
The CLI creates the `my-app` directory for you - it must **not already exist**.
|
||||
|
||||
Options: `--no-git` (skip git init), `--no-install` (skip bun install)
|
||||
|
||||
### Manual Setup
|
||||
|
||||
```bash
|
||||
mkdir my-tui && cd my-tui
|
||||
bun init
|
||||
bun install @opentui/react @opentui/core react
|
||||
```
|
||||
|
||||
## TypeScript Configuration
|
||||
|
||||
### tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "@opentui/react",
|
||||
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["bun-types"]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
```
|
||||
|
||||
**Critical settings:**
|
||||
- `jsx: "react-jsx"` - Use the new JSX transform
|
||||
- `jsxImportSource: "@opentui/react"` - Import JSX runtime from OpenTUI
|
||||
- `module` / `moduleResolution: "NodeNext"` - Recommended for OpenTUI compatibility
|
||||
|
||||
### Why DOM lib?
|
||||
|
||||
The `DOM` lib is needed for React types. OpenTUI's JSX types extend React's.
|
||||
|
||||
## Package Configuration
|
||||
|
||||
### package.json
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "my-tui-app",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "bun run src/index.tsx",
|
||||
"dev": "bun --watch run src/index.tsx",
|
||||
"test": "bun test",
|
||||
"build": "bun build src/index.tsx --outdir=dist --target=bun"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opentui/core": "latest",
|
||||
"@opentui/react": "latest",
|
||||
"react": ">=19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"@types/react": ">=19.0.0",
|
||||
"typescript": "latest"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
Recommended structure:
|
||||
|
||||
```
|
||||
my-tui-app/
|
||||
├── src/
|
||||
│ ├── components/
|
||||
│ │ ├── Header.tsx
|
||||
│ │ ├── Sidebar.tsx
|
||||
│ │ └── MainContent.tsx
|
||||
│ ├── hooks/
|
||||
│ │ └── useAppState.ts
|
||||
│ ├── App.tsx
|
||||
│ └── index.tsx
|
||||
├── package.json
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
### Entry Point (src/index.tsx)
|
||||
|
||||
```tsx
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
import { createRoot } from "@opentui/react"
|
||||
import { App } from "./App"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
exitOnCtrlC: true,
|
||||
})
|
||||
|
||||
createRoot(renderer).render(<App />)
|
||||
```
|
||||
|
||||
### App Component (src/App.tsx)
|
||||
|
||||
```tsx
|
||||
import { Header } from "./components/Header"
|
||||
import { Sidebar } from "./components/Sidebar"
|
||||
import { MainContent } from "./components/MainContent"
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
<Header />
|
||||
<box flexDirection="row" flexGrow={1}>
|
||||
<Sidebar />
|
||||
<MainContent />
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Renderer Configuration
|
||||
|
||||
### createCliRenderer Options
|
||||
|
||||
```tsx
|
||||
import { createCliRenderer, ConsolePosition } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
// Rendering
|
||||
targetFPS: 60,
|
||||
|
||||
// Behavior
|
||||
exitOnCtrlC: true, // Set false to handle Ctrl+C yourself
|
||||
autoFocus: true, // Auto-focus elements on click (default: true)
|
||||
useMouse: true, // Enable mouse support (default: true)
|
||||
|
||||
// Debug console
|
||||
consoleOptions: {
|
||||
position: ConsolePosition.BOTTOM,
|
||||
sizePercent: 30,
|
||||
startInDebugMode: false,
|
||||
},
|
||||
|
||||
// Cleanup
|
||||
onDestroy: () => {
|
||||
// Cleanup code
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Building for Distribution
|
||||
|
||||
### Bundling with Bun
|
||||
|
||||
```typescript
|
||||
// build.ts
|
||||
await Bun.build({
|
||||
entrypoints: ["./src/index.tsx"],
|
||||
outdir: "./dist",
|
||||
target: "bun",
|
||||
minify: true,
|
||||
})
|
||||
```
|
||||
|
||||
Run: `bun run build.ts`
|
||||
|
||||
### Creating Executables
|
||||
|
||||
```typescript
|
||||
// build.ts
|
||||
await Bun.build({
|
||||
entrypoints: ["./src/index.tsx"],
|
||||
outdir: "./dist",
|
||||
target: "bun",
|
||||
compile: {
|
||||
target: "bun-darwin-arm64", // or bun-linux-x64, etc.
|
||||
outfile: "my-app",
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create `.env` for development:
|
||||
|
||||
```env
|
||||
# Debug settings
|
||||
OTUI_SHOW_STATS=false
|
||||
SHOW_CONSOLE=false
|
||||
|
||||
# App settings
|
||||
API_URL=https://api.example.com
|
||||
```
|
||||
|
||||
Bun auto-loads `.env` files. Access via `process.env`:
|
||||
|
||||
```tsx
|
||||
const apiUrl = process.env.API_URL
|
||||
```
|
||||
|
||||
## React DevTools
|
||||
|
||||
OpenTUI React supports React DevTools for debugging.
|
||||
|
||||
### Setup
|
||||
|
||||
1. Install DevTools as a dev dependency (must use version 7):
|
||||
```bash
|
||||
bun add react-devtools-core@7 -d
|
||||
```
|
||||
|
||||
2. Run DevTools standalone app:
|
||||
```bash
|
||||
npx react-devtools@7
|
||||
```
|
||||
|
||||
3. Start your app with `DEV=true` environment variable:
|
||||
```bash
|
||||
DEV=true bun run src/index.tsx
|
||||
```
|
||||
|
||||
**Important**: Auto-connect to DevTools ONLY happens when `DEV=true` is set. Without this environment variable, the DevTools connection code is not loaded.
|
||||
|
||||
### How It Works
|
||||
|
||||
OpenTUI checks for `process.env["DEV"] === "true"` at startup. When true, it dynamically imports `react-devtools-core` and connects to the standalone DevTools app.
|
||||
|
||||
## Testing Configuration
|
||||
|
||||
### Test Setup
|
||||
|
||||
```typescript
|
||||
// src/test-utils.tsx
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { createRoot } from "@opentui/react"
|
||||
|
||||
export async function renderForTest(
|
||||
element: React.ReactElement,
|
||||
options = { width: 80, height: 24 }
|
||||
) {
|
||||
const testSetup = await createTestRenderer(options)
|
||||
createRoot(testSetup.renderer).render(element)
|
||||
return testSetup
|
||||
}
|
||||
```
|
||||
|
||||
### Test Example
|
||||
|
||||
```typescript
|
||||
// src/components/Counter.test.tsx
|
||||
import { test, expect } from "bun:test"
|
||||
import { renderForTest } from "../test-utils"
|
||||
import { Counter } from "./Counter"
|
||||
|
||||
test("Counter renders initial value", async () => {
|
||||
const { snapshot } = await renderForTest(<Counter initialValue={5} />)
|
||||
expect(snapshot()).toContain("Count: 5")
|
||||
})
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
|
||||
### JSX Types Not Working
|
||||
|
||||
Ensure `jsxImportSource` is set:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "@opentui/react"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### React Version Mismatch
|
||||
|
||||
Ensure React 19+:
|
||||
|
||||
```bash
|
||||
bun install react@19 @types/react@19
|
||||
```
|
||||
|
||||
### Module Resolution Errors
|
||||
|
||||
Use `moduleResolution: "bundler"` for Bun compatibility.
|
||||
@@ -0,0 +1,443 @@
|
||||
# React Gotchas
|
||||
|
||||
## Critical
|
||||
|
||||
### Never use `process.exit()` directly
|
||||
|
||||
**This is the most common mistake.** Using `process.exit()` leaves the terminal in a broken state (cursor hidden, raw mode, alternate screen).
|
||||
|
||||
```tsx
|
||||
// WRONG - Terminal left in broken state
|
||||
process.exit(0)
|
||||
|
||||
// CORRECT - Use renderer.destroy()
|
||||
import { useRenderer } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
const handleExit = () => {
|
||||
renderer.destroy() // Cleans up and exits properly
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`renderer.destroy()` restores the terminal (exits alternate screen, restores cursor, etc.) before exiting.
|
||||
|
||||
### Signal Handling
|
||||
|
||||
OpenTUI automatically handles cleanup for these signals:
|
||||
- `SIGINT` (Ctrl+C), `SIGTERM`, `SIGQUIT` - Standard termination
|
||||
- `SIGHUP` - Terminal closed/hangup
|
||||
- `SIGBREAK` - Ctrl+Break (Windows)
|
||||
- `SIGPIPE` - Broken pipe (output closed)
|
||||
- `SIGBUS`, `SIGFPE` - Hardware errors
|
||||
|
||||
This ensures terminal state is restored even on unexpected termination. If you need custom signal handling, use `exitOnCtrlC: false` and handle signals yourself while still calling `renderer.destroy()`.
|
||||
|
||||
## JSX Configuration
|
||||
|
||||
### Missing jsxImportSource
|
||||
|
||||
**Symptom**: JSX elements have wrong types, components don't render
|
||||
|
||||
```
|
||||
// Error: Property 'text' does not exist on type 'JSX.IntrinsicElements'
|
||||
```
|
||||
|
||||
**Fix**: Configure tsconfig.json:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "@opentui/react"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### HTML Elements vs TUI Elements
|
||||
|
||||
OpenTUI's JSX elements are **not** HTML elements:
|
||||
|
||||
```tsx
|
||||
// WRONG - These are HTML concepts
|
||||
<div>Not supported</div>
|
||||
<button>Not supported</button>
|
||||
<span>Only works inside <text></span>
|
||||
|
||||
// CORRECT - OpenTUI elements
|
||||
<box>Container</box>
|
||||
<text>Display text</text>
|
||||
<text><span>Inline styled</span></text>
|
||||
```
|
||||
|
||||
## Component Issues
|
||||
|
||||
### Text Modifiers Outside Text
|
||||
|
||||
Text modifiers only work inside `<text>`:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<box>
|
||||
<strong>This won't work</strong>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box>
|
||||
<text>
|
||||
<strong>This works</strong>
|
||||
</text>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Focus Not Working
|
||||
|
||||
Components must be explicitly focused:
|
||||
|
||||
```tsx
|
||||
// WRONG - Won't receive keyboard input
|
||||
<input placeholder="Type here..." />
|
||||
|
||||
// CORRECT
|
||||
<input placeholder="Type here..." focused />
|
||||
|
||||
// Or manage focus state
|
||||
const [isFocused, setIsFocused] = useState(true)
|
||||
<input placeholder="Type here..." focused={isFocused} />
|
||||
```
|
||||
|
||||
### Select Not Responding
|
||||
|
||||
Select requires focus and proper options format:
|
||||
|
||||
```tsx
|
||||
// WRONG - Missing required properties
|
||||
<select options={["a", "b", "c"]} />
|
||||
|
||||
// CORRECT
|
||||
<select
|
||||
options={[
|
||||
{ name: "Option A", description: "First option", value: "a" },
|
||||
{ name: "Option B", description: "Second option", value: "b" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
// Called when Enter is pressed
|
||||
console.log("Selected:", option.name)
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
```
|
||||
|
||||
### Select Events Confusion
|
||||
|
||||
Remember: `onSelect` fires on Enter (selection confirmed), `onChange` fires on navigation:
|
||||
|
||||
```tsx
|
||||
// WRONG - expecting onChange to fire on Enter
|
||||
<select
|
||||
options={options}
|
||||
onChange={(i, opt) => submitForm(opt)} // This fires on arrow keys!
|
||||
/>
|
||||
|
||||
// CORRECT
|
||||
<select
|
||||
options={options}
|
||||
onSelect={(i, opt) => submitForm(opt)} // Enter pressed - submit
|
||||
onChange={(i, opt) => showPreview(opt)} // Arrow keys - preview
|
||||
/>
|
||||
```
|
||||
|
||||
## Hook Issues
|
||||
|
||||
### useKeyboard Not Firing
|
||||
|
||||
Multiple `useKeyboard` hooks can conflict:
|
||||
|
||||
```tsx
|
||||
// Both handlers fire - may cause issues
|
||||
function App() {
|
||||
useKeyboard((key) => { /* parent handler */ })
|
||||
return <ChildWithKeyboard />
|
||||
}
|
||||
|
||||
function ChildWithKeyboard() {
|
||||
useKeyboard((key) => { /* child handler */ })
|
||||
return <text>Child</text>
|
||||
}
|
||||
```
|
||||
|
||||
**Solution**: Use a single keyboard handler or implement event stopping:
|
||||
|
||||
```tsx
|
||||
function App() {
|
||||
const [handled, setHandled] = useState(false)
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (handled) {
|
||||
setHandled(false)
|
||||
return
|
||||
}
|
||||
// Handle at app level
|
||||
})
|
||||
|
||||
return <Child onKeyHandled={() => setHandled(true)} />
|
||||
}
|
||||
```
|
||||
|
||||
### useEffect Cleanup
|
||||
|
||||
Always clean up intervals and listeners:
|
||||
|
||||
```tsx
|
||||
// WRONG - Memory leak
|
||||
useEffect(() => {
|
||||
setInterval(() => updateData(), 1000)
|
||||
}, [])
|
||||
|
||||
// CORRECT
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => updateData(), 1000)
|
||||
return () => clearInterval(interval) // Cleanup!
|
||||
}, [])
|
||||
```
|
||||
|
||||
## Styling Issues
|
||||
|
||||
### Colors Not Applying
|
||||
|
||||
Check color format:
|
||||
|
||||
```tsx
|
||||
// CORRECT formats
|
||||
<text fg="#FF0000">Red</text>
|
||||
<text fg="red">Red</text>
|
||||
<box backgroundColor="#1a1a2e">Box</box>
|
||||
|
||||
// WRONG
|
||||
<text fg="FF0000">Missing #</text>
|
||||
<text color="#FF0000">Wrong prop name (use fg)</text>
|
||||
```
|
||||
|
||||
### Layout Not Working
|
||||
|
||||
Ensure parent has dimensions:
|
||||
|
||||
```tsx
|
||||
// WRONG - Parent has no height
|
||||
<box flexDirection="column">
|
||||
<box flexGrow={1}>Won't grow</box>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box flexDirection="column" height="100%">
|
||||
<box flexGrow={1}>Will grow</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
### Percentage Widths Not Working
|
||||
|
||||
Parent must have explicit dimensions:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<box>
|
||||
<box width="50%">Won't work</box>
|
||||
</box>
|
||||
|
||||
// CORRECT
|
||||
<box width="100%">
|
||||
<box width="50%">Works</box>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Performance Issues
|
||||
|
||||
### Too Many Re-renders
|
||||
|
||||
Avoid inline objects/functions in props:
|
||||
|
||||
```tsx
|
||||
// WRONG - New object every render
|
||||
<box style={{ padding: 2 }}>Content</box>
|
||||
|
||||
// BETTER - Use direct props
|
||||
<box padding={2}>Content</box>
|
||||
|
||||
// OR memoize style objects
|
||||
const style = useMemo(() => ({ padding: 2 }), [])
|
||||
<box style={style}>Content</box>
|
||||
```
|
||||
|
||||
### Heavy Components
|
||||
|
||||
Use React.memo for expensive components:
|
||||
|
||||
```tsx
|
||||
const ExpensiveList = React.memo(function ExpensiveList({
|
||||
items
|
||||
}: {
|
||||
items: Item[]
|
||||
}) {
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
{items.map(item => (
|
||||
<text key={item.id}>{item.name}</text>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
### State Updates During Render
|
||||
|
||||
Don't update state during render:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
function Component({ value }: { value: number }) {
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
// This causes infinite loop!
|
||||
if (value > 10) {
|
||||
setCount(value)
|
||||
}
|
||||
|
||||
return <text>{count}</text>
|
||||
}
|
||||
|
||||
// CORRECT
|
||||
function Component({ value }: { value: number }) {
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (value > 10) {
|
||||
setCount(value)
|
||||
}
|
||||
}, [value])
|
||||
|
||||
return <text>{count}</text>
|
||||
}
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
### Console Not Visible
|
||||
|
||||
OpenTUI captures console output. Show the overlay:
|
||||
|
||||
```tsx
|
||||
import { useRenderer } from "@opentui/react"
|
||||
import { useEffect } from "react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useEffect(() => {
|
||||
renderer.console.show()
|
||||
console.log("Now you can see this!")
|
||||
}, [renderer])
|
||||
|
||||
return <box>{/* ... */}</box>
|
||||
}
|
||||
```
|
||||
|
||||
### Component Not Rendering
|
||||
|
||||
Check if component is in the tree:
|
||||
|
||||
```tsx
|
||||
// WRONG - Conditional returns nothing
|
||||
function MaybeComponent({ show }: { show: boolean }) {
|
||||
if (!show) return // Returns undefined!
|
||||
return <text>Visible</text>
|
||||
}
|
||||
|
||||
// CORRECT
|
||||
function MaybeComponent({ show }: { show: boolean }) {
|
||||
if (!show) return null // Explicit null
|
||||
return <text>Visible</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Events Not Firing
|
||||
|
||||
Check event handler names:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<box onClick={() => {}}>Click</box> // No onClick in TUI
|
||||
|
||||
// CORRECT
|
||||
<box onMouseDown={() => {}}>Click</box>
|
||||
<box onMouseUp={() => {}}>Click</box>
|
||||
```
|
||||
|
||||
## Runtime Issues
|
||||
|
||||
### Use Bun, Not Node
|
||||
|
||||
```bash
|
||||
# WRONG
|
||||
node src/index.tsx
|
||||
npm run start
|
||||
|
||||
# CORRECT
|
||||
bun run src/index.tsx
|
||||
bun run start
|
||||
```
|
||||
|
||||
### Async Top-level
|
||||
|
||||
Bun supports top-level await, but be careful:
|
||||
|
||||
```tsx
|
||||
// index.tsx - This works in Bun
|
||||
const renderer = await createCliRenderer()
|
||||
createRoot(renderer).render(<App />)
|
||||
|
||||
// If you need to handle errors
|
||||
try {
|
||||
const renderer = await createCliRenderer()
|
||||
createRoot(renderer).render(<App />)
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize:", error)
|
||||
process.exit(1)
|
||||
}
|
||||
```
|
||||
|
||||
## Common Error Messages
|
||||
|
||||
### "Cannot read properties of undefined (reading 'root')"
|
||||
|
||||
Renderer not initialized:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
const renderer = createCliRenderer() // Missing await!
|
||||
createRoot(renderer).render(<App />)
|
||||
|
||||
// CORRECT
|
||||
const renderer = await createCliRenderer()
|
||||
createRoot(renderer).render(<App />)
|
||||
```
|
||||
|
||||
### "Invalid hook call"
|
||||
|
||||
Hooks called outside component:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
const dimensions = useTerminalDimensions() // Outside component!
|
||||
|
||||
function App() {
|
||||
return <text>{dimensions.width}</text>
|
||||
}
|
||||
|
||||
// CORRECT
|
||||
function App() {
|
||||
const dimensions = useTerminalDimensions()
|
||||
return <text>{dimensions.width}</text>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,501 @@
|
||||
# React Patterns
|
||||
|
||||
## State Management
|
||||
|
||||
### Local State with useState
|
||||
|
||||
```tsx
|
||||
import { useState } from "react"
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
return (
|
||||
<box flexDirection="row" gap={2}>
|
||||
<text>Count: {count}</text>
|
||||
<box border onMouseDown={() => setCount(c => c - 1)}>
|
||||
<text>-</text>
|
||||
</box>
|
||||
<box border onMouseDown={() => setCount(c => c + 1)}>
|
||||
<text>+</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Complex State with useReducer
|
||||
|
||||
```tsx
|
||||
import { useReducer } from "react"
|
||||
|
||||
type State = {
|
||||
items: string[]
|
||||
selectedIndex: number
|
||||
}
|
||||
|
||||
type Action =
|
||||
| { type: "ADD_ITEM"; item: string }
|
||||
| { type: "REMOVE_ITEM"; index: number }
|
||||
| { type: "SELECT"; index: number }
|
||||
|
||||
function reducer(state: State, action: Action): State {
|
||||
switch (action.type) {
|
||||
case "ADD_ITEM":
|
||||
return { ...state, items: [...state.items, action.item] }
|
||||
case "REMOVE_ITEM":
|
||||
return {
|
||||
...state,
|
||||
items: state.items.filter((_, i) => i !== action.index),
|
||||
}
|
||||
case "SELECT":
|
||||
return { ...state, selectedIndex: action.index }
|
||||
}
|
||||
}
|
||||
|
||||
function ItemList() {
|
||||
const [state, dispatch] = useReducer(reducer, {
|
||||
items: [],
|
||||
selectedIndex: 0,
|
||||
})
|
||||
|
||||
// Use state and dispatch...
|
||||
}
|
||||
```
|
||||
|
||||
### Context for Global State
|
||||
|
||||
```tsx
|
||||
import { createContext, useContext, useState, ReactNode } from "react"
|
||||
|
||||
type Theme = "dark" | "light"
|
||||
|
||||
const ThemeContext = createContext<{
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
} | null>(null)
|
||||
|
||||
function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>("dark")
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, setTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function useTheme() {
|
||||
const context = useContext(ThemeContext)
|
||||
if (!context) throw new Error("useTheme must be used within ThemeProvider")
|
||||
return context
|
||||
}
|
||||
|
||||
// Usage
|
||||
function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<ThemedBox />
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ThemedBox() {
|
||||
const { theme } = useTheme()
|
||||
return (
|
||||
<box backgroundColor={theme === "dark" ? "#1a1a2e" : "#f0f0f0"}>
|
||||
<text fg={theme === "dark" ? "#fff" : "#000"}>
|
||||
Current theme: {theme}
|
||||
</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Focus Management
|
||||
|
||||
### Focus State
|
||||
|
||||
```tsx
|
||||
import { useState } from "react"
|
||||
import { useKeyboard } from "@opentui/react"
|
||||
|
||||
function FocusableForm() {
|
||||
const [focusIndex, setFocusIndex] = useState(0)
|
||||
const fields = ["name", "email", "message"]
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "tab") {
|
||||
setFocusIndex(i => (i + 1) % fields.length)
|
||||
}
|
||||
if (key.shift && key.name === "tab") {
|
||||
setFocusIndex(i => (i - 1 + fields.length) % fields.length)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
{fields.map((field, i) => (
|
||||
<input
|
||||
key={field}
|
||||
placeholder={`Enter ${field}...`}
|
||||
focused={i === focusIndex}
|
||||
/>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Ref-based Focus
|
||||
|
||||
```tsx
|
||||
import { useRef, useEffect } from "react"
|
||||
|
||||
function AutoFocusInput() {
|
||||
const inputRef = useRef<any>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Focus on mount
|
||||
inputRef.current?.focus()
|
||||
}, [])
|
||||
|
||||
return <input ref={inputRef} placeholder="Auto-focused" />
|
||||
}
|
||||
```
|
||||
|
||||
## Keyboard Navigation
|
||||
|
||||
### Global Shortcuts
|
||||
|
||||
```tsx
|
||||
import { useKeyboard, useRenderer } from "@opentui/react"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useKeyboard((key) => {
|
||||
// Quit on Escape or Ctrl+C - use renderer.destroy(), never process.exit()
|
||||
if (key.name === "escape" || (key.ctrl && key.name === "c")) {
|
||||
renderer.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
// Toggle help on ?
|
||||
if (key.name === "?" || (key.shift && key.name === "/")) {
|
||||
setShowHelp(h => !h)
|
||||
}
|
||||
|
||||
// Vim-style navigation
|
||||
if (key.name === "j") moveDown()
|
||||
if (key.name === "k") moveUp()
|
||||
})
|
||||
|
||||
return <box>{/* ... */}</box>
|
||||
}
|
||||
```
|
||||
|
||||
### Component-level Shortcuts
|
||||
|
||||
```tsx
|
||||
function Editor() {
|
||||
const [mode, setMode] = useState<"normal" | "insert">("normal")
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (mode === "normal") {
|
||||
if (key.name === "i") setMode("insert")
|
||||
if (key.name === "escape") setMode("normal")
|
||||
} else {
|
||||
if (key.name === "escape") setMode("normal")
|
||||
// Handle text input in insert mode
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box>
|
||||
<text>Mode: {mode}</text>
|
||||
<textarea focused={mode === "insert"} />
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Form Handling
|
||||
|
||||
### Controlled Inputs
|
||||
|
||||
```tsx
|
||||
import { useState } from "react"
|
||||
|
||||
function LoginForm() {
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
|
||||
const handleSubmit = () => {
|
||||
console.log("Login:", { username, password })
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1} padding={2} border>
|
||||
<text>Login</text>
|
||||
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text>Username:</text>
|
||||
<input
|
||||
value={username}
|
||||
onChange={setUsername}
|
||||
width={20}
|
||||
/>
|
||||
</box>
|
||||
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text>Password:</text>
|
||||
<input
|
||||
value={password}
|
||||
onChange={setPassword}
|
||||
width={20}
|
||||
/>
|
||||
</box>
|
||||
|
||||
<box border onMouseDown={handleSubmit}>
|
||||
<text>Submit</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Form Validation
|
||||
|
||||
```tsx
|
||||
function ValidatedForm() {
|
||||
const [email, setEmail] = useState("")
|
||||
const [error, setError] = useState("")
|
||||
|
||||
const validateEmail = (value: string) => {
|
||||
if (!value.includes("@")) {
|
||||
setError("Invalid email address")
|
||||
} else {
|
||||
setError("")
|
||||
}
|
||||
setEmail(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<input
|
||||
value={email}
|
||||
onChange={validateEmail}
|
||||
placeholder="Email"
|
||||
/>
|
||||
{error && <text fg="red">{error}</text>}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Responsive Design
|
||||
|
||||
### Terminal-size Responsive
|
||||
|
||||
```tsx
|
||||
import { useTerminalDimensions } from "@opentui/react"
|
||||
|
||||
function ResponsiveLayout() {
|
||||
const { width } = useTerminalDimensions()
|
||||
|
||||
// Stack vertically on narrow terminals
|
||||
const isNarrow = width < 80
|
||||
|
||||
return (
|
||||
<box flexDirection={isNarrow ? "column" : "row"}>
|
||||
<box flexGrow={isNarrow ? 0 : 1} height={isNarrow ? 10 : "100%"}>
|
||||
<text>Sidebar</text>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
<text>Main Content</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Dynamic Layouts
|
||||
|
||||
```tsx
|
||||
function DynamicGrid({ items }: { items: string[] }) {
|
||||
const { width } = useTerminalDimensions()
|
||||
const columns = Math.max(1, Math.floor(width / 20))
|
||||
|
||||
return (
|
||||
<box flexDirection="row" flexWrap="wrap">
|
||||
{items.map((item, i) => (
|
||||
<box key={i} width={`${100 / columns}%`} padding={1}>
|
||||
<text>{item}</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Async Data Loading
|
||||
|
||||
### Loading States
|
||||
|
||||
```tsx
|
||||
import { useState, useEffect } from "react"
|
||||
|
||||
function DataDisplay() {
|
||||
const [data, setData] = useState<string[] | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
try {
|
||||
const response = await fetch("https://api.example.com/data")
|
||||
const json = await response.json()
|
||||
setData(json.items)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Unknown error")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
load()
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
return <text>Loading...</text>
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <text fg="red">Error: {error}</text>
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
{data?.map((item, i) => (
|
||||
<text key={i}>{item}</text>
|
||||
))}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Animation Patterns
|
||||
|
||||
### Simple Animations
|
||||
|
||||
```tsx
|
||||
import { useState, useEffect } from "react"
|
||||
import { useTimeline } from "@opentui/react"
|
||||
|
||||
function ProgressBar() {
|
||||
const [progress, setProgress] = useState(0)
|
||||
|
||||
const timeline = useTimeline({ duration: 3000 })
|
||||
|
||||
useEffect(() => {
|
||||
timeline.add(
|
||||
{ value: 0 },
|
||||
{
|
||||
value: 100,
|
||||
duration: 3000,
|
||||
ease: "linear",
|
||||
onUpdate: (anim) => {
|
||||
setProgress(Math.round(anim.targets[0].value))
|
||||
},
|
||||
}
|
||||
)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text>Progress: {progress}%</text>
|
||||
<box width={50} height={1} backgroundColor="#333">
|
||||
<box
|
||||
width={`${progress}%`}
|
||||
height={1}
|
||||
backgroundColor="#00ff00"
|
||||
/>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Interval-based Updates
|
||||
|
||||
```tsx
|
||||
function Clock() {
|
||||
const [time, setTime] = useState(new Date())
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setTime(new Date())
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
return <text>{time.toLocaleTimeString()}</text>
|
||||
}
|
||||
```
|
||||
|
||||
## Component Composition
|
||||
|
||||
### Render Props
|
||||
|
||||
```tsx
|
||||
function Focusable({
|
||||
children
|
||||
}: {
|
||||
children: (focused: boolean) => React.ReactNode
|
||||
}) {
|
||||
const [focused, setFocused] = useState(false)
|
||||
|
||||
return (
|
||||
<box
|
||||
onMouseDown={() => setFocused(true)}
|
||||
onMouseUp={() => setFocused(false)}
|
||||
>
|
||||
{children(focused)}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
<Focusable>
|
||||
{(focused) => (
|
||||
<text fg={focused ? "#00ff00" : "#ffffff"}>
|
||||
{focused ? "Focused!" : "Click me"}
|
||||
</text>
|
||||
)}
|
||||
</Focusable>
|
||||
```
|
||||
|
||||
### Higher-Order Components
|
||||
|
||||
```tsx
|
||||
function withBorder<P extends object>(
|
||||
Component: React.ComponentType<P>,
|
||||
borderStyle: string = "single"
|
||||
) {
|
||||
return function BorderedComponent(props: P) {
|
||||
return (
|
||||
<box border borderStyle={borderStyle} padding={1}>
|
||||
<Component {...props} />
|
||||
</box>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const BorderedText = withBorder(({ content }: { content: string }) => (
|
||||
<text>{content}</text>
|
||||
))
|
||||
|
||||
<BorderedText content="Hello!" />
|
||||
```
|
||||
@@ -0,0 +1,201 @@
|
||||
# OpenTUI Solid (@opentui/solid)
|
||||
|
||||
A SolidJS reconciler for building terminal user interfaces with fine-grained reactivity. Get optimal performance with Solid's signal-based approach.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTUI Solid provides:
|
||||
- **Custom reconciler**: Solid components render to OpenTUI renderables
|
||||
- **JSX intrinsics**: `<text>`, `<box>`, `<input>`, etc.
|
||||
- **Hooks**: `useKeyboard`, `useRenderer`, `useTimeline`, etc.
|
||||
- **Fine-grained reactivity**: Only what changes re-renders
|
||||
- **Portal & Dynamic**: Advanced composition primitives
|
||||
|
||||
## When to Use Solid
|
||||
|
||||
Use the Solid reconciler when:
|
||||
- You want optimal re-rendering performance
|
||||
- You prefer signal-based reactivity
|
||||
- You need fine-grained control over updates
|
||||
- Building performance-critical applications
|
||||
- You already know SolidJS
|
||||
|
||||
## When NOT to Use Solid
|
||||
|
||||
| Scenario | Use Instead |
|
||||
|----------|-------------|
|
||||
| Team knows React, not Solid | `@opentui/react` |
|
||||
| Maximum control needed | `@opentui/core` |
|
||||
| Smallest bundle size | `@opentui/core` |
|
||||
| Building a framework/library | `@opentui/core` |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
bunx create-tui@latest -t solid my-app
|
||||
cd my-app && bun install
|
||||
```
|
||||
|
||||
The CLI creates the `my-app` directory for you - it must **not already exist**.
|
||||
|
||||
Options: `--no-git` (skip git init), `--no-install` (skip bun install)
|
||||
|
||||
**Agent guidance**: Always use autonomous mode with `-t <template>` flag. Never use interactive mode (`bunx create-tui@latest my-app` without `-t`) as it requires user prompts that agents cannot respond to.
|
||||
|
||||
Or manually:
|
||||
|
||||
```bash
|
||||
bun install @opentui/solid @opentui/core solid-js
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
import { createSignal } from "solid-js"
|
||||
|
||||
function App() {
|
||||
const [count, setCount] = createSignal(0)
|
||||
|
||||
return (
|
||||
<box border padding={2}>
|
||||
<text>Count: {count()}</text>
|
||||
<box
|
||||
border
|
||||
onMouseDown={() => setCount(c => c + 1)}
|
||||
>
|
||||
<text>Click me!</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
render(() => <App />)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Signals
|
||||
|
||||
Solid uses signals for reactive state:
|
||||
|
||||
```tsx
|
||||
import { createSignal, createEffect } from "solid-js"
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = createSignal(0)
|
||||
|
||||
// Effect runs when count changes
|
||||
createEffect(() => {
|
||||
console.log("Count is now:", count())
|
||||
})
|
||||
|
||||
return <text>Count: {count()}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### JSX Elements
|
||||
|
||||
Solid maps JSX intrinsic elements to OpenTUI renderables:
|
||||
|
||||
```tsx
|
||||
// Note: Some use underscores (Solid convention)
|
||||
<text>Hello</text> // TextRenderable
|
||||
<box border>Content</box> // BoxRenderable
|
||||
<input placeholder="..." /> // InputRenderable
|
||||
<select options={[...]} /> // SelectRenderable
|
||||
<tab_select /> // TabSelectRenderable (underscore!)
|
||||
<ascii_font /> // ASCIIFontRenderable (underscore!)
|
||||
<line_number /> // LineNumberRenderable (underscore!)
|
||||
```
|
||||
|
||||
### Text Modifiers
|
||||
|
||||
Inside `<text>`, use modifier elements:
|
||||
|
||||
```tsx
|
||||
<text>
|
||||
<strong>Bold</strong>, <em>italic</em>, and <u>underlined</u>
|
||||
<span fg="red">Colored text</span>
|
||||
<br />
|
||||
New line with <a href="https://example.com">link</a>
|
||||
</text>
|
||||
```
|
||||
|
||||
## Available Components
|
||||
|
||||
### Layout & Display
|
||||
- `<text>` - Styled text content
|
||||
- `<box>` - Container with borders and layout
|
||||
- `<scrollbox>` - Scrollable container
|
||||
- `<ascii_font>` - ASCII art text (note underscore)
|
||||
|
||||
### Input
|
||||
- `<input>` - Single-line text input
|
||||
- `<textarea>` - Multi-line text input
|
||||
- `<select>` - List selection
|
||||
- `<tab_select>` - Tab-based selection (note underscore)
|
||||
|
||||
### Code & Diff
|
||||
- `<code>` - Syntax-highlighted code
|
||||
- `<line_number>` - Code with line numbers (note underscore)
|
||||
- `<diff>` - Unified or split diff viewer
|
||||
|
||||
### Text Modifiers (inside `<text>`)
|
||||
- `<span>` - Inline styled text
|
||||
- `<strong>`, `<b>` - Bold
|
||||
- `<em>`, `<i>` - Italic
|
||||
- `<u>` - Underline
|
||||
- `<br>` - Line break
|
||||
- `<a>` - Link
|
||||
|
||||
## Special Components
|
||||
|
||||
### Portal
|
||||
|
||||
Render children to a different mount node:
|
||||
|
||||
```tsx
|
||||
import { Portal } from "@opentui/solid"
|
||||
|
||||
function Overlay() {
|
||||
return (
|
||||
<Portal mount={renderer.root}>
|
||||
<box position="absolute" left={10} top={5} border>
|
||||
<text>Overlay content</text>
|
||||
</box>
|
||||
</Portal>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Dynamic
|
||||
|
||||
Render components dynamically:
|
||||
|
||||
```tsx
|
||||
import { Dynamic } from "@opentui/solid"
|
||||
|
||||
function DynamicInput(props: { multiline: boolean }) {
|
||||
return (
|
||||
<Dynamic
|
||||
component={props.multiline ? "textarea" : "input"}
|
||||
placeholder="Enter text..."
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## In This Reference
|
||||
|
||||
- [Configuration](./configuration.md) - Project setup, tsconfig, bunfig, building
|
||||
- [API](./api.md) - Components, hooks, render function
|
||||
- [Patterns](./patterns.md) - Signals, stores, control flow, composition
|
||||
- [Gotchas](./gotchas.md) - Common issues, debugging, limitations
|
||||
|
||||
## See Also
|
||||
|
||||
- [Core](../core/REFERENCE.md) - Underlying imperative API
|
||||
- [React](../react/REFERENCE.md) - Alternative declarative approach
|
||||
- [Components](../components/REFERENCE.md) - Component reference by category
|
||||
- [Layout](../layout/REFERENCE.md) - Flexbox layout system
|
||||
- [Keyboard](../keyboard/REFERENCE.md) - Input handling and shortcuts
|
||||
- [Testing](../testing/REFERENCE.md) - Test renderer and snapshots
|
||||
@@ -0,0 +1,564 @@
|
||||
# Solid API Reference
|
||||
|
||||
## Rendering
|
||||
|
||||
### render(node, rendererOrConfig?)
|
||||
|
||||
Renders a Solid component tree into a CLI renderer.
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
|
||||
// Simple usage - creates renderer automatically
|
||||
render(() => <App />)
|
||||
|
||||
// With config
|
||||
render(() => <App />, {
|
||||
exitOnCtrlC: false,
|
||||
targetFPS: 60,
|
||||
})
|
||||
|
||||
// With existing renderer
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
render(() => <App />, renderer)
|
||||
```
|
||||
|
||||
### testRender(node, options?)
|
||||
|
||||
Create a test renderer for snapshots and tests.
|
||||
|
||||
```tsx
|
||||
import { testRender } from "@opentui/solid"
|
||||
|
||||
const testSetup = await testRender(() => <App />, {
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
// Access test utilities
|
||||
testSetup.snapshot() // Get current render
|
||||
testSetup.renderer // Access renderer
|
||||
```
|
||||
|
||||
### extend(components)
|
||||
|
||||
Register custom renderables as JSX intrinsic elements.
|
||||
|
||||
```tsx
|
||||
import { extend } from "@opentui/solid"
|
||||
import { CustomRenderable } from "./custom"
|
||||
|
||||
extend({
|
||||
custom: CustomRenderable,
|
||||
})
|
||||
|
||||
// Now usable in JSX
|
||||
<custom prop="value" />
|
||||
```
|
||||
|
||||
### getComponentCatalogue()
|
||||
|
||||
Returns the current component catalogue.
|
||||
|
||||
```tsx
|
||||
import { getComponentCatalogue } from "@opentui/solid"
|
||||
|
||||
const catalogue = getComponentCatalogue()
|
||||
console.log(Object.keys(catalogue))
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
### useRenderer()
|
||||
|
||||
Access the OpenTUI renderer instance.
|
||||
|
||||
```tsx
|
||||
import { useRenderer } from "@opentui/solid"
|
||||
import { onMount } from "solid-js"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
onMount(() => {
|
||||
console.log(`Terminal: ${renderer.width}x${renderer.height}`)
|
||||
renderer.console.show()
|
||||
|
||||
// Access theme mode (dark/light based on terminal settings)
|
||||
console.log(`Theme: ${renderer.themeMode}`) // "dark" | "light" | null
|
||||
})
|
||||
|
||||
return <text>Hello</text>
|
||||
}
|
||||
|
||||
// Listen for theme mode changes
|
||||
function ThemedApp() {
|
||||
const renderer = useRenderer()
|
||||
const [theme, setTheme] = createSignal(renderer.themeMode ?? "dark")
|
||||
|
||||
onMount(() => {
|
||||
renderer.on("theme_mode", (mode: "dark" | "light") => setTheme(mode))
|
||||
})
|
||||
|
||||
return (
|
||||
<box backgroundColor={theme() === "dark" ? "#1a1a2e" : "#ffffff"}>
|
||||
<text fg={theme() === "dark" ? "#fff" : "#000"}>
|
||||
Current theme: {theme()}
|
||||
</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### useKeyboard(handler, options?)
|
||||
|
||||
Handle keyboard events.
|
||||
|
||||
```tsx
|
||||
import { useKeyboard, useRenderer } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy() // Never use process.exit() directly!
|
||||
}
|
||||
if (key.ctrl && key.name === "s") {
|
||||
saveDocument()
|
||||
}
|
||||
})
|
||||
|
||||
return <text>Press ESC to exit</text>
|
||||
}
|
||||
|
||||
// With release events
|
||||
function GameControls() {
|
||||
const [pressed, setPressed] = createSignal(new Set<string>())
|
||||
|
||||
useKeyboard(
|
||||
(event) => {
|
||||
setPressed(keys => {
|
||||
const newKeys = new Set(keys)
|
||||
if (event.eventType === "release") {
|
||||
newKeys.delete(event.name)
|
||||
} else {
|
||||
newKeys.add(event.name)
|
||||
}
|
||||
return newKeys
|
||||
})
|
||||
},
|
||||
{ release: true }
|
||||
)
|
||||
|
||||
return <text>Pressed: {Array.from(pressed()).join(", ")}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### usePaste(handler)
|
||||
|
||||
Handle paste events. Receives a `PasteEvent` with raw bytes.
|
||||
|
||||
```tsx
|
||||
import { usePaste } from "@opentui/solid"
|
||||
import { decodePasteBytes } from "@opentui/core"
|
||||
|
||||
function PasteHandler() {
|
||||
usePaste((event) => {
|
||||
const text = decodePasteBytes(event.bytes)
|
||||
console.log("Pasted:", text)
|
||||
})
|
||||
|
||||
return <text>Paste something</text>
|
||||
}
|
||||
```
|
||||
|
||||
### onResize(callback)
|
||||
|
||||
Handle terminal resize events.
|
||||
|
||||
```tsx
|
||||
import { onResize } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
onResize((width, height) => {
|
||||
console.log(`Resized to ${width}x${height}`)
|
||||
})
|
||||
|
||||
return <text>Resize the terminal</text>
|
||||
}
|
||||
```
|
||||
|
||||
### useTerminalDimensions()
|
||||
|
||||
Get reactive terminal dimensions.
|
||||
|
||||
```tsx
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
|
||||
function ResponsiveLayout() {
|
||||
const dimensions = useTerminalDimensions()
|
||||
|
||||
return (
|
||||
<box flexDirection={dimensions().width > 80 ? "row" : "column"}>
|
||||
<text>Width: {dimensions().width}</text>
|
||||
<text>Height: {dimensions().height}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### onFocus(callback) / onBlur(callback)
|
||||
|
||||
Handle terminal window focus and blur events. Solid-only hooks.
|
||||
|
||||
```tsx
|
||||
import { onFocus, onBlur } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
onFocus(() => {
|
||||
console.log("Terminal window gained focus")
|
||||
})
|
||||
|
||||
onBlur(() => {
|
||||
console.log("Terminal window lost focus")
|
||||
})
|
||||
|
||||
return <text>Focus/blur tracking</text>
|
||||
}
|
||||
```
|
||||
|
||||
These hooks fire when the terminal emulator window gains or loses operating system focus. The renderer deduplicates events (won't re-emit the same focus state).
|
||||
|
||||
### useSelectionHandler(handler)
|
||||
|
||||
Handle text selection events. Fires when the user finishes a mouse selection (mouse-up). Solid-only hook - React does not have this.
|
||||
|
||||
```tsx
|
||||
import { useSelectionHandler } from "@opentui/solid"
|
||||
import type { Selection } from "@opentui/core"
|
||||
|
||||
function SelectableText() {
|
||||
const [selected, setSelected] = createSignal("")
|
||||
const renderer = useRenderer()
|
||||
|
||||
useSelectionHandler((selection: Selection) => {
|
||||
const text = selection.getSelectedText()
|
||||
if (text) {
|
||||
setSelected(text)
|
||||
renderer.copyToClipboardOSC52(text)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text selectable>Select this text with your mouse</text>
|
||||
<text fg="#888">Selected: {selected()}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The `Selection` object aggregates selected text from all selectable renderables in the tree. See `keyboard/REFERENCE.md` (selection) for full details on the selection API and traversal model.
|
||||
|
||||
### useTimeline(options?)
|
||||
|
||||
Create animations with the timeline system.
|
||||
|
||||
```tsx
|
||||
import { useTimeline } from "@opentui/solid"
|
||||
import { createSignal, onMount } from "solid-js"
|
||||
|
||||
function AnimatedBox() {
|
||||
const [width, setWidth] = createSignal(0)
|
||||
|
||||
const timeline = useTimeline({
|
||||
duration: 2000,
|
||||
loop: false,
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
timeline.add(
|
||||
{ width: 0 },
|
||||
{
|
||||
width: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].width))
|
||||
},
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return <box style={{ width: width(), height: 3, backgroundColor: "#6a5acd" }} />
|
||||
}
|
||||
```
|
||||
|
||||
## Components
|
||||
|
||||
### Text Component
|
||||
|
||||
```tsx
|
||||
<text
|
||||
content="Hello" // Or use children
|
||||
fg="#FFFFFF" // Foreground color
|
||||
bg="#000000" // Background color
|
||||
selectable={true} // Allow text selection
|
||||
>
|
||||
{/* Use nested modifier tags for styling */}
|
||||
<span fg="red">Red</span>
|
||||
<strong>Bold</strong>
|
||||
<em>Italic</em>
|
||||
<u>Underline</u>
|
||||
<br />
|
||||
<a href="https://...">Link</a>
|
||||
</text>
|
||||
```
|
||||
|
||||
> **Note**: Do NOT use `bold`, `italic`, `underline` as props on `<text>`. Use nested modifier tags like `<strong>`, `<em>`, `<u>` instead.
|
||||
|
||||
### Box Component
|
||||
|
||||
```tsx
|
||||
<box
|
||||
// Borders
|
||||
border // Enable border
|
||||
borderStyle="single" // single | double | rounded | bold
|
||||
borderColor="#FFFFFF"
|
||||
title="Title"
|
||||
titleAlignment="center" // left | center | right
|
||||
|
||||
// Colors
|
||||
backgroundColor="#1a1a2e"
|
||||
|
||||
// Layout
|
||||
flexDirection="row"
|
||||
justifyContent="center"
|
||||
alignItems="center"
|
||||
gap={2}
|
||||
|
||||
// Spacing
|
||||
padding={2}
|
||||
paddingX={2} // Horizontal (left + right)
|
||||
paddingY={1} // Vertical (top + bottom)
|
||||
margin={1}
|
||||
marginX={2} // Horizontal (left + right)
|
||||
marginY={1} // Vertical (top + bottom)
|
||||
|
||||
// Dimensions
|
||||
width={40}
|
||||
height={10}
|
||||
flexGrow={1}
|
||||
|
||||
// Focus
|
||||
focusable // Allow box to receive focus
|
||||
focused={isFocused()} // Controlled focus state
|
||||
|
||||
// Events
|
||||
onMouseDown={(e) => {}}
|
||||
onMouseUp={(e) => {}}
|
||||
>
|
||||
{children}
|
||||
</box>
|
||||
```
|
||||
|
||||
### Scrollbox Component
|
||||
|
||||
```tsx
|
||||
<scrollbox
|
||||
focused // Enable keyboard scrolling
|
||||
style={{
|
||||
scrollbarOptions: {
|
||||
showArrows: true,
|
||||
trackOptions: {
|
||||
foregroundColor: "#7aa2f7",
|
||||
backgroundColor: "#414868",
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<For each={items()}>
|
||||
{(item) => <text>{item}</text>}
|
||||
</For>
|
||||
</scrollbox>
|
||||
```
|
||||
|
||||
### Input Component
|
||||
|
||||
```tsx
|
||||
<input
|
||||
value={value()}
|
||||
onInput={(newValue) => setValue(newValue)}
|
||||
placeholder="Enter text..."
|
||||
focused
|
||||
width={30}
|
||||
/>
|
||||
```
|
||||
|
||||
### Textarea Component
|
||||
|
||||
```tsx
|
||||
<textarea
|
||||
value={text()}
|
||||
onInput={(newValue) => setText(newValue)}
|
||||
placeholder="Enter multiple lines..."
|
||||
focused
|
||||
width={40}
|
||||
height={10}
|
||||
/>
|
||||
```
|
||||
|
||||
### Select Component
|
||||
|
||||
```tsx
|
||||
<select
|
||||
options={[
|
||||
{ name: "Option 1", description: "First", value: "1" },
|
||||
{ name: "Option 2", description: "Second", value: "2" },
|
||||
]}
|
||||
onChange={(index, option) => setSelected(option)}
|
||||
selectedIndex={0}
|
||||
focused
|
||||
/>
|
||||
```
|
||||
|
||||
### Tab Select Component (Note: underscore)
|
||||
|
||||
```tsx
|
||||
<tab_select
|
||||
options={[
|
||||
{ name: "Home", description: "Dashboard" },
|
||||
{ name: "Settings", description: "Configuration" },
|
||||
]}
|
||||
onChange={(index, option) => setTab(option)}
|
||||
tabWidth={20}
|
||||
focused
|
||||
/>
|
||||
```
|
||||
|
||||
### ASCII Font Component (Note: underscore)
|
||||
|
||||
```tsx
|
||||
<ascii_font
|
||||
text="TITLE"
|
||||
font="tiny" // tiny | block | slick | shade
|
||||
color="#FFFFFF"
|
||||
/>
|
||||
```
|
||||
|
||||
### Code Component
|
||||
|
||||
```tsx
|
||||
<code
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
/>
|
||||
```
|
||||
|
||||
### Line Number Component (Note: underscore)
|
||||
|
||||
```tsx
|
||||
<line_number
|
||||
code={sourceCode}
|
||||
language="typescript"
|
||||
startLine={1}
|
||||
highlightedLines={[5]}
|
||||
/>
|
||||
```
|
||||
|
||||
### Diff Component
|
||||
|
||||
```tsx
|
||||
<diff
|
||||
oldCode={originalCode}
|
||||
newCode={modifiedCode}
|
||||
language="typescript"
|
||||
mode="unified" // unified | split
|
||||
syncScroll // Sync scroll between split view panes
|
||||
/>
|
||||
```
|
||||
|
||||
## Control Flow
|
||||
|
||||
Solid's control flow components work with OpenTUI:
|
||||
|
||||
### For
|
||||
|
||||
```tsx
|
||||
import { For } from "solid-js"
|
||||
|
||||
<For each={items()}>
|
||||
{(item, index) => (
|
||||
<box key={index()}>
|
||||
<text>{item.name}</text>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
```
|
||||
|
||||
### Show
|
||||
|
||||
```tsx
|
||||
import { Show } from "solid-js"
|
||||
|
||||
<Show when={isVisible()} fallback={<text>Hidden</text>}>
|
||||
<text>Visible content</text>
|
||||
</Show>
|
||||
```
|
||||
|
||||
### Switch/Match
|
||||
|
||||
```tsx
|
||||
import { Switch, Match } from "solid-js"
|
||||
|
||||
<Switch>
|
||||
<Match when={status() === "loading"}>
|
||||
<text>Loading...</text>
|
||||
</Match>
|
||||
<Match when={status() === "error"}>
|
||||
<text fg="red">Error!</text>
|
||||
</Match>
|
||||
<Match when={status() === "success"}>
|
||||
<text fg="green">Success!</text>
|
||||
</Match>
|
||||
</Switch>
|
||||
```
|
||||
|
||||
### Index
|
||||
|
||||
```tsx
|
||||
import { Index } from "solid-js"
|
||||
|
||||
<Index each={items()}>
|
||||
{(item, index) => (
|
||||
<text>{index}: {item().name}</text>
|
||||
)}
|
||||
</Index>
|
||||
```
|
||||
|
||||
## Special Components
|
||||
|
||||
### Portal
|
||||
|
||||
```tsx
|
||||
import { Portal } from "@opentui/solid"
|
||||
|
||||
<Portal mount={targetNode}>
|
||||
<box>Portal content</box>
|
||||
</Portal>
|
||||
```
|
||||
|
||||
### Dynamic
|
||||
|
||||
```tsx
|
||||
import { Dynamic } from "@opentui/solid"
|
||||
|
||||
<Dynamic
|
||||
component={isMultiline() ? "textarea" : "input"}
|
||||
placeholder="Enter text..."
|
||||
focused
|
||||
/>
|
||||
```
|
||||
@@ -0,0 +1,316 @@
|
||||
# Solid Configuration
|
||||
|
||||
## Project Setup
|
||||
|
||||
### Quick Start
|
||||
|
||||
```bash
|
||||
bunx create-tui@latest -t solid my-app
|
||||
cd my-app && bun install
|
||||
```
|
||||
|
||||
The CLI creates the `my-app` directory for you - it must **not already exist**.
|
||||
|
||||
Options: `--no-git` (skip git init), `--no-install` (skip bun install)
|
||||
|
||||
### Manual Setup
|
||||
|
||||
```bash
|
||||
mkdir my-tui && cd my-tui
|
||||
bun init
|
||||
bun install @opentui/solid @opentui/core solid-js
|
||||
```
|
||||
|
||||
## TypeScript Configuration
|
||||
|
||||
### tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
|
||||
"jsx": "preserve",
|
||||
"jsxImportSource": "@opentui/solid",
|
||||
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["bun-types"]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
```
|
||||
|
||||
**Critical settings:**
|
||||
- `jsx: "preserve"` - Let Solid's compiler handle JSX
|
||||
- `jsxImportSource: "@opentui/solid"` - Import JSX runtime from OpenTUI Solid
|
||||
- `module` / `moduleResolution: "NodeNext"` - Recommended for OpenTUI compatibility
|
||||
|
||||
## Bun Configuration
|
||||
|
||||
### bunfig.toml
|
||||
|
||||
**Required** for the Solid compiler:
|
||||
|
||||
```toml
|
||||
preload = ["@opentui/solid/preload"]
|
||||
```
|
||||
|
||||
This loads the Solid JSX transform before your code runs.
|
||||
|
||||
## Package Configuration
|
||||
|
||||
### package.json
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "my-tui-app",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "bun run src/index.tsx",
|
||||
"dev": "bun --watch run src/index.tsx",
|
||||
"test": "bun test",
|
||||
"build": "bun run build.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opentui/core": "latest",
|
||||
"@opentui/solid": "latest",
|
||||
"solid-js": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"typescript": "latest"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
Recommended structure:
|
||||
|
||||
```
|
||||
my-tui-app/
|
||||
├── src/
|
||||
│ ├── components/
|
||||
│ │ ├── Header.tsx
|
||||
│ │ ├── Sidebar.tsx
|
||||
│ │ └── MainContent.tsx
|
||||
│ ├── stores/
|
||||
│ │ └── appStore.ts
|
||||
│ ├── App.tsx
|
||||
│ └── index.tsx
|
||||
├── bunfig.toml # Required!
|
||||
├── package.json
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
### Entry Point (src/index.tsx)
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
import { App } from "./App"
|
||||
|
||||
render(() => <App />)
|
||||
```
|
||||
|
||||
### App Component (src/App.tsx)
|
||||
|
||||
```tsx
|
||||
import { Header } from "./components/Header"
|
||||
import { Sidebar } from "./components/Sidebar"
|
||||
import { MainContent } from "./components/MainContent"
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
<Header />
|
||||
<box flexDirection="row" flexGrow={1}>
|
||||
<Sidebar />
|
||||
<MainContent />
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Renderer Configuration
|
||||
|
||||
### render() Options
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
import { ConsolePosition } from "@opentui/core"
|
||||
|
||||
render(() => <App />, {
|
||||
// Rendering
|
||||
targetFPS: 60,
|
||||
|
||||
// Behavior
|
||||
exitOnCtrlC: true,
|
||||
autoFocus: true, // Auto-focus elements on click (default: true)
|
||||
useMouse: true, // Enable mouse support (default: true)
|
||||
|
||||
// Debug console
|
||||
consoleOptions: {
|
||||
position: ConsolePosition.BOTTOM,
|
||||
sizePercent: 30,
|
||||
startInDebugMode: false,
|
||||
},
|
||||
|
||||
// Cleanup
|
||||
onDestroy: () => {
|
||||
// Cleanup code
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Using Existing Renderer
|
||||
|
||||
```tsx
|
||||
import { render } from "@opentui/solid"
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
|
||||
const renderer = await createCliRenderer({
|
||||
exitOnCtrlC: false,
|
||||
})
|
||||
|
||||
render(() => <App />, renderer)
|
||||
```
|
||||
|
||||
## Building for Distribution
|
||||
|
||||
### Build Script (build.ts)
|
||||
|
||||
```typescript
|
||||
import solidPlugin from "@opentui/solid/bun-plugin"
|
||||
|
||||
await Bun.build({
|
||||
entrypoints: ["./src/index.tsx"],
|
||||
outdir: "./dist",
|
||||
target: "bun",
|
||||
minify: true,
|
||||
plugins: [solidPlugin],
|
||||
})
|
||||
|
||||
console.log("Build complete!")
|
||||
```
|
||||
|
||||
Run: `bun run build.ts`
|
||||
|
||||
### Creating Executables
|
||||
|
||||
```typescript
|
||||
import solidPlugin from "@opentui/solid/bun-plugin"
|
||||
|
||||
await Bun.build({
|
||||
entrypoints: ["./src/index.tsx"],
|
||||
target: "bun",
|
||||
plugins: [solidPlugin],
|
||||
compile: {
|
||||
target: "bun-darwin-arm64", // or bun-linux-x64, etc.
|
||||
outfile: "my-app",
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
**Available targets:**
|
||||
- `bun-darwin-arm64` - macOS Apple Silicon
|
||||
- `bun-darwin-x64` - macOS Intel
|
||||
- `bun-linux-x64` - Linux x64
|
||||
- `bun-linux-arm64` - Linux ARM64
|
||||
- `bun-windows-x64` - Windows x64
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create `.env` for development:
|
||||
|
||||
```env
|
||||
# Debug settings
|
||||
OTUI_SHOW_STATS=false
|
||||
SHOW_CONSOLE=false
|
||||
|
||||
# App settings
|
||||
API_URL=https://api.example.com
|
||||
```
|
||||
|
||||
Bun auto-loads `.env` files:
|
||||
|
||||
```tsx
|
||||
const apiUrl = process.env.API_URL
|
||||
```
|
||||
|
||||
## Testing Configuration
|
||||
|
||||
### Test Setup
|
||||
|
||||
```typescript
|
||||
// src/test-utils.tsx
|
||||
import { testRender } from "@opentui/solid"
|
||||
|
||||
export async function renderForTest(
|
||||
Component: () => JSX.Element,
|
||||
options = { width: 80, height: 24 }
|
||||
) {
|
||||
return await testRender(Component, options)
|
||||
}
|
||||
```
|
||||
|
||||
### Test Example
|
||||
|
||||
```typescript
|
||||
// src/components/Counter.test.tsx
|
||||
import { test, expect } from "bun:test"
|
||||
import { renderForTest } from "../test-utils"
|
||||
import { Counter } from "./Counter"
|
||||
|
||||
test("Counter renders initial value", async () => {
|
||||
const { snapshot } = await renderForTest(() => <Counter initialValue={5} />)
|
||||
expect(snapshot()).toContain("Count: 5")
|
||||
})
|
||||
```
|
||||
|
||||
## Common Configuration Issues
|
||||
|
||||
### Missing bunfig.toml
|
||||
|
||||
**Symptom**: JSX not transformed, syntax errors
|
||||
|
||||
**Fix**: Create `bunfig.toml` with preload:
|
||||
|
||||
```toml
|
||||
preload = ["@opentui/solid/preload"]
|
||||
```
|
||||
|
||||
### Wrong JSX Settings
|
||||
|
||||
**Symptom**: JSX compiles to React calls
|
||||
|
||||
**Fix**: Ensure tsconfig has:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "preserve",
|
||||
"jsxImportSource": "@opentui/solid"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Build Missing Plugin
|
||||
|
||||
**Symptom**: Built output has untransformed JSX
|
||||
|
||||
**Fix**: Add Solid plugin to build:
|
||||
|
||||
```typescript
|
||||
import solidPlugin from "@opentui/solid/bun-plugin"
|
||||
|
||||
await Bun.build({
|
||||
// ...
|
||||
plugins: [solidPlugin],
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,427 @@
|
||||
# Solid Gotchas
|
||||
|
||||
## Critical
|
||||
|
||||
### Never use `process.exit()` directly
|
||||
|
||||
**This is the most common mistake.** Using `process.exit()` leaves the terminal in a broken state (cursor hidden, raw mode, alternate screen).
|
||||
|
||||
```tsx
|
||||
// WRONG - Terminal left in broken state
|
||||
process.exit(0)
|
||||
|
||||
// CORRECT - Use renderer.destroy()
|
||||
import { useRenderer } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
const handleExit = () => {
|
||||
renderer.destroy() // Cleans up and exits properly
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`renderer.destroy()` restores the terminal (exits alternate screen, restores cursor, etc.) before exiting.
|
||||
|
||||
## Configuration Issues
|
||||
|
||||
### Missing bunfig.toml
|
||||
|
||||
**Symptom**: JSX syntax errors, components not rendering
|
||||
|
||||
```
|
||||
SyntaxError: Unexpected token '<'
|
||||
```
|
||||
|
||||
**Fix**: Create `bunfig.toml` in project root:
|
||||
|
||||
```toml
|
||||
preload = ["@opentui/solid/preload"]
|
||||
```
|
||||
|
||||
### Wrong JSX Settings
|
||||
|
||||
**Symptom**: JSX compiles to React, errors about React not found
|
||||
|
||||
**Fix**: Ensure tsconfig.json has:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "preserve",
|
||||
"jsxImportSource": "@opentui/solid"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Build Without Plugin
|
||||
|
||||
**Symptom**: Built bundle has raw JSX
|
||||
|
||||
**Fix**: Add Solid plugin to build:
|
||||
|
||||
```typescript
|
||||
import solidPlugin from "@opentui/solid/bun-plugin"
|
||||
|
||||
await Bun.build({
|
||||
// ...
|
||||
plugins: [solidPlugin],
|
||||
})
|
||||
```
|
||||
|
||||
## Reactivity Issues
|
||||
|
||||
### Accessing Signals Without Calling
|
||||
|
||||
**Symptom**: Value never updates, shows `[Function]`
|
||||
|
||||
```tsx
|
||||
// WRONG - Missing ()
|
||||
const [count, setCount] = createSignal(0)
|
||||
<text>Count: {count}</text> // Shows [Function]
|
||||
|
||||
// CORRECT
|
||||
<text>Count: {count()}</text>
|
||||
```
|
||||
|
||||
### Breaking Reactivity with Destructuring
|
||||
|
||||
**Symptom**: Props stop being reactive
|
||||
|
||||
```tsx
|
||||
// WRONG - Breaks reactivity
|
||||
function Component(props: { value: number }) {
|
||||
const { value } = props // Destructured once, never updates!
|
||||
return <text>{value}</text>
|
||||
}
|
||||
|
||||
// CORRECT - Keep props reactive
|
||||
function Component(props: { value: number }) {
|
||||
return <text>{props.value}</text>
|
||||
}
|
||||
|
||||
// OR use splitProps
|
||||
function Component(props: { value: number; other: string }) {
|
||||
const [local, rest] = splitProps(props, ["value"])
|
||||
return <text>{local.value}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Effects Not Running
|
||||
|
||||
**Symptom**: createEffect doesn't trigger
|
||||
|
||||
```tsx
|
||||
// WRONG - Signal not accessed in effect
|
||||
const [count, setCount] = createSignal(0)
|
||||
|
||||
createEffect(() => {
|
||||
console.log("Count changed") // Never runs after initial!
|
||||
})
|
||||
|
||||
// CORRECT - Access the signal
|
||||
createEffect(() => {
|
||||
console.log("Count:", count()) // Runs when count changes
|
||||
})
|
||||
```
|
||||
|
||||
## HTML Entity Decoding
|
||||
|
||||
Solid's reconciler automatically decodes HTML entities in JSX text content. This means `<`, `>`, `&`, etc. render as their literal characters:
|
||||
|
||||
```tsx
|
||||
// These render correctly in Solid
|
||||
<text>Use <box> for containers</text> // Displays: Use <box> for containers
|
||||
<text>A & B</text> // Displays: A & B
|
||||
```
|
||||
|
||||
This applies to text nodes, the `content` prop, and the `text` prop.
|
||||
|
||||
## Component Naming
|
||||
|
||||
### Underscore vs Hyphen
|
||||
|
||||
Solid uses underscores for multi-word component names:
|
||||
|
||||
```tsx
|
||||
// WRONG - React-style naming
|
||||
<tab-select /> // Error!
|
||||
<ascii-font /> // Error!
|
||||
<line-number /> // Error!
|
||||
|
||||
// CORRECT - Solid naming
|
||||
<tab_select />
|
||||
<ascii_font />
|
||||
<line_number />
|
||||
```
|
||||
|
||||
**Component mapping:**
|
||||
| Concept | React | Solid |
|
||||
|---------|-------|-------|
|
||||
| Tab Select | `<tab-select>` | `<tab_select>` |
|
||||
| ASCII Font | `<ascii-font>` | `<ascii_font>` |
|
||||
| Line Number | `<line-number>` | `<line_number>` |
|
||||
|
||||
## Focus Issues
|
||||
|
||||
### Focus Not Working
|
||||
|
||||
Components need explicit focus:
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<input placeholder="Type here..." />
|
||||
|
||||
// CORRECT
|
||||
<input placeholder="Type here..." focused />
|
||||
```
|
||||
|
||||
### Select Not Responding
|
||||
|
||||
```tsx
|
||||
// WRONG
|
||||
<select options={["a", "b"]} />
|
||||
|
||||
// CORRECT
|
||||
<select
|
||||
options={[
|
||||
{ name: "A", description: "Option A", value: "a" },
|
||||
{ name: "B", description: "Option B", value: "b" },
|
||||
]}
|
||||
onSelect={(index, option) => {
|
||||
// Called when Enter is pressed
|
||||
console.log("Selected:", option.name)
|
||||
}}
|
||||
focused
|
||||
/>
|
||||
```
|
||||
|
||||
### Select Events Confusion
|
||||
|
||||
Remember: `onSelect` fires on Enter (selection confirmed), `onChange` fires on navigation:
|
||||
|
||||
```tsx
|
||||
// WRONG - expecting onChange to fire on Enter
|
||||
<select
|
||||
options={options()}
|
||||
onChange={(i, opt) => submitForm(opt)} // This fires on arrow keys!
|
||||
/>
|
||||
|
||||
// CORRECT
|
||||
<select
|
||||
options={options()}
|
||||
onSelect={(i, opt) => submitForm(opt)} // Enter pressed - submit
|
||||
onChange={(i, opt) => showPreview(opt)} // Arrow keys - preview
|
||||
/>
|
||||
```
|
||||
|
||||
## Control Flow Issues
|
||||
|
||||
### For vs Index
|
||||
|
||||
Use `For` for arrays of objects, `Index` for primitives:
|
||||
|
||||
```tsx
|
||||
// For objects - item is reactive
|
||||
<For each={objects()}>
|
||||
{(obj) => <text>{obj.name}</text>}
|
||||
</For>
|
||||
|
||||
// For primitives - use Index, item() is reactive
|
||||
<Index each={strings()}>
|
||||
{(str, index) => <text>{index}: {str()}</text>}
|
||||
</Index>
|
||||
```
|
||||
|
||||
### Missing Fallback
|
||||
|
||||
Show requires fallback for proper rendering:
|
||||
|
||||
```tsx
|
||||
// May cause issues
|
||||
<Show when={data()}>
|
||||
<Component />
|
||||
</Show>
|
||||
|
||||
// Better - explicit fallback
|
||||
<Show when={data()} fallback={<text>Loading...</text>}>
|
||||
<Component />
|
||||
</Show>
|
||||
```
|
||||
|
||||
## Cleanup Issues
|
||||
|
||||
### Forgetting onCleanup
|
||||
|
||||
**Symptom**: Memory leaks, multiple intervals running
|
||||
|
||||
```tsx
|
||||
// WRONG - Interval never cleared
|
||||
function Timer() {
|
||||
const [time, setTime] = createSignal(0)
|
||||
|
||||
setInterval(() => setTime(t => t + 1), 1000)
|
||||
|
||||
return <text>{time()}</text>
|
||||
}
|
||||
|
||||
// CORRECT
|
||||
function Timer() {
|
||||
const [time, setTime] = createSignal(0)
|
||||
|
||||
const interval = setInterval(() => setTime(t => t + 1), 1000)
|
||||
onCleanup(() => clearInterval(interval))
|
||||
|
||||
return <text>{time()}</text>
|
||||
}
|
||||
```
|
||||
|
||||
### Effect Cleanup
|
||||
|
||||
```tsx
|
||||
createEffect(() => {
|
||||
const subscription = subscribe(data())
|
||||
|
||||
// WRONG - No cleanup
|
||||
// subscription stays active
|
||||
|
||||
// CORRECT
|
||||
onCleanup(() => subscription.unsubscribe())
|
||||
})
|
||||
```
|
||||
|
||||
## Store Issues
|
||||
|
||||
### Mutating Store Directly
|
||||
|
||||
**Symptom**: Changes don't trigger updates
|
||||
|
||||
```tsx
|
||||
const [state, setState] = createStore({ items: [] })
|
||||
|
||||
// WRONG - Direct mutation
|
||||
state.items.push(newItem) // Won't trigger updates!
|
||||
|
||||
// CORRECT - Use setState
|
||||
setState("items", items => [...items, newItem])
|
||||
```
|
||||
|
||||
### Nested Updates
|
||||
|
||||
```tsx
|
||||
const [state, setState] = createStore({
|
||||
user: { profile: { name: "John" } }
|
||||
})
|
||||
|
||||
// WRONG
|
||||
state.user.profile.name = "Jane"
|
||||
|
||||
// CORRECT
|
||||
setState("user", "profile", "name", "Jane")
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
### Console Not Visible
|
||||
|
||||
OpenTUI captures console output:
|
||||
|
||||
```tsx
|
||||
import { useRenderer } from "@opentui/solid"
|
||||
import { onMount } from "solid-js"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
onMount(() => {
|
||||
renderer.console.show()
|
||||
console.log("Now visible!")
|
||||
})
|
||||
|
||||
return <box>{/* ... */}</box>
|
||||
}
|
||||
```
|
||||
|
||||
### Tracking Reactivity
|
||||
|
||||
Use `createEffect` to debug:
|
||||
|
||||
```tsx
|
||||
createEffect(() => {
|
||||
console.log("State:", {
|
||||
count: count(),
|
||||
items: items(),
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Runtime Issues
|
||||
|
||||
### Use Bun
|
||||
|
||||
```bash
|
||||
# WRONG
|
||||
node src/index.tsx
|
||||
npm run start
|
||||
|
||||
# CORRECT
|
||||
bun run src/index.tsx
|
||||
bun run start
|
||||
```
|
||||
|
||||
### Async render()
|
||||
|
||||
The render function is async when creating a renderer:
|
||||
|
||||
```tsx
|
||||
// This is fine - Bun supports top-level await
|
||||
render(() => <App />)
|
||||
|
||||
// If you need the renderer
|
||||
import { createCliRenderer } from "@opentui/core"
|
||||
import { render } from "@opentui/solid"
|
||||
|
||||
const renderer = await createCliRenderer()
|
||||
render(() => <App />, renderer)
|
||||
```
|
||||
|
||||
## Common Error Messages
|
||||
|
||||
### "Cannot read properties of undefined"
|
||||
|
||||
Usually a missing reactive access:
|
||||
|
||||
```tsx
|
||||
// Check if signal is being called
|
||||
<text>{count()}</text> // Note the ()
|
||||
|
||||
// Check if props are being accessed correctly
|
||||
<text>{props.value}</text> // Not destructured
|
||||
```
|
||||
|
||||
### "JSX element has no corresponding closing tag"
|
||||
|
||||
Check component naming:
|
||||
|
||||
```tsx
|
||||
// Wrong
|
||||
<tab-select></tab-select>
|
||||
|
||||
// Correct
|
||||
<tab_select></tab_select>
|
||||
```
|
||||
|
||||
### "store is not a function"
|
||||
|
||||
Stores aren't called like signals:
|
||||
|
||||
```tsx
|
||||
const [store, setStore] = createStore({ count: 0 })
|
||||
|
||||
// WRONG
|
||||
<text>{store().count}</text>
|
||||
|
||||
// CORRECT
|
||||
<text>{store.count}</text>
|
||||
```
|
||||
@@ -0,0 +1,560 @@
|
||||
# Solid Patterns
|
||||
|
||||
## Reactive State
|
||||
|
||||
### Signals
|
||||
|
||||
Basic reactive state with signals:
|
||||
|
||||
```tsx
|
||||
import { createSignal } from "solid-js"
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = createSignal(0)
|
||||
|
||||
return (
|
||||
<box flexDirection="row" gap={2}>
|
||||
<text>Count: {count()}</text>
|
||||
<box border onMouseDown={() => setCount(c => c - 1)}>
|
||||
<text>-</text>
|
||||
</box>
|
||||
<box border onMouseDown={() => setCount(c => c + 1)}>
|
||||
<text>+</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Derived State
|
||||
|
||||
Compute values from signals:
|
||||
|
||||
```tsx
|
||||
import { createSignal, createMemo } from "solid-js"
|
||||
|
||||
function PriceCalculator() {
|
||||
const [quantity, setQuantity] = createSignal(1)
|
||||
const [price, setPrice] = createSignal(9.99)
|
||||
|
||||
// Derived value - only recalculates when dependencies change
|
||||
const total = createMemo(() => quantity() * price())
|
||||
const formatted = createMemo(() => `$${total().toFixed(2)}`)
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text>Quantity: {quantity()}</text>
|
||||
<text>Price: ${price()}</text>
|
||||
<text>Total: {formatted()}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Effects
|
||||
|
||||
React to state changes:
|
||||
|
||||
```tsx
|
||||
import { createSignal, createEffect, onCleanup } from "solid-js"
|
||||
|
||||
function AutoSave() {
|
||||
const [content, setContent] = createSignal("")
|
||||
|
||||
createEffect(() => {
|
||||
const text = content()
|
||||
|
||||
// Debounced save
|
||||
const timeout = setTimeout(() => {
|
||||
saveToFile(text)
|
||||
}, 1000)
|
||||
|
||||
// Cleanup on next run or disposal
|
||||
onCleanup(() => clearTimeout(timeout))
|
||||
})
|
||||
|
||||
return (
|
||||
<textarea
|
||||
value={content()}
|
||||
onInput={setContent}
|
||||
placeholder="Auto-saves after 1 second..."
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Stores
|
||||
|
||||
### createStore for Complex State
|
||||
|
||||
```tsx
|
||||
import { createStore } from "solid-js/store"
|
||||
|
||||
interface AppState {
|
||||
user: { name: string; email: string } | null
|
||||
items: Array<{ id: number; name: string; done: boolean }>
|
||||
settings: { theme: "dark" | "light" }
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [state, setState] = createStore<AppState>({
|
||||
user: null,
|
||||
items: [],
|
||||
settings: { theme: "dark" },
|
||||
})
|
||||
|
||||
const addItem = (name: string) => {
|
||||
setState("items", items => [
|
||||
...items,
|
||||
{ id: Date.now(), name, done: false }
|
||||
])
|
||||
}
|
||||
|
||||
const toggleItem = (id: number) => {
|
||||
setState("items", item => item.id === id, "done", done => !done)
|
||||
}
|
||||
|
||||
const setTheme = (theme: "dark" | "light") => {
|
||||
setState("settings", "theme", theme)
|
||||
}
|
||||
|
||||
return (
|
||||
<box backgroundColor={state.settings.theme === "dark" ? "#1a1a2e" : "#f0f0f0"}>
|
||||
<For each={state.items}>
|
||||
{(item) => (
|
||||
<text
|
||||
fg={item.done ? "#888" : "#fff"}
|
||||
onMouseDown={() => toggleItem(item.id)}
|
||||
>
|
||||
{item.done ? "[x]" : "[ ]"} {item.name}
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Store with Context
|
||||
|
||||
Share state across components:
|
||||
|
||||
```tsx
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createContext, useContext, ParentComponent } from "solid-js"
|
||||
|
||||
interface Store {
|
||||
count: number
|
||||
items: string[]
|
||||
}
|
||||
|
||||
type StoreContextValue = [
|
||||
Store,
|
||||
{
|
||||
increment: () => void
|
||||
addItem: (item: string) => void
|
||||
}
|
||||
]
|
||||
|
||||
const StoreContext = createContext<StoreContextValue>()
|
||||
|
||||
const StoreProvider: ParentComponent = (props) => {
|
||||
const [state, setState] = createStore<Store>({
|
||||
count: 0,
|
||||
items: [],
|
||||
})
|
||||
|
||||
const actions = {
|
||||
increment: () => setState("count", c => c + 1),
|
||||
addItem: (item: string) => setState("items", i => [...i, item]),
|
||||
}
|
||||
|
||||
return (
|
||||
<StoreContext.Provider value={[state, actions]}>
|
||||
{props.children}
|
||||
</StoreContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function useStore() {
|
||||
const context = useContext(StoreContext)
|
||||
if (!context) throw new Error("useStore must be used within StoreProvider")
|
||||
return context
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Counter() {
|
||||
const [state, { increment }] = useStore()
|
||||
return (
|
||||
<box onMouseDown={increment}>
|
||||
<text>Count: {state.count}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Control Flow
|
||||
|
||||
### Conditional Rendering with Show
|
||||
|
||||
```tsx
|
||||
import { Show, createSignal } from "solid-js"
|
||||
|
||||
function ToggleableContent() {
|
||||
const [visible, setVisible] = createSignal(false)
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<box border onMouseDown={() => setVisible(v => !v)}>
|
||||
<text>Toggle</text>
|
||||
</box>
|
||||
|
||||
<Show
|
||||
when={visible()}
|
||||
fallback={<text fg="#888">Content is hidden</text>}
|
||||
>
|
||||
<text fg="#0f0">Content is visible!</text>
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Lists with For
|
||||
|
||||
```tsx
|
||||
import { For, createSignal } from "solid-js"
|
||||
|
||||
function TodoList() {
|
||||
const [todos, setTodos] = createSignal([
|
||||
{ id: 1, text: "Learn Solid", done: false },
|
||||
{ id: 2, text: "Build TUI", done: false },
|
||||
])
|
||||
|
||||
const toggle = (id: number) => {
|
||||
setTodos(todos =>
|
||||
todos.map(t =>
|
||||
t.id === id ? { ...t, done: !t.done } : t
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<For each={todos()}>
|
||||
{(todo) => (
|
||||
<box onMouseDown={() => toggle(todo.id)}>
|
||||
<text fg={todo.done ? "#888" : "#fff"}>
|
||||
{todo.done ? "[x]" : "[ ]"} {todo.text}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Index for Primitive Arrays
|
||||
|
||||
Use `Index` when array items are primitives:
|
||||
|
||||
```tsx
|
||||
import { Index, createSignal } from "solid-js"
|
||||
|
||||
function StringList() {
|
||||
const [items, setItems] = createSignal(["apple", "banana", "cherry"])
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<Index each={items()}>
|
||||
{(item, index) => (
|
||||
<text>{index}: {item()}</text>
|
||||
)}
|
||||
</Index>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Switch/Match for Multiple Conditions
|
||||
|
||||
```tsx
|
||||
import { Switch, Match, createSignal } from "solid-js"
|
||||
|
||||
type Status = "idle" | "loading" | "success" | "error"
|
||||
|
||||
function StatusDisplay() {
|
||||
const [status, setStatus] = createSignal<Status>("idle")
|
||||
|
||||
return (
|
||||
<Switch>
|
||||
<Match when={status() === "idle"}>
|
||||
<text>Ready</text>
|
||||
</Match>
|
||||
<Match when={status() === "loading"}>
|
||||
<text fg="#ff0">Loading...</text>
|
||||
</Match>
|
||||
<Match when={status() === "success"}>
|
||||
<text fg="#0f0">Success!</text>
|
||||
</Match>
|
||||
<Match when={status() === "error"}>
|
||||
<text fg="#f00">Error occurred</text>
|
||||
</Match>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Focus Management
|
||||
|
||||
### Focus State
|
||||
|
||||
```tsx
|
||||
import { createSignal } from "solid-js"
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
|
||||
function FocusableForm() {
|
||||
const [focusIndex, setFocusIndex] = createSignal(0)
|
||||
const fields = ["name", "email", "message"]
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "tab") {
|
||||
setFocusIndex(i => (i + 1) % fields.length)
|
||||
}
|
||||
if (key.shift && key.name === "tab") {
|
||||
setFocusIndex(i => (i - 1 + fields.length) % fields.length)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<Index each={fields}>
|
||||
{(field, i) => (
|
||||
<input
|
||||
placeholder={`Enter ${field()}...`}
|
||||
focused={i === focusIndex()}
|
||||
/>
|
||||
)}
|
||||
</Index>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Keyboard Navigation
|
||||
|
||||
### Global Shortcuts
|
||||
|
||||
```tsx
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
|
||||
function App() {
|
||||
const renderer = useRenderer()
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") {
|
||||
renderer.destroy() // Never use process.exit() directly!
|
||||
}
|
||||
|
||||
if (key.ctrl && key.name === "s") {
|
||||
save()
|
||||
}
|
||||
|
||||
// Vim-style
|
||||
if (key.name === "j") moveDown()
|
||||
if (key.name === "k") moveUp()
|
||||
})
|
||||
|
||||
return <box>{/* ... */}</box>
|
||||
}
|
||||
```
|
||||
|
||||
## Responsive Design
|
||||
|
||||
### Terminal-size Responsive
|
||||
|
||||
```tsx
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
|
||||
function ResponsiveLayout() {
|
||||
const dims = useTerminalDimensions()
|
||||
|
||||
return (
|
||||
<box flexDirection={dims().width > 80 ? "row" : "column"}>
|
||||
<box flexGrow={1}>
|
||||
<text>Panel 1</text>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
<text>Panel 2</text>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Async Data
|
||||
|
||||
### Resources
|
||||
|
||||
```tsx
|
||||
import { createResource, Suspense } from "solid-js"
|
||||
|
||||
async function fetchData() {
|
||||
const response = await fetch("https://api.example.com/data")
|
||||
return response.json()
|
||||
}
|
||||
|
||||
function DataDisplay() {
|
||||
const [data] = createResource(fetchData)
|
||||
|
||||
return (
|
||||
<Suspense fallback={<text>Loading...</text>}>
|
||||
<Show when={data()}>
|
||||
{(items) => (
|
||||
<For each={items()}>
|
||||
{(item) => <text>{item.name}</text>}
|
||||
</For>
|
||||
)}
|
||||
</Show>
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```tsx
|
||||
import { createResource, Show, ErrorBoundary } from "solid-js"
|
||||
|
||||
function SafeDataDisplay() {
|
||||
const [data] = createResource(fetchData)
|
||||
|
||||
return (
|
||||
<ErrorBoundary fallback={(err) => <text fg="red">Error: {err.message}</text>}>
|
||||
<Show
|
||||
when={!data.loading}
|
||||
fallback={<text>Loading...</text>}
|
||||
>
|
||||
<Show
|
||||
when={!data.error}
|
||||
fallback={<text fg="red">Failed to load</text>}
|
||||
>
|
||||
<For each={data()}>
|
||||
{(item) => <text>{item.name}</text>}
|
||||
</For>
|
||||
</Show>
|
||||
</Show>
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Component Composition
|
||||
|
||||
### Props and Children
|
||||
|
||||
```tsx
|
||||
import { ParentComponent, JSX } from "solid-js"
|
||||
|
||||
interface PanelProps {
|
||||
title: string
|
||||
children: JSX.Element
|
||||
}
|
||||
|
||||
const Panel: ParentComponent<{ title: string }> = (props) => {
|
||||
return (
|
||||
<box border padding={1} flexDirection="column">
|
||||
<text fg="#0ff">{props.title}</text>
|
||||
<box marginTop={1}>
|
||||
{props.children}
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
<Panel title="Settings">
|
||||
<text>Panel content here</text>
|
||||
</Panel>
|
||||
```
|
||||
|
||||
### Spread Props
|
||||
|
||||
```tsx
|
||||
import { splitProps } from "solid-js"
|
||||
|
||||
interface ButtonProps {
|
||||
label: string
|
||||
onClick: () => void
|
||||
// ...rest goes to box
|
||||
}
|
||||
|
||||
function Button(props: ButtonProps) {
|
||||
const [local, rest] = splitProps(props, ["label", "onClick"])
|
||||
|
||||
return (
|
||||
<box border onMouseDown={local.onClick} {...rest}>
|
||||
<text>{local.label}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Animation
|
||||
|
||||
### With Timeline
|
||||
|
||||
```tsx
|
||||
import { createSignal, onMount } from "solid-js"
|
||||
import { useTimeline } from "@opentui/solid"
|
||||
|
||||
function AnimatedProgress() {
|
||||
const [width, setWidth] = createSignal(0)
|
||||
|
||||
const timeline = useTimeline({
|
||||
duration: 2000,
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
timeline.add(
|
||||
{ value: 0 },
|
||||
{
|
||||
value: 50,
|
||||
duration: 2000,
|
||||
ease: "easeOutQuad",
|
||||
onUpdate: (anim) => {
|
||||
setWidth(Math.round(anim.targets[0].value))
|
||||
},
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text>Progress: {width()}%</text>
|
||||
<box width={50} height={1} backgroundColor="#333">
|
||||
<box width={width()} height={1} backgroundColor="#0f0" />
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Interval-based
|
||||
|
||||
```tsx
|
||||
import { createSignal, onCleanup } from "solid-js"
|
||||
|
||||
function Clock() {
|
||||
const [time, setTime] = createSignal(new Date())
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setTime(new Date())
|
||||
}, 1000)
|
||||
|
||||
onCleanup(() => clearInterval(interval))
|
||||
|
||||
return <text>{time().toLocaleTimeString()}</text>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,614 @@
|
||||
# Testing OpenTUI Applications
|
||||
|
||||
How to test terminal user interfaces built with OpenTUI.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTUI provides:
|
||||
- **Test Renderer**: Headless renderer for testing
|
||||
- **Snapshot Testing**: Verify visual output
|
||||
- **Interaction Testing**: Simulate user input
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this reference when you need snapshot tests, interaction testing, or renderer-based regression checks.
|
||||
|
||||
## Test Setup
|
||||
|
||||
### Bun Test Runner
|
||||
|
||||
OpenTUI uses Bun's built-in test runner:
|
||||
|
||||
```typescript
|
||||
import { test, expect, beforeEach, afterEach } from "bun:test"
|
||||
```
|
||||
|
||||
### Test Renderer
|
||||
|
||||
Create a test renderer for headless testing:
|
||||
|
||||
```typescript
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
|
||||
const testSetup = await createTestRenderer({
|
||||
width: 80, // Terminal width
|
||||
height: 24, // Terminal height
|
||||
})
|
||||
```
|
||||
|
||||
## Core Testing
|
||||
|
||||
### Basic Test
|
||||
|
||||
```typescript
|
||||
import { test, expect } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { TextRenderable } from "@opentui/core"
|
||||
|
||||
test("renders text", async () => {
|
||||
const testSetup = await createTestRenderer({
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
const text = new TextRenderable(testSetup.renderer, {
|
||||
id: "greeting",
|
||||
content: "Hello, World!",
|
||||
})
|
||||
|
||||
testSetup.renderer.root.add(text)
|
||||
await testSetup.renderOnce()
|
||||
|
||||
expect(testSetup.captureCharFrame()).toContain("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
||||
### Snapshot Testing
|
||||
|
||||
```typescript
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { BoxRenderable, TextRenderable } from "@opentui/core"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof createTestRenderer>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("component matches snapshot", async () => {
|
||||
testSetup = await createTestRenderer({
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
const box = new BoxRenderable(testSetup.renderer, {
|
||||
id: "box",
|
||||
border: true,
|
||||
width: 20,
|
||||
height: 5,
|
||||
})
|
||||
box.add(new TextRenderable(testSetup.renderer, {
|
||||
content: "Content",
|
||||
}))
|
||||
|
||||
testSetup.renderer.root.add(box)
|
||||
await testSetup.renderOnce()
|
||||
|
||||
expect(testSetup.captureCharFrame()).toMatchSnapshot()
|
||||
})
|
||||
```
|
||||
|
||||
## React Testing
|
||||
|
||||
### Test Utilities
|
||||
|
||||
React provides a built-in `testRender` utility via the `@opentui/react/test-utils` subpath export:
|
||||
|
||||
```tsx
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
```
|
||||
|
||||
This utility:
|
||||
- Creates a headless test renderer
|
||||
- Sets up the React Act environment automatically
|
||||
- Handles proper unmounting on destroy
|
||||
- Returns the standard test setup object
|
||||
|
||||
### Basic Component Test
|
||||
|
||||
```tsx
|
||||
import { test, expect } from "bun:test"
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
function Greeting({ name }: { name: string }) {
|
||||
return <text>Hello, {name}!</text>
|
||||
}
|
||||
|
||||
test("Greeting renders name", async () => {
|
||||
const testSetup = await testRender(
|
||||
<Greeting name="World" />,
|
||||
{ width: 80, height: 24 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
expect(frame).toContain("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
||||
### Snapshot Testing
|
||||
|
||||
```tsx
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("component matches snapshot", async () => {
|
||||
testSetup = await testRender(
|
||||
<box style={{ width: 20, height: 5, border: true }}>
|
||||
<text>Content</text>
|
||||
</box>,
|
||||
{ width: 25, height: 8 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
expect(frame).toMatchSnapshot()
|
||||
})
|
||||
```
|
||||
|
||||
### State Testing
|
||||
|
||||
```tsx
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { useState } from "react"
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0)
|
||||
return (
|
||||
<box>
|
||||
<text>Count: {count}</text>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
test("Counter shows initial value", async () => {
|
||||
testSetup = await testRender(
|
||||
<Counter />,
|
||||
{ width: 20, height: 5 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
expect(frame).toContain("Count: 0")
|
||||
})
|
||||
```
|
||||
|
||||
### Test Setup/Teardown Pattern
|
||||
|
||||
For multiple tests, use beforeEach/afterEach to manage the renderer lifecycle:
|
||||
|
||||
```tsx
|
||||
import { describe, test, expect, beforeEach, afterEach } from "bun:test"
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
describe("MyComponent", () => {
|
||||
beforeEach(async () => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("renders correctly", async () => {
|
||||
testSetup = await testRender(<MyComponent />, {
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
expect(frame).toMatchSnapshot()
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### Test Setup Return Object
|
||||
|
||||
The `testRender` function returns a test setup object with these properties:
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| `renderer` | `Renderer` | The headless renderer instance |
|
||||
| `renderOnce` | `() => Promise<void>` | Triggers a single render cycle |
|
||||
| `captureCharFrame` | `() => string` | Captures current output as text |
|
||||
| `resize` | `(width, height) => void` | Resize the virtual terminal |
|
||||
|
||||
## Solid Testing
|
||||
|
||||
### Test Utilities
|
||||
|
||||
Solid exports `testRender` directly from the main package:
|
||||
|
||||
```tsx
|
||||
import { testRender } from "@opentui/solid"
|
||||
```
|
||||
|
||||
Note: Unlike React, Solid's `testRender` takes a **function component** (not a JSX element).
|
||||
|
||||
### Basic Component Test
|
||||
|
||||
```tsx
|
||||
import { test, expect } from "bun:test"
|
||||
import { testRender } from "@opentui/solid"
|
||||
|
||||
function Greeting(props: { name: string }) {
|
||||
return <text>Hello, {props.name}!</text>
|
||||
}
|
||||
|
||||
test("Greeting renders name", async () => {
|
||||
const testSetup = await testRender(
|
||||
() => <Greeting name="World" />,
|
||||
{ width: 80, height: 24 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
expect(frame).toContain("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
||||
### Snapshot Testing
|
||||
|
||||
```tsx
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { testRender } from "@opentui/solid"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("component matches snapshot", async () => {
|
||||
testSetup = await testRender(
|
||||
() => (
|
||||
<box style={{ width: 20, height: 5, border: true }}>
|
||||
<text>Content</text>
|
||||
</box>
|
||||
),
|
||||
{ width: 25, height: 8 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
expect(frame).toMatchSnapshot()
|
||||
})
|
||||
```
|
||||
|
||||
## Snapshot Format
|
||||
|
||||
Snapshots capture the rendered terminal output as text:
|
||||
|
||||
```
|
||||
┌──────────────────┐
|
||||
│ Hello, World! │
|
||||
│ │
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
### Updating Snapshots
|
||||
|
||||
```bash
|
||||
bun test --update-snapshots
|
||||
```
|
||||
|
||||
## Interaction Testing
|
||||
|
||||
### Simulating Key Presses
|
||||
|
||||
```typescript
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof createTestRenderer>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("responds to keyboard", async () => {
|
||||
testSetup = await createTestRenderer({
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
// Create component that responds to keys
|
||||
// ...
|
||||
|
||||
// Simulate keypress
|
||||
testSetup.renderer.keyInput.emit("keypress", {
|
||||
name: "enter",
|
||||
sequence: "\r",
|
||||
ctrl: false,
|
||||
shift: false,
|
||||
meta: false,
|
||||
option: false,
|
||||
eventType: "press",
|
||||
repeated: false,
|
||||
})
|
||||
|
||||
// Render after the keypress
|
||||
await testSetup.renderOnce()
|
||||
|
||||
expect(testSetup.captureCharFrame()).toContain("Selected")
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Focus
|
||||
|
||||
```typescript
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { InputRenderable } from "@opentui/core"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof createTestRenderer>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("input receives focus", async () => {
|
||||
testSetup = await createTestRenderer({
|
||||
width: 40,
|
||||
height: 10,
|
||||
})
|
||||
|
||||
const input = new InputRenderable(testSetup.renderer, {
|
||||
id: "test-input",
|
||||
placeholder: "Type here",
|
||||
})
|
||||
testSetup.renderer.root.add(input)
|
||||
|
||||
input.focus()
|
||||
|
||||
expect(input.isFocused()).toBe(true)
|
||||
})
|
||||
```
|
||||
|
||||
## Test Organization
|
||||
|
||||
### File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Button.tsx
|
||||
│ └── Button.test.tsx
|
||||
├── hooks/
|
||||
│ ├── useCounter.ts
|
||||
│ └── useCounter.test.ts
|
||||
└── test-utils.tsx
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
bun test
|
||||
|
||||
# Run specific test file
|
||||
bun test src/components/Button.test.tsx
|
||||
|
||||
# Run with filter
|
||||
bun test --filter "Button"
|
||||
|
||||
# Watch mode
|
||||
bun test --watch
|
||||
```
|
||||
|
||||
## Patterns
|
||||
|
||||
### Testing Conditional Rendering (React)
|
||||
|
||||
```tsx
|
||||
import { test, expect, afterEach } from "bun:test"
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("shows loading state", async () => {
|
||||
testSetup = await testRender(
|
||||
<DataLoader loading={true} />,
|
||||
{ width: 40, height: 10 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
expect(testSetup.captureCharFrame()).toContain("Loading...")
|
||||
})
|
||||
|
||||
test("shows data when loaded", async () => {
|
||||
testSetup = await testRender(
|
||||
<DataLoader loading={false} data={["Item 1", "Item 2"]} />,
|
||||
{ width: 40, height: 10 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
expect(frame).toContain("Item 1")
|
||||
expect(frame).toContain("Item 2")
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Lists
|
||||
|
||||
```tsx
|
||||
test("renders all items", async () => {
|
||||
const items = ["Apple", "Banana", "Cherry"]
|
||||
|
||||
testSetup = await testRender(
|
||||
<ItemList items={items} />,
|
||||
{ width: 40, height: 10 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
items.forEach(item => {
|
||||
expect(frame).toContain(item)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Layouts
|
||||
|
||||
```tsx
|
||||
test("matches layout snapshot", async () => {
|
||||
testSetup = await testRender(
|
||||
<AppLayout />,
|
||||
{ width: 120, height: 40 } // Larger viewport
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
expect(testSetup.captureCharFrame()).toMatchSnapshot()
|
||||
})
|
||||
```
|
||||
|
||||
## Debugging Tests
|
||||
|
||||
### Print Frame Output
|
||||
|
||||
```tsx
|
||||
import { testRender } from "@opentui/react/test-utils"
|
||||
|
||||
test("debug output", async () => {
|
||||
const testSetup = await testRender(
|
||||
<MyComponent />,
|
||||
{ width: 40, height: 10 }
|
||||
)
|
||||
|
||||
await testSetup.renderOnce()
|
||||
const frame = testSetup.captureCharFrame()
|
||||
|
||||
// Print to see what's rendered
|
||||
console.log(frame)
|
||||
|
||||
expect(frame).toContain("expected")
|
||||
})
|
||||
```
|
||||
|
||||
### Verbose Mode
|
||||
|
||||
```bash
|
||||
bun test --verbose
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
### Async Rendering
|
||||
|
||||
Always call `renderOnce()` after setting up your component to ensure rendering is complete:
|
||||
|
||||
```typescript
|
||||
const testSetup = await testRender(<MyComponent />, { width: 40, height: 10 })
|
||||
await testSetup.renderOnce() // Required before capturing frame
|
||||
const frame = testSetup.captureCharFrame()
|
||||
```
|
||||
|
||||
### Test Isolation and Cleanup
|
||||
|
||||
Always destroy the renderer after each test to avoid resource leaks:
|
||||
|
||||
```typescript
|
||||
import { afterEach } from "bun:test"
|
||||
|
||||
let testSetup: Awaited<ReturnType<typeof testRender>>
|
||||
|
||||
afterEach(() => {
|
||||
if (testSetup) {
|
||||
testSetup.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("test 1", async () => {
|
||||
testSetup = await testRender(<Component1 />, { width: 40, height: 10 })
|
||||
// ...
|
||||
})
|
||||
|
||||
test("test 2", async () => {
|
||||
testSetup = await testRender(<Component2 />, { width: 40, height: 10 })
|
||||
// ...
|
||||
})
|
||||
```
|
||||
|
||||
### Snapshot Dimensions
|
||||
|
||||
Be consistent with test dimensions for stable snapshots:
|
||||
|
||||
```typescript
|
||||
const testSetup = await createTestRenderer({
|
||||
width: 80, // Standard width
|
||||
height: 24, // Standard height
|
||||
})
|
||||
```
|
||||
|
||||
### Running from Package Directory
|
||||
|
||||
Run tests from the package directory:
|
||||
|
||||
```bash
|
||||
cd packages/core
|
||||
bun test
|
||||
|
||||
# Not from repo root for package-specific tests
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [Core API](../core/api.md) - `createTestRenderer` and renderable classes
|
||||
- [React Configuration](../react/configuration.md) - React test setup
|
||||
- [Solid Configuration](../solid/configuration.md) - Solid test setup
|
||||
- [Keyboard](../keyboard/REFERENCE.md) - Simulating key events in tests
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.cline/skills/publish-cli
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
fix: use correct base URL for Vertex AI global endpoint with Claude models
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../.clinerules/workflows/hotfix-release.md
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.clinerules/workflows/release.md
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# Only run in Claude Code remote environments
|
||||
if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cd "$CLAUDE_PROJECT_DIR"
|
||||
|
||||
echo "=== Claude Code for Web Setup ==="
|
||||
echo ""
|
||||
|
||||
# Install latest gh CLI tool
|
||||
echo "Installing GitHub CLI..."
|
||||
GH_VERSION=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/^v//')
|
||||
curl -sL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz" -o /tmp/gh.tar.gz
|
||||
tar -xzf /tmp/gh.tar.gz -C /tmp
|
||||
sudo mv "/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh" /usr/local/bin/gh
|
||||
rm -rf /tmp/gh.tar.gz /tmp/gh_${GH_VERSION}_linux_amd64
|
||||
echo "Installed gh version: $(gh --version | head -1)"
|
||||
echo ""
|
||||
|
||||
# Check if GITHUB_TOKEN is set and configure gh
|
||||
if [ -n "${GITHUB_TOKEN:-}" ]; then
|
||||
echo "GITHUB_TOKEN is configured - gh CLI is ready to use"
|
||||
echo ""
|
||||
echo "You can use gh commands directly, for example:"
|
||||
echo " gh issue list --repo cline/cline --limit 5"
|
||||
echo " gh pr list --repo cline/cline --state open"
|
||||
echo " gh issue view 123 --repo cline/cline"
|
||||
echo ""
|
||||
else
|
||||
echo "GITHUB_TOKEN is not set - gh CLI will have limited functionality"
|
||||
echo ""
|
||||
echo "To enable full GitHub API access:"
|
||||
echo "1. Create a Fine-grained Personal Access Token at https://github.com/settings/tokens?type=beta"
|
||||
echo "2. Add it as GITHUB_TOKEN in your Claude Code environment settings"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Install project dependencies
|
||||
echo "Installing dependencies..."
|
||||
bun run install:all
|
||||
|
||||
# Generate gRPC/protobuf types (required for TypeScript)
|
||||
echo "Generating proto types..."
|
||||
bun run protos
|
||||
|
||||
echo ""
|
||||
echo "Session setup complete!"
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/claude-code-for-web-setup.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/cline-sdk
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/opentui
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.cline/skills/publish-cli
|
||||
@@ -0,0 +1,266 @@
|
||||
---
|
||||
name: publish-cli
|
||||
description: Use when preparing, tagging, and publishing an apps/cli npm release. Guides changelog drafting, apps/cli/package.json version bumps, cli-vX.Y.Z tags, local npm publishing, and the publish-cli GitHub workflow.
|
||||
---
|
||||
|
||||
# CLI Release
|
||||
|
||||
Use this skill when the user asks to release the CLI, publish `cline`, bump the CLI version, draft release notes, create a `cli-vX.Y.Z` tag, or trigger the CLI publish workflow.
|
||||
|
||||
The CLI is npm-only. Do not add alternate distribution or signing steps.
|
||||
|
||||
> Working directory: run every command below from the repository root. Paths and scripts (e.g. `apps/cli/package.json`, `sdk/packages/`, `bun release cli`, `bun run version`) are written relative to the repo root.
|
||||
|
||||
The skill should guide the user through one release preparation flow, then offer the publish path options. The two normal publish paths are GitHub Actions and local publishing from an authenticated machine.
|
||||
|
||||
## Release contract
|
||||
|
||||
- SDK prerequisite: the CLI depends on the SDK via `workspace:*` (`@cline/core`, `@cline/shared`, and friends). If the SDK changed since its last release, release the SDK first and wait for it to finish publishing before releasing the CLI. See "Step 0: Release the SDK first if it changed" below.
|
||||
- Version source: `apps/cli/package.json`.
|
||||
- Main release tag: `cli-vX.Y.Z`, where `X.Y.Z` matches `apps/cli/package.json`.
|
||||
- Nightly release version: `X.Y.Z-nightly.TIMESTAMP`.
|
||||
- Release prep includes approved release notes, a version bump, and an `apps/cli/CHANGELOG.md` update.
|
||||
- Publish paths:
|
||||
- GitHub workflow: `.github/workflows/cli-publish.yml`.
|
||||
- Local publish helper: `bun release cli`.
|
||||
- npm dist-tags and git tags are separate. `--tag latest` and `--tag nightly` are npm registry channels. `cli-vX.Y.Z` is a git tag for source history and GitHub releases.
|
||||
- The GitHub main release workflow runs from `main`, requires an existing `cli-vX.Y.Z` tag, checks out that tag, and publishes from it.
|
||||
- The GitHub nightly workflow publishes to npm with the `nightly` dist-tag and does not create a tag.
|
||||
- The local release helper requires a clean checkout and `cli-vX.Y.Z` to point at `HEAD` locally and on `origin` before publishing.
|
||||
- Local GitHub release creation requires `gh` to be authenticated with release permissions for the repo.
|
||||
- Always ask before pushing commits or tags.
|
||||
- Do not amend commits unless explicitly requested.
|
||||
|
||||
## Step 0: Release the SDK first if it changed
|
||||
|
||||
Do this before anything else in the Workflow below.
|
||||
|
||||
The CLI builds and ships against the SDK source in the monorepo (`workspace:*` for `@cline/core`, `@cline/shared`, and the rest), so a CLI release always contains the latest SDK code whether or not the SDK was released. The build and tests use that source too, not anything from npm. Releasing the SDK alongside the CLI is still worth doing for two reasons:
|
||||
|
||||
- Hub freshness. The hub daemon lives in `@cline/core` and stamps a `buildId` that defaults to the `@cline/core` package version (`resolveHubBuildId` in `sdk/packages/core/src/hub/discovery/index.ts`). A running hub is only retired and respawned when that `buildId` changes (`isCompatibleHubRecord` / `retireIncompatibleHub` in `sdk/packages/core/src/hub/daemon/index.ts`). So if the SDK code changed but the version did not, a user who upgrades the CLI keeps talking to their already-running hub, which is still executing the old SDK code. Bumping the SDK version makes the new CLI's `buildId` differ, so the stale hub is detected as incompatible and respawned with the fresh code.
|
||||
- Release hygiene. We want regular SDK releases; cutting one whenever we cut a CLI release keeps the published SDK in step with what the CLI ships.
|
||||
|
||||
So when the SDK has changed, release it first (which bumps the `@cline/core` version), then cut the CLI release on top of that bump. Leave the CLI's SDK dependency as `workspace:*` — the fix is to release the SDK, not to pin the CLI.
|
||||
|
||||
1. Check for unreleased SDK changes.
|
||||
|
||||
```sh
|
||||
git fetch origin --tags
|
||||
git tag --list 'sdk/sdk/v*' 'sdk-v*' --sort=-v:refname | head -1
|
||||
git log <last-sdk-tag>..origin/main --oneline --no-merges -- sdk/packages
|
||||
```
|
||||
|
||||
`sdk/<pkg>/v*` tags are created by the `sdk-publish.yml` workflow; `sdk-v*` tags are created by the local `bun release sdk` helper. Use whichever is newest as the baseline.
|
||||
|
||||
If `git log` prints no commits, the SDK is already up to date. Skip the rest of Step 0 and continue with the Workflow below.
|
||||
|
||||
If it prints commits, sanity-check the diff (ignore entries that are only the previous version-bump commit's lockfile or generated files), then release the SDK.
|
||||
|
||||
2. Decide the SDK version bump.
|
||||
|
||||
All SDK packages share one version, read from `sdk/packages/llms/package.json`. Ask whether this is patch, minor, major, or an explicit version. Patch is the default. Do not guess if the user has not made it clear.
|
||||
|
||||
3. Draft the SDK release notes and update the changelog.
|
||||
|
||||
Draft user-facing notes from the SDK commits found in step 1, translating commit messages into user-facing language (same approach as the CLI release notes below). Prepend a new `## <version>` section with those notes to the top of `sdk/CHANGELOG.md`, using the header format `## <version>` with no date — the same flat, newest-on-top format as `apps/cli/CHANGELOG.md`. This is the SDK changelog (all SDK packages share one version) and it is maintained by hand; the `sdk-publish.yml` workflow does not read it.
|
||||
|
||||
4. Bump versions and regenerate.
|
||||
|
||||
```sh
|
||||
bun run version <version>
|
||||
```
|
||||
|
||||
This bumps every SDK `package.json` to the new version, regenerates the lockfile and the generated model catalog, formats, and builds. Review the result.
|
||||
|
||||
5. Commit and push the bump to `main`.
|
||||
|
||||
The `sdk-publish.yml` workflow publishes the version that is committed on `main` and tags that commit, so the bump must land on `main` before the workflow runs.
|
||||
|
||||
```sh
|
||||
git add -A
|
||||
git commit -m "chore(sdk): release v<version>"
|
||||
```
|
||||
|
||||
Ask before pushing:
|
||||
|
||||
```sh
|
||||
git push origin HEAD
|
||||
```
|
||||
|
||||
6. Trigger the SDK publish workflow on the `latest` channel.
|
||||
|
||||
```sh
|
||||
gh workflow run sdk-publish.yml -f channel=latest -f confirm_publish=publish
|
||||
gh run list --workflow=sdk-publish.yml --limit=1 --json databaseId,url,status,createdAt --jq '.[0]'
|
||||
```
|
||||
|
||||
The workflow runs the SDK tests, publishes `@cline/shared`, `@cline/llms`, `@cline/agents`, `@cline/core`, and `@cline/sdk` to npm with the `latest` dist-tag in dependency order, and pushes `sdk/<pkg>/v<version>` git tags.
|
||||
|
||||
7. Wait for the SDK workflow to succeed before starting the CLI release.
|
||||
|
||||
```sh
|
||||
gh run watch <run-id> --exit-status
|
||||
```
|
||||
|
||||
Do not start the CLI release until this run has finished successfully. The CLI does not install the SDK from npm, but cutting the CLI release on top of a clean, completed SDK release keeps the two in step: the CLI release commit then sits on top of the `@cline/core` version bump, so the shipped CLI carries the new version that forces a running hub to respawn with the new code, and you are not building a CLI release on top of an SDK release that failed midway.
|
||||
|
||||
After the SDK release succeeds, pull `main` so the CLI release is prepared on top of the SDK version bump:
|
||||
|
||||
```sh
|
||||
git checkout main && git pull --ff-only
|
||||
```
|
||||
|
||||
Then continue with the Workflow below.
|
||||
|
||||
For a local SDK publish from an authenticated machine instead of the workflow, `bun release sdk <version>` exists, but prefer the `sdk-publish.yml` workflow for normal releases so the CLI release can gate on a single GitHub Actions run.
|
||||
|
||||
## Workflow
|
||||
|
||||
Complete Step 0 first. Only proceed once the SDK is released (or you confirmed no SDK release was needed).
|
||||
|
||||
1. Gather context.
|
||||
|
||||
```sh
|
||||
git status --short --branch
|
||||
git fetch origin --tags
|
||||
git tag --list 'cli-v*' --sort=-v:refname | head -10
|
||||
node -p "require('./apps/cli/package.json').version"
|
||||
```
|
||||
|
||||
Find the latest CLI tag. If there is no `cli-v*` tag, use the first relevant CLI release commit as the baseline and say that the baseline is inferred.
|
||||
|
||||
2. Collect release commits.
|
||||
|
||||
```sh
|
||||
git log <last-cli-tag>..HEAD --oneline --no-merges -- apps/cli sdk/packages sdk/scripts .github/workflows/cli-publish.yml
|
||||
```
|
||||
|
||||
The `sdk/packages` commits matter here even though the SDK was released separately in Step 0: the CLI bundles the SDK, so SDK changes ship in this CLI release too. Read those commits and fold anything user-relevant to the CLI into the release notes (provider/model updates, behavior changes, fixes the CLI inherits). Skip SDK changes that are purely internal or have no CLI-visible effect.
|
||||
|
||||
3. Draft user-facing release notes.
|
||||
|
||||
Include user-facing features, fixes, behavior changes, compatibility changes, and notable install or release changes. Exclude pure refactors, tests, style, chores, and internal file moves unless they matter to users.
|
||||
|
||||
Write a flat bullet list. Translate commit messages into user-facing language. If a commit is unclear, read the full commit before summarizing it.
|
||||
|
||||
Present the draft and wait for approval before editing files.
|
||||
|
||||
4. Decide the version bump.
|
||||
|
||||
Ask whether this should be patch, minor, major, or an explicit version. Do not guess if the user has not made it clear.
|
||||
|
||||
5. Update release files.
|
||||
|
||||
Update `apps/cli/package.json` to the approved version.
|
||||
|
||||
Prepend a section to `apps/cli/CHANGELOG.md` for the approved version using the approved release notes. Use the header format `## X.Y.Z` with no date. The publish workflow extracts the top section of the changelog by matching `^## [0-9]` and pastes it verbatim into the GitHub release body and the Slack release announcement, so the section content is the release notes that get shipped.
|
||||
|
||||
6. Verify before committing.
|
||||
|
||||
Run focused checks first:
|
||||
|
||||
```sh
|
||||
bun -F @cline/cli typecheck
|
||||
bun -F @cline/cli test:unit
|
||||
```
|
||||
|
||||
For higher confidence, run:
|
||||
|
||||
```sh
|
||||
bun run types
|
||||
bun --cwd apps/cli run build:platforms:single
|
||||
```
|
||||
|
||||
If the user wants full release confidence before tagging, run:
|
||||
|
||||
```sh
|
||||
bun run test
|
||||
bun --cwd apps/cli run build:platforms
|
||||
```
|
||||
|
||||
Known local-only test failure: `src/commands/distribution-package.test.ts > rejects direct source package packing by default` will fail on machines that have `ignore-scripts=true` in `~/.npmrc` (set by the npm supply-chain hardening guide). Bun reads npm's `ignore-scripts` from `~/.npmrc`, so `bun pm pack --dry-run` skips the source-publish `prepack` guard and exits 0, which the test reads as a failure. CI does not set `ignore-scripts`, so the test passes there. Confirm by running `bun pm pack --dry-run` directly: with `~/.npmrc` in place it exits 0 with no guard output; with `~/.npmrc` moved aside it exits 1 and prints the guard message. This is not a release blocker by itself, but it does mean the local-publish path (`bun release cli`) will also bypass the source-publish guard on this machine; prefer the GitHub Actions publish path on machines with `ignore-scripts=true` set globally, or temporarily unset it (`npm config delete ignore-scripts` or `mv ~/.npmrc ~/.npmrc.bak`) for the duration of a local publish.
|
||||
|
||||
7. Commit release changes.
|
||||
|
||||
Only after the user approves the notes and version:
|
||||
|
||||
```sh
|
||||
git add apps/cli/package.json apps/cli/CHANGELOG.md
|
||||
git commit -m "chore(cli): release vX.Y.Z"
|
||||
```
|
||||
|
||||
Ask before pushing the release commit:
|
||||
|
||||
```sh
|
||||
git push origin HEAD
|
||||
```
|
||||
|
||||
For the GitHub main release path, ask before creating and pushing the release tag:
|
||||
|
||||
```sh
|
||||
git tag -a cli-vX.Y.Z -m "CLI vX.Y.Z"
|
||||
git push origin refs/tags/cli-vX.Y.Z
|
||||
```
|
||||
|
||||
8. Publish.
|
||||
|
||||
Ask the user which path to use:
|
||||
|
||||
- GitHub main release. Use this after the release commit is on `main` and the matching `cli-vX.Y.Z` tag has been pushed. The workflow publishes to npm from that tag, creates the GitHub release, and posts to Slack.
|
||||
- Local release. Use this when the user wants to publish from this machine. The local machine must be authenticated to npm and GitHub.
|
||||
- GitHub nightly release.
|
||||
- Stop after the version commit.
|
||||
|
||||
For GitHub main release:
|
||||
|
||||
```sh
|
||||
gh workflow run cli-publish.yml -f publish_target=main -f git_tag=cli-vX.Y.Z -f confirm_publish=publish
|
||||
gh run list --workflow=cli-publish.yml --limit=1 --json url,status,conclusion,createdAt --jq '.[0]'
|
||||
```
|
||||
|
||||
For GitHub nightly release:
|
||||
|
||||
```sh
|
||||
gh workflow run cli-publish.yml -f publish_target=nightly
|
||||
```
|
||||
|
||||
For forced GitHub nightly release:
|
||||
|
||||
```sh
|
||||
gh workflow run cli-publish.yml -f publish_target=nightly -f force_nightly_publish=true
|
||||
```
|
||||
|
||||
For local publish:
|
||||
|
||||
```sh
|
||||
gh auth status
|
||||
npm whoami
|
||||
git tag -a cli-vX.Y.Z -m "CLI vX.Y.Z"
|
||||
git push origin refs/tags/cli-vX.Y.Z
|
||||
bun release cli
|
||||
```
|
||||
|
||||
After a successful local publish, ask before running:
|
||||
|
||||
```sh
|
||||
gh release create cli-vX.Y.Z --verify-tag --title "CLI vX.Y.Z" --notes "Paste the approved release notes here."
|
||||
```
|
||||
|
||||
If publishing with another npm dist-tag:
|
||||
|
||||
```sh
|
||||
bun release cli --tag next
|
||||
```
|
||||
|
||||
9. Final response.
|
||||
|
||||
Report:
|
||||
|
||||
- version
|
||||
- tag
|
||||
- changelog file updated
|
||||
- commit hash
|
||||
- whether anything was pushed
|
||||
- publish path selected
|
||||
- workflow URL or local publish result
|
||||
- tests and builds run
|
||||
@@ -0,0 +1,55 @@
|
||||
# Bun (tooling) and Node (runtime)
|
||||
|
||||
This repo uses **bun** for package management and task running, and **Node** as
|
||||
the execution runtime. Both are correct at the same time; the distinction is the
|
||||
source of most confusion, so keep it straight before editing scripts, configs,
|
||||
docs, or comments.
|
||||
|
||||
## Use bun for tooling
|
||||
|
||||
- `bun install` (never `npm install` / `npm ci`)
|
||||
- `bun run <script>` (never `npm run <script>`)
|
||||
- `bunx <bin>` (never `npx <bin>`)
|
||||
- `bun <file>.ts` to run a TS entrypoint directly (no `ts-node` / `tsx`)
|
||||
- `bun esbuild.mjs` to drive the build (esbuild/vite are still the bundlers)
|
||||
- `bun run --parallel ...` for parallel tasks
|
||||
|
||||
The root `bun.lock` is the single lockfile for the whole workspace, including
|
||||
`apps/vscode`, `webview-ui`, and `testing-platform`. There are no per-package npm
|
||||
lockfiles.
|
||||
|
||||
## Node is the runtime — do NOT rewrite these to bun
|
||||
|
||||
The build product runs on Node: the VS Code extension host loads
|
||||
`dist/extension.js` as CommonJS under Node, and the standalone `cline-core` is a
|
||||
Node process. The following are Node runtime/ABI references and are correct as-is:
|
||||
|
||||
| Reference | Why it is Node |
|
||||
|-----------|----------------|
|
||||
| esbuild `platform: "node"` / `target: "node..."` | The bundle targets the Node runtime (extension host, standalone core). |
|
||||
| `TARGET_NODE_VERSION` (`scripts/package-standalone.mjs`) | Pins the Node ABI of the bundled standalone runtime (matches the JetBrains-packaged Node). |
|
||||
| `prebuild-install --target=<node version>` | Downloads native `.node` binaries for that Node ABI. |
|
||||
| `NODE_PATH=... node cline-core.js` | The standalone core is launched by Node, not bun. |
|
||||
| `node:` import specifiers (e.g. `node:fs`) | Node builtin module scheme; unrelated to tooling. |
|
||||
| `process.versions.node`, `engines.node`, `@types/node` | Runtime version probe / declared runtime / its types. |
|
||||
| `ELECTRON_RUN_AS_NODE` | VS Code/Electron runs the extension host as Node. |
|
||||
|
||||
When a file legitimately uses both bun and node (e.g. `package-standalone.mjs`
|
||||
does `bun install` but `prebuild-install --target=<node>`), the `node` token is
|
||||
the runtime/ABI target, not tooling. If unsure, leave it.
|
||||
|
||||
## Tests: bun vs the VS Code host
|
||||
|
||||
A test file's runner is decided by its import:
|
||||
|
||||
- **`import ... from "bun:test"`** → runs under `bun test` (the node-side unit
|
||||
suites + the SDK/model-catalog suites). `scripts/run-bun-unit-tests.ts`
|
||||
discovers these by the `bun:test` import and runs one isolated bun process per
|
||||
file. `build-tests.js` excludes them from the integration compile so the
|
||||
`bun:test` builtin never reaches Node.
|
||||
- **`import ... from "mocha"`** → runs under `@vscode/test-cli` in a real VS Code
|
||||
extension host (Node). These exercise the live `vscode` API and cannot run
|
||||
under bun.
|
||||
|
||||
So a file imports `bun:test` XOR `mocha`. Don't add `bun:test` to a test that
|
||||
needs the real extension host.
|
||||
@@ -0,0 +1,764 @@
|
||||
# Cline Extension Architecture & Development Guide
|
||||
|
||||
## Project Overview
|
||||
|
||||
Cline is a VSCode extension that provides AI assistance through a combination of a core extension backend and a React-based webview frontend. The extension is built with TypeScript and follows a modular architecture pattern.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph VSCodeExtensionHost[VSCode Extension Host]
|
||||
subgraph CoreExtension[Core Extension]
|
||||
ExtensionEntry[Extension Entry<br/>src/extension.ts]
|
||||
WebviewProvider[WebviewProvider<br/>src/core/webview/index.ts]
|
||||
Controller[Controller<br/>src/core/controller/index.ts]
|
||||
Task[Task<br/>src/core/task/index.ts]
|
||||
GlobalState[VSCode Global State]
|
||||
SecretsStorage[VSCode Secrets Storage]
|
||||
McpHub[McpHub<br/>src/services/mcp/McpHub.ts]
|
||||
end
|
||||
|
||||
subgraph WebviewUI[Webview UI]
|
||||
WebviewApp[React App<br/>webview-ui/src/App.tsx]
|
||||
ExtStateContext[ExtensionStateContext<br/>webview-ui/src/context/ExtensionStateContext.tsx]
|
||||
ReactComponents[React Components]
|
||||
end
|
||||
|
||||
subgraph Storage
|
||||
TaskStorage[Task Storage<br/>Per-Task Files & History]
|
||||
CheckpointSystem[Git-based Checkpoints]
|
||||
end
|
||||
|
||||
subgraph apiProviders[API Providers]
|
||||
AnthropicAPI[Anthropic]
|
||||
OpenRouterAPI[OpenRouter]
|
||||
BedrockAPI[AWS Bedrock]
|
||||
OtherAPIs[Other Providers]
|
||||
end
|
||||
|
||||
subgraph MCPServers[MCP Servers]
|
||||
ExternalMcpServers[External MCP Servers]
|
||||
end
|
||||
end
|
||||
|
||||
%% Core Extension Data Flow
|
||||
ExtensionEntry --> WebviewProvider
|
||||
WebviewProvider --> Controller
|
||||
Controller --> Task
|
||||
Controller --> McpHub
|
||||
Task --> GlobalState
|
||||
Task --> SecretsStorage
|
||||
Task --> TaskStorage
|
||||
Task --> CheckpointSystem
|
||||
Task --> |API Requests| apiProviders
|
||||
McpHub --> |Connects to| ExternalMcpServers
|
||||
Task --> |Uses| McpHub
|
||||
|
||||
%% Webview Data Flow
|
||||
WebviewApp --> ExtStateContext
|
||||
ExtStateContext --> ReactComponents
|
||||
|
||||
%% Bidirectional Communication
|
||||
WebviewProvider <-->|postMessage| ExtStateContext
|
||||
|
||||
style GlobalState fill:#f9f,stroke:#333,stroke-width:2px
|
||||
style SecretsStorage fill:#f9f,stroke:#333,stroke-width:2px
|
||||
style ExtStateContext fill:#bbf,stroke:#333,stroke-width:2px
|
||||
style WebviewProvider fill:#bfb,stroke:#333,stroke-width:2px
|
||||
style McpHub fill:#bfb,stroke:#333,stroke-width:2px
|
||||
style apiProviders fill:#fdb,stroke:#333,stroke-width:2px
|
||||
```
|
||||
|
||||
## Definitions
|
||||
|
||||
- **Core Extension**: Anything inside the src folder, organized into modular components
|
||||
- **Core Extension State**: Managed by the Controller class in src/core/controller/index.ts, which serves as the single source of truth for the extension's state. It manages multiple types of persistent storage (global state, workspace state, and secrets), handles state distribution to both the core extension and webview components, and coordinates state across multiple extension instances. This includes managing API configurations, task history, settings, and MCP configurations.
|
||||
- **Webview**: Anything inside the webview-ui. All the react or view's seen by the user and user interaction components
|
||||
- **Webview State**: Managed by ExtensionStateContext in webview-ui/src/context/ExtensionStateContext.tsx, which provides React components with access to the extension's state through a context provider pattern. It maintains local state for UI components, handles real-time updates through message events, manages partial message updates, and provides methods for state modifications. The context includes extension version, messages, task history, theme, API configurations, MCP servers, marketplace catalog, and workspace file paths. It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to state through a custom hook (useExtensionState).
|
||||
|
||||
### Core Extension Architecture
|
||||
|
||||
The core extension follows a clear hierarchical structure:
|
||||
|
||||
1. **WebviewProvider** (src/core/webview/index.ts): Manages the webview lifecycle and communication
|
||||
2. **Controller** (src/core/controller/index.ts): Handles webview messages and task management
|
||||
3. **Task** (src/core/task/index.ts): Executes API requests and tool operations
|
||||
|
||||
This architecture provides clear separation of concerns:
|
||||
- WebviewProvider focuses on VSCode webview integration
|
||||
- Controller manages state and coordinates tasks
|
||||
- Task handles the execution of AI requests and tool operations
|
||||
|
||||
### WebviewProvider Implementation
|
||||
|
||||
The WebviewProvider class in `src/core/webview/index.ts` is responsible for:
|
||||
|
||||
- Managing multiple active instances through a static set (`activeInstances`)
|
||||
- Handling webview lifecycle events (creation, visibility changes, disposal)
|
||||
- Implementing HTML content generation with proper CSP headers
|
||||
- Supporting Hot Module Replacement (HMR) for development
|
||||
- Setting up message listeners between the webview and extension
|
||||
|
||||
The WebviewProvider maintains a reference to the Controller and delegates message handling to it. It also handles the creation of both sidebar and tab panel webviews, allowing Cline to be used in different contexts within VSCode.
|
||||
|
||||
### Core Extension State
|
||||
|
||||
The `Controller` class manages multiple types of persistent storage:
|
||||
|
||||
- **Global State:** Stored across all VSCode instances. Used for settings and data that should persist globally.
|
||||
- **Workspace State:** Specific to the current workspace. Used for task-specific data and settings.
|
||||
- **Secrets:** Secure storage for sensitive information like API keys.
|
||||
|
||||
The `Controller` handles the distribution of state to both the core extension and webview components. It also coordinates state across multiple extension instances, ensuring consistency.
|
||||
|
||||
State synchronization between instances is handled through:
|
||||
- File-based storage for task history and conversation data
|
||||
- VSCode's global state API for settings and configuration
|
||||
- Secrets storage for sensitive information
|
||||
- Event listeners for file changes and configuration updates
|
||||
|
||||
The Controller implements methods for:
|
||||
- Saving and loading task state
|
||||
- Managing API configurations
|
||||
- Handling user authentication
|
||||
- Coordinating MCP server connections
|
||||
- Managing task history and checkpoints
|
||||
|
||||
### Webview State
|
||||
|
||||
The `ExtensionStateContext` in `webview-ui/src/context/ExtensionStateContext.tsx` provides React components with access to the extension's state. It uses a context provider pattern and maintains local state for UI components. The context includes:
|
||||
|
||||
- Extension version
|
||||
- Messages
|
||||
- Task history
|
||||
- Theme
|
||||
- API configurations
|
||||
- MCP servers
|
||||
- Marketplace catalog
|
||||
- Workspace file paths
|
||||
|
||||
It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to the state via a custom hook (`useExtensionState`).
|
||||
|
||||
The ExtensionStateContext handles:
|
||||
- Real-time updates through message events
|
||||
- Partial message updates for streaming content
|
||||
- State modifications through setter methods
|
||||
- Type-safe access to state through a custom hook
|
||||
|
||||
## API Provider System
|
||||
|
||||
Cline supports multiple AI providers through a modular API provider system. Each provider is implemented as a separate module in the `src/api/providers/` directory and follows a common interface.
|
||||
|
||||
### API Provider Architecture
|
||||
|
||||
The API system consists of:
|
||||
|
||||
1. **API Handlers**: Provider-specific implementations in `src/api/providers/`
|
||||
2. **API Transformers**: Stream transformation utilities in `src/api/transform/`
|
||||
3. **API Configuration**: User settings for API keys and endpoints
|
||||
4. **API Factory**: Builder function to create the appropriate handler
|
||||
|
||||
Key providers include:
|
||||
- **Anthropic**: Direct integration with Claude models
|
||||
- **OpenRouter**: Meta-provider supporting multiple model providers
|
||||
- **AWS Bedrock**: Integration with Amazon's AI services
|
||||
- **Gemini**: Google's AI models
|
||||
- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
|
||||
- **Ollama**: Local model hosting
|
||||
- **LM Studio**: Local model hosting
|
||||
- **VSCode LM**: VSCode's built-in language models
|
||||
|
||||
### API Configuration Management
|
||||
|
||||
API configurations are stored securely:
|
||||
- API keys are stored in VSCode's secrets storage
|
||||
- Model selections and non-sensitive settings are stored in global state
|
||||
- The Controller manages switching between providers and updating configurations
|
||||
|
||||
The system supports:
|
||||
- Secure storage of API keys
|
||||
- Model selection and configuration
|
||||
- Automatic retry and error handling
|
||||
- Token usage tracking and cost calculation
|
||||
- Context window management
|
||||
|
||||
### Plan/Act Mode API Configuration
|
||||
|
||||
Cline supports separate model configurations for Plan and Act modes:
|
||||
- Different models can be used for planning vs. execution
|
||||
- The system preserves model selections when switching modes
|
||||
- The Controller handles the transition between modes and updates the API configuration accordingly
|
||||
|
||||
## Task Execution System
|
||||
|
||||
The Task class is responsible for executing AI requests and tool operations. Each task runs in its own instance of the Task class, ensuring isolation and proper state management.
|
||||
|
||||
### Task Execution Loop
|
||||
|
||||
The core task execution loop follows this pattern:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async initiateTaskLoop(userContent: UserContent, isNewTask: boolean) {
|
||||
while (!this.abort) {
|
||||
// 1. Make API request and stream response
|
||||
const stream = this.attemptApiRequest()
|
||||
|
||||
// 2. Parse and present content blocks
|
||||
for await (const chunk of stream) {
|
||||
switch (chunk.type) {
|
||||
case "text":
|
||||
// Parse into content blocks
|
||||
this.assistantMessageContent = parseAssistantMessageV2(chunk.text)
|
||||
// Present blocks to user
|
||||
await this.presentAssistantMessage()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Wait for tool execution to complete
|
||||
await pWaitFor(() => this.userMessageContentReady)
|
||||
|
||||
// 4. Continue loop with tool result
|
||||
const recDidEndLoop = await this.recursivelyMakeClineRequests(
|
||||
this.userMessageContent
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Message Streaming System
|
||||
|
||||
The streaming system handles real-time updates and partial content:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async presentAssistantMessage() {
|
||||
// Handle streaming locks to prevent race conditions
|
||||
if (this.presentAssistantMessageLocked) {
|
||||
this.presentAssistantMessageHasPendingUpdates = true
|
||||
return
|
||||
}
|
||||
this.presentAssistantMessageLocked = true
|
||||
|
||||
// Present current content block
|
||||
const block = this.assistantMessageContent[this.currentStreamingContentIndex]
|
||||
|
||||
// Handle different types of content
|
||||
switch (block.type) {
|
||||
case "text":
|
||||
await this.say("text", content, undefined, block.partial)
|
||||
break
|
||||
case "tool_use":
|
||||
// Handle tool execution
|
||||
break
|
||||
}
|
||||
|
||||
// Move to next block if complete
|
||||
if (!block.partial) {
|
||||
this.currentStreamingContentIndex++
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Execution Flow
|
||||
|
||||
Tools follow a strict execution pattern:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async executeToolWithApproval(block: ToolBlock) {
|
||||
// 1. Check auto-approval settings
|
||||
if (this.shouldAutoApproveTool(block.name)) {
|
||||
await this.say("tool", message)
|
||||
this.consecutiveAutoApprovedRequestsCount++
|
||||
} else {
|
||||
// 2. Request user approval
|
||||
const didApprove = await askApproval("tool", message)
|
||||
if (!didApprove) {
|
||||
this.didRejectTool = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Execute tool
|
||||
const result = await this.executeTool(block)
|
||||
|
||||
// 4. Save checkpoint
|
||||
await this.saveCheckpoint()
|
||||
|
||||
// 5. Return result to API
|
||||
return result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling & Recovery
|
||||
|
||||
The system includes robust error handling:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async handleError(action: string, error: Error) {
|
||||
// 1. Check if task was abandoned
|
||||
if (this.abandoned) return
|
||||
|
||||
// 2. Format error message
|
||||
const errorString = `Error ${action}: ${error.message}`
|
||||
|
||||
// 3. Present error to user
|
||||
await this.say("error", errorString)
|
||||
|
||||
// 4. Add error to tool results
|
||||
pushToolResult(formatResponse.toolError(errorString))
|
||||
|
||||
// 5. Cleanup resources
|
||||
await this.diffViewProvider.revertChanges()
|
||||
await this.browserSession.closeBrowser()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API Request & Token Management
|
||||
|
||||
The Task class handles API requests with built-in retry, streaming, and token management:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
|
||||
// 1. Wait for MCP servers to connect
|
||||
await pWaitFor(() => this.controllerRef.deref()?.mcpHub?.isConnecting !== true)
|
||||
|
||||
// 2. Manage context window
|
||||
const previousRequest = this.clineMessages[previousApiReqIndex]
|
||||
if (previousRequest?.text) {
|
||||
const { tokensIn, tokensOut } = JSON.parse(previousRequest.text || "{}")
|
||||
const totalTokens = (tokensIn || 0) + (tokensOut || 0)
|
||||
|
||||
// Truncate conversation if approaching context limit
|
||||
if (totalTokens >= maxAllowedSize) {
|
||||
this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
|
||||
this.apiConversationHistory,
|
||||
this.conversationHistoryDeletedRange,
|
||||
totalTokens / 2 > maxAllowedSize ? "quarter" : "half"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Handle streaming with automatic retry
|
||||
try {
|
||||
this.isWaitingForFirstChunk = true
|
||||
const firstChunk = await iterator.next()
|
||||
yield firstChunk.value
|
||||
this.isWaitingForFirstChunk = false
|
||||
|
||||
// Stream remaining chunks
|
||||
yield* iterator
|
||||
} catch (error) {
|
||||
// 4. Error handling with retry
|
||||
if (isOpenRouter && !this.didAutomaticallyRetryFailedApiRequest) {
|
||||
await setTimeoutPromise(1000)
|
||||
this.didAutomaticallyRetryFailedApiRequest = true
|
||||
yield* this.attemptApiRequest(previousApiReqIndex)
|
||||
return
|
||||
}
|
||||
|
||||
// 5. Ask user to retry if automatic retry failed
|
||||
const { response } = await this.ask(
|
||||
"api_req_failed",
|
||||
this.formatErrorWithStatusCode(error)
|
||||
)
|
||||
if (response === "yesButtonClicked") {
|
||||
await this.say("api_req_retried")
|
||||
yield* this.attemptApiRequest(previousApiReqIndex)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key features:
|
||||
|
||||
1. **Context Window Management**
|
||||
- Tracks token usage across requests
|
||||
- Automatically truncates conversation when needed
|
||||
- Preserves important context while freeing space
|
||||
- Handles different model context sizes
|
||||
|
||||
2. **Streaming Architecture**
|
||||
- Real-time chunk processing
|
||||
- Partial content handling
|
||||
- Race condition prevention
|
||||
- Error recovery during streaming
|
||||
|
||||
3. **Error Handling**
|
||||
- Automatic retry for transient failures
|
||||
- User-prompted retry for persistent issues
|
||||
- Detailed error reporting
|
||||
- State cleanup on failure
|
||||
|
||||
4. **Token Tracking**
|
||||
- Per-request token counting
|
||||
- Cumulative usage tracking
|
||||
- Cost calculation
|
||||
- Cache hit monitoring
|
||||
|
||||
### Context Management System
|
||||
|
||||
The Context Management System handles conversation history truncation to prevent context window overflow errors. Implemented in the `ContextManager` class, it ensures long-running conversations remain within model context limits while preserving critical context.
|
||||
|
||||
Key features:
|
||||
|
||||
1. **Model-Aware Sizing**: Dynamically adjusts based on different model context windows (64K for DeepSeek, 128K for most models, 200K for Claude).
|
||||
|
||||
2. **Proactive Truncation**: Monitors token usage and preemptively truncates conversations when approaching limits, maintaining buffers of 27K-40K tokens depending on the model.
|
||||
|
||||
3. **Intelligent Preservation**: Always preserves the original task message and maintains the user-assistant conversation structure when truncating.
|
||||
|
||||
4. **Adaptive Strategies**: Uses different truncation strategies based on context pressure - removing half of the conversation for moderate pressure or three-quarters for severe pressure.
|
||||
|
||||
5. **Error Recovery**: Includes specialized detection for context window errors from different providers with automatic retry and more aggressive truncation when needed.
|
||||
|
||||
### Task State & Resumption
|
||||
|
||||
The Task class provides robust task state management and resumption capabilities:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async resumeTaskFromHistory() {
|
||||
// 1. Load saved state
|
||||
this.clineMessages = await getSavedClineMessages(this.getContext(), this.taskId)
|
||||
this.apiConversationHistory = await getSavedApiConversationHistory(this.getContext(), this.taskId)
|
||||
|
||||
// 2. Handle interrupted tool executions
|
||||
const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
|
||||
if (lastMessage.role === "assistant") {
|
||||
const toolUseBlocks = content.filter(block => block.type === "tool_use")
|
||||
if (toolUseBlocks.length > 0) {
|
||||
// Add interrupted tool responses
|
||||
const toolResponses = toolUseBlocks.map(block => ({
|
||||
type: "tool_result",
|
||||
tool_use_id: block.id,
|
||||
content: "Task was interrupted before this tool call could be completed."
|
||||
}))
|
||||
modifiedOldUserContent = [...toolResponses]
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Notify about interruption
|
||||
const agoText = this.getTimeAgoText(lastMessage?.ts)
|
||||
newUserContent.push({
|
||||
type: "text",
|
||||
text: `[TASK RESUMPTION] This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context.`
|
||||
})
|
||||
|
||||
// 4. Resume task execution
|
||||
await this.initiateTaskLoop(newUserContent, false)
|
||||
}
|
||||
|
||||
private async saveTaskState() {
|
||||
// Save conversation history
|
||||
await saveApiConversationHistory(this.getContext(), this.taskId, this.apiConversationHistory)
|
||||
await saveClineMessages(this.getContext(), this.taskId, this.clineMessages)
|
||||
|
||||
// Create checkpoint
|
||||
const commitHash = await this.checkpointTracker?.commit()
|
||||
|
||||
// Update task history
|
||||
await this.controllerRef.deref()?.updateTaskHistory({
|
||||
id: this.taskId,
|
||||
ts: lastMessage.ts,
|
||||
task: taskMessage.text,
|
||||
// ... other metadata
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key aspects of task state management:
|
||||
|
||||
1. **Task Persistence**
|
||||
- Each task has a unique ID and dedicated storage directory
|
||||
- Conversation history is saved after each message
|
||||
- File changes are tracked through Git-based checkpoints
|
||||
- Terminal output and browser state are preserved
|
||||
|
||||
2. **State Recovery**
|
||||
- Tasks can be resumed from any point
|
||||
- Interrupted tool executions are handled gracefully
|
||||
- File changes can be restored from checkpoints
|
||||
- Context is preserved across VSCode sessions
|
||||
|
||||
3. **Workspace Synchronization**
|
||||
- File changes are tracked through Git
|
||||
- Checkpoints are created after tool executions
|
||||
- State can be restored to any checkpoint
|
||||
- Changes can be compared between checkpoints
|
||||
|
||||
4. **Error Recovery**
|
||||
- Failed API requests can be retried
|
||||
- Interrupted tool executions are marked
|
||||
- Resources are cleaned up properly
|
||||
- User is notified of state changes
|
||||
|
||||
## Plan/Act Mode System
|
||||
|
||||
Cline implements a dual-mode system that separates planning from execution:
|
||||
|
||||
### Mode Architecture
|
||||
|
||||
The Plan/Act mode system consists of:
|
||||
|
||||
1. **Mode State**: Stored in `chatSettings.mode` in the Controller's state
|
||||
2. **Mode Switching**: Handled by `togglePlanActModeWithChatSettings` in the Controller
|
||||
3. **Mode-specific Models**: Optional configuration to use different models for each mode
|
||||
4. **Mode-specific Prompting**: Different system prompts for planning vs. execution
|
||||
|
||||
### Mode Switching Process
|
||||
|
||||
When switching between modes:
|
||||
|
||||
1. The current model configuration is saved to mode-specific state
|
||||
2. The previous mode's model configuration is restored
|
||||
3. The Task instance is updated with the new mode
|
||||
4. The webview is notified of the mode change
|
||||
5. Telemetry events are captured for analytics
|
||||
|
||||
### Plan Mode
|
||||
|
||||
Plan mode is designed for:
|
||||
- Information gathering and context building
|
||||
- Asking clarifying questions
|
||||
- Creating detailed execution plans
|
||||
- Discussing approaches with the user
|
||||
|
||||
In Plan mode, the AI uses the `plan_mode_respond` tool to engage in conversational planning without executing actions.
|
||||
|
||||
### Act Mode
|
||||
|
||||
Act mode is designed for:
|
||||
- Executing the planned actions
|
||||
- Using tools to modify files, run commands, etc.
|
||||
- Implementing the solution
|
||||
- Providing results and completion feedback
|
||||
|
||||
In Act mode, the AI has access to all tools except `plan_mode_respond` and focuses on implementation rather than discussion.
|
||||
|
||||
## Data Flow & State Management
|
||||
|
||||
### Core Extension Role
|
||||
|
||||
The Controller acts as the single source of truth for all persistent state. It:
|
||||
- Manages VSCode global state and secrets storage
|
||||
- Coordinates state updates between components
|
||||
- Ensures state consistency across webview reloads
|
||||
- Handles task-specific state persistence
|
||||
- Manages checkpoint creation and restoration
|
||||
|
||||
### Terminal Management
|
||||
|
||||
The Task class manages terminal instances and command execution:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async executeCommandTool(command: string): Promise<[boolean, ToolResponse]> {
|
||||
// 1. Get or create terminal
|
||||
const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd)
|
||||
terminalInfo.terminal.show()
|
||||
|
||||
// 2. Execute command with output streaming
|
||||
const process = this.terminalManager.runCommand(terminalInfo, command)
|
||||
|
||||
// 3. Handle real-time output
|
||||
let result = ""
|
||||
process.on("line", (line) => {
|
||||
result += line + "\n"
|
||||
if (!didContinue) {
|
||||
sendCommandOutput(line)
|
||||
} else {
|
||||
this.say("command_output", line)
|
||||
}
|
||||
})
|
||||
|
||||
// 4. Wait for completion or user feedback
|
||||
let completed = false
|
||||
process.once("completed", () => {
|
||||
completed = true
|
||||
})
|
||||
|
||||
await process
|
||||
|
||||
// 5. Return result
|
||||
if (completed) {
|
||||
return [false, `Command executed.\n${result}`]
|
||||
} else {
|
||||
return [
|
||||
false,
|
||||
`Command is still running in the user's terminal.\n${result}\n\nYou will be updated on the terminal status and new output in the future.`
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key features:
|
||||
1. **Terminal Instance Management**
|
||||
- Multiple terminal support
|
||||
- Terminal state tracking (busy/inactive)
|
||||
- Process cooldown monitoring
|
||||
- Output history per terminal
|
||||
|
||||
2. **Command Execution**
|
||||
- Real-time output streaming
|
||||
- User feedback handling
|
||||
- Process state monitoring
|
||||
- Error recovery
|
||||
|
||||
### Browser Session Management
|
||||
|
||||
The Task class handles browser automation through Puppeteer:
|
||||
|
||||
```typescript
|
||||
class Task {
|
||||
async executeBrowserAction(action: BrowserAction): Promise<BrowserActionResult> {
|
||||
switch (action) {
|
||||
case "launch":
|
||||
// 1. Launch browser with fixed resolution
|
||||
await this.browserSession.launchBrowser()
|
||||
return await this.browserSession.navigateToUrl(url)
|
||||
|
||||
case "click":
|
||||
// 2. Handle click actions with coordinates
|
||||
return await this.browserSession.click(coordinate)
|
||||
|
||||
case "type":
|
||||
// 3. Handle keyboard input
|
||||
return await this.browserSession.type(text)
|
||||
|
||||
case "close":
|
||||
// 4. Clean up resources
|
||||
return await this.browserSession.closeBrowser()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key aspects:
|
||||
1. **Browser Control**
|
||||
- Fixed 900x600 resolution window
|
||||
- Single instance per task lifecycle
|
||||
- Automatic cleanup on task completion
|
||||
- Console log capture
|
||||
|
||||
2. **Interaction Handling**
|
||||
- Coordinate-based clicking
|
||||
- Keyboard input simulation
|
||||
- Screenshot capture
|
||||
- Error recovery
|
||||
|
||||
## MCP (Model Context Protocol) Integration
|
||||
|
||||
### MCP Architecture
|
||||
|
||||
The MCP system consists of:
|
||||
|
||||
1. **McpHub Class**: Central manager in `src/services/mcp/McpHub.ts`
|
||||
2. **MCP Connections**: Manages connections to external MCP servers
|
||||
3. **MCP Settings**: Configuration stored in a JSON file
|
||||
4. **MCP Marketplace**: Online catalog of available MCP servers
|
||||
5. **MCP Tools & Resources**: Capabilities exposed by connected servers
|
||||
|
||||
The McpHub class:
|
||||
- Manages the lifecycle of MCP server connections
|
||||
- Handles server configuration through a settings file
|
||||
- Provides methods for calling tools and accessing resources
|
||||
- Implements auto-approval settings for MCP tools
|
||||
- Monitors server health and handles reconnection
|
||||
|
||||
### MCP Server Types
|
||||
|
||||
Cline supports two types of MCP server connections:
|
||||
- **Stdio**: Command-line based servers that communicate via standard I/O
|
||||
- **SSE**: HTTP-based servers that communicate via Server-Sent Events
|
||||
|
||||
### MCP Server Management
|
||||
|
||||
The McpHub class provides methods for:
|
||||
- Discovering and connecting to MCP servers
|
||||
- Monitoring server health and status
|
||||
- Restarting servers when needed
|
||||
- Managing server configurations
|
||||
- Setting timeouts and auto-approval rules
|
||||
|
||||
### MCP Tool Integration
|
||||
|
||||
MCP tools are integrated into the Task execution system:
|
||||
- Tools are discovered and registered at connection time
|
||||
- The Task class can call MCP tools through the McpHub
|
||||
- Tool results are streamed back to the AI
|
||||
- Auto-approval settings can be configured per tool
|
||||
|
||||
### MCP Marketplace
|
||||
|
||||
The MCP Marketplace provides:
|
||||
- A catalog of available MCP servers
|
||||
- One-click installation
|
||||
- README previews
|
||||
- Server status monitoring
|
||||
|
||||
The Controller class manages MCP servers through the McpHub service:
|
||||
|
||||
```typescript
|
||||
class Controller {
|
||||
mcpHub?: McpHub
|
||||
|
||||
constructor(context: vscode.ExtensionContext, webviewProvider: WebviewProvider) {
|
||||
this.mcpHub = new McpHub(this)
|
||||
}
|
||||
|
||||
async downloadMcp(mcpId: string) {
|
||||
// Fetch server details from marketplace
|
||||
const response = await axios.post<McpDownloadResponse>(
|
||||
"https://api.cline.bot/v1/mcp/download",
|
||||
{ mcpId },
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 10000,
|
||||
}
|
||||
)
|
||||
|
||||
// Create task with context from README
|
||||
const task = `Set up the MCP server from ${mcpDetails.githubUrl}...`
|
||||
|
||||
// Initialize task and show chat view
|
||||
await this.initClineWithTask(task)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
This guide provides a comprehensive overview of the Cline extension architecture, with special focus on state management, data persistence, and code organization. Following these patterns ensures robust feature implementation with proper state handling across the extension's components.
|
||||
|
||||
Remember:
|
||||
- Always persist important state in the extension
|
||||
- The core extension follows a WebviewProvider -> Controller -> Task flow
|
||||
- Use proper typing for all state and messages
|
||||
- Handle errors and edge cases
|
||||
- Test state persistence across webview reloads
|
||||
- Follow the established patterns for consistency
|
||||
- Place new code in appropriate directories
|
||||
- Maintain clear separation of concerns
|
||||
- Install dependencies in correct package.json
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions to the Cline extension are welcome! Please follow these guidelines:
|
||||
|
||||
When adding new tools or API providers, follow the existing patterns in the `src/integrations/` and `src/api/providers/` directories, respectively. Ensure that your code is well-documented and includes appropriate error handling.
|
||||
|
||||
The `.clineignore` file allows users to specify files and directories that Cline should not access. When implementing new features, respect the `.clineignore` rules and ensure that your code does not attempt to read or modify ignored files.
|
||||
@@ -0,0 +1,128 @@
|
||||
# Debug Harness
|
||||
|
||||
HTTP-controlled debugger for the VSCode extension at `src/dev/debug-harness/server.ts`.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# Build extension first if needed (protos + esbuild):
|
||||
bun run protos && IS_DEV=true bun esbuild.mjs
|
||||
|
||||
# Launch (skip-build if already built):
|
||||
bun src/dev/debug-harness/server.ts --skip-build --auto-launch
|
||||
|
||||
# In another terminal:
|
||||
curl localhost:19229/api -d '{"method":"status"}'
|
||||
```
|
||||
|
||||
## Data Isolation
|
||||
|
||||
The debugee runs with `CLINE_DIR=~/.cline2` by default, separate from your real `~/.cline`.
|
||||
This prevents the debugee's logout from logging out the debugger, and vice versa.
|
||||
Override with `--cline-dir /tmp/test-dir`. Check with `status()` → `clineDir`.
|
||||
|
||||
## Browser Capture & OAuth
|
||||
|
||||
The debugee runs with `CLINE_CAPTURE_BROWSER=1`, which intercepts `openExternal()` in
|
||||
`src/utils/env.ts`. URLs are captured instead of opening a real browser:
|
||||
|
||||
- Logged to `$CLINE_DIR/data/debug-captured-urls.jsonl`
|
||||
- POSTed in real-time to `/captured-url` on the harness server
|
||||
- Queryable via `oauth.captured_urls`
|
||||
|
||||
### OAuth API
|
||||
|
||||
- **`oauth.captured_urls`** `{clear?}` — URLs the debugee tried to open
|
||||
- **`oauth.read_stored_token`** — Check auth token presence in secrets.json
|
||||
- **`oauth.simulate_callback`** `{path, code?, state?, provider?, token?}` — Build vscode:// callback URI
|
||||
- **`oauth.read_captured_urls_file`** — Read on-disk JSONL of captured URLs
|
||||
|
||||
### OAuth testing flow
|
||||
|
||||
For **Cline OAuth** (SDK local callback): The SDK starts a local HTTP server, the auth URL
|
||||
is captured. To complete: open the captured URL in a real browser (it redirects back to the
|
||||
SDK's callback server), OR extract the callback port and `curl http://127.0.0.1:PORT/callback?code=...`.
|
||||
|
||||
For **MCP/Provider OAuth** (vscode:// URI): The redirect goes to a vscode:// URI.
|
||||
`oauth.simulate_callback` only *builds* the URI — it does not deliver it, and the ESM
|
||||
extension host can't `require()` the handler. To actually deliver the callback, call the
|
||||
debug-only hook via `ext.evaluate` (with `awaitPromise: true`):
|
||||
`globalThis.__clineHandleUri("vscode://saoudrizwan.claude-dev/...?code=...&state=...")`.
|
||||
It runs the same `SharedUriHandler.handleUri` as VSCode's real URI handler and exists only
|
||||
when `CLINE_CAPTURE_BROWSER` is set (the harness always sets it; never ships in prod).
|
||||
For end-to-end MCP OAuth, get a real `code` from the local MCP OAuth test server
|
||||
(`bun run dev:mcp-oauth-test-server`).
|
||||
|
||||
## Navigating Views — Use Commands, Not Clicks
|
||||
|
||||
Don't try to find/click small sidebar icons. Use VSCode commands via command palette.
|
||||
Registered in `src/registry.ts`:
|
||||
|
||||
| Command | View |
|
||||
|---------|------|
|
||||
| `cline.accountButtonClicked` | Account / sign-in |
|
||||
| `cline.historyButtonClicked` | Task history |
|
||||
| `cline.settingsButtonClicked` | Settings |
|
||||
| `cline.mcpButtonClicked` | MCP servers |
|
||||
| `cline.plusButtonClicked` | New task (chat) |
|
||||
| `cline.worktreesButtonClicked` | Worktrees |
|
||||
|
||||
```bash
|
||||
curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
|
||||
```
|
||||
|
||||
## Key commands
|
||||
|
||||
All via `POST localhost:19229/api` with `{"method":"...", "params":{...}}`:
|
||||
|
||||
- **`launch`** / **`shutdown`** — lifecycle
|
||||
- **`ui.screenshot`** — screenshot to `/tmp/cline-debug/`; returns `{path}` — **use `read_file` on the path to examine, do NOT `open` the file** (Preview.app covers the VSCode window)
|
||||
- **`ui.open_sidebar`** — open the Cline sidebar
|
||||
- **`ext.set_breakpoint`** `{file, line, condition?}` — breakpoint by source file (sourcemap-resolved)
|
||||
- **`ext.evaluate`** `{expression, callFrameId?}` — eval in extension host
|
||||
- **`ext.resume`** / **`ext.step_over`** / **`ext.step_into`** — stepping
|
||||
- **`ext.call_stack`** — inspect when paused
|
||||
- **`web.evaluate`** `{expression}` — eval in webview
|
||||
- **`web.post_message`** `{message}` — send postMessage to extension host via exposed vsCodeApi
|
||||
- **`wait_for_pause`** `{timeout?}` — block until breakpoint hit
|
||||
- **`ui.locator`** `{role?, testId?, text?, frame?}` — Playwright locator (auto-retries on stale sidebar frame)
|
||||
- **`ui.react_input`** `{text, selector?, clear?, submit?}` — set React textarea value via `execCommand('insertText')`; works reliably across multiple tasks
|
||||
- **`ui.send_message`** `{text, images?, files?, responseType?}` — send chat message bypassing the textarea entirely (via gRPC postMessage)
|
||||
- **`ui.command_palette`** `{command}` — run VSCode command
|
||||
|
||||
## Typical Session
|
||||
|
||||
```bash
|
||||
# 1. Launch
|
||||
curl localhost:19229/api -d '{"method":"launch","params":{"skipBuild":true}}'
|
||||
|
||||
# 2. Open sidebar + dismiss overlays (ALWAYS do this first)
|
||||
curl localhost:19229/api -d '{"method":"ui.open_sidebar"}'
|
||||
curl localhost:19229/api -d '{"method":"web.evaluate","params":{"expression":"document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
|
||||
|
||||
# 3. Navigate to view
|
||||
curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
|
||||
|
||||
# 4. Check captured OAuth URLs if testing auth
|
||||
curl localhost:19229/api -d '{"method":"oauth.captured_urls"}'
|
||||
|
||||
# 5. Verify
|
||||
curl localhost:19229/api -d '{"method":"ui.screenshot"}'
|
||||
```
|
||||
|
||||
## Caveats
|
||||
|
||||
- **⚠️ Dismiss promotional overlays FIRST**: On fresh launches, full-screen promo overlays block the sidebar. **Dismiss immediately after `ui.open_sidebar`**, before any other interaction or screenshot. May need to run twice:
|
||||
```bash
|
||||
curl localhost:19229/api -d '{"method": "ui.open_sidebar"}'
|
||||
curl localhost:19229/api -d '{"method": "web.evaluate", "params": {"expression": "document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
|
||||
```
|
||||
- **Screenshots — don't open the file**: `ui.screenshot` and `ui.sidebar_screenshot` save PNGs to `/tmp/cline-debug/` and return the `{path}`. Use `read_file` on that path to examine screenshots. Running `open <path>` launches Preview.app on macOS which covers the VSCode window.
|
||||
- **Scripts count = 0 after launch**: CDP connects after extension host starts, so scripts parsed during startup aren't tracked. Breakpoints still work via sourcemap resolution.
|
||||
- **Port 9230**: Extension host inspector. If another VSCode instance uses this port, the harness will fail to connect. Kill other debug instances first.
|
||||
- **macOS only** for now (Playwright Electron launch behavior).
|
||||
- **Webview CDP**: `connect_webview` may fail depending on Electron version. `web.evaluate` still works via Playwright's `frame.evaluate()` fallback.
|
||||
- **Sourcemap paths**: esbuild outputs relative paths like `../src/extension.ts` in the sourcemap. The resolver handles this, but if a file isn't found, use `ext.source_files` to see exact paths.
|
||||
- **OAuth with fake codes**: Browser capture intercepts the URL but doesn't provide a valid auth code. For real OAuth testing, open the captured URL in a browser. For unit testing, mock the token exchange.
|
||||
|
||||
See `src/dev/debug-harness/README.md` for full API reference.
|
||||
@@ -0,0 +1,204 @@
|
||||
This file is the secret sauce for working effectively in this codebase. It captures tribal knowledge—the nuanced, non-obvious patterns that make the difference between a quick fix and hours of back-and-forth & human intervention.
|
||||
|
||||
**When to add to this file:**
|
||||
- User had to intervene, correct, or hand-hold
|
||||
- Multiple back-and-forth attempts were needed to get something working
|
||||
- You discovered something that required reading many files to understand
|
||||
- A change touched files you wouldn't have guessed
|
||||
- Something worked differently than you expected
|
||||
- User explicitly asks to "add this to CLAUDE.md"
|
||||
|
||||
**Proactively suggest additions** when any of the above happen—don't wait to be asked.
|
||||
|
||||
**What NOT to add:** Stuff you can figure out from reading a few files, obvious patterns, or standard practices. This file should be high-signal, not comprehensive.
|
||||
|
||||
## Miscellaneous
|
||||
- The whole repo (including `apps/vscode`) uses **bun** for package management and task running. Emit `bun run X` / `bun install` / `bunx <bin>` / `bun file.ts`, never npm/npx. Node remains the *runtime* (VS Code's extension host and the standalone cline-core are Node), so Node-runtime tokens are legitimate and must not be "fixed" to bun — see @.clinerules/bun-and-node.md for the keep-list vs rewrite-list.
|
||||
- Avoid provider-specific string matching / hardcoded provider branches when fixing provider/config plumbing. Prefer provider metadata, shared catalog/defaults, explicit protocol/client capabilities, or centralized normalization utilities that apply by data shape rather than `providerId === "..."`. If a provider exception seems necessary, stop and explain why instead of adding ad-hoc string matching.
|
||||
- This is a VS Code extension—check `package.json` for available scripts before trying to verify builds (e.g., `bun run compile`, not `bun run build`).
|
||||
- When creating PRs, contributors should not create changelog-entry files. Maintainers handle release versioning and changelog curation during the release process.
|
||||
- When adding new feature flags, see this PR as a reference https://github.com/cline/cline/pull/7566
|
||||
- Additional instructions about making requests: @.clinerules/network.md
|
||||
|
||||
## Searching the Codebase — Avoiding Build Output
|
||||
|
||||
Several directories contain build output or generated code that produces
|
||||
noisy or unusable results with `search_files` / `grep`:
|
||||
|
||||
| Directory | What it is | Why it's a problem |
|
||||
|-----------|-----------|-------------------|
|
||||
| `out/` | esbuild bundle output | Mirrors `src/` structure as minified JS — every search gets duplicate hits on single-line files |
|
||||
| `dist/` | Packaged extension | Entire extension bundled into one minified `extension.js` (~1 long line) |
|
||||
| `dist-standalone/` | Standalone build output | Same minification issue |
|
||||
| `src/generated/` | Generated protobuf code | Auto-generated from `proto/`; not the source of truth |
|
||||
| `src/shared/proto/` | Generated proto type defs | Auto-generated from `proto/`; not the source of truth |
|
||||
| `node_modules/` | Dependencies | Huge, not project source |
|
||||
|
||||
### How to skip build output
|
||||
|
||||
**`search_files`** — Point at `src/` (not the project root) and use `file_pattern`:
|
||||
```
|
||||
search_files(path="src/core", regex="myFunction", file_pattern="*.ts")
|
||||
```
|
||||
The `file_pattern` parameter is the most effective filter — e.g. `"*.ts"`,
|
||||
`"*.tsx"`, `"*.proto"`.
|
||||
|
||||
**`grep` directly** — Exclude build dirs and restrict to source extensions:
|
||||
```bash
|
||||
grep -rn "myFunction" src/ --include="*.ts" --exclude-dir={out,dist,node_modules,generated}
|
||||
```
|
||||
|
||||
### When you must search minified files
|
||||
|
||||
Sometimes you need to verify what got bundled (e.g., checking if a change
|
||||
made it into the build). Minified files are typically one long line, so
|
||||
normal `grep` shows the entire file as context. Use these approaches:
|
||||
|
||||
- **`grep -oP`** to extract just the match with limited surrounding context:
|
||||
```bash
|
||||
grep -oP '.{0,40}myFunction.{0,40}' dist/extension.js
|
||||
```
|
||||
- **`read_file`** on files in `out/src/` — these have source maps and are
|
||||
more readable than `dist/extension.js` (which is the fully bundled output).
|
||||
- **Source maps** — `out/src/*.js.map` and `dist/extension.js.map` can be
|
||||
used to trace minified output back to original source locations.
|
||||
|
||||
## gRPC/Protobuf Communication
|
||||
The extension and webview communicate via gRPC-like protocol over VS Code message passing.
|
||||
|
||||
**Proto files live in `proto/`** (e.g., `proto/cline/task.proto`, `proto/cline/ui.proto`)
|
||||
- Each feature domain has its own `.proto` file
|
||||
- For simple data, use shared types in `proto/cline/common.proto` (`StringRequest`, `Empty`, `Int64Request`)
|
||||
- For complex data, define custom messages in the feature's `.proto` file
|
||||
- Naming: Services `PascalCaseService`, RPCs `camelCase`, Messages `PascalCase`
|
||||
- For streaming responses, use `stream` keyword (see `subscribeToAuthCallback` in `account.proto`)
|
||||
|
||||
**Run `bun run protos`** after any proto changes—generates types in:
|
||||
- `src/shared/proto/` - Shared type definitions
|
||||
- `src/generated/grpc-js/` - Service implementations
|
||||
- `src/generated/nice-grpc/` - Promise-based clients
|
||||
- `src/generated/hosts/` - Generated handlers
|
||||
|
||||
**Adding new enum values** (like a new `ClineSay` type) requires updating conversion mappings in `src/shared/proto-conversions/cline-message.ts`
|
||||
|
||||
**Adding new RPC methods** requires:
|
||||
- Handler in `src/core/controller/<domain>/`
|
||||
- Call from webview via generated client: `UiServiceClient.scrollToSettings(StringRequest.create({ value: "browser" }))`
|
||||
|
||||
**Example—the `explain-changes` feature touched:**
|
||||
- `proto/cline/task.proto` - Added `ExplainChangesRequest` message and `explainChanges` RPC
|
||||
- `proto/cline/ui.proto` - Added `GENERATE_EXPLANATION = 29` to `ClineSay` enum
|
||||
- `src/shared/ExtensionMessage.ts` - Added `ClineSayGenerateExplanation` type
|
||||
- `src/shared/proto-conversions/cline-message.ts` - Added mapping for new say type
|
||||
- `src/core/controller/task/explainChanges.ts` - Handler implementation
|
||||
- `webview-ui/src/components/chat/ChatRow.tsx` - UI rendering
|
||||
|
||||
## Adding New Global State Keys
|
||||
Adding a new key to global state requires updates in multiple places. Missing any step causes silent failures.
|
||||
|
||||
Required steps:
|
||||
1. Type definition in `src/shared/storage/state-keys.ts` - Add to `GlobalState` or `Settings` interface
|
||||
2. Add any default value or transform in `src/shared/storage/state-keys.ts` if the key needs one
|
||||
3. Read and write the value through `StateManager` (`setGlobalState()` / `getGlobalStateKey()`) after initialization
|
||||
|
||||
Persistent state is file-backed through `StateManager`; do not add new runtime reads or writes against VS Code `ExtensionContext` storage. That storage is only a legacy migration source.
|
||||
|
||||
Settings plumbing gotcha: if a key is user-toggleable from settings, wire both controller update paths:
|
||||
- `src/core/controller/state/updateSettings.ts` for webview `updateSetting(...)`
|
||||
- `src/core/controller/state/updateSettingsCli.ts` for CLI/ACP settings updates
|
||||
Missing one path causes a toggle to appear to change in one surface while the backend state stays unchanged.
|
||||
|
||||
Webview toggle gotcha: settings changes must also round-trip back in state payloads.
|
||||
- Add the field to `UpdateSettingsRequest` in `proto/cline/state.proto` (for webview update requests), then run `bun run protos`
|
||||
- Include the key in `Controller.getStateToPostToWebview()` (`src/core/controller/index.ts`)
|
||||
- Ensure `ExtensionState` and webview defaults include the key (`src/shared/ExtensionMessage.ts`, `webview-ui/src/context/ExtensionStateContext.tsx`)
|
||||
If this round-trip wiring is missing, the backend value can update but the toggle in webview appears stuck or reverts.
|
||||
|
||||
## StateManager Cache vs Direct globalState Access
|
||||
StateManager uses an in-memory cache populated during `StateManager.initialize()` from file-backed storage. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
|
||||
|
||||
Exception: host migration code may read legacy VS Code storage before file-backed storage is initialized.
|
||||
|
||||
Example pattern:
|
||||
```typescript
|
||||
// Writing (normal pattern)
|
||||
controller.stateManager.setGlobalState("myKey", value)
|
||||
|
||||
// Reading after initialization
|
||||
const value = controller.stateManager.getGlobalStateKey("myKey")
|
||||
```
|
||||
|
||||
Use `context.globalState` only in VS Code migration code that copies legacy ExtensionContext values into the shared file-backed stores.
|
||||
|
||||
## ChatRow Cancelled/Interrupted States
|
||||
When a ChatRow displays a loading/in-progress state (spinner), you must handle what happens when the task is cancelled. This is non-obvious because cancellation doesn't update the message content—you have to infer it from context.
|
||||
|
||||
**The pattern:**
|
||||
1. A message has a `status` field (e.g., `"generating"`, `"complete"`, `"error"`) stored in `message.text` as JSON
|
||||
2. When cancelled mid-operation, the status stays `"generating"` forever—no one updates it
|
||||
3. To detect cancellation, check TWO conditions:
|
||||
- `!isLast` — if this message is no longer the last message, something else happened after it (interrupted)
|
||||
- `lastModifiedMessage?.ask === "resume_task" || "resume_completed_task"` — task was just cancelled and is waiting to resume
|
||||
|
||||
**Example from `generate_explanation`:**
|
||||
```tsx
|
||||
const wasCancelled =
|
||||
explanationInfo.status === "generating" &&
|
||||
(!isLast ||
|
||||
lastModifiedMessage?.ask === "resume_task" ||
|
||||
lastModifiedMessage?.ask === "resume_completed_task")
|
||||
const isGenerating = explanationInfo.status === "generating" && !wasCancelled
|
||||
```
|
||||
|
||||
**Why both checks?**
|
||||
- `!isLast` catches: cancelled → resumed → did other stuff → this old message is stale
|
||||
- `lastModifiedMessage?.ask === "resume_task"` catches: just cancelled, hasn't resumed yet, this message is still technically "last"
|
||||
|
||||
**See also:** `BrowserSessionRow.tsx` uses similar pattern with `isLastApiReqInterrupted` and `isLastMessageResume`.
|
||||
|
||||
**Backend side:** When streaming is cancelled, clean up properly (close tabs, clear comments, etc.) by checking `taskState.abort` after the streaming function returns.
|
||||
|
||||
## Debug Harness: clear inherited VSCode/Electron env vars before launching
|
||||
|
||||
The debug harness (`apps/vscode/src/dev/debug-harness/server.ts`) launches a child
|
||||
VSCode via Playwright's `_electron.launch({ env: { ...process.env, ... } })`. If you
|
||||
run the harness from a process that was itself spawned by VSCode (e.g. the Cline
|
||||
extension host, an integrated terminal, or an agent running inside VSCode), the
|
||||
parent's VSCode/Electron env vars leak into the child and break the launch.
|
||||
|
||||
The fatal one is **`ELECTRON_RUN_AS_NODE=1`**: it makes the child VSCode binary run
|
||||
as plain Node, so it rejects every VSCode CLI flag. Symptom:
|
||||
|
||||
```
|
||||
.../Visual Studio Code.app/Contents/MacOS/Code: bad option: --extensionDevelopmentPath=...
|
||||
Error: Process failed to launch! (Playwright _electron.launch)
|
||||
```
|
||||
|
||||
This is NOT the macOS Playwright flakiness mentioned in the harness README — it's
|
||||
env inheritance. Fix: strip the inherited vars before starting the harness:
|
||||
|
||||
```bash
|
||||
env -u ELECTRON_RUN_AS_NODE -u ELECTRON_NO_ATTACH_CONSOLE \
|
||||
-u VSCODE_CLI -u VSCODE_CODE_CACHE_PATH -u VSCODE_CRASH_REPORTER_PROCESS_TYPE \
|
||||
-u VSCODE_CWD -u VSCODE_ESM_ENTRYPOINT -u VSCODE_HANDLES_UNCAUGHT_ERRORS \
|
||||
-u VSCODE_IPC_HOOK -u VSCODE_NLS_CONFIG -u VSCODE_PID -u VSCODE_L10N_BUNDLE_LOCATION \
|
||||
bun src/dev/debug-harness/server.ts --auto-launch --skip-build
|
||||
```
|
||||
|
||||
Check your own env with `env | grep -iE 'electron|vscode_'` first; `ELECTRON_RUN_AS_NODE=1`
|
||||
present means you must scrub before launching.
|
||||
|
||||
Other harness notes confirmed in practice:
|
||||
- The extension host is **ESM** (`VSCODE_ESM_ENTRYPOINT`), so `ext.evaluate` has no
|
||||
`require` and module-internal functions aren't reachable as globals. To inspect
|
||||
internal builders (e.g. `buildBedrockProviderConfig`), set a breakpoint with
|
||||
`ext.set_breakpoint` and read locals via `ext.evaluate` with the paused `callFrameId`
|
||||
— don't try to `require()` the bundle.
|
||||
- `web.evaluate` wraps the expression as a single returned expression; multi-statement
|
||||
snippets must be an IIFE `(() => { ...; return x; })()`, otherwise you get
|
||||
`SyntaxError: Unexpected token ';'`.
|
||||
- Webview settings inputs are `vscode-text-field` web components with debounced React
|
||||
onChange. Setting `.value` + dispatching events via `web.evaluate` is unreliable for
|
||||
some fields; focus the inner shadow `input` then use real keystrokes (`ui.type` +
|
||||
`ui.press Tab`, or click the dropdown option) to make the value persist.
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
# Cline Hooks Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
Cline hooks allow you to execute custom scripts at specific points in the agentic workflow. Hooks can be placed in either:
|
||||
- **Global hooks directory**: `~/Documents/Cline/Hooks/` (applies to all workspaces)
|
||||
- **Workspace hooks directory**: `.clinerules/hooks/` (applies to the workspace the repo is part of)
|
||||
|
||||
Hooks run automatically when enabled.
|
||||
|
||||
## Enabling Hooks
|
||||
|
||||
1. Open Cline settings in VSCode
|
||||
2. Navigate to the Feature Settings section
|
||||
3. Check the "Enable Hooks" checkbox
|
||||
4. Hooks must be executable files (on Unix/Linux/macOS use `chmod +x hookname`)
|
||||
|
||||
## Available Hooks
|
||||
|
||||
### TaskStart Hook
|
||||
- **When**: Runs when a NEW task is started (not when resuming)
|
||||
- **Purpose**: Initialize task context, validate task requirements, set up environment
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/TaskStart`
|
||||
- **Workspace Location**: `.clinerules/hooks/TaskStart`
|
||||
|
||||
### TaskResume Hook
|
||||
- **When**: Runs when an EXISTING task is resumed (after user clicks resume button)
|
||||
- **Purpose**: Validate resumed task state, restore context, check for changes since last run
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/TaskResume`
|
||||
- **Workspace Location**: `.clinerules/hooks/TaskResume`
|
||||
|
||||
### TaskCancel Hook
|
||||
- **When**: Runs when a task is cancelled or a hook is aborted by the user (only if there's actual active work or work was started)
|
||||
- **Purpose**: Clean up resources, log cancellation, save state
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/TaskCancel`
|
||||
- **Workspace Location**: `.clinerules/hooks/TaskCancel`
|
||||
- **Note**: This hook is NOT cancellable
|
||||
|
||||
### TaskComplete Hook (coming soon!)
|
||||
- **When**: Runs when a task is marked as complete
|
||||
- **Purpose**: Log completion status, perform final cleanup, generate reports
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/TaskComplete`
|
||||
- **Workspace Location**: `.clinerules/hooks/TaskComplete`
|
||||
|
||||
### UserPromptSubmit Hook
|
||||
- **When**: Runs when the user submits a prompt/message (initial task, resume, or feedback)
|
||||
- **Purpose**: Validate user input, preprocess prompts, add context to user messages
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/UserPromptSubmit`
|
||||
- **Workspace Location**: `.clinerules/hooks/UserPromptSubmit`
|
||||
|
||||
### PreToolUse Hook
|
||||
- **When**: Runs BEFORE a tool is executed
|
||||
- **Purpose**: Validate parameters, block execution, or add context
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/PreToolUse`
|
||||
- **Workspace Location**: `.clinerules/hooks/PreToolUse`
|
||||
|
||||
### PostToolUse Hook
|
||||
- **When**: Runs AFTER a tool completes
|
||||
- **Purpose**: Observe results, track patterns, or add context
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/PostToolUse`
|
||||
- **Workspace Location**: `.clinerules/hooks/PostToolUse`
|
||||
|
||||
### PreCompact Hook (coming soon!)
|
||||
- **When**: Runs BEFORE the conversation context is compacted/truncated
|
||||
- **Purpose**: Observe compaction events, log context management, track token usage
|
||||
- **Global Location**: `~/Documents/Cline/Hooks/PreCompact`
|
||||
- **Workspace Location**: `.clinerules/hooks/PreCompact`
|
||||
|
||||
## Cross-Platform Hook Format
|
||||
|
||||
Cline uses a git-style approach for hooks that works consistently across all platforms:
|
||||
|
||||
### Hook Files (All Platforms)
|
||||
- **No file extensions**: Hooks are named exactly `PreToolUse` or `PostToolUse` (no `.bat`, `.cmd`, `.sh` etc.)
|
||||
- **Shebang required**: First line must be a shebang (e.g., `#!/usr/bin/env bash` or `#!/usr/bin/env node`)
|
||||
- **Executable on Unix**: On Unix/Linux/macOS, hooks must be executable: `chmod +x PreToolUse`
|
||||
- **Windows**: Not currently supported.
|
||||
|
||||
### How It Works
|
||||
|
||||
Like git hooks, Cline executes hook files through a shell that interprets the shebang line:
|
||||
- On Unix/Linux/macOS: Native shell execution with shebang support
|
||||
|
||||
This means:
|
||||
- ✅ Same hook script works on all platforms
|
||||
- ✅ Write once, run anywhere
|
||||
- ✅ Use any scripting language (bash, node, python, etc.)
|
||||
|
||||
### Creating Hooks
|
||||
|
||||
**On Unix/Linux/macOS:**
|
||||
```bash
|
||||
# Create hook file
|
||||
nano ~/Documents/Cline/Hooks/PreToolUse
|
||||
|
||||
# Make executable
|
||||
chmod +x ~/Documents/Cline/Hooks/PreToolUse
|
||||
```
|
||||
|
||||
## Context Injection Timing
|
||||
|
||||
**IMPORTANT**: Context injected by hooks affects **FUTURE AI decisions**, not the current tool execution.
|
||||
|
||||
### Why This Matters
|
||||
|
||||
When a hook runs:
|
||||
1. The AI has already decided what tool to use and with what parameters
|
||||
2. The hook cannot modify those parameters
|
||||
3. Context from the hook is added to the conversation
|
||||
4. The AI sees this context in the **NEXT API request** and can adjust future decisions
|
||||
|
||||
### PreToolUse Hook Flow
|
||||
```
|
||||
1. AI decides: "I'll use write_to_file with these parameters"
|
||||
2. PreToolUse hook runs → can block or add context
|
||||
3. If allowed, tool executes with original parameters
|
||||
4. Context is added to conversation
|
||||
5. Next API request includes this context
|
||||
6. AI adjusts future decisions based on context
|
||||
```
|
||||
|
||||
### PostToolUse Hook Flow
|
||||
```
|
||||
1. Tool completes execution
|
||||
2. PostToolUse hook runs → observes results
|
||||
3. Hook adds context about the outcome
|
||||
4. Context is added to conversation
|
||||
5. Next API request includes this context
|
||||
6. AI can learn from the results
|
||||
```
|
||||
|
||||
## Hook Input/Output
|
||||
|
||||
### Input (via stdin as JSON)
|
||||
|
||||
All hooks receive:
|
||||
```json
|
||||
{
|
||||
"clineVersion": "string",
|
||||
"hookName": "TaskStart" | "TaskResume" | "TaskCancel" | "TaskComplete" | "UserPromptSubmit" | "PreToolUse" | "PostToolUse" | "PreCompact",
|
||||
"timestamp": "string",
|
||||
"taskId": "string",
|
||||
"workspaceRoots": ["string"],
|
||||
"userId": "string",
|
||||
"taskStart": { // Only for TaskStart
|
||||
"taskMetadata": {
|
||||
"taskId": "string",
|
||||
"ulid": "string",
|
||||
"initialTask": "string"
|
||||
}
|
||||
},
|
||||
"taskResume": { // Only for TaskResume
|
||||
"taskMetadata": {
|
||||
"taskId": "string",
|
||||
"ulid": "string"
|
||||
},
|
||||
"previousState": {
|
||||
"lastMessageTs": "string",
|
||||
"messageCount": "string",
|
||||
"conversationHistoryDeleted": "string"
|
||||
}
|
||||
},
|
||||
"taskCancel": { // Only for TaskCancel
|
||||
"taskMetadata": {
|
||||
"taskId": "string",
|
||||
"ulid": "string",
|
||||
"completionStatus": "string"
|
||||
}
|
||||
},
|
||||
"taskComplete": { // Only for TaskComplete
|
||||
"taskMetadata": {
|
||||
"taskId": "string",
|
||||
"ulid": "string"
|
||||
}
|
||||
},
|
||||
"userPromptSubmit": { // Only for UserPromptSubmit
|
||||
"prompt": "string",
|
||||
"attachments": ["string"]
|
||||
},
|
||||
"preToolUse": { // Only for PreToolUse
|
||||
"toolName": "string",
|
||||
"parameters": {}
|
||||
},
|
||||
"postToolUse": { // Only for PostToolUse
|
||||
"toolName": "string",
|
||||
"parameters": {},
|
||||
"result": "string",
|
||||
"success": boolean,
|
||||
"executionTimeMs": number
|
||||
},
|
||||
"preCompact": { // Only for PreCompact
|
||||
"contextSize": number,
|
||||
"messagesToCompact": number,
|
||||
"compactionStrategy": "string"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Output (via stdout as JSON)
|
||||
|
||||
All hooks must return:
|
||||
```json
|
||||
{
|
||||
"cancel": boolean, // Required: false to continue, true to block execution
|
||||
"contextModification": "string", // Optional: Context for future AI decisions
|
||||
"errorMessage": "string" // Optional: Error details if blocking
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: The `cancel` field works as follows:
|
||||
- `false` (or omitted): Allow execution to continue
|
||||
- `true`: Block execution and show error message to user
|
||||
|
||||
## Hook Execution Limits
|
||||
|
||||
- **Timeout**: Hooks must complete within 30 seconds (configurable via `HOOK_EXECUTION_TIMEOUT_MS`)
|
||||
- **Context Size**: Context modifications are limited to 50KB (configurable via `MAX_CONTEXT_MODIFICATION_SIZE`)
|
||||
- **Error Handling**: Expected errors (file not found, permission denied, not a directory) are handled silently; unexpected file system errors are propagated
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### 1. Validation - Block Invalid Operations
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
input=$(cat)
|
||||
tool_name=$(echo "$input" | jq -r '.preToolUse.toolName')
|
||||
path=$(echo "$input" | jq -r '.preToolUse.parameters.path // ""')
|
||||
|
||||
if [[ "$tool_name" == "write_to_file" && "$path" == *.js ]]; then
|
||||
cat <<EOF
|
||||
{
|
||||
"cancel": true,
|
||||
"errorMessage": "Cannot create .js files in TypeScript project",
|
||||
"contextModification": "Use .ts/.tsx extensions only"
|
||||
}
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo '{"cancel": false}'
|
||||
```
|
||||
|
||||
### 2. Context Building - Learn from Operations
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
input=$(cat)
|
||||
tool_name=$(echo "$input" | jq -r '.postToolUse.toolName')
|
||||
success=$(echo "$input" | jq -r '.postToolUse.success')
|
||||
path=$(echo "$input" | jq -r '.postToolUse.parameters.path // ""')
|
||||
|
||||
if [[ "$tool_name" == "write_to_file" && "$success" == "true" ]]; then
|
||||
cat <<EOF
|
||||
{
|
||||
"cancel": false,
|
||||
"contextModification": "Created '$path'. Maintain consistency with this file's patterns in future operations."
|
||||
}
|
||||
EOF
|
||||
else
|
||||
echo '{"cancel": false}'
|
||||
fi
|
||||
```
|
||||
|
||||
### 3. Performance Monitoring
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
input=$(cat)
|
||||
execution_time=$(echo "$input" | jq -r '.postToolUse.executionTimeMs')
|
||||
tool_name=$(echo "$input" | jq -r '.postToolUse.toolName')
|
||||
|
||||
if [[ "$execution_time" -gt 5000 ]]; then
|
||||
cat <<EOF
|
||||
{
|
||||
"cancel": false,
|
||||
"contextModification": "Tool '$tool_name' took ${execution_time}ms. Consider optimizing future similar operations."
|
||||
}
|
||||
EOF
|
||||
else
|
||||
echo '{"cancel": false}'
|
||||
fi
|
||||
```
|
||||
|
||||
### 4. Logging and Telemetry
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
input=$(cat)
|
||||
|
||||
# Log to file
|
||||
echo "$input" >> ~/.cline/hook-logs/tool-usage.jsonl
|
||||
|
||||
# Allow execution
|
||||
echo '{"cancel": false}'
|
||||
```
|
||||
|
||||
## Global vs Workspace Hooks
|
||||
|
||||
Cline supports two levels of hooks:
|
||||
|
||||
### Global Hooks
|
||||
- **Location**: `~/Documents/Cline/Hooks/` (macOS/Linux)
|
||||
- **Scope**: Apply to ALL workspaces and projects
|
||||
- **Use Case**: Organization-wide policies, personal preferences, universal validations
|
||||
- **Priority**: Order not guaranteed when combined with workspace hooks
|
||||
|
||||
### Workspace Hooks
|
||||
- **Location**: `.clinerules/hooks/` in each workspace root
|
||||
- **Scope**: Apply only to the specific workspace
|
||||
- **Use Case**: Project-specific rules, team conventions, repository requirements
|
||||
- **Priority**: Order not guaranteed when combined with global hooks
|
||||
|
||||
### Hook Execution
|
||||
|
||||
When multiple hooks exist (global and/or workspace):
|
||||
- All hooks for a given step are executed **concurrently** using `Promise.all`
|
||||
- **Execution order is not guaranteed** - hooks run in parallel
|
||||
- If ALL hooks allow execution (`cancel: false`), the tool proceeds
|
||||
- If ANY hook blocks (`cancel: true`), execution is blocked
|
||||
|
||||
**Result Combination:**
|
||||
- `cancel`: If ANY hook returns `true`, execution is blocked
|
||||
- `contextModification`: All context strings are concatenated with double newlines (`\n\n`)
|
||||
- `errorMessage`: All error messages are concatenated with single newlines (`\n`)
|
||||
|
||||
### Setting Up Global Hooks
|
||||
|
||||
1. The global hooks directory is automatically created at:
|
||||
- macOS/Linux: `~/Documents/Cline/Hooks/`
|
||||
|
||||
2. Add your hook script:
|
||||
```bash
|
||||
# Unix/Linux/macOS
|
||||
nano ~/Documents/Cline/Hooks/PreToolUse
|
||||
chmod +x ~/Documents/Cline/Hooks/PreToolUse
|
||||
```
|
||||
|
||||
3. Enable hooks in Cline settings
|
||||
|
||||
### Example: Global + Workspace Hooks
|
||||
|
||||
**Global Hook** (applies to all projects):
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
# ~/Documents/Cline/Hooks/PreToolUse
|
||||
# Universal rule: Never delete package.json
|
||||
input=$(cat)
|
||||
tool_name=$(echo "$input" | jq -r '.preToolUse.toolName')
|
||||
path=$(echo "$input" | jq -r '.preToolUse.parameters.path // ""')
|
||||
|
||||
if [[ "$tool_name" == "write_to_file" && "$path" == *"package.json"* ]]; then
|
||||
echo '{"cancel": true, "errorMessage": "Global policy: Cannot modify package.json"}'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo '{"cancel": false}'
|
||||
```
|
||||
|
||||
**Workspace Hook** (applies to specific project):
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
# .clinerules/hooks/PreToolUse
|
||||
# Project rule: Only TypeScript files
|
||||
input=$(cat)
|
||||
tool_name=$(echo "$input" | jq -r '.preToolUse.toolName')
|
||||
path=$(echo "$input" | jq -r '.preToolUse.parameters.path // ""')
|
||||
|
||||
if [[ "$tool_name" == "write_to_file" && "$path" == *.js ]]; then
|
||||
echo '{"cancel": true, "errorMessage": "Project rule: Use .ts files only"}'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo '{"cancel": false}'
|
||||
```
|
||||
|
||||
**All hooks must allow execution for the tool to proceed.** Hooks may execute concurrently.
|
||||
|
||||
## Multi-Root Workspaces
|
||||
|
||||
If you have multiple workspace roots, you can place hooks in each root's `.clinerules/hooks/` directory. All hooks (global and workspace) may execute concurrently. Their results will be combined:
|
||||
|
||||
- **cancel**: If ANY hook returns `true`, execution is blocked
|
||||
- **contextModification**: All context modifications are concatenated
|
||||
- **errorMessage**: All error messages are concatenated
|
||||
|
||||
**Note:** No execution order is guaranteed between hooks from different directories.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Hook Not Running
|
||||
- Ensure the "Enable Hooks" setting is checked
|
||||
- Verify the hook file is executable (`chmod +x hookname`)
|
||||
- Check the hook file has no syntax errors
|
||||
- Look for errors in VSCode's Output panel (Cline channel)
|
||||
|
||||
### Hook Timing Out
|
||||
- Reduce complexity of the hook script
|
||||
- Avoid expensive operations (network calls, heavy computations)
|
||||
- Consider moving complex logic to a background process
|
||||
|
||||
### Context Not Affecting Behavior
|
||||
- Remember: context affects FUTURE decisions, not the current tool
|
||||
- Ensure context modifications are clear and actionable
|
||||
- Check that context isn't being truncated (50KB limit)
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- Hooks run with the same permissions as VSCode
|
||||
- Be cautious with hooks from untrusted sources
|
||||
- Review hook scripts before enabling them
|
||||
- Consider using `.gitignore` to avoid committing sensitive hook logic
|
||||
- Hooks can access all workspace files and environment variables
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep hooks fast** - Aim for <100ms execution time
|
||||
2. **Make context actionable** - Be specific about what the AI should do
|
||||
3. **Use structured prefixes** - Help the AI categorize context
|
||||
4. **Handle errors gracefully** - Always return valid JSON
|
||||
5. **Log for debugging** - Keep logs of hook executions for troubleshooting
|
||||
6. **Test incrementally** - Start with simple hooks and add complexity
|
||||
7. **Document your hooks** - Add comments explaining the purpose and logic
|
||||
@@ -0,0 +1,90 @@
|
||||
# Networking & Proxy Support
|
||||
|
||||
To ensure Cline works correctly in all environments (VSCode, JetBrains, CLI) and with various network configurations (especially corporate proxies), strictly follow these guidelines for all network activity.
|
||||
|
||||
In extension code, do NOT use the global `fetch` or a default `axios` instance. (Note, `shared/net.ts` is exempt from these rules because it sets up the fetch wrappers.) In Webview code, you SHOULD use global `fetch`.
|
||||
|
||||
Global `fetch` and default `axios` do not automatically pick up proxy configurations in all environments (specifically JetBrains and CLI). You MUST use the provided utilities in `@/shared/net` which handle proxy agent configuration. In the webview, the browser/embedder handles proxies.
|
||||
|
||||
## Guidelines
|
||||
|
||||
### 1. Using `fetch`
|
||||
|
||||
Instead of `fetch(...)`, import the proxy-aware wrapper:
|
||||
|
||||
```typescript
|
||||
import { fetch } from '@/shared/net'
|
||||
|
||||
// Usage is identical to global fetch
|
||||
const response = await fetch('https://api.example.com/data')
|
||||
```
|
||||
|
||||
### 2. Using `axios`
|
||||
|
||||
When using `axios`, you must apply the settings from `getAxiosSettings()`:
|
||||
|
||||
```typescript
|
||||
import axios from 'axios'
|
||||
import { getAxiosSettings } from '@/shared/net'
|
||||
|
||||
const response = await axios.get('https://api.example.com/data', {
|
||||
headers: { 'Authorization': '...' },
|
||||
...getAxiosSettings() // <--- CRITICAL: Injects the proxy agent if needed
|
||||
})
|
||||
```
|
||||
|
||||
### 3. Third-Party Clients (OpenAI, Ollama, etc.)
|
||||
|
||||
Most API client libraries allow you to customize the `fetch` implementation. You **MUST** pass the proxy-aware `fetch` to these clients.
|
||||
|
||||
**Example (OpenAI):**
|
||||
```typescript
|
||||
import OpenAI from "openai"
|
||||
import { fetch } from "@/shared/net"
|
||||
|
||||
this.client = new OpenAI({
|
||||
apiKey: '...',
|
||||
fetch, // <--- CRITICAL: Pass our fetch wrapper
|
||||
})
|
||||
```
|
||||
|
||||
### 4. Tests
|
||||
|
||||
Use `mockFetchForTesting` to mock the underlying fetch implementation.
|
||||
|
||||
**Example (callback):**
|
||||
|
||||
```
|
||||
import { mockFetchForTesting } from "@/shared/net"
|
||||
|
||||
...
|
||||
let mockFetch = ...
|
||||
mockFetchForTesting(mockFetch, () => {
|
||||
// This calls mockFetch
|
||||
fetch('https://foo.example').then(...)
|
||||
})
|
||||
// Original fetch is restored immediately when the call returns.
|
||||
```
|
||||
|
||||
**Example (Promise):**
|
||||
|
||||
```
|
||||
import { mockFetchForTesting } from "@/shared/net"
|
||||
|
||||
...
|
||||
let mockFetch = ...
|
||||
await mockFetchForTesting(mockFetch, async () => {
|
||||
await ...
|
||||
// This calls mockFetch
|
||||
await fetch('https://foo.example')
|
||||
...
|
||||
})
|
||||
// Original fetch is restored when the Promise from the callback settles
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
If you are adding a new network call or integration:
|
||||
1. Check `@/shared/net.ts` is imported.
|
||||
2. Ensure `fetch` or `getAxiosSettings` is being used.
|
||||
3. Verify that third-party clients are configured to use the custom fetch.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Cline Protobuf Development Guide
|
||||
|
||||
This guide outlines how to add new gRPC endpoints for communication between the webview (frontend) and the extension host (backend).
|
||||
|
||||
## Overview
|
||||
|
||||
Cline uses [Protobuf](https://protobuf.dev/) to define a strongly-typed API, ensuring efficient and type-safe communication. All definitions are in the `/proto` directory. The compiler and plugins are included as project dependencies, so no manual installation is needed.
|
||||
|
||||
## Key Concepts & Best Practices
|
||||
|
||||
- **File Structure**: Each feature domain should have its own `.proto` file (e.g., `account.proto`, `task.proto`).
|
||||
- **Message Design**:
|
||||
- For simple, single-value data, use the shared types in `proto/common.proto` (e.g., `StringRequest`, `Empty`, `Int64Request`). This promotes consistency.
|
||||
- For complex data structures, define custom messages within the feature's `.proto` file (see `task.proto` for examples like `NewTaskRequest`).
|
||||
- **Naming Conventions**:
|
||||
- Services: `PascalCaseService` (e.g., `AccountService`).
|
||||
- RPCs: `camelCase` (e.g., `accountEmailIdentified`).
|
||||
- Messages: `PascalCase` (e.g., `StringRequest`).
|
||||
- **Streaming**: For server-to-client streaming, use the `stream` keyword on the response type. See `subscribeToAuthCallback` in `account.proto` for an example.
|
||||
|
||||
---
|
||||
|
||||
## 4-Step Development Workflow
|
||||
|
||||
Here’s how to add a new RPC, using `scrollToSettings` as an example.
|
||||
|
||||
### 1. Define the RPC in a `.proto` File
|
||||
|
||||
Add your service method to the appropriate file in the `proto/` directory.
|
||||
|
||||
**File: `proto/ui.proto`**
|
||||
```proto
|
||||
service UiService {
|
||||
// ... other RPCs
|
||||
// Scrolls to a specific settings section in the settings view
|
||||
rpc scrollToSettings(StringRequest) returns (KeyValuePair);
|
||||
}
|
||||
```
|
||||
Here, we use the common `StringRequest` and `KeyValuePair` types.
|
||||
|
||||
### 2. Compile Definitions
|
||||
|
||||
After editing a `.proto` file, regenerate the TypeScript code. From the project root, run:
|
||||
```bash
|
||||
bun run protos
|
||||
```
|
||||
This command compiles all `.proto` files and outputs the generated code to `src/generated/` and `src/shared/`. Do not edit these generated files manually.
|
||||
|
||||
### 3. Implement the Backend Handler
|
||||
|
||||
Create the RPC implementation in the backend. Handlers are located in `src/core/controller/[service-name]/`.
|
||||
|
||||
**File: `src/core/controller/ui/scrollToSettings.ts`**
|
||||
```typescript
|
||||
import { Controller } from ".."
|
||||
import { StringRequest, KeyValuePair } from "../../../shared/proto/common"
|
||||
|
||||
/**
|
||||
* Executes a scroll to settings action
|
||||
* @param controller The controller instance
|
||||
* @param request The request containing the ID of the settings section to scroll to
|
||||
* @returns KeyValuePair with action and value fields for the UI to process
|
||||
*/
|
||||
export async function scrollToSettings(controller: Controller, request: StringRequest): Promise<KeyValuePair> {
|
||||
return KeyValuePair.create({
|
||||
key: "scrollToSettings",
|
||||
value: request.value || "",
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Call the RPC from the Webview
|
||||
|
||||
Call the new RPC from a React component in `webview-ui/`. The generated client makes this simple.
|
||||
|
||||
**File: `webview-ui/src/components/browser/BrowserSettingsMenu.tsx`** (Example)
|
||||
```tsx
|
||||
import { UiServiceClient } from "../../../services/grpc"
|
||||
import { StringRequest } from "../../../../shared/proto/common"
|
||||
|
||||
// ... inside a React component
|
||||
const handleMenuClick = async () => {
|
||||
try {
|
||||
await UiServiceClient.scrollToSettings(StringRequest.create({ value: "browser" }))
|
||||
} catch (error) {
|
||||
console.error("Error scrolling to browser settings:", error)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
# SDK Adapter
|
||||
|
||||
The VSCode extension runs on the Cline SDK (`@cline/core`, `@cline/llms`,
|
||||
`@cline/shared`) through an adapter layer in `apps/vscode/src/sdk/`. The
|
||||
webview still talks gRPC; the adapter translates between gRPC handlers and SDK
|
||||
calls. See `apps/vscode/src/dev/debug-harness/README.md` for the debug harness.
|
||||
|
||||
## Conventions
|
||||
|
||||
1. **Look up SDK APIs, don't guess.** Use `kb_search(name="sdk", query="...")`
|
||||
before implementing against an SDK surface.
|
||||
2. **Reference the pre-SDK implementation when replacing a module.** Add a
|
||||
`// Replaces classic src/core/... (see origin/main)` header and use
|
||||
`kb_search(name="cline", commit="origin/main")` or
|
||||
`git show origin/main:path` to consult the prior implementation.
|
||||
3. **Single entry point.** There is one codepath — the SDK adapter. No
|
||||
`CLINE_SDK` env flag.
|
||||
4. **Use `{appBaseUrl}`**, never hardcode `app.cline.bot`.
|
||||
5. **Avoid `as` casts.** Use explicit conversion functions with tests. The
|
||||
branded types in `apps/vscode/src/sdk/model-catalog/contracts.ts` exist so
|
||||
casts are unnecessary outside parse/compute boundaries.
|
||||
|
||||
## Debug harness
|
||||
|
||||
- **Dismiss the Kanban/promo overlay** before any debug harness interaction.
|
||||
- **Use the command palette** to navigate tabs in the debug harness.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Storage Architecture
|
||||
|
||||
Global settings, secrets and workspace state are stored in **file-backed JSON stores** under `~/.cline/data/`. This is the shared storage layer used by VSCode, CLI, and JetBrains.
|
||||
|
||||
## Key Abstractions
|
||||
|
||||
### `StorageContext` (src/shared/storage/storage-context.ts)
|
||||
The entry point. Created via `createStorageContext()` and passed to `StateManager.initialize()`. Contains three `ClineFileStorage` instances:
|
||||
- `globalState` → `~/.cline/data/globalState.json`
|
||||
- `secrets` → `~/.cline/data/secrets.json` (mode 0o600)
|
||||
- `workspaceState` → `~/.cline/data/workspaces/<hash>/workspaceState.json`
|
||||
|
||||
### `ClineFileStorage` (src/shared/storage/ClineFileStorage.ts)
|
||||
Synchronous JSON key-value store backed by a single file. Supports `get()`, `set()`, `setBatch()`, `delete()`. Writes are atomic (write-then-rename).
|
||||
|
||||
### `StateManager` (src/core/storage/StateManager.ts)
|
||||
In-memory cache on top of `StorageContext`. All runtime reads hit the cache; writes update cache immediately and debounce-flush to disk.
|
||||
|
||||
## ⚠️ Do NOT Use VSCode's ExtensionContext for Storage
|
||||
|
||||
**Do not** read from or write to `context.globalState`, `context.workspaceState`, or `context.secrets` for persistent data. These are VSCode-specific and not available on CLI or JetBrains.
|
||||
|
||||
Instead, use:
|
||||
```typescript
|
||||
// Reading state
|
||||
StateManager.get().getGlobalStateKey("myKey")
|
||||
StateManager.get().getSecretKey("mySecretKey")
|
||||
StateManager.get().getWorkspaceStateKey("myWsKey")
|
||||
|
||||
// Writing state
|
||||
StateManager.get().setGlobalState("myKey", value)
|
||||
StateManager.get().setSecret("mySecretKey", value)
|
||||
StateManager.get().setWorkspaceState("myWsKey", value)
|
||||
```
|
||||
|
||||
Remember that your data may be read by a different client than the one that wrote it. For example, a value written by Cline in JetBrains may be read by Cline CLI.
|
||||
|
||||
## VSCode Migration (src/hosts/vscode/vscode-to-file-migration.ts)
|
||||
|
||||
On VSCode startup, a migration copies data from VSCode's `ExtensionContext` storage into the file-backed stores. This runs in `src/common.ts` before `StateManager.initialize()`.
|
||||
|
||||
- **Sentinel**: `__vscodeMigrationVersion` key in global state and workspace state — prevents re-migration.
|
||||
- **Merge strategy**: File store wins. Existing values are never overwritten.
|
||||
- **Safe downgrade**: VSCode storage is NOT cleared, so older extension versions still work.
|
||||
|
||||
## Adding New Storage Keys
|
||||
|
||||
1. Add to `src/shared/storage/state-keys.ts` (see existing patterns)
|
||||
2. Read/write via `StateManager` (NOT via `context.globalState`)
|
||||
3. If adding a secret, add to `SecretKeys` array in `state-keys.ts`
|
||||
|
||||
## File Layout
|
||||
|
||||
```
|
||||
~/.cline/
|
||||
data/
|
||||
globalState.json # Global settings & state
|
||||
secrets.json # API keys (mode 0o600)
|
||||
tasks/
|
||||
taskHistory.json # Task history (separate file)
|
||||
workspaces/
|
||||
<hash>/
|
||||
workspaceState.json # Per-workspace toggles
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Address PR Comments
|
||||
|
||||
Review and address all comments on the current branch's PR.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Get the current branch name and find the associated PR:
|
||||
```bash
|
||||
gh pr view --json number,title,body
|
||||
```
|
||||
|
||||
2. Understand the PR context:
|
||||
- Get the full diff: `git diff origin/main...HEAD`
|
||||
- Read the changed files to understand what the PR is doing
|
||||
- Read related files if needed to understand the broader context
|
||||
- Understand the intent and spirit of the changes, not just the code
|
||||
|
||||
3. Fetch all PR comments:
|
||||
- Inline comments: `gh api repos/{owner}/{repo}/pulls/{pr_number}/comments`
|
||||
- General comments: `gh pr view {pr_number} --json comments,reviews`
|
||||
|
||||
4. Present a summary of all comments with your recommendation for each (apply, skip, or respond). Ignore bot noise (release automation, CI status, etc.).
|
||||
|
||||
5. **Wait for my approval** before proceeding.
|
||||
|
||||
6. After approval:
|
||||
- Apply code changes and commit
|
||||
- Reply to comments that were addressed or intentionally skipped
|
||||
- Push commits
|
||||
@@ -0,0 +1,49 @@
|
||||
# Find Best Reviewers for Current Branch
|
||||
|
||||
Analyze my current branch to find the best people to review my PR based on **domain expertise** and git history.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Get the current branch name and verify it's not `main`
|
||||
2. Get the diff between the current branch and `origin/main`:
|
||||
- Use `git diff origin/main...HEAD --name-only` to get changed files
|
||||
- Use `git diff origin/main...HEAD` to understand the nature/spirit of the changes
|
||||
3. **Identify the domain/feature area** being changed:
|
||||
- Read the diff carefully to understand WHAT is being changed conceptually (e.g., "slash commands", "authentication", "API client", "UI components")
|
||||
- This semantic understanding is crucial for finding the right reviewers
|
||||
4. Find domain experts by searching for related files and their contributors:
|
||||
- Identify all files related to the feature/domain (not just the ones changed)
|
||||
- Example: if changing slash commands, find ALL slash-command related files across the codebase
|
||||
- Use `git log --format="%an <%ae>" -- <related-files-pattern>` to find who has expertise in that domain
|
||||
5. For additional context, also gather:
|
||||
- `git blame -L <start>,<end> origin/main -- <file-path>` for exact lines changed
|
||||
- Recent commit activity on related files
|
||||
6. Score and rank contributors by:
|
||||
- **Highest weight: Domain expertise** - who has the most commits to files in this feature area (even files not touched by this PR)
|
||||
- **Medium weight: Direct file expertise** - commits to the specific files being changed
|
||||
- **Lower weight: Line-level ownership** - authored the exact lines being modified
|
||||
7. Exclude myself (check against my git config user.email)
|
||||
8. Present the top 5 reviewers as an ordered list
|
||||
|
||||
## Output Format
|
||||
|
||||
Output an ordered list:
|
||||
|
||||
1. **Name** - Domain expert: 15 commits to slash-command related files, authored core parsing logic
|
||||
2. **Name** - 8 commits to affected files, recently added the feature being modified
|
||||
3. ...
|
||||
|
||||
## Commands Reference
|
||||
```bash
|
||||
git config user.email
|
||||
git diff origin/main...HEAD --name-only
|
||||
git diff origin/main...HEAD
|
||||
# Find related files for a domain (adjust pattern based on what you learn from the diff)
|
||||
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) | head -20
|
||||
# Get contributors for related files
|
||||
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) -print0 | xargs -0 git log --format="%an <%ae>" -- | sort | uniq -c | sort -rn
|
||||
git log --format="%an <%ae>" -- <file> | sort | uniq -c | sort -rn
|
||||
git blame -L 10,20 origin/main -- <file>
|
||||
```
|
||||
|
||||
Do NOT ask questions - analyze the changes, identify the domain, and output the reviewer list.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Git Diff Analysis Workflow
|
||||
|
||||
## Objective
|
||||
Analyze the current branch's changes against main to provide informed insights and context for development decisions.
|
||||
|
||||
## Step 1: Gather Git Information
|
||||
<important>Do not return any text or conversation other than what is necessary to run these commands</important>
|
||||
|
||||
**Run the following command to get the latest changes (bash):**
|
||||
```bash
|
||||
B=$(for c in main master origin/main origin/master; do git rev-parse --verify -q "$c" >/dev/null && echo "$c" && break; done); B=${B:-HEAD}; r(){ git branch --show-current; printf "=== STATUS ===\n"; git status --porcelain | cat; printf "=== COMMIT MESSAGES ===\n"; git log "$B"..HEAD --oneline | cat; printf "=== CHANGED FILES ===\n"; git diff "$B" --name-only | cat; printf "=== FULL DIFF ===\n"; git diff "$B" | cat; }; L=$(r | wc -l); if [ "$L" -gt 500 ]; then r > cline-git-analysis.temp && echo "::OUTPUT_FILE=cline-git-analysis.temp"; else r; fi
|
||||
```
|
||||
|
||||
```powershell
|
||||
$B=$null;foreach($c in 'main','master','origin/main','origin/master'){git rev-parse --verify -q $c *> $null;if($LASTEXITCODE -eq 0){$B=$c;break}};if(-not $B){$B='HEAD'};function r([string]$b){git rev-parse --abbrev-ref HEAD; '=== STATUS ==='; git status --porcelain | cat; '=== COMMIT MESSAGES ==='; git log "$b"..HEAD --oneline | cat; '=== CHANGED FILES ==='; git diff "$b" --name-only | cat; '=== FULL DIFF ==='; git diff "$b" | cat};$out=r $B|Out-String;$lines=($out -split "`r?`n").Count;if($lines -gt 500){$out|Set-Content -NoNewline cline-git-analysis.temp; '::OUTPUT_FILE=cline-git-analysis.temp'}else{$out}
|
||||
```
|
||||
|
||||
## Step 2: Silent, Structured Analysis Phase
|
||||
- Analyze all git output without providing commentary or narration
|
||||
- Read the full diff to understand the scope and nature of changes
|
||||
- Identify patterns, architectural modifications, or potential impacts
|
||||
- Use `read_file` to examine any related files providing additional context on the changes you have observed
|
||||
|
||||
## Step 3: Context Gathering
|
||||
- Analyze related code without providing commentary or narration
|
||||
- Read relevant related source files if needed for complete understanding
|
||||
- Check dependencies, imports, or cross-references spanning the changes
|
||||
- Understand the broader codebase context around modifications
|
||||
- This additional context gathering should include related backend code, as well as related ui/frontend code
|
||||
- You will typically need to analyze at least several files, potentially many, in order to fully complete this step
|
||||
- You should not continue reading additional context if you have exhausted more than 60% of your available context window
|
||||
- If you have exhausted less than 40% of your context window, you should continue reviewing additional context
|
||||
|
||||
## Step 4: Ready for User Interaction
|
||||
**Only after completing the full analysis:**
|
||||
- Engage with the user based on comprehensive understanding
|
||||
- Provide insights about specific modifications and their impacts
|
||||
- If you are certain they exist, note potential breaking changes or compatibility issues
|
||||
- Answer questions with informed context from the complete change set and context gathering
|
||||
- If the user has not provided a question, or the question is insufficient to provide a quality response, ask brief (one sentence) clarifying questions.
|
||||
- Only offer recommendations if they are applicable to the user's request and relevant to the changes that you have observed
|
||||
|
||||
## Key Rules
|
||||
- **No prose or conversation during git research phase**
|
||||
- **No prose or conversation during context gathering phase**
|
||||
- **Complete all analysis before any user interaction**
|
||||
- **Use gathered information for all subsequent questions and insights**
|
||||
- **Focus on understanding the complete picture before discussing**
|
||||
|
||||
## Optional: Additional Analysis Commands
|
||||
For deeper investigation when needed:
|
||||
|
||||
```shell
|
||||
# Detailed commit history with author info
|
||||
git log main..HEAD --format="%h %s (%an)" | cat
|
||||
|
||||
# Change statistics
|
||||
git diff main --stat | cat
|
||||
|
||||
# Specific file type changes
|
||||
git diff main --name-only | grep -E '\.(ts|js|tsx|jsx|py|md)$' | cat
|
||||
@@ -0,0 +1,187 @@
|
||||
# Hotfix Release
|
||||
|
||||
Create a hotfix release by cherry-picking specific commits from main onto the latest release tag.
|
||||
|
||||
## Overview
|
||||
|
||||
This workflow helps you:
|
||||
1. Select specific commits from main to include in a hotfix
|
||||
2. Create a release notes commit on main (changelog + version bump)
|
||||
3. Cherry-pick everything onto the latest release tag
|
||||
4. Tag and push the new release
|
||||
|
||||
## Step 1: Setup and Gather Information
|
||||
|
||||
First, ensure we're on main and up to date:
|
||||
|
||||
```bash
|
||||
git checkout main && git pull origin main
|
||||
```
|
||||
|
||||
Get the latest release tag:
|
||||
|
||||
```bash
|
||||
git tag --sort=-v:refname | head -1
|
||||
```
|
||||
|
||||
## Step 2: Present Commits Since Last Release
|
||||
|
||||
Show all commits on main since the last release tag:
|
||||
|
||||
```bash
|
||||
LAST_TAG=$(git tag --sort=-v:refname | head -1)
|
||||
git log ${LAST_TAG}..HEAD --oneline --format="%h %s (%an)"
|
||||
```
|
||||
|
||||
Also get the commit messages already on the tag (to identify previously cherry-picked commits). Note: Run these as separate commands to avoid shell parsing issues with parentheses in author names:
|
||||
|
||||
```bash
|
||||
LAST_TAG=$(git tag --sort=-v:refname | head -1)
|
||||
PREV_TAG=$(git tag --sort=-v:refname | head -2 | tail -1)
|
||||
```
|
||||
|
||||
```bash
|
||||
git log $PREV_TAG..$LAST_TAG --oneline --format="%s"
|
||||
```
|
||||
|
||||
**Present the list** to the user in a numbered format with commit hash, subject, and author. For any commits whose subject line already appears in the tag's history (previously cherry-picked in an earlier hotfix) or are "Release Notes" commits, add `(already in previous hotfix)` or `(release notes - skip)` after them so the user knows to skip those.
|
||||
|
||||
Ask which commits to include in the hotfix.
|
||||
|
||||
Use the ask_followup_question tool to let the user specify which commits they want (by number or hash).
|
||||
|
||||
## Step 3: Analyze Selected Commits
|
||||
|
||||
For each selected commit:
|
||||
1. Get the full commit message: `git show --no-patch --format="%B" <hash>`
|
||||
2. Get the diff to understand the change: `git show <hash> --stat`
|
||||
3. Find the associated PR if any: `gh pr list --search "<hash>" --state merged --json number,title --jq '.[0]'`
|
||||
|
||||
Build a mental model of what these changes do for the changelog.
|
||||
|
||||
## Step 4: Determine New Version Number
|
||||
|
||||
Parse the current version from package.json and the last tag:
|
||||
|
||||
```bash
|
||||
LAST_TAG=$(git tag --sort=-v:refname | head -1)
|
||||
echo "Last release: $LAST_TAG"
|
||||
cat package.json | grep '"version"'
|
||||
```
|
||||
|
||||
Hotfixes always increment the patch version (e.g., 3.40.0 -> 3.40.1, or 3.40.1 -> 3.40.2).
|
||||
|
||||
**Ask the user to confirm the new version number.**
|
||||
|
||||
## Step 5: Create Release Notes Commit on Main
|
||||
|
||||
On the main branch, create a commit that updates:
|
||||
|
||||
1. **CHANGELOG.md** - Add a new section for the hotfix version at the top:
|
||||
```markdown
|
||||
## [3.40.1]
|
||||
|
||||
- Description of fix 1
|
||||
- Description of fix 2
|
||||
```
|
||||
|
||||
Write clear, user-friendly descriptions based on your analysis of the commits.
|
||||
|
||||
2. **package.json** - Update the version field to the new version
|
||||
|
||||
3. No changelog-entry file cleanup is needed. Contributors do not create changelog-entry files in this repo.
|
||||
|
||||
**No dependency install is needed.** A CHANGELOG + `version` bump does not change any dependency, and `bun.lock` does not pin workspace-package versions, so the lockfile stays consistent. The publish workflow runs `bun install --frozen-lockfile`, which would *fail* on an out-of-sync lock — so only run `bun install` here if you actually change dependencies (then commit the updated `bun.lock`).
|
||||
|
||||
Commit with message format: `v{VERSION} Release Notes (hotfix)`
|
||||
|
||||
In the commit body, mention:
|
||||
- This is for a hotfix release
|
||||
- List the cherry-picked commits that will be included
|
||||
|
||||
```bash
|
||||
git add CHANGELOG.md package.json
|
||||
git commit -m "v3.40.1 Release Notes (hotfix)
|
||||
|
||||
Hotfix release including:
|
||||
- <commit1-hash>: <description>
|
||||
- <commit2-hash>: <description>
|
||||
"
|
||||
```
|
||||
|
||||
Push to main:
|
||||
|
||||
```bash
|
||||
git push origin main
|
||||
```
|
||||
|
||||
## Step 6: Build the Hotfix on the Tag
|
||||
|
||||
Checkout the last release tag (detached HEAD):
|
||||
|
||||
```bash
|
||||
LAST_TAG=$(git tag --sort=-v:refname | head -1)
|
||||
git checkout $LAST_TAG
|
||||
```
|
||||
|
||||
Cherry-pick the selected commits in order:
|
||||
|
||||
```bash
|
||||
git cherry-pick <commit1-hash>
|
||||
git cherry-pick <commit2-hash>
|
||||
# ... etc
|
||||
```
|
||||
|
||||
Finally, cherry-pick the release notes commit you just pushed to main:
|
||||
|
||||
```bash
|
||||
# Get the hash of the release notes commit (should be HEAD of main)
|
||||
RELEASE_NOTES_COMMIT=$(git rev-parse main)
|
||||
git cherry-pick $RELEASE_NOTES_COMMIT
|
||||
```
|
||||
|
||||
## Step 7: Tag and Push
|
||||
|
||||
After all cherry-picks are applied successfully:
|
||||
|
||||
```bash
|
||||
# Tag the new release
|
||||
git tag v{VERSION}
|
||||
|
||||
# Push the tag to remote
|
||||
git push origin v{VERSION}
|
||||
```
|
||||
|
||||
## Step 8: Return to Main and Summary
|
||||
|
||||
Return to main branch:
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
```
|
||||
|
||||
**Copy a Slack announcement message to clipboard** with the version and PR links for each included fix:
|
||||
|
||||
```
|
||||
VS Code Hotfix v{VERSION} Published
|
||||
|
||||
- Description of fix 1 https://github.com/cline/cline/pull/{PR_NUMBER}
|
||||
- Description of fix 2 https://github.com/cline/cline/pull/{PR_NUMBER}
|
||||
```
|
||||
|
||||
Present a final summary:
|
||||
- New version: v{VERSION}
|
||||
- Tag pushed: yes
|
||||
- Commits included: (list them)
|
||||
- Slack message copied to clipboard: yes
|
||||
|
||||
Remind the user to:
|
||||
1. Manually trigger the publish release GitHub Action at: https://github.com/cline/cline/actions/workflows/ext-vscode-publish-stable.yml (paste `v{VERSION}` as the tag)
|
||||
2. Post the Slack message to announce the hotfix
|
||||
|
||||
## Important Notes
|
||||
|
||||
- This workflow does NOT create a release branch - only tags
|
||||
- The release notes commit goes to main first, then gets cherry-picked to the tag
|
||||
- This keeps main's history accurate while allowing hotfix releases from tags
|
||||
- If cherry-pick conflicts occur, resolve them before continuing
|
||||
@@ -0,0 +1,352 @@
|
||||
You have access to the `gh` terminal command. I already authenticated it for you. Please review it to use the PR that I asked you to review. You're already in the `cline` repo.
|
||||
|
||||
<detailed_sequence_of_steps>
|
||||
# GitHub PR Review Process - Detailed Sequence of Steps
|
||||
|
||||
## 1. Gather PR Information
|
||||
1. Get the PR title, description, and comments:
|
||||
```bash
|
||||
gh pr view <PR-number> --json title,body,comments
|
||||
```
|
||||
|
||||
2. Get the full diff of the PR:
|
||||
```bash
|
||||
gh pr diff <PR-number>
|
||||
```
|
||||
|
||||
## 2. Understand the Context
|
||||
1. Identify which files were modified in the PR:
|
||||
```bash
|
||||
gh pr view <PR-number> --json files
|
||||
```
|
||||
|
||||
2. Examine the original files in the main branch to understand the context:
|
||||
```xml
|
||||
<read_file>
|
||||
<path>path/to/file</path>
|
||||
</read_file>
|
||||
```
|
||||
|
||||
3. For specific sections of a file, you can use search_files:
|
||||
```xml
|
||||
<search_files>
|
||||
<path>path/to/directory</path>
|
||||
<regex>search term</regex>
|
||||
<file_pattern>*.ts</file_pattern>
|
||||
</search_files>
|
||||
```
|
||||
|
||||
## 3. Analyze the Changes
|
||||
1. For each modified file, understand:
|
||||
- What was changed
|
||||
- Why it was changed (based on PR description)
|
||||
- How it affects the codebase
|
||||
- Potential side effects
|
||||
|
||||
2. Look for:
|
||||
- Code quality issues
|
||||
- Potential bugs
|
||||
- Performance implications
|
||||
- Security concerns
|
||||
- Test coverage
|
||||
|
||||
## 4. Ask for User Confirmation
|
||||
1. Before making a decision, ask the user if you should approve the PR, providing your assessment and justification:
|
||||
```xml
|
||||
<ask_followup_question>
|
||||
<question>Based on my review of PR #<PR-number>, I recommend [approving/requesting changes]. Here's my justification:
|
||||
|
||||
[Detailed justification with key points about the PR quality, implementation, and any concerns]
|
||||
|
||||
Would you like me to proceed with this recommendation?</question>
|
||||
<options>["Yes, approve the PR", "Yes, request changes", "No, I'd like to discuss further"]</options>
|
||||
</ask_followup_question>
|
||||
```
|
||||
|
||||
## 5. Ask if User Wants a Comment Drafted
|
||||
1. After the user decides on approval/rejection, ask if they would like a comment drafted:
|
||||
```xml
|
||||
<ask_followup_question>
|
||||
<question>Would you like me to draft a comment for this PR that you can copy and paste?</question>
|
||||
<options>["Yes, please draft a comment", "No, I'll handle the comment myself"]</options>
|
||||
</ask_followup_question>
|
||||
```
|
||||
|
||||
2. If the user wants a comment drafted, provide a well-structured comment they can copy:
|
||||
```
|
||||
Thank you for this PR! Here's my assessment:
|
||||
|
||||
[Detailed assessment with key points about the PR quality, implementation, and any suggestions]
|
||||
|
||||
[Include specific feedback on code quality, functionality, and testing]
|
||||
```
|
||||
|
||||
## 6. Make a Decision
|
||||
1. Approve the PR if it meets quality standards:
|
||||
```bash
|
||||
# For single-line comments:
|
||||
gh pr review <PR-number> --approve --body "Your approval message"
|
||||
|
||||
# For multi-line comments with proper whitespace formatting:
|
||||
cat << EOF | gh pr review <PR-number> --approve --body-file -
|
||||
Thanks @username for this PR! The implementation looks good.
|
||||
|
||||
I particularly like how you've handled X and Y.
|
||||
|
||||
Great work!
|
||||
EOF
|
||||
```
|
||||
|
||||
2. Request changes if improvements are needed:
|
||||
```bash
|
||||
# For single-line comments:
|
||||
gh pr review <PR-number> --request-changes --body "Your feedback message"
|
||||
|
||||
# For multi-line comments with proper whitespace formatting:
|
||||
cat << EOF | gh pr review <PR-number> --request-changes --body-file -
|
||||
Thanks @username for this PR!
|
||||
|
||||
The implementation looks promising, but there are a few things to address:
|
||||
|
||||
1. Issue one
|
||||
2. Issue two
|
||||
|
||||
Please make these changes and we can merge this.
|
||||
EOF
|
||||
```
|
||||
|
||||
Note: The `cat << EOF | ... --body-file -` approach preserves all whitespace and formatting without requiring temporary files. The `-` parameter tells the command to read from standard input.
|
||||
</detailed_sequence_of_steps>
|
||||
|
||||
<example_review_process>
|
||||
# Example PR Review Process
|
||||
|
||||
Let's walk through a real example of reviewing PR #3627 which fixes the thinking mode calculation for Claude 3.7 models.
|
||||
|
||||
## Step 1: Gather PR Information
|
||||
|
||||
```bash
|
||||
# Get PR details
|
||||
gh pr view 3627 --json title,body,comments
|
||||
|
||||
# Get the full diff
|
||||
gh pr diff 3627
|
||||
```
|
||||
|
||||
## Step 2: Understand the Context
|
||||
|
||||
```xml
|
||||
# Examine the original files to understand what's being changed
|
||||
<read_file>
|
||||
<path>src/shared/api.ts</path>
|
||||
</read_file>
|
||||
|
||||
# Look at the ThinkingBudgetSlider component implementation
|
||||
<read_file>
|
||||
<path>webview-ui/src/components/settings/ThinkingBudgetSlider.tsx</path>
|
||||
</read_file>
|
||||
|
||||
# Check how thinking mode is currently handled in API providers
|
||||
<search_files>
|
||||
<path>src/api/providers</path>
|
||||
<regex>reasoningOn</regex>
|
||||
<file_pattern>*.ts</file_pattern>
|
||||
</search_files>
|
||||
```
|
||||
|
||||
## Step 3: Analyze the Changes
|
||||
|
||||
From the PR information and code examination, we can see that:
|
||||
|
||||
1. The PR fixes an issue with the thinking mode budget calculation for Claude 3.7 models
|
||||
2. Currently, the thinking budget is incorrectly calculated as 80% of maxTokens (8192), resulting in 6553 tokens
|
||||
3. Claude 3.7 actually supports a much larger thinking budget (up to 64000 tokens)
|
||||
4. The PR adds a `thinkingConfig` property with `maxBudget: 64000` to model definitions
|
||||
5. It updates API handlers to use this value when reasoning mode is enabled
|
||||
6. It enhances the slider component to calculate max values based on model-specific percentages
|
||||
7. Comprehensive tests were added to verify the calculations
|
||||
|
||||
## Step 4: Ask for User Confirmation
|
||||
|
||||
```xml
|
||||
<ask_followup_question>
|
||||
<question>Based on my review of PR #3627, I recommend approving this PR. Here's my justification:
|
||||
|
||||
1. The PR correctly fixes the thinking mode budget calculation for Claude 3.7 models
|
||||
2. It properly implements the thinkingConfig.maxBudget property (64000) for Claude 3.7 models
|
||||
3. It applies the appropriate percentage (50%) for the slider calculation
|
||||
4. The changes are well-tested with comprehensive unit tests
|
||||
5. The implementation is clean and follows the project's coding standards
|
||||
6. The PR includes helpful screenshots demonstrating the fix
|
||||
|
||||
Would you like me to proceed with approving this PR?</question>
|
||||
<options>["Yes, approve the PR", "No, I'd like to discuss further", "Let me review it myself first"]</options>
|
||||
</ask_followup_question>
|
||||
```
|
||||
|
||||
## Step 5: Ask if User Wants a Comment Drafted
|
||||
|
||||
```xml
|
||||
<ask_followup_question>
|
||||
<question>Would you like me to draft a comment for this PR that you can copy and paste?</question>
|
||||
<options>["Yes, please draft a comment", "No, I'll handle the comment myself"]</options>
|
||||
</ask_followup_question>
|
||||
```
|
||||
|
||||
## Step 6: Make a Decision
|
||||
|
||||
```bash
|
||||
# Option 1: Simple one-line comment
|
||||
gh pr review 3627 --approve --body "This PR looks good! It correctly fixes the thinking mode budget calculation for Claude 3.7 models."
|
||||
|
||||
# Option 2: Multi-line comment with proper whitespace formatting
|
||||
cat << EOF | gh pr review 3627 --approve --body-file -
|
||||
This PR looks good! It correctly fixes the thinking mode budget calculation for Claude 3.7 models.
|
||||
|
||||
I particularly like:
|
||||
1. The proper implementation of thinkingConfig.maxBudget property (64000)
|
||||
2. The appropriate percentage (50%) for the slider calculation
|
||||
3. The comprehensive unit tests
|
||||
4. The clean implementation that follows project coding standards
|
||||
|
||||
Great work!
|
||||
EOF
|
||||
```
|
||||
</example_review_process>
|
||||
|
||||
<common_gh_commands>
|
||||
# Common GitHub CLI Commands for PR Review
|
||||
|
||||
## Basic PR Commands
|
||||
```bash
|
||||
# Get current PR number
|
||||
gh pr view --json number -q .number
|
||||
|
||||
# List open PRs
|
||||
gh pr list
|
||||
|
||||
# View a specific PR
|
||||
gh pr view <PR-number>
|
||||
|
||||
# View PR with specific fields
|
||||
gh pr view <PR-number> --json title,body,comments,files,commits
|
||||
|
||||
# Check PR status
|
||||
gh pr status
|
||||
```
|
||||
|
||||
## Diff and File Commands
|
||||
```bash
|
||||
# Get the full diff of a PR
|
||||
gh pr diff <PR-number>
|
||||
|
||||
# List files changed in a PR
|
||||
gh pr view <PR-number> --json files
|
||||
|
||||
# Check out a PR locally
|
||||
gh pr checkout <PR-number>
|
||||
```
|
||||
|
||||
## Review Commands
|
||||
```bash
|
||||
# Approve a PR (single-line comment)
|
||||
gh pr review <PR-number> --approve --body "Your approval message"
|
||||
|
||||
# Approve a PR (multi-line comment with proper whitespace)
|
||||
cat << EOF | gh pr review <PR-number> --approve --body-file -
|
||||
Your multi-line
|
||||
approval message with
|
||||
|
||||
proper whitespace formatting
|
||||
EOF
|
||||
|
||||
# Request changes on a PR (single-line comment)
|
||||
gh pr review <PR-number> --request-changes --body "Your feedback message"
|
||||
|
||||
# Request changes on a PR (multi-line comment with proper whitespace)
|
||||
cat << EOF | gh pr review <PR-number> --request-changes --body-file -
|
||||
Your multi-line
|
||||
change request with
|
||||
|
||||
proper whitespace formatting
|
||||
EOF
|
||||
|
||||
# Add a comment review (without approval/rejection)
|
||||
gh pr review <PR-number> --comment --body "Your comment message"
|
||||
|
||||
# Add a comment review with proper whitespace
|
||||
cat << EOF | gh pr review <PR-number> --comment --body-file -
|
||||
Your multi-line
|
||||
comment with
|
||||
|
||||
proper whitespace formatting
|
||||
EOF
|
||||
```
|
||||
|
||||
## Additional Commands
|
||||
```bash
|
||||
# View PR checks status
|
||||
gh pr checks <PR-number>
|
||||
|
||||
# View PR commits
|
||||
gh pr view <PR-number> --json commits
|
||||
|
||||
# Merge a PR (if you have permission)
|
||||
gh pr merge <PR-number> --merge
|
||||
```
|
||||
</common_gh_commands>
|
||||
|
||||
<general_guidelines_for_commenting>
|
||||
When reviewing a PR, please talk normally and like a friendly reviwer. You should keep it short, and start out by thanking the author of the pr and @ mentioning them.
|
||||
|
||||
Whether or not you approve the PR, you should then give a quick summary of the changes without being too verbose or definitive, staying humble like that this is your understanding of the changes. Kind of how I'm talking to you right now.
|
||||
|
||||
If you have any suggestions, or things that need to be changed, request changes instead of approving the PR.
|
||||
|
||||
Leaving inline comments in code is good, but only do so if you have something specific to say about the code. And make sure you leave those comments first, and then request changes in the PR with a short comment explaining the overall theme of what you're asking them to change.
|
||||
</general_guidelines_for_commenting>
|
||||
|
||||
<example_comments_that_i_have_written_before>
|
||||
<brief_approve_comment>
|
||||
Looks good, though we should make this generic for all providers & models at some point
|
||||
</brief_approve_comment>
|
||||
<brief_approve_comment>
|
||||
Will this work for models that may not match across OR/Gemini? Like the thinking models?
|
||||
</brief_approve_comment>
|
||||
<approve_comment>
|
||||
This looks great! I like how you've handled the global endpoint support - adding it to the ModelInfo interface makes total sense since it's just another capability flag, similar to how we handle other model features.
|
||||
|
||||
The filtered model list approach is clean and will be easier to maintain than hardcoding which models work with global endpoints. And bumping the genai library was obviously needed for this to work.
|
||||
|
||||
Thanks for adding the docs about the limitations too - good for users to know they can't use context caches with global endpoints but might get fewer 429 errors.
|
||||
</approve_comment>
|
||||
<requesst_changes_comment>
|
||||
This is awesome. Thanks @scottsus.
|
||||
|
||||
My main concern though - does this work for all the possible VS Code themes? We struggled with this initially which is why it's not super styled currently. Please test and share screenshots with the different themes to make sure before we can merge
|
||||
</request_changes_comment>
|
||||
<request_changes_comment>
|
||||
Hey, the PR looks good overall but I'm concerned about removing those timeouts. Those were probably there for a reason - VSCode's UI can be finicky with timing.
|
||||
|
||||
Could you add back the timeouts after focusing the sidebar? Something like:
|
||||
|
||||
```typescript
|
||||
await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus")
|
||||
await setTimeoutPromise(100) // Give UI time to update
|
||||
visibleWebview = WebviewProvider.getSidebarInstance()
|
||||
```
|
||||
</request_changes_comment>
|
||||
<request_changes_comment>
|
||||
Heya @alejandropta thanks for working on this!
|
||||
|
||||
A few notes:
|
||||
1 - Adding additional info to the environment variables is fairly problematic because env variables get appended to **every single message**. I don't think this is justifiable for a somewhat niche use case.
|
||||
2 - Adding this option to settings to include that could be an option, but we want our options to be simple and straightforward for new users
|
||||
3 - We're working on revisualizing the way our settings page is displayed/organized, and this could potentially be reconciled once that is in and our settings page is more clearly delineated.
|
||||
|
||||
So until the settings page is update, and this is added to settings in a way that's clean and doesn't confuse new users, I don't think we can merge this. Please bear with us.
|
||||
</request_changes_comment>
|
||||
<request_changes_comment>
|
||||
The architectural change is solid - moving the focus logic to the command handlers makes sense. Just don't want to introduce subtle timing issues by removing those timeouts.
|
||||
</request_changes_comment>
|
||||
</example_comments_that_i_have_written_before>
|
||||
@@ -0,0 +1,64 @@
|
||||
# Release
|
||||
|
||||
Prepare and publish a release directly from `main`.
|
||||
|
||||
## Overview
|
||||
|
||||
This workflow helps you:
|
||||
1. Select/confirm the target version
|
||||
2. Curate `CHANGELOG.md` entries manually for end users
|
||||
3. Ensure `package.json` version matches the changelog
|
||||
4. Create and push a release commit + tag
|
||||
5. Trigger publish workflow
|
||||
6. Update GitHub release notes and share a summary
|
||||
|
||||
## Process
|
||||
|
||||
### 1) Sync and determine version
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
git pull origin main
|
||||
cat package.json | grep '"version"'
|
||||
```
|
||||
|
||||
Confirm the release version with the maintainer (patch/minor/major).
|
||||
|
||||
### 2) Curate changelog and version
|
||||
|
||||
- Edit `CHANGELOG.md` for the target version using human-friendly release notes.
|
||||
- Ensure version headers use bracket format, e.g. `## [3.66.1]`.
|
||||
- Update `package.json` version to the same value.
|
||||
|
||||
### 3) Commit and tag
|
||||
|
||||
```bash
|
||||
git add CHANGELOG.md package.json package-lock.json
|
||||
git commit -m "v<version> Release Notes"
|
||||
git push origin main
|
||||
git tag v<version>
|
||||
git push origin v<version>
|
||||
```
|
||||
|
||||
### 4) Trigger publish workflow
|
||||
|
||||
Tell the maintainer to run:
|
||||
https://github.com/cline/cline/actions/workflows/ext-vscode-publish-stable.yml
|
||||
|
||||
Use `v<version>` as the release tag.
|
||||
|
||||
### 5) Update GitHub release notes
|
||||
|
||||
After publish completes:
|
||||
|
||||
```bash
|
||||
gh release view v<version> --json body --jq '.body'
|
||||
gh release edit v<version> --notes "<final curated release notes>"
|
||||
```
|
||||
|
||||
### 6) Final summary
|
||||
|
||||
Provide:
|
||||
- Released version/tag
|
||||
- Link to release page
|
||||
- Summary of top end-user changes
|
||||
@@ -0,0 +1,392 @@
|
||||
# General writing guide
|
||||
|
||||
# How I want you to write
|
||||
|
||||
I'm gonna write something technical.
|
||||
|
||||
It's often less about the nitty-gritty details of the tech stuff and more about learning something new or getting a solution handed to me on a silver platter.
|
||||
|
||||
Look, when I read, I want something out of it. So when I write, I gotta remember that my readers want something too. This whole piece? It's about cluing in anyone who writes for me, or wants me to write for them, on how I see this whole writing product thing.
|
||||
|
||||
I'm gonna lay out a checklist of stuff I'd like to have. It'll make the whole writing gig a bit smoother, you know?
|
||||
|
||||
## Crafting Compelling Titles
|
||||
|
||||
I often come across titles like "How to do X with Y,Z technology." These don't excite me because X or Y are usually unfamiliar unless they're already well-known. Its rarely the dream to use X unless X is the dream.
|
||||
|
||||
My dream isn’t to use instructor, its to do something valueble with the data it extracts
|
||||
|
||||
An effective title should:
|
||||
|
||||
- Evoke an emotional response
|
||||
- Highlight someone's goal
|
||||
- Offer a dream or aspiration
|
||||
- Challenge or comment on a belief
|
||||
- Address someone's problems
|
||||
|
||||
I believe it's more impactful to write about specific problems. If this approach works, you can replicate it across various scenarios rather than staying too general.
|
||||
|
||||
- Time management for everyone can be a 15$ ebook
|
||||
- Time management for executives is a 2000$ workshop
|
||||
|
||||
Aim for titles that answer questions you think everyone is asking, or address thoughts people have but can't quite articulate.
|
||||
|
||||
Instead of "How I do something" or "How to do something," frame it from the reader's perspective with "How you can do something." This makes the title more engaging. Just make sure the difference is advisory if the content is subjective. “How I made a million dollars” might be more reasonable than “How to make a million dollars” since you are the subject and the goal might be to share your story in hopes of helping others.
|
||||
|
||||
This approach ultimately trains the reader to have a stronger emotional connection to your content.
|
||||
|
||||
- "How I do X"
|
||||
- "How You Can do X"
|
||||
|
||||
Between these two titles, it's obvious which one resonates more emotionally.
|
||||
|
||||
You can take it further by adding specific conditions. For instance, you could target a particular audience or set a timeframe:
|
||||
|
||||
- How to set up Braintrust
|
||||
- How to set up Braintrust in 5 minutes
|
||||
|
||||
## NO adjectiives
|
||||
|
||||
I want you to almost always avoid adjectives and try to use evidence instead. Instead of saying "production ready," you can write something like "scaling this to 100 servers or 1 million documents per second." Numbers like that will tell you exactly what the specificity of your product is. If you have to use adjectives rather than evidence, you are probably making something up.
|
||||
|
||||
There's no reason to say something like "blazingly fast" unless those things are already known phrases.
|
||||
|
||||
Instead, say "200 times faster" or "30% faster." A 30% improvement in recommendation system speed is insane.
|
||||
|
||||
There's a 200 times performance improvement because we went from one programming language to another. It's just something that's a little bit more expected and understandable.
|
||||
|
||||
Another test that I really like using recently is tracking whether or not the statements you make can be:
|
||||
|
||||
- Visualized
|
||||
- Proven false
|
||||
- Said only by you
|
||||
|
||||
If you can nail all three, the claim you make will be more likely to resonate with an audience because only you can say it.
|
||||
|
||||
Earlier this year, I had an example where I embedded all of Wikipedia in 17 minutes with 20 bucks, and it got half a million views. All we posted was a video of me kicking off the job, and then you can see all the log lines go through. You see the number of containers go from 1 out of 50 to 50 out of 50.
|
||||
|
||||
It was easy to visualize and could have been proven false by being unreproducible. Lastly, Modal is the only company that could do that in such an effortless way, which made it unique.
|
||||
|
||||
## Keep It Digestible
|
||||
- Aim for 5-minute reads
|
||||
- Write at a Grade 10 reading level
|
||||
- Break up long paragraphs
|
||||
- Use headers and bullet points
|
||||
|
||||
## Make It Scannable
|
||||
- Bold key points
|
||||
- Use subheadings every 3-4 paragraphs
|
||||
- Include plenty of white space
|
||||
- Add relevant examples
|
||||
|
||||
This structure works whether you're writing a tweet thread or a full blog post. The key is making complex ideas accessible.
|
||||
|
||||
# Guide to Writing Cline Documentation
|
||||
|
||||
## Some general principles for explaining features
|
||||
|
||||
If you're talking about a feature, it's helpful to start with a human-readable explanations that cover what the feature is in simple terms. Skip jargon and explain it like you're talking to someone who's never seen it before. This sets the foundation for everything that follows.
|
||||
|
||||
Combine location and usage into one flowing section. Tell users exactly where to find the feature and how to use it, but weave the instructions into natural prose with a good balance of bullet points, numbered lists, code examples (if applicable), mintlify components, and headers/subheaders. Users shouldn't have to jump between separate "where is it" and "how do I use it" sections.
|
||||
|
||||
Show the feature in action with real examples like actual files, workflows, or code. Users need to see concrete implementations, not just abstract descriptions. This is where understanding turns into practical knowledge.
|
||||
|
||||
When talking about a feature, include an inspiration section that sparks imagination. This section pushes people from understanding to action by showing them what becomes possible when they use this feature creatively. It's what separates good documentation from great documentation.
|
||||
|
||||
## Writing Principles That Actually Work
|
||||
|
||||
### Write for Action, Not Just Understanding
|
||||
|
||||
Documentation should motivate users to try things. Instead of just explaining how something works, focus on what users can accomplish with it. The inspiration section is crucial - it's what transforms passive readers into active users.
|
||||
|
||||
### Create a Natural Story Flow
|
||||
|
||||
It should feel like a conversation that naturally progresses from "what is this?" to "how do I use it?" to "here's a real example" to "imagine what you could do with this."
|
||||
|
||||
### Show Real Examples, Not Toy Demos
|
||||
|
||||
Provide actual workflow files, real code snippets, and concrete implementations that users can copy and adapt. Abstract examples don't help anyone - users want to see exactly what they'll be working with.
|
||||
|
||||
### Keep It Scannable But Not Fragmented
|
||||
|
||||
Write in prose that flows naturally when read completely, but structure it so users can quickly find specific information when they're troubleshooting. Avoid dense walls of text, but also avoid over-formatting with excessive bullet points and bold headers. There should be a nice visual heirarchy of balance between all elements, so you can quickly scan the page and find what you're looking for.
|
||||
|
||||
## Language and Tone Guidelines
|
||||
|
||||
Write clearly without dumbing things down. Use simple language when possible, but don't avoid technical terms that users need to know. Explain concepts in terms of what users can achieve rather than how the software works internally.
|
||||
|
||||
Make your writing conversational and encouraging. Phrases like "you can also try" or "when that works" feel more natural than rigid instructional language. Help users feel confident about trying new things.
|
||||
|
||||
Keep content concise and purposeful. Every sentence should either help users understand something or help them do something. If it doesn't serve one of those purposes, cut it.
|
||||
|
||||
Build in context and reasoning. Users want to understand why they're doing something, not just what to do. This builds confidence and helps them troubleshoot when things don't work exactly as expected.
|
||||
|
||||
## Practical Implementation
|
||||
|
||||
Structure each feature page consistently with the four-section approach, but let the content flow naturally within that structure. Use visual assets like videos and screenshots to complement the written content - they often communicate more effectively than paragraphs of description.
|
||||
|
||||
Link generously to related resources, examples, and deeper documentation. Users should never feel stuck or wonder where to go next. Maintain a repository of real examples that users can reference and adapt to their own needs.
|
||||
|
||||
The goal is documentation that feels more like helpful guidance from an experienced colleague than a technical manual. Users should finish reading feeling excited about what they can accomplish, not just informed about what the feature does.
|
||||
|
||||
## Balance Structure with Flexibility
|
||||
|
||||
While they discuss having consistent documentation structure, there's also mention of making content feel less rigid and more natural. The writing should follow guidelines while still feeling conversational and engaging.
|
||||
|
||||
## Bad examples
|
||||
|
||||
I personally hate this pattern of bullet point **Bold Text** colon and then more text:
|
||||
<bad_example_of_writing>
|
||||
#### macOS
|
||||
|
||||
1. **Switch to bash**: Go to Cline Settings → Terminal → Default Terminal Profile → Select "bash"
|
||||
2. **Disable Oh-My-Zsh temporarily**: If using zsh, try `mv ~/.zshrc ~/.zshrc.backup` and restart VSCode
|
||||
3. **Set environment**: Add to your shell config: `export TERM=xterm-256color`
|
||||
|
||||
#### Windows
|
||||
|
||||
1. **Use PowerShell 7**: Install from Microsoft Store, then select it in Cline settings
|
||||
2. **Disable Windows ConPTY**: VSCode Settings → Terminal › Integrated: Windows Enable Conpty → Uncheck
|
||||
3. **Try Command Prompt**: Sometimes simpler is better - switch to cmd.exe
|
||||
|
||||
#### Linux
|
||||
|
||||
1. **Use bash**: Most reliable option - select in Cline settings
|
||||
2. **Check permissions**: Ensure VSCode has terminal access permissions
|
||||
3. **Disable custom prompts**: Comment out prompt customizations in `.bashrc`
|
||||
|
||||
</bad_example_of_writing>
|
||||
|
||||
We should instead strive to write beautiful docs that read well. We can use bullet points and numbered lists but it should read naturally and be delightful to look at hierachally when scanning through the doc. There should be a good balance between blocks of text, code snippets, paragraphs, numbered lists, and bullet points. When scanning the documentation visually, you should feel like you're adminiring a tasteful art piece.
|
||||
|
||||
<good_example_of_writing>
|
||||
#### macOS
|
||||
|
||||
The most common fix is switching to bash. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown.
|
||||
|
||||
If you're still having issues, Oh-My-Zsh might be interfering with terminal integration. Try temporarily disabling it:
|
||||
- Run `mv ~/.zshrc ~/.zshrc.backup`
|
||||
- Restart VSCode
|
||||
|
||||
You can also add `export TERM=xterm-256color` to your shell configuration file to improve compatibility.
|
||||
|
||||
#### Windows
|
||||
|
||||
PowerShell 7 provides the most reliable experience. Install it from the Microsoft Store, then select it in your Cline settings.
|
||||
|
||||
Still seeing problems? Try these solutions:
|
||||
- Disable Windows ConPTY: VSCode Settings → Terminal › Integrated: Windows Enable Conpty → uncheck
|
||||
- Switch to Command Prompt (cmd.exe) - sometimes simpler shells work better
|
||||
|
||||
#### Linux
|
||||
|
||||
Bash is your most dependable option. Select it in Cline settings if you haven't already.
|
||||
|
||||
Check these common issues:
|
||||
- Ensure VSCode has terminal access permissions
|
||||
- Temporarily comment out custom prompt configurations in your `.bashrc`
|
||||
</good_example_of_writing>
|
||||
|
||||
This is much more natural to read. Writing this way creates a conversational flow, and bullet points are used idiomatically.
|
||||
|
||||
# Using Mintlify Components Idiomatically
|
||||
|
||||
Mintlify's custom components can transform basic documentation into engaging, scannable content that users actually want to read. Here's how to use them effectively.
|
||||
|
||||
## Visual Content with Frames
|
||||
|
||||
Videos and images should be wrapped in `<Frame>` components rather than using raw HTML or markdown. This creates consistent styling and proper responsive behavior.
|
||||
|
||||
For videos, embed them directly rather than linking externally. Users are much more likely to watch a 30-second demonstration than click through to another platform:
|
||||
|
||||
```jsx
|
||||
<Frame>
|
||||
<iframe
|
||||
style={{ width: "100%", aspectRatio: "16/9" }}
|
||||
src="https://www.youtube.com/embed/your-video-id"
|
||||
title="Feature demonstration"
|
||||
frameBorder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowFullScreen
|
||||
/>
|
||||
</Frame>
|
||||
```
|
||||
|
||||
Screenshots work similarly - the frame provides visual polish and consistency:
|
||||
|
||||
```jsx
|
||||
<Frame>
|
||||
<img src="/path/to/screenshot.png" alt="Descriptive alt text" />
|
||||
</Frame>
|
||||
```
|
||||
|
||||
## Cards for Navigation and Overview
|
||||
|
||||
Cards excel at creating scannable overviews that link to detailed documentation. They're perfect for feature listings, getting started guides, or any section where users need to choose their path.
|
||||
|
||||
Use the two-column layout for related features:
|
||||
|
||||
```jsx
|
||||
<Columns cols={2}>
|
||||
<Card title="Feature Name" icon="relevant-icon" href="/link/to/docs">
|
||||
Brief description that explains what this feature does and why someone would use it.
|
||||
</Card>
|
||||
|
||||
<Card title="Related Feature" icon="another-icon" href="/another/link">
|
||||
Another concise explanation that helps users understand the value proposition.
|
||||
</Card>
|
||||
</Columns>
|
||||
```
|
||||
|
||||
The key is writing card descriptions that are informative enough to help users decide whether to click through, but concise enough to scan quickly. Each card should answer "what does this do?" and "why would I need this?"
|
||||
|
||||
## Tips and Notes for Context
|
||||
|
||||
Use `<Tip>` components for helpful information that enhances the main content without cluttering it:
|
||||
|
||||
```jsx
|
||||
<Tip>
|
||||
Pro tip: You can combine multiple @ mentions in a single message to give Cline
|
||||
comprehensive context about your issue.
|
||||
</Tip>
|
||||
```
|
||||
|
||||
`<Note>` components work well for important caveats or technical limitations:
|
||||
|
||||
```jsx
|
||||
<Note>
|
||||
Due to VS Code limitations, some features require specific settings to work properly.
|
||||
</Note>
|
||||
```
|
||||
|
||||
`<Info>` is also cool:
|
||||
|
||||
<Info>
|
||||
**Quick Fix**: If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings.
|
||||
This resolves 90% of terminal integration problems.
|
||||
</Info>
|
||||
|
||||
**Never** fall into that awful **Bold Text** - description pattern that we specifically identified as bad writing. The content should flow naturally as connected thoughts rather than feeling like a templated AI response with forced formatting.
|
||||
|
||||
|
||||
## When to Use Bullet Points and Numbered Lists Strategically
|
||||
|
||||
Bullet points serve functional purposes - use them for:
|
||||
|
||||
**Sequential actions or troubleshooting steps** where users need to follow a specific order:
|
||||
1. Install the extension
|
||||
2. Restart VSCode
|
||||
3. Check the settings panel
|
||||
|
||||
**Lists of related options** where users need to choose one approach:
|
||||
- Try PowerShell 7 for the most reliable experience
|
||||
- Switch to Command Prompt if you're still having issues
|
||||
- Use WSL Bash for Linux compatibility
|
||||
|
||||
**Quick reference items** that users might need to scan quickly when problem-solving.
|
||||
|
||||
**Improving Visual Hierarchy** when there's a wall of text - that's a good time to introduce bullet points or numbered lists.
|
||||
|
||||
Each bulleted item or numbered list should be a discrete action or piece of information that benefits from being visually separated. This is a key weapon you can employ when going for that artwork experience I mentioned earlier.
|
||||
|
||||
<good_example_of_bullet_points>
|
||||
## Finding and Configuring Terminal Settings
|
||||
|
||||
You can access Cline's terminal settings by clicking the settings icon in the Cline sidebar, then navigating to the Terminal section. These settings control how Cline interacts with your system's terminal.
|
||||
|
||||
- The **Default Terminal Profile** setting determines which shell Cline uses for executing commands. If you're experiencing issues, this is usually the first thing to change. I personally keep this set to `bash` on all my systems because it's the most reliable option, even though I use `zsh` for my regular terminal work.
|
||||
|
||||
- **Shell Integration Timeout** controls how long Cline waits for the terminal to become ready. The default is 4 seconds, but if you have a heavy shell configuration (lots of plugins, slow startup scripts), you might need to increase this to 10 or even 15 seconds. I've found that WSL environments and SSH connections often need longer timeouts.
|
||||
|
||||
- The **Enable Aggressive Terminal Reuse** setting determines whether Cline tries to reuse existing terminals even when they're not in the correct directory. When this causes problems (commands running in the wrong directory, virtual environment issues), disabling it creates more terminal instances but ensures each command runs in a clean state.
|
||||
|
||||
- **Terminal Output Line Limit** sets how many lines of output Cline will read from commands. The default of 500 lines works for most cases, but you might need to adjust it. For verbose build outputs, increase it. For commands with progress bars that spam thousands of lines, decrease it to around 100 to avoid consuming too many tokens.
|
||||
</good_example_of_bullet_points>
|
||||
|
||||
## Write Like a Human, Not an AI
|
||||
|
||||
Keep it short and direct. If you can say something in fewer words, do it. Long explanations often confuse more than they help.
|
||||
|
||||
Use normal sentence lengths. Mix short and long sentences naturally, like you would when talking to someone. Avoid those meandering compound sentences that go on forever.
|
||||
|
||||
Cut the corporate speak. Instead of "utilize," say "use." Instead of "in order to," just say "to." Write like you're explaining something to a colleague, not drafting a press release.
|
||||
|
||||
Don't over-explain obvious things. If users are reading documentation, they probably understand basic concepts. Respect their intelligence.
|
||||
|
||||
## Never use em dashes or emojis
|
||||
|
||||
That's pretty much it. Never use them. Only AI writes with em dashes or emojis.
|
||||
|
||||
# Anthropomorphizing Cline
|
||||
|
||||
When referring to Cline, always call him a "him" not an "it".
|
||||
|
||||
Bad example:
|
||||
- When Cline can’t execute commands or read their output, you lose access to one of its most powerful capabilities.
|
||||
|
||||
Good Example:
|
||||
|
||||
- When Cline can’t execute commands or read their output, you lose access to one of his most powerful capabilities.
|
||||
|
||||
# Using "I" when sharing your workflow
|
||||
|
||||
Adding a personal touch goes a long way. There are great examples in the docs currently where I use "I" to share how I personally use cline, from dev to dev. It's a great technique.
|
||||
|
||||
# Crosslinking relevant documentation pages
|
||||
|
||||
Make sure you crosslink when you're done writing the docs. If there are relevant docs, just link to them.
|
||||
|
||||
# Brevity is the soul of wit
|
||||
|
||||
Don't ramble if you don't need to. Use bullet points and numbered lists. Keep things easy to read.
|
||||
|
||||
<bad_example>
|
||||
|
||||
When Cline can't execute commands or read their output, you lose access to one of his most powerful capabilities. Terminal integration problems are frustrating, but they're usually fixable with a few simple changes.
|
||||
|
||||
## The Most Common Problem: Shell Integration Issues
|
||||
|
||||
If you're seeing "Shell integration unavailable" or Cline isn't getting command output, the issue is almost always your shell configuration. Complex shell setups with custom prompts, plugins, and fancy configurations can interfere with VSCode's terminal integration.
|
||||
|
||||
**Switch to bash first.** This fixes the problem 90% of the time. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown. Restart VSCode after making this change.
|
||||
|
||||
Still having issues? Try increasing the shell integration timeout. Go to Cline Settings → Terminal → Shell Integration Timeout and change it from 4 seconds to 10 seconds. Heavy shell configurations need more time to initialize properly.
|
||||
|
||||
If commands are running in the wrong directories or you're seeing weird behavior, disable aggressive terminal reuse. In Cline Settings → Terminal, uncheck "Enable aggressive terminal reuse." This creates more terminal instances but ensures each command runs in a clean environment.
|
||||
|
||||
|
||||
</bad_exaxmple>
|
||||
|
||||
The first part is total filler, useless to any serious developer. You can tell it's written by a non technical person that doesn't value clean, straightforward information.
|
||||
|
||||
<good_example>
|
||||
## Shell Integration Issues
|
||||
|
||||
If you're seeing "Shell integration unavailable" or Cline can't read command output, your shell configuration is interfering with VSCode's terminal integration.
|
||||
|
||||
**Switch to bash first.** Go to Cline Settings → Terminal → Default Terminal Profile and select "bash." This fixes 90% of problems.
|
||||
|
||||
Still broken? Try these:
|
||||
- Increase shell integration timeout to 10 seconds in Cline Settings → Terminal
|
||||
- Disable "aggressive terminal reuse" if commands run in wrong directories
|
||||
- Restart VSCode after making changes
|
||||
</good_example>
|
||||
|
||||
The good version cuts straight to the problem and solution. No hand-holding, no emotional language about frustration, just the facts: what's wrong, how to fix it, what to try next. Respects that developers want information, not sympathy.RetryClaude can make mistakes. Please double-check responses.
|
||||
|
||||
ALWAYS consider your audience. And your audience is devs who don't want their time wasted. Give them the info. I cannot stress this enough. Use bullet points and numbered lists. Prose is good, but every word should actually mean something to the dev reading it.
|
||||
|
||||
# Lastly, before you start writing docs
|
||||
|
||||
1. Internalize these guidelines. I mean it.
|
||||
|
||||
2. Read `docs/docs.json` and get an understanding of the structure of the docs. This will come in handly at the end when you're doing a final pass so you can cross link to docs where relevant.
|
||||
|
||||
3. Read some good examples that I personally wrote and am proud of:
|
||||
|
||||
- docs/features/slash-commands/workflows.mdx
|
||||
- docs/features/slash-commands/new-task.mdx
|
||||
- docs/features/at-mentions/overview.mdx
|
||||
- docs/features/drag-and-drop.mdx
|
||||
|
||||
4. If the user specifies any other instructions make sure you follow them.
|
||||
@@ -0,0 +1,50 @@
|
||||
# THIS IS AUTOGENERATED. DO NOT EDIT MANUALLY
|
||||
version = 1
|
||||
name = "cline"
|
||||
|
||||
[setup]
|
||||
script = '''
|
||||
if [ ! -d "node_modules" ]; then
|
||||
MAIN_WORKTREE="$(git worktree list | head -n1 | awk '{print $1}')"
|
||||
ln -s "$MAIN_WORKTREE/node_modules" node_modules
|
||||
ln -s "$MAIN_WORKTREE/webview-ui/node_modules" webview-ui/node_modules
|
||||
fi
|
||||
'''
|
||||
|
||||
[[actions]]
|
||||
name = "VS Code"
|
||||
icon = "run"
|
||||
command = "chmod +x ./scripts/run-extension-host.sh && ./scripts/run-extension-host.sh production"
|
||||
|
||||
[[actions]]
|
||||
name = "CLI"
|
||||
icon = "run"
|
||||
command = '''
|
||||
cd sdk
|
||||
bun install
|
||||
bun run cli
|
||||
'''
|
||||
|
||||
[[actions]]
|
||||
name = "npm install"
|
||||
icon = "tool"
|
||||
command = '''
|
||||
rm node_modules
|
||||
rm webview-ui/node_modules
|
||||
npm run install:all
|
||||
'''
|
||||
|
||||
[[actions]]
|
||||
name = "pull main"
|
||||
icon = "tool"
|
||||
command = '''
|
||||
git fetch origin main
|
||||
|
||||
if ! git merge-base --is-ancestor main origin/main; then
|
||||
echo "Local main has commits not on origin/main. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git update-ref refs/heads/main refs/remotes/origin/main
|
||||
echo "main updated to $(git rev-parse --short main)"
|
||||
'''
|
||||
@@ -0,0 +1,4 @@
|
||||
demo.gif filter=lfs diff=lfs merge=lfs -text
|
||||
assets/docs/demo.gif filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,2 @@
|
||||
/.github/ @saoudrizwan @arafatkatze @maxpaulus43 @dominiccooney
|
||||
/README.md @saoudrizwan @juanpflores
|
||||
@@ -0,0 +1,88 @@
|
||||
name: 🐛 Bug Report
|
||||
description: File a bug report
|
||||
labels: ['bug']
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**Important:** All bug reports must be reproducible using Claude Sonnet 4.5. Cline uses complex prompts so less capable models may not work as expected.
|
||||
- type: dropdown
|
||||
id: cline-surface
|
||||
attributes:
|
||||
label: Cline Surface
|
||||
description: Which Cline surface are you reporting a bug for?
|
||||
options:
|
||||
- VSCode Extension
|
||||
- JetBrains Plugin
|
||||
- CLI
|
||||
default: 0
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: cline-version
|
||||
attributes:
|
||||
label: Cline Version
|
||||
description: What version of Cline are you using? (You can find this at the bottom of the Settings view)
|
||||
placeholder: 'e.g., 1.2.3'
|
||||
validations:
|
||||
required: true
|
||||
- type: checkboxes
|
||||
id: beta
|
||||
attributes:
|
||||
label: Beta version
|
||||
options:
|
||||
- label: I am using a beta version of Cline
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: Also tell us, what did you expect to happen?
|
||||
placeholder: Tell us what you see!
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: How do you trigger this bug? Please walk us through it step by step.
|
||||
value: |
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
validations:
|
||||
required: false
|
||||
- type: input
|
||||
id: provider-model
|
||||
attributes:
|
||||
label: Provider/Model
|
||||
description: What provider and model were you using when the issue occurred?
|
||||
placeholder: 'e.g., cline:anthropic/claude-sonnet-4.5, gemini:gemini-2.5-pro-exp-03-25'
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: ide-diagnostics
|
||||
attributes:
|
||||
label: IDE / CLI Diagnostics
|
||||
description: |
|
||||
Paste the "About" diagnostics for your Cline surface. This captures the IDE build, runtime, and host details we need.
|
||||
- VSCode Extension: open `Help → About` (Windows/Linux) or `Code → About Visual Studio Code` (macOS), then copy the info.
|
||||
- JetBrains Plugin: open `Help → About` (Windows/Linux) or `<IDE name> → About` (macOS), then click `Copy` to grab build, runtime, OS, memory, and cores.
|
||||
- CLI: there is no About dialog. Run `cline --version` and paste the output.
|
||||
placeholder: Paste the copied About info or `cline --version` output here.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: system-info
|
||||
attributes:
|
||||
label: System Information
|
||||
description: What operating system and hardware are you using?
|
||||
placeholder: |
|
||||
Operating System: Windows 11, macOS Sonoma, Ubuntu 22.04, etc.
|
||||
Hardware: CPU, GPU, RAM specifications if relevant
|
||||
e.g.,
|
||||
OS: Windows 11
|
||||
CPU: Intel Core i7-11700K
|
||||
GPU: NVIDIA GeForce RTX 3070
|
||||
RAM: 32GB DDR4
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: ✨ Feature Request
|
||||
url: https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop
|
||||
about: Share and vote on feature requests for Cline
|
||||
- name: 👋 Cline Discord
|
||||
url: https://discord.gg/cline
|
||||
about: Join our Discord community for discussions and support
|
||||
@@ -0,0 +1,57 @@
|
||||
# Copilot Instructions for Cline
|
||||
|
||||
This is a VS Code extension. Read `.clinerules/general.md` for tribal knowledge and nuanced patterns.
|
||||
|
||||
## Architecture
|
||||
- **Core** (`src/`): `extension.ts` → `WebviewProvider` → `Controller` (single source of truth) → `Task` (agent loop).
|
||||
- **Webview** (`webview-ui/`): React/Vite app. State via `ExtensionStateContext.tsx`, synced through message passing.
|
||||
- **Communication**: Protobuf-defined gRPC-like protocol over VS Code message passing. Schemas in `proto/`.
|
||||
- **MCP**: `src/services/mcp/McpHub.ts`.
|
||||
|
||||
## Build & Test (Critical — non-obvious commands)
|
||||
- **Build**: `bun run compile` — NOT `bun run build`.
|
||||
- **Watch**: `bun run watch` (extension + webview).
|
||||
- **Protos**: `bun run protos` — run **immediately** after any `.proto` change. Generates into `src/shared/proto/`, `src/generated/`.
|
||||
- **Tests**: `bun run test:unit`. After prompt/tool changes: `UPDATE_SNAPSHOTS=true bun run test:unit`.
|
||||
|
||||
## Protobuf RPC Workflow (4 steps)
|
||||
1. **Define** in `proto/cline/*.proto`. Naming: `PascalCaseService`, `camelCase` RPCs, `PascalCase` Messages. Use `common.proto` shared types for simple data.
|
||||
2. **Generate**: `bun run protos`.
|
||||
3. **Backend handler**: `src/core/controller/<domain>/`.
|
||||
4. **Frontend call**: `UiServiceClient.myMethod(Request.create({...}))`.
|
||||
- Adding enums (e.g. `ClineSay`) → also update `src/shared/proto-conversions/cline-message.ts`.
|
||||
|
||||
## Adding API Providers (silent failure risk)
|
||||
Three proto conversion updates are **required** or the provider silently resets to Anthropic:
|
||||
1. `proto/cline/models.proto` — add to `ApiProvider` enum.
|
||||
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts`.
|
||||
3. `convertProtoToApiProvider()` in the same file.
|
||||
|
||||
Also update: `src/shared/api.ts`, `src/shared/providers/providers.json`, `src/core/api/index.ts`, `webview-ui/.../providerUtils.ts`, `webview-ui/.../validate.ts`, `webview-ui/.../ApiOptions.tsx`.
|
||||
|
||||
For Responses API providers: add to `isNextGenModelProvider()` in `src/utils/model-utils.ts` and set `apiFormat: ApiFormat.OPENAI_RESPONSES` on models.
|
||||
|
||||
## Adding Tools to System Prompt (5+ file chain)
|
||||
1. Add enum to `ClineDefaultTool` in `src/shared/tools.ts`.
|
||||
2. Create definition in `src/core/prompts/system-prompt/tools/` (export `[GENERIC]` minimum).
|
||||
3. Register in `src/core/prompts/system-prompt/tools/init.ts`.
|
||||
4. Whitelist in `src/core/prompts/system-prompt/variants/*/config.ts` for each model family.
|
||||
5. Handler in `src/core/task/tools/handlers/`, wire in `ToolExecutor.ts`.
|
||||
6. If tool has UI: add `ClineSay` enum in proto → `ExtensionMessage.ts` → `cline-message.ts` → `ChatRow.tsx`.
|
||||
7. Regenerate snapshots: `UPDATE_SNAPSHOTS=true bun run test:unit`.
|
||||
|
||||
## Modifying System Prompt
|
||||
Modular: `components/` (shared) + `variants/` (model-specific) + `templates/` (`{{PLACEHOLDER}}`). Variants override components via `componentOverrides` in `config.ts` or custom `template.ts`. XS variant is heavily condensed inline. Always regenerate snapshots after changes.
|
||||
|
||||
## Global State Keys (silent failure risk)
|
||||
Adding a key requires updating the typed storage definitions in `src/shared/storage/state-keys.ts`; runtime reads and writes should go through `StateManager`, not VS Code `ExtensionContext` storage. Persistent state is file-backed so it works across VS Code, CLI, and JetBrains hosts.
|
||||
|
||||
## Slash Commands (3 places)
|
||||
- `src/core/slash-commands/index.ts` — definitions.
|
||||
- `src/core/prompts/commands.ts` — system prompt integration.
|
||||
- `webview-ui/src/utils/slash-commands.ts` — webview autocomplete.
|
||||
|
||||
## Conventions
|
||||
- **Paths**: Always use `src/utils/path` helpers (`toPosixString`) for cross-platform compatibility.
|
||||
- **Logging**: `src/shared/services/Logger.ts`.
|
||||
- **Feature flags**: See PR #7566 as reference pattern.
|
||||
@@ -0,0 +1,36 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Main extension dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/apps/vscode"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
# Group all updates into a single PR
|
||||
groups:
|
||||
all-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
ignore:
|
||||
# Ignore all non-security updates (security vulnerabilities bypass these ignore rules)
|
||||
- dependency-name: "*"
|
||||
update-types:
|
||||
- "version-update:semver-major"
|
||||
- "version-update:semver-minor"
|
||||
- "version-update:semver-patch"
|
||||
|
||||
# Webview UI dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/apps/vscode/webview-ui"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
all-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
ignore:
|
||||
- dependency-name: "@testing-library/*"
|
||||
- dependency-name: "*"
|
||||
update-types:
|
||||
- "version-update:semver-major"
|
||||
- "version-update:semver-minor"
|
||||
- "version-update:semver-patch"
|
||||
@@ -0,0 +1,79 @@
|
||||
<!--
|
||||
Thank you for contributing to Cline!
|
||||
|
||||
⚠️ Important: Before submitting this PR, please ensure you have:
|
||||
- For feature requests: Created a discussion in our Feature Requests discussions board https://github.com/cline/cline/discussions/categories/feature-requests and received approval from core maintainers before implementation
|
||||
- For all changes: Link the associated issue/discussion in the "Related Issue" section below
|
||||
|
||||
Limited exceptions:
|
||||
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly without prior discussion.
|
||||
|
||||
Why this requirement?
|
||||
We deeply appreciate all community contributions - they are essential to Cline's success! To ensure the best use of everyone's time and maintain project direction, we use our Feature Requests discussions board to gauge community interest and validate feature ideas before implementation begins. This helps us focus development efforts on features that will benefit the most users.
|
||||
-->
|
||||
|
||||
### Related Issue
|
||||
|
||||
<!-- Replace XXXX with the issue number that this PR addresses -->
|
||||
**Issue:** #XXXX
|
||||
|
||||
### Description
|
||||
|
||||
<!--
|
||||
Help reviewers understand your changes by making this PR readable and well-organized:
|
||||
|
||||
- What problem does this PR solve?
|
||||
- Why were these changes introduced and what purpose do they serve?
|
||||
- For larger changes, provide context about your approach and reasoning
|
||||
|
||||
Small PRs may need minimal description, but larger changes benefit from explaining where you're coming from. Much of this context can be in the linked issue above, so feel free to reference it rather than repeating everything here.
|
||||
-->
|
||||
|
||||
### Test Procedure
|
||||
|
||||
<!--
|
||||
Please walk us through your testing approach and thought process. This helps reviewers understand that you've thoroughly considered the impact of your changes:
|
||||
|
||||
- How did you test this change?
|
||||
- What could potentially break and how did you verify it doesn't?
|
||||
- What existing functionality might be affected and how did you check it still works?
|
||||
- Why are you confident this is ready for merge?
|
||||
|
||||
We're not looking for exhaustive documentation - just evidence that you've thought through the implications of your changes and tested accordingly.
|
||||
-->
|
||||
|
||||
### Type of Change
|
||||
|
||||
<!-- Put an 'x' in all boxes that apply -->
|
||||
|
||||
- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] ✨ New feature (non-breaking change which adds functionality)
|
||||
- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
|
||||
- [ ] ♻️ Refactor Changes
|
||||
- [ ] 💅 Cosmetic Changes
|
||||
- [ ] 📚 Documentation update
|
||||
- [ ] 🏃 Workflow Changes
|
||||
|
||||
### Pre-flight Checklist
|
||||
|
||||
<!-- Put an 'x' in all boxes that apply -->
|
||||
|
||||
- [ ] Changes are limited to a single feature, bugfix or chore (split larger changes into separate PRs)
|
||||
- [ ] Tests are passing (`bun test`) and code is formatted and linted (`bun run format && bun run lint`)
|
||||
- [ ] I have reviewed [contributor guidelines](https://github.com/cline/cline/blob/main/CONTRIBUTING.md)
|
||||
|
||||
### Screenshots
|
||||
|
||||
<!--
|
||||
Help reviewers quickly understand your changes:
|
||||
|
||||
- **UI Changes**: Please include screenshots showing before/after states
|
||||
- **Complex Workflows**: Consider uploading a screen recording (video) if your changes involve multiple steps or state transitions
|
||||
- **Backend Changes**: Not required, but feel free to include terminal output or other evidence that demonstrates functionality
|
||||
|
||||
This helps reviewers see what you've built without having to pull down and test your branch first.
|
||||
-->
|
||||
|
||||
### Additional Notes
|
||||
|
||||
<!-- Add any additional notes for reviewers -->
|
||||
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
Coverage utility package for GitHub Actions workflows.
|
||||
This package handles extracting coverage percentages, comparing them, and generating PR comments.
|
||||
"""
|
||||
|
||||
# Import external dependencies
|
||||
import requests
|
||||
|
||||
# Import main function for CLI usage
|
||||
from .__main__ import main
|
||||
|
||||
# Import functions from extraction module
|
||||
from .extraction import extract_coverage, compare_coverage, run_coverage, set_verbose
|
||||
|
||||
# Import functions from github_api module
|
||||
from .github_api import generate_comment, post_comment, set_github_output
|
||||
|
||||
# Import functions from workflow module
|
||||
from .workflow import process_coverage_workflow
|
||||
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
Main module.
|
||||
This module provides the CLI interface for the coverage utility script.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
|
||||
from .extraction import extract_coverage, compare_coverage, run_coverage, set_verbose
|
||||
from .github_api import generate_comment, post_comment, set_github_output
|
||||
from .workflow import process_coverage_workflow
|
||||
from .util import log
|
||||
|
||||
def setup_verbose_mode(args):
|
||||
"""
|
||||
Set up verbose mode based on command line arguments.
|
||||
|
||||
Args:
|
||||
args: Parsed command line arguments
|
||||
"""
|
||||
if getattr(args, 'verbose', False):
|
||||
set_verbose(True)
|
||||
log("Verbose mode enabled")
|
||||
|
||||
def main():
|
||||
# Create parent parser with common arguments
|
||||
parent_parser = argparse.ArgumentParser(add_help=False)
|
||||
parent_parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')
|
||||
|
||||
# Create main parser that inherits common arguments
|
||||
parser = argparse.ArgumentParser(description='Coverage utility script for GitHub Actions workflows', parents=[parent_parser])
|
||||
subparsers = parser.add_subparsers(dest='command', help='Command to run')
|
||||
|
||||
# extract-coverage command - used directly in workflow
|
||||
extract_parser = subparsers.add_parser('extract-coverage', help='Extract coverage percentage from a file', parents=[parent_parser])
|
||||
extract_parser.add_argument('file_path', help='Path to the coverage report file')
|
||||
extract_parser.add_argument('--type', choices=['extension', 'webview'], default='extension',
|
||||
help='Type of coverage report')
|
||||
extract_parser.add_argument('--github-output', action='store_true', help='Output in GitHub Actions format')
|
||||
|
||||
# compare-coverage command - used by process-workflow
|
||||
compare_parser = subparsers.add_parser('compare-coverage', help='Compare coverage percentages', parents=[parent_parser])
|
||||
compare_parser.add_argument('base_cov', help='Base branch coverage percentage')
|
||||
compare_parser.add_argument('pr_cov', help='PR branch coverage percentage')
|
||||
compare_parser.add_argument('--output-prefix', default='', help='Prefix for GitHub Actions output variables')
|
||||
compare_parser.add_argument('--github-output', action='store_true', help='Output in GitHub Actions format')
|
||||
|
||||
# generate-comment command - used by process-workflow
|
||||
comment_parser = subparsers.add_parser('generate-comment', help='Generate PR comment with coverage comparison', parents=[parent_parser])
|
||||
comment_parser.add_argument('base_ext_cov', help='Base branch extension coverage')
|
||||
comment_parser.add_argument('pr_ext_cov', help='PR branch extension coverage')
|
||||
comment_parser.add_argument('ext_decreased', help='Whether extension coverage decreased (true/false)')
|
||||
comment_parser.add_argument('ext_diff', help='Extension coverage difference')
|
||||
comment_parser.add_argument('base_web_cov', help='Base branch webview coverage')
|
||||
comment_parser.add_argument('pr_web_cov', help='PR branch webview coverage')
|
||||
comment_parser.add_argument('web_decreased', help='Whether webview coverage decreased (true/false)')
|
||||
comment_parser.add_argument('web_diff', help='Webview coverage difference')
|
||||
|
||||
# post-comment command - used by process-workflow
|
||||
post_parser = subparsers.add_parser('post-comment', help='Post a comment to a GitHub PR', parents=[parent_parser])
|
||||
post_parser.add_argument('comment_path', help='Path to the file containing the comment text')
|
||||
post_parser.add_argument('pr_number', help='PR number')
|
||||
post_parser.add_argument('repo', help='Repository in the format "owner/repo"')
|
||||
post_parser.add_argument('--token', help='GitHub token')
|
||||
|
||||
# run-coverage command - used by process-workflow
|
||||
run_parser = subparsers.add_parser('run-coverage', help='Run a coverage command and extract the coverage percentage', parents=[parent_parser])
|
||||
run_parser.add_argument('coverage_cmd', help='Command to run')
|
||||
run_parser.add_argument('output_file', help='File to save the output to')
|
||||
run_parser.add_argument('--type', choices=['extension', 'webview'], default='extension',
|
||||
help='Type of coverage report')
|
||||
run_parser.add_argument('--github-output', action='store_true', help='Output in GitHub Actions format')
|
||||
|
||||
# process-workflow command - used directly in workflow
|
||||
workflow_parser = subparsers.add_parser('process-workflow', help='Process the entire coverage workflow', parents=[parent_parser])
|
||||
workflow_parser.add_argument('--base-branch', required=True, help='Base branch name')
|
||||
workflow_parser.add_argument('--pr-number', help='PR number')
|
||||
workflow_parser.add_argument('--repo', help='Repository in the format "owner/repo"')
|
||||
workflow_parser.add_argument('--token', help='GitHub token')
|
||||
|
||||
# set-github-output command - used by process-workflow
|
||||
output_parser = subparsers.add_parser('set-github-output', help='Set GitHub Actions output variable', parents=[parent_parser])
|
||||
output_parser.add_argument('name', help='Output variable name')
|
||||
output_parser.add_argument('value', help='Output variable value')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Set up verbose mode
|
||||
setup_verbose_mode(args)
|
||||
|
||||
if args.command == 'extract-coverage':
|
||||
log(f"Extracting coverage from file: {args.file_path} (type: {args.type})")
|
||||
coverage_pct = extract_coverage(args.file_path, args.type)
|
||||
if args.github_output:
|
||||
set_github_output(f"{args.type}_coverage", coverage_pct)
|
||||
else:
|
||||
log(f"Coverage: {coverage_pct}%")
|
||||
|
||||
elif args.command == 'compare-coverage':
|
||||
log(f"Comparing coverage: base={args.base_cov}%, PR={args.pr_cov}%")
|
||||
decreased, diff = compare_coverage(args.base_cov, args.pr_cov)
|
||||
if args.github_output:
|
||||
prefix = args.output_prefix
|
||||
set_github_output(f"{prefix}decreased", str(decreased).lower())
|
||||
set_github_output(f"{prefix}diff", diff)
|
||||
log(f"Coverage difference: {diff}%")
|
||||
log(f"Coverage decreased: {decreased}")
|
||||
else:
|
||||
log(f"decreased={str(decreased).lower()}")
|
||||
log(f"diff={diff}")
|
||||
|
||||
elif args.command == 'generate-comment':
|
||||
log("Generating coverage comparison comment")
|
||||
comment = generate_comment(
|
||||
args.base_ext_cov, args.pr_ext_cov, args.ext_decreased, args.ext_diff,
|
||||
args.base_web_cov, args.pr_web_cov, args.web_decreased, args.web_diff
|
||||
)
|
||||
# Output the comment to stdout
|
||||
log(comment)
|
||||
|
||||
elif args.command == 'post-comment':
|
||||
log(f"Posting comment from {args.comment_path} to PR #{args.pr_number} in {args.repo}")
|
||||
post_comment(args.comment_path, args.pr_number, args.repo, args.token)
|
||||
|
||||
elif args.command == 'run-coverage':
|
||||
log(f"Running coverage command: {args.coverage_cmd}")
|
||||
log(f"Output file: {args.output_file}")
|
||||
log(f"Coverage type: {args.type}")
|
||||
coverage_pct = run_coverage(args.coverage_cmd, args.output_file, args.type)
|
||||
if args.github_output:
|
||||
set_github_output(f"{args.type}_coverage", coverage_pct)
|
||||
else:
|
||||
log(f"Coverage: {coverage_pct}%")
|
||||
|
||||
elif args.command == 'process-workflow':
|
||||
log("Processing coverage workflow")
|
||||
log(f"Base branch: {args.base_branch}")
|
||||
if args.pr_number:
|
||||
log(f"PR number: {args.pr_number}")
|
||||
if args.repo:
|
||||
log(f"Repository: {args.repo}")
|
||||
process_coverage_workflow(args)
|
||||
|
||||
elif args.command == 'set-github-output':
|
||||
log(f"Setting GitHub output: {args.name}={args.value}")
|
||||
set_github_output(args.name, args.value)
|
||||
|
||||
else:
|
||||
log("No command specified")
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,265 @@
|
||||
"""
|
||||
Coverage extraction module.
|
||||
This module handles extracting coverage percentages from coverage report files.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import shlex
|
||||
import subprocess
|
||||
import traceback
|
||||
from .util import log, file_exists, get_file_size, list_directory, is_safe_command, run_command
|
||||
|
||||
# Global verbose flag
|
||||
verbose = False
|
||||
|
||||
def set_verbose(value):
|
||||
"""Set the global verbose flag."""
|
||||
global verbose
|
||||
verbose = value
|
||||
|
||||
def print_debug_output(content, coverage_type):
|
||||
"""
|
||||
Print debug information about the coverage output.
|
||||
|
||||
Args:
|
||||
content: The content of the coverage file
|
||||
coverage_type: Type of coverage report (extension or webview)
|
||||
"""
|
||||
if not verbose:
|
||||
return
|
||||
|
||||
# Extract and print only the coverage summary section
|
||||
if coverage_type == "extension":
|
||||
# Look for the coverage summary section
|
||||
summary_match = re.search(r'=============================== Coverage summary ===============================\n(.*?)\n=+', content, re.DOTALL)
|
||||
if summary_match:
|
||||
sys.stdout.write("\n##[group]EXTENSION COVERAGE SUMMARY\n")
|
||||
sys.stdout.write("=============================== Coverage summary ===============================\n")
|
||||
sys.stdout.write(summary_match.group(1) + "\n")
|
||||
sys.stdout.write("================================================================================\n")
|
||||
sys.stdout.write("##[endgroup]\n")
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
sys.stdout.write("\n##[warning]No coverage summary found in extension coverage file\n")
|
||||
sys.stdout.flush()
|
||||
else: # webview
|
||||
# Look for the coverage table - specifically the "All files" row
|
||||
table_match = re.search(r'% Coverage report from v8.*?-+\|.*?\n.*?\n(All files.*?)(?:\n[^\n]*\|)', content, re.DOTALL)
|
||||
if table_match:
|
||||
sys.stdout.write("\n##[group]WEBVIEW COVERAGE SUMMARY\n")
|
||||
sys.stdout.write("% Coverage report from v8\n")
|
||||
sys.stdout.write("-------------------|---------|----------|---------|---------|-------------------\n")
|
||||
sys.stdout.write("File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n")
|
||||
sys.stdout.write("-------------------|---------|----------|---------|---------|-------------------\n")
|
||||
sys.stdout.write(table_match.group(1) + "\n")
|
||||
sys.stdout.write("-------------------|---------|----------|---------|---------|-------------------\n")
|
||||
sys.stdout.write("##[endgroup]\n")
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
sys.stdout.write("\n##[warning]No coverage table found in webview coverage file\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
def extract_coverage(file_path, coverage_type="extension"):
|
||||
"""
|
||||
Extract coverage percentage from a coverage report file.
|
||||
|
||||
Args:
|
||||
file_path: Path to the coverage report file
|
||||
coverage_type: Type of coverage report (extension or webview)
|
||||
|
||||
Returns:
|
||||
Coverage percentage as a float
|
||||
"""
|
||||
|
||||
# Always print file path for debugging
|
||||
log(f"Checking coverage file: {file_path}")
|
||||
|
||||
# Check if file exists and get its size
|
||||
if not file_exists(file_path):
|
||||
sys.stdout.write(f"\n##[error]File {file_path} does not exist\n")
|
||||
sys.stdout.flush()
|
||||
log(f"Error: File {file_path} does not exist")
|
||||
|
||||
# Check if the directory exists
|
||||
dir_path = os.path.dirname(file_path)
|
||||
if not os.path.exists(dir_path):
|
||||
sys.stdout.write(f"\n##[error]Directory {dir_path} does not exist\n")
|
||||
sys.stdout.flush()
|
||||
log(f"Error: Directory {dir_path} does not exist")
|
||||
else:
|
||||
# List directory contents for debugging
|
||||
log(f"Directory {dir_path} exists, listing contents:")
|
||||
try:
|
||||
dir_contents = list_directory(dir_path)
|
||||
for name, size in dir_contents:
|
||||
log(f" {name} - {size}")
|
||||
sys.stdout.write(f" {name} - {size}\n")
|
||||
sys.stdout.flush()
|
||||
except Exception as e:
|
||||
log(f"Error listing directory: {e}")
|
||||
|
||||
return 0.0
|
||||
|
||||
file_size = get_file_size(file_path)
|
||||
log(f"File size: {file_size} bytes")
|
||||
sys.stdout.write(f"\n##[info]Coverage file {file_path} exists, size: {file_size} bytes\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
if file_size == 0:
|
||||
sys.stdout.write(f"\n##[warning]File {file_path} is empty\n")
|
||||
sys.stdout.flush()
|
||||
log(f"Warning: File {file_path} is empty")
|
||||
return 0.0
|
||||
|
||||
# List directory contents for debugging
|
||||
dir_path = os.path.dirname(file_path)
|
||||
log(f"Directory contents of {dir_path}:")
|
||||
try:
|
||||
dir_contents = list_directory(dir_path)
|
||||
for name, size in dir_contents:
|
||||
log(f" {name} - {size}")
|
||||
except Exception as e:
|
||||
log(f"Error listing directory: {e}")
|
||||
|
||||
with open(file_path, 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
# Print debug information if verbose
|
||||
print_debug_output(content, coverage_type)
|
||||
|
||||
# Extract coverage percentage based on coverage type
|
||||
if coverage_type == "extension":
|
||||
# Extract the percentage from the "Lines" row in the coverage summary
|
||||
# Pattern: Lines : xx.xx% ( xxxxxxx/xxxxxxx )
|
||||
lines_match = re.search(r'Lines\s*:\s*(\d+\.\d+)%', content)
|
||||
if lines_match:
|
||||
coverage_pct = float(lines_match.group(1))
|
||||
if verbose:
|
||||
sys.stdout.write(f"Pattern matched (Lines percentage): {coverage_pct}\n")
|
||||
sys.stdout.flush()
|
||||
return coverage_pct
|
||||
else:
|
||||
# No coverage data found, log full content for debugging
|
||||
log("No coverage data found. Full file content:")
|
||||
log("=== Full file content ===")
|
||||
log(content)
|
||||
log("=== End file content ===")
|
||||
else: # webview
|
||||
# Extract the percentage from the "% Lines" column in the "All files" row
|
||||
# Pattern: All files | xx.xx | xx.xx | xx.xx | xx.xx |
|
||||
all_files_match = re.search(r'All files\s+\|\s+\d+\.\d+\s+\|\s+\d+\.\d+\s+\|\s+\d+\.\d+\s+\|\s+(\d+\.\d+)', content)
|
||||
if all_files_match:
|
||||
coverage_pct = float(all_files_match.group(1))
|
||||
if verbose:
|
||||
sys.stdout.write(f"Pattern matched (All files % Lines): {coverage_pct}\n")
|
||||
sys.stdout.flush()
|
||||
return coverage_pct
|
||||
else:
|
||||
# No coverage data found, log full content for debugging
|
||||
log("No coverage data found. Full file content:")
|
||||
log("=== Full file content ===")
|
||||
log(content)
|
||||
log("=== End file content ===")
|
||||
|
||||
# If no match found, return 0.0
|
||||
return 0.0
|
||||
|
||||
def compare_coverage(base_cov, pr_cov):
|
||||
"""
|
||||
Compare coverage percentages between base and PR branches.
|
||||
|
||||
Args:
|
||||
base_cov: Base branch coverage percentage
|
||||
pr_cov: PR branch coverage percentage
|
||||
|
||||
Returns:
|
||||
Tuple of (decreased, diff)
|
||||
"""
|
||||
try:
|
||||
base_cov = float(base_cov)
|
||||
pr_cov = float(pr_cov)
|
||||
except ValueError:
|
||||
sys.stdout.write(f"Error: Invalid coverage values - base: {base_cov}, PR: {pr_cov}\n")
|
||||
sys.stdout.flush()
|
||||
return False, 0
|
||||
|
||||
diff = pr_cov - base_cov
|
||||
decreased = diff < 0
|
||||
|
||||
return decreased, abs(diff)
|
||||
|
||||
def run_coverage(command, output_file, coverage_type="extension"):
|
||||
"""
|
||||
Run a coverage command and extract the coverage percentage.
|
||||
|
||||
Args:
|
||||
command: Command to run
|
||||
output_file: File to save the output to
|
||||
coverage_type: Type of coverage report (extension or webview)
|
||||
|
||||
Returns:
|
||||
Coverage percentage as a float
|
||||
|
||||
Raises:
|
||||
SystemExit: If the output file is not created or is empty
|
||||
"""
|
||||
|
||||
try:
|
||||
# Run the command and capture output
|
||||
if not is_safe_command(command):
|
||||
error_msg = f"ERROR: Unsafe command detected: {command}"
|
||||
log(error_msg)
|
||||
sys.stdout.write(f"\n##[error]{error_msg}\n")
|
||||
sys.stdout.flush()
|
||||
sys.exit(1)
|
||||
|
||||
# Run command using safe execution from util
|
||||
returncode, stdout, stderr = run_command(command)
|
||||
|
||||
# Log command result
|
||||
log(f"Command exit code: {returncode}")
|
||||
log(f"Command stdout length: {len(stdout)} bytes")
|
||||
log(f"Command stderr length: {len(stderr)} bytes")
|
||||
|
||||
# Save output to file
|
||||
log(f"Saving command output to {output_file}")
|
||||
with open(output_file, 'w') as f:
|
||||
f.write(stdout)
|
||||
if stderr:
|
||||
f.write("\n\n=== STDERR ===\n")
|
||||
f.write(stderr)
|
||||
|
||||
# Verify file was created and has content
|
||||
if not file_exists(output_file):
|
||||
error_msg = f"ERROR: Output file {output_file} was not created"
|
||||
log(error_msg)
|
||||
sys.stdout.write(f"\n##[error]{error_msg}\n")
|
||||
sys.stdout.flush()
|
||||
sys.exit(1) # Exit with error code to fail the workflow
|
||||
|
||||
file_size = get_file_size(output_file)
|
||||
if file_size == 0:
|
||||
error_msg = f"ERROR: Output file {output_file} is empty"
|
||||
log(error_msg)
|
||||
sys.stdout.write(f"\n##[error]{error_msg}\n")
|
||||
sys.stdout.flush()
|
||||
sys.exit(1) # Exit with error code to fail the workflow
|
||||
|
||||
log(f"Output file size: {file_size} bytes")
|
||||
|
||||
# Extract coverage percentage
|
||||
coverage_pct = extract_coverage(output_file, coverage_type)
|
||||
|
||||
log(f"{coverage_type.capitalize()} coverage: {coverage_pct}%")
|
||||
return coverage_pct
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error running coverage command: {e}"
|
||||
log(error_msg)
|
||||
sys.stdout.write(f"\n##[error]{error_msg}\n")
|
||||
sys.stdout.flush()
|
||||
# Print stack trace for debugging
|
||||
log(traceback.format_exc())
|
||||
sys.exit(1) # Exit with error code to fail the workflow
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
GitHub API module.
|
||||
This module handles interactions with the GitHub API for posting comments to PRs.
|
||||
"""
|
||||
|
||||
import os
|
||||
import requests
|
||||
from .util import log, file_exists
|
||||
|
||||
def generate_comment(base_ext_cov, pr_ext_cov, ext_decreased, ext_diff,
|
||||
base_web_cov, pr_web_cov, web_decreased, web_diff):
|
||||
"""
|
||||
Generate a PR comment with coverage comparison.
|
||||
|
||||
Args:
|
||||
base_ext_cov: Base branch extension coverage
|
||||
pr_ext_cov: PR branch extension coverage
|
||||
ext_decreased: Whether extension coverage decreased
|
||||
ext_diff: Extension coverage difference
|
||||
base_web_cov: Base branch webview coverage
|
||||
pr_web_cov: PR branch webview coverage
|
||||
web_decreased: Whether webview coverage decreased
|
||||
web_diff: Webview coverage difference
|
||||
|
||||
Returns:
|
||||
Comment text
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
# Convert string inputs to appropriate types
|
||||
try:
|
||||
base_ext_cov = float(base_ext_cov)
|
||||
pr_ext_cov = float(pr_ext_cov)
|
||||
# Handle ext_decreased as either string or boolean
|
||||
if isinstance(ext_decreased, str):
|
||||
ext_decreased = ext_decreased.lower() == 'true'
|
||||
else:
|
||||
ext_decreased = bool(ext_decreased)
|
||||
ext_diff = float(ext_diff)
|
||||
base_web_cov = float(base_web_cov)
|
||||
pr_web_cov = float(pr_web_cov)
|
||||
# Handle web_decreased as either string or boolean
|
||||
if isinstance(web_decreased, str):
|
||||
web_decreased = web_decreased.lower() == 'true'
|
||||
else:
|
||||
web_decreased = bool(web_decreased)
|
||||
web_diff = float(web_diff)
|
||||
except ValueError as e:
|
||||
log(f"Error converting input values: {e}")
|
||||
return ""
|
||||
|
||||
# Add a unique identifier to find this comment later
|
||||
comment = '<!-- COVERAGE_REPORT -->\n'
|
||||
comment += '## Coverage Report\n\n'
|
||||
|
||||
# Extension coverage
|
||||
comment += '### Extension Coverage\n\n'
|
||||
comment += f'Base branch: {base_ext_cov:.0f}%\n\n'
|
||||
comment += f'PR branch: {pr_ext_cov:.0f}%\n\n'
|
||||
|
||||
if ext_decreased:
|
||||
comment += f'⚠️ **Warning: Coverage decreased by {ext_diff:.2f}%**\n\n'
|
||||
comment += 'Consider adding tests to cover your changes.\n\n'
|
||||
else:
|
||||
comment += '✅ Coverage increased or remained the same\n\n'
|
||||
|
||||
# Webview coverage
|
||||
comment += '### Webview Coverage\n\n'
|
||||
comment += f'Base branch: {base_web_cov:.0f}%\n\n'
|
||||
comment += f'PR branch: {pr_web_cov:.0f}%\n\n'
|
||||
|
||||
if web_decreased:
|
||||
comment += f'⚠️ **Warning: Coverage decreased by {web_diff:.2f}%**\n\n'
|
||||
comment += 'Consider adding tests to cover your changes.\n\n'
|
||||
else:
|
||||
comment += '✅ Coverage increased or remained the same\n\n'
|
||||
|
||||
# Overall assessment
|
||||
comment += '### Overall Assessment\n\n'
|
||||
if ext_decreased or web_decreased:
|
||||
comment += '⚠️ **Test coverage has decreased in this PR**\n\n'
|
||||
comment += 'Please consider adding tests to maintain or improve coverage.\n\n'
|
||||
else:
|
||||
comment += '✅ **Test coverage has been maintained or improved**\n\n'
|
||||
|
||||
# Add timestamp
|
||||
comment += f'\n\n<sub>Last updated: {datetime.now().isoformat()}</sub>'
|
||||
|
||||
return comment
|
||||
|
||||
def post_comment(comment_path, pr_number, repo, token=None):
|
||||
"""
|
||||
Post a comment to a GitHub PR.
|
||||
|
||||
Args:
|
||||
comment_path: Path to the file containing the comment text
|
||||
pr_number: PR number
|
||||
repo: Repository in the format "owner/repo"
|
||||
token: GitHub token
|
||||
"""
|
||||
if not file_exists(comment_path):
|
||||
log(f"Error: Comment file {comment_path} does not exist")
|
||||
return
|
||||
|
||||
with open(comment_path, 'r') as f:
|
||||
comment_body = f.read()
|
||||
|
||||
if not token:
|
||||
token = os.environ.get('GITHUB_TOKEN')
|
||||
if not token:
|
||||
log("Error: GitHub token not provided")
|
||||
return
|
||||
|
||||
# Find existing comment
|
||||
headers = {
|
||||
'Authorization': f'token {token}',
|
||||
'Accept': 'application/vnd.github.v3+json'
|
||||
}
|
||||
|
||||
# Get all comments
|
||||
comments_url = f'https://api.github.com/repos/{repo}/issues/{pr_number}/comments'
|
||||
log(f"Getting comments from: {comments_url}")
|
||||
response = requests.get(comments_url, headers=headers)
|
||||
|
||||
if response.status_code != 200:
|
||||
log(f"Error getting comments: {response.status_code} - {response.text}")
|
||||
return
|
||||
|
||||
comments = response.json()
|
||||
log(f"Found {len(comments)} existing comments")
|
||||
|
||||
# Find comment with our identifier
|
||||
comment_id = None
|
||||
for comment in comments:
|
||||
if '<!-- COVERAGE_REPORT -->' in comment['body']:
|
||||
comment_id = comment['id']
|
||||
log(f"Found existing coverage report comment with ID: {comment_id}")
|
||||
break
|
||||
|
||||
if comment_id:
|
||||
# Update existing comment
|
||||
update_url = f'https://api.github.com/repos/{repo}/issues/comments/{comment_id}'
|
||||
log(f"Updating existing comment at: {update_url}")
|
||||
response = requests.patch(update_url, headers=headers, json={'body': comment_body})
|
||||
|
||||
if response.status_code == 200:
|
||||
log(f"Successfully updated existing comment: {comment_id}")
|
||||
else:
|
||||
log(f"Error updating comment: {response.status_code} - {response.text}")
|
||||
else:
|
||||
# Create new comment
|
||||
log(f"Creating new comment at: {comments_url}")
|
||||
response = requests.post(comments_url, headers=headers, json={'body': comment_body})
|
||||
|
||||
if response.status_code == 201:
|
||||
log("Successfully created new comment")
|
||||
else:
|
||||
log(f"Error creating comment: {response.status_code} - {response.text}")
|
||||
|
||||
def set_github_output(name, value):
|
||||
"""
|
||||
Set GitHub Actions output variable.
|
||||
|
||||
Args:
|
||||
name: Output variable name
|
||||
value: Output variable value
|
||||
"""
|
||||
# Write to the GitHub output file if available
|
||||
if 'GITHUB_OUTPUT' in os.environ:
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as f:
|
||||
f.write(f"{name}={value}\n")
|
||||
else:
|
||||
# Fallback to the deprecated method for backward compatibility
|
||||
log(f"::set-output name={name}::{value}")
|
||||
|
||||
# Also print for human readability
|
||||
log(f"{name}: {value}")
|
||||
@@ -0,0 +1,245 @@
|
||||
"""
|
||||
Utility module.
|
||||
This module provides utility functions used across the coverage check scripts.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import traceback
|
||||
from typing import List, Tuple, Dict, Any, Optional, Union
|
||||
|
||||
# List of allowed commands and their arguments
|
||||
ALLOWED_COMMANDS = {
|
||||
'xvfb-run': ['-a'],
|
||||
'npm': ['run', 'test:coverage', 'ci', 'install', '--no-save', '@vitest/coverage-v8', 'check-types', 'lint', 'format', 'compile'],
|
||||
'cd': ['webview-ui'],
|
||||
'python': ['-m', 'coverage_check'],
|
||||
'git': ['fetch', 'checkout', 'origin'],
|
||||
}
|
||||
|
||||
def is_safe_command(command: Union[str, List[str]]) -> bool:
|
||||
"""
|
||||
Check if a command is safe to execute.
|
||||
|
||||
Args:
|
||||
command: Command to check (string or list)
|
||||
|
||||
Returns:
|
||||
True if command is safe, False otherwise
|
||||
"""
|
||||
# Convert string command to list
|
||||
if isinstance(command, str):
|
||||
try:
|
||||
cmd_parts = shlex.split(command)
|
||||
except ValueError:
|
||||
return False
|
||||
else:
|
||||
cmd_parts = command
|
||||
|
||||
if not cmd_parts:
|
||||
return False
|
||||
|
||||
# Get base command
|
||||
base_cmd = os.path.basename(cmd_parts[0])
|
||||
|
||||
# Check if command is in allowed list
|
||||
if base_cmd not in ALLOWED_COMMANDS:
|
||||
return False
|
||||
|
||||
# For each argument, check for suspicious patterns
|
||||
for arg in cmd_parts[1:]:
|
||||
# Check for shell metacharacters
|
||||
if re.search(r'[;&|`$]', arg):
|
||||
return False
|
||||
# Check for path traversal
|
||||
if '..' in arg and not (base_cmd == 'npm' and arg.startswith('@')):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def log(message: str) -> None:
|
||||
"""
|
||||
Write a message to stdout and flush.
|
||||
|
||||
Args:
|
||||
message: The message to write
|
||||
"""
|
||||
sys.stdout.write(f"{message}\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
def file_exists(file_path: str) -> bool:
|
||||
"""
|
||||
Check if a file exists.
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
|
||||
Returns:
|
||||
True if the file exists, False otherwise
|
||||
"""
|
||||
return os.path.exists(file_path) and os.path.isfile(file_path)
|
||||
|
||||
def get_file_size(file_path: str) -> int:
|
||||
"""
|
||||
Get the size of a file in bytes.
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
|
||||
Returns:
|
||||
Size of the file in bytes, or 0 if the file doesn't exist
|
||||
"""
|
||||
if file_exists(file_path):
|
||||
return os.path.getsize(file_path)
|
||||
return 0
|
||||
|
||||
def list_directory(dir_path: str) -> List[Tuple[str, Union[int, str]]]:
|
||||
"""
|
||||
List the contents of a directory.
|
||||
|
||||
Args:
|
||||
dir_path: Path to the directory
|
||||
|
||||
Returns:
|
||||
List of (name, size) tuples for each file/directory in the directory
|
||||
"""
|
||||
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
|
||||
return []
|
||||
|
||||
contents = []
|
||||
for item in os.listdir(dir_path):
|
||||
item_path = os.path.join(dir_path, item)
|
||||
if os.path.isfile(item_path):
|
||||
contents.append((item, os.path.getsize(item_path)))
|
||||
else:
|
||||
contents.append((item, "DIR"))
|
||||
|
||||
return contents
|
||||
|
||||
def read_file_content(file_path: str, default: str = "") -> str:
|
||||
"""
|
||||
Read file content with error handling.
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
default: Default value to return if file cannot be read
|
||||
|
||||
Returns:
|
||||
File content or default value
|
||||
"""
|
||||
if not file_exists(file_path):
|
||||
log(f"File does not exist: {file_path}")
|
||||
return default
|
||||
|
||||
try:
|
||||
with open(file_path, 'r') as f:
|
||||
return f.read()
|
||||
except Exception as e:
|
||||
log(f"Error reading file {file_path}: {e}")
|
||||
return default
|
||||
|
||||
def write_file_content(file_path: str, content: str) -> bool:
|
||||
"""
|
||||
Write content to file with error handling.
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
content: Content to write
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Create directory if it doesn't exist
|
||||
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||||
|
||||
with open(file_path, 'w') as f:
|
||||
f.write(content)
|
||||
return True
|
||||
except Exception as e:
|
||||
log(f"Error writing to file {file_path}: {e}")
|
||||
return False
|
||||
|
||||
def run_command(command: Union[str, List[str]], capture_output: bool = True) -> Tuple[int, str, str]:
|
||||
"""
|
||||
Run a command and return the result.
|
||||
|
||||
Args:
|
||||
command: Command to run (string or list)
|
||||
capture_output: Whether to capture stdout/stderr
|
||||
|
||||
Returns:
|
||||
Tuple of (returncode, stdout, stderr)
|
||||
"""
|
||||
if not is_safe_command(command):
|
||||
error_msg = f"Unsafe command detected: {command}"
|
||||
log(error_msg)
|
||||
return 1, "", error_msg
|
||||
|
||||
log(f"Running command: {command}")
|
||||
try:
|
||||
# Convert string command to list
|
||||
if isinstance(command, str):
|
||||
cmd_list = shlex.split(command)
|
||||
else:
|
||||
cmd_list = command
|
||||
|
||||
result = subprocess.run(
|
||||
cmd_list,
|
||||
shell=False, # Never use shell=True for security
|
||||
capture_output=capture_output,
|
||||
text=True
|
||||
)
|
||||
log(f"Command exit code: {result.returncode}")
|
||||
return result.returncode, result.stdout, result.stderr
|
||||
except Exception as e:
|
||||
log(f"Error running command: {e}")
|
||||
log(traceback.format_exc())
|
||||
return 1, "", str(e)
|
||||
|
||||
def find_pattern(content: str, pattern: str, group: int = 0,
|
||||
default: Optional[str] = None) -> Optional[str]:
|
||||
"""
|
||||
Find a pattern in content and return the specified group.
|
||||
|
||||
Args:
|
||||
content: Text content to search
|
||||
pattern: Regex pattern to search for
|
||||
group: Group number to return (default: 0 for entire match)
|
||||
default: Default value to return if pattern not found
|
||||
|
||||
Returns:
|
||||
Matched text or default value
|
||||
"""
|
||||
match = re.search(pattern, content, re.DOTALL)
|
||||
if match:
|
||||
return match.group(group)
|
||||
return default
|
||||
|
||||
def get_env_var(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
"""
|
||||
Get environment variable with default value.
|
||||
|
||||
Args:
|
||||
name: Environment variable name
|
||||
default: Default value if not set
|
||||
|
||||
Returns:
|
||||
Environment variable value or default
|
||||
"""
|
||||
return os.environ.get(name, default)
|
||||
|
||||
def format_exception(e: Exception) -> str:
|
||||
"""
|
||||
Format an exception with traceback for logging.
|
||||
|
||||
Args:
|
||||
e: Exception to format
|
||||
|
||||
Returns:
|
||||
Formatted exception string
|
||||
"""
|
||||
return f"{type(e).__name__}: {str(e)}\n{traceback.format_exc()}"
|
||||
@@ -0,0 +1,432 @@
|
||||
"""
|
||||
Workflow module.
|
||||
This module handles the main workflow logic for running coverage tests and processing results.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import subprocess
|
||||
import traceback
|
||||
|
||||
from .extraction import run_coverage, compare_coverage, extract_coverage
|
||||
from .github_api import generate_comment, post_comment, set_github_output
|
||||
from .util import log, file_exists, get_file_size, list_directory, run_command
|
||||
|
||||
def is_valid_branch_name(branch_name: str) -> bool:
|
||||
"""
|
||||
Validate a git branch name.
|
||||
|
||||
Args:
|
||||
branch_name: Branch name to validate
|
||||
|
||||
Returns:
|
||||
True if valid, False otherwise
|
||||
"""
|
||||
# Check for common branch name patterns
|
||||
if not re.match(r'^[a-zA-Z0-9_\-./]+$', branch_name):
|
||||
return False
|
||||
|
||||
# Check for path traversal
|
||||
if '..' in branch_name:
|
||||
return False
|
||||
|
||||
# Check for shell metacharacters
|
||||
if re.search(r'[;&|`$]', branch_name):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def checkout_branch(branch_name: str) -> None:
|
||||
"""
|
||||
Checkout a branch for testing.
|
||||
|
||||
Args:
|
||||
branch_name: Branch name to checkout
|
||||
|
||||
Raises:
|
||||
RuntimeError: If branch checkout fails
|
||||
ValueError: If branch name is invalid
|
||||
"""
|
||||
if not is_valid_branch_name(branch_name):
|
||||
raise ValueError(f"Invalid branch name: {branch_name}")
|
||||
|
||||
log(f"=== Checking out branch: {branch_name} ===")
|
||||
|
||||
# Fetch the branch
|
||||
returncode, stdout, stderr = run_command(['git', 'fetch', 'origin', branch_name])
|
||||
if returncode != 0:
|
||||
log(f"ERROR: Failed to fetch branch {branch_name}")
|
||||
log(f"Error details: {stderr}")
|
||||
raise RuntimeError(f"Git fetch failed: {stderr}")
|
||||
|
||||
# Checkout the branch
|
||||
returncode, stdout, stderr = run_command(['git', 'checkout', branch_name])
|
||||
if returncode != 0:
|
||||
log(f"ERROR: Failed to checkout branch {branch_name}")
|
||||
log(f"Error details: {stderr}")
|
||||
raise RuntimeError(f"Git checkout failed: {stderr}")
|
||||
|
||||
log(f"Successfully checked out branch: {branch_name}")
|
||||
|
||||
def extract_extension_coverage_from_file(file_path):
|
||||
"""Extract extension coverage from file when run_coverage returns 0."""
|
||||
if not file_exists(file_path):
|
||||
log(f"File {file_path} does not exist, cannot extract extension coverage")
|
||||
return 0.0
|
||||
|
||||
file_size = get_file_size(file_path)
|
||||
if file_size == 0:
|
||||
log(f"File {file_path} is empty, cannot extract extension coverage")
|
||||
return 0.0
|
||||
|
||||
log(f"Extension coverage is 0.0, trying to read from file directly: {file_path} (size: {file_size} bytes)")
|
||||
with open(file_path, 'r') as f:
|
||||
content = f.read()
|
||||
# Extract the percentage from the "Lines" row in the coverage summary
|
||||
# Pattern: Lines : xx.xx% ( xxxxxxx/xxxxxxx )
|
||||
lines_match = re.search(r'Lines\s*:\s*(\d+\.\d+)%', content)
|
||||
if lines_match:
|
||||
coverage = float(lines_match.group(1))
|
||||
log(f"Found extension coverage in file: {coverage}%")
|
||||
return coverage
|
||||
return 0.0
|
||||
|
||||
def extract_webview_coverage_from_file(file_path):
|
||||
"""Extract webview coverage from file when run_coverage returns 0."""
|
||||
if not file_exists(file_path):
|
||||
log(f"File {file_path} does not exist, cannot extract webview coverage")
|
||||
return 0.0
|
||||
|
||||
file_size = get_file_size(file_path)
|
||||
if file_size == 0:
|
||||
log(f"File {file_path} is empty, cannot extract webview coverage")
|
||||
return 0.0
|
||||
|
||||
log(f"Webview coverage is 0.0, trying to read from file directly: {file_path} (size: {file_size} bytes)")
|
||||
with open(file_path, 'r') as f:
|
||||
content = f.read()
|
||||
# Extract the percentage from the "% Lines" column in the "All files" row
|
||||
# Pattern: All files | xx.xx | xx.xx | xx.xx | xx.xx |
|
||||
all_files_match = re.search(r'All files\s+\|\s+\d+\.\d+\s+\|\s+\d+\.\d+\s+\|\s+\d+\.\d+\s+\|\s+(\d+\.\d+)', content)
|
||||
if all_files_match:
|
||||
coverage = float(all_files_match.group(1))
|
||||
log(f"Found webview coverage in file: {coverage}%")
|
||||
return coverage
|
||||
return 0.0
|
||||
|
||||
def run_extension_coverage(branch_name=None):
|
||||
"""Run extension coverage tests and extract results."""
|
||||
prefix = 'base_' if branch_name else ''
|
||||
file_path = f"{prefix}extension_coverage.txt"
|
||||
|
||||
# Run coverage tests
|
||||
ext_cov = run_coverage(
|
||||
["xvfb-run", "-a", "npm", "run", "test:coverage"],
|
||||
file_path,
|
||||
"extension"
|
||||
)
|
||||
|
||||
# If coverage is 0.0, try to extract from file directly
|
||||
if ext_cov == 0.0:
|
||||
ext_cov = extract_extension_coverage_from_file(file_path)
|
||||
|
||||
return ext_cov
|
||||
|
||||
def run_webview_coverage(branch_name=None):
|
||||
"""Run webview coverage tests and extract results."""
|
||||
prefix = 'base_' if branch_name else ''
|
||||
file_path = f"{prefix}webview_coverage.txt"
|
||||
|
||||
# Save current directory
|
||||
original_dir = os.getcwd()
|
||||
|
||||
try:
|
||||
# Change to webview-ui directory
|
||||
os.chdir('webview-ui')
|
||||
|
||||
# Install coverage dependency
|
||||
returncode, stdout, stderr = run_command(["npm", "install", "--no-save", "@vitest/coverage-v8"])
|
||||
if returncode != 0:
|
||||
log(f"Failed to install coverage dependency: {stderr}")
|
||||
return 0.0
|
||||
|
||||
# Run coverage tests from webview-ui directory
|
||||
web_cov = run_coverage(
|
||||
["npm", "run", "test:coverage"],
|
||||
os.path.join('..', file_path),
|
||||
"webview"
|
||||
)
|
||||
finally:
|
||||
# Always change back to original directory
|
||||
os.chdir(original_dir)
|
||||
|
||||
# If coverage is 0.0, try to extract from file directly
|
||||
if web_cov == 0.0:
|
||||
web_cov = extract_webview_coverage_from_file(file_path)
|
||||
|
||||
return web_cov
|
||||
|
||||
def run_branch_coverage(branch_name=None):
|
||||
"""
|
||||
Run coverage tests for a branch.
|
||||
|
||||
Args:
|
||||
branch_name: Name of the branch to checkout before running tests (optional)
|
||||
|
||||
Returns:
|
||||
Tuple of (extension_coverage, webview_coverage)
|
||||
"""
|
||||
# Checkout branch if specified
|
||||
if branch_name:
|
||||
checkout_branch(branch_name)
|
||||
|
||||
# Run coverage tests
|
||||
log(f"=== Running coverage tests{' for ' + branch_name if branch_name else ''} ===")
|
||||
|
||||
# Run extension and webview coverage
|
||||
ext_cov = run_extension_coverage(branch_name)
|
||||
web_cov = run_webview_coverage(branch_name)
|
||||
|
||||
return ext_cov, web_cov
|
||||
|
||||
def find_potential_coverage_files():
|
||||
"""Find potential coverage files in the current directory and webview-ui."""
|
||||
log("Searching for potential coverage files...")
|
||||
|
||||
# Find files in current directory
|
||||
current_dir_files = list_directory('.')
|
||||
for name, size in current_dir_files:
|
||||
if 'coverage' in name.lower() and size != "DIR":
|
||||
log(f"Found potential coverage file: {name} (size: {size} bytes)")
|
||||
|
||||
# Find files in webview-ui directory
|
||||
if os.path.exists('webview-ui') and os.path.isdir('webview-ui'):
|
||||
webview_files = list_directory('webview-ui')
|
||||
for name, size in webview_files:
|
||||
if 'coverage' in name.lower() and size != "DIR":
|
||||
log(f"Found potential webview coverage file: webview-ui/{name} (size: {size} bytes)")
|
||||
else:
|
||||
log("webview-ui directory not found")
|
||||
|
||||
def generate_warnings(base_ext_cov, pr_ext_cov, ext_decreased, ext_diff,
|
||||
base_web_cov, pr_web_cov, web_decreased, web_diff):
|
||||
"""Generate warnings for coverage decreases."""
|
||||
if not (ext_decreased or web_decreased):
|
||||
return []
|
||||
|
||||
warnings = [
|
||||
"Test coverage has decreased in this PR",
|
||||
f"Extension coverage: {base_ext_cov}% -> {pr_ext_cov}% (Diff: {ext_diff}%)",
|
||||
f"Webview coverage: {base_web_cov}% -> {pr_web_cov}% (Diff: {web_diff}%)"
|
||||
]
|
||||
|
||||
# Additional warning for significant decrease (more than 1%)
|
||||
if ext_decreased and ext_diff > 1.0:
|
||||
warnings.append(f"Extension coverage decreased by more than 1% ({ext_diff}%). Consider adding tests to cover your changes.")
|
||||
|
||||
if web_decreased and web_diff > 1.0:
|
||||
warnings.append(f"Webview coverage decreased by more than 1% ({web_diff}%). Consider adding tests to cover your changes.")
|
||||
|
||||
return warnings
|
||||
|
||||
def output_warnings(warnings):
|
||||
"""Output warnings to GitHub step summary and console."""
|
||||
if not warnings:
|
||||
return
|
||||
|
||||
# Get the GitHub step summary file path from environment variable
|
||||
github_step_summary = os.environ.get('GITHUB_STEP_SUMMARY')
|
||||
|
||||
# Write to GitHub step summary if available
|
||||
if github_step_summary:
|
||||
with open(github_step_summary, 'a') as f:
|
||||
f.write("## Coverage Warnings\n\n")
|
||||
for warning in warnings:
|
||||
f.write(f"⚠️ {warning}\n\n")
|
||||
|
||||
# Also output to console with ::warning:: syntax for backward compatibility
|
||||
for warning in warnings:
|
||||
log(f"::warning::{warning}")
|
||||
|
||||
def output_github_results(pr_ext_cov, pr_web_cov, base_ext_cov, base_web_cov,
|
||||
ext_decreased, ext_diff, web_decreased, web_diff):
|
||||
"""Output results for GitHub Actions."""
|
||||
set_github_output("pr_extension_coverage", pr_ext_cov)
|
||||
set_github_output("pr_webview_coverage", pr_web_cov)
|
||||
set_github_output("base_extension_coverage", base_ext_cov)
|
||||
set_github_output("base_webview_coverage", base_web_cov)
|
||||
set_github_output("extension_decreased", str(ext_decreased).lower())
|
||||
set_github_output("extension_diff", ext_diff)
|
||||
set_github_output("webview_decreased", str(web_decreased).lower())
|
||||
set_github_output("webview_diff", web_diff)
|
||||
|
||||
def extract_pr_coverage_from_artifacts():
|
||||
"""
|
||||
Extract PR branch coverage from artifact files.
|
||||
|
||||
Returns:
|
||||
Tuple of (extension_coverage, webview_coverage)
|
||||
|
||||
Raises:
|
||||
SystemExit: If the coverage files don't exist
|
||||
"""
|
||||
log("=== Extracting PR branch coverage from artifacts ===")
|
||||
|
||||
# Check if the coverage files exist
|
||||
ext_file_path = "extension_coverage.txt"
|
||||
web_file_path = "webview-ui/webview_coverage.txt"
|
||||
|
||||
# Extract extension coverage
|
||||
log(f"Extracting extension coverage from {ext_file_path}")
|
||||
if not file_exists(ext_file_path):
|
||||
error_msg = f"ERROR: PR extension coverage file {ext_file_path} not found"
|
||||
log(error_msg)
|
||||
|
||||
# List directory contents for debugging
|
||||
log("Current directory contents:")
|
||||
try:
|
||||
dir_contents = list_directory('.')
|
||||
for name, size in dir_contents:
|
||||
log(f" {name} - {size}\n")
|
||||
except Exception as e:
|
||||
log(f"Error listing directory: {e}")
|
||||
|
||||
sys.exit(1) # Exit with error code to fail the workflow
|
||||
|
||||
ext_cov = extract_extension_coverage_from_file(ext_file_path)
|
||||
log(f"PR extension coverage from artifact: {ext_cov}%")
|
||||
|
||||
# Extract webview coverage
|
||||
log(f"Extracting webview coverage from {web_file_path}")
|
||||
if not file_exists(web_file_path):
|
||||
error_msg = f"ERROR: PR webview coverage file {web_file_path} not found"
|
||||
log(error_msg)
|
||||
|
||||
# Check if the webview-ui directory exists
|
||||
if not os.path.exists('webview-ui'):
|
||||
log("ERROR: webview-ui directory not found")
|
||||
else:
|
||||
# List webview-ui directory contents for debugging
|
||||
log("webview-ui directory contents:")
|
||||
try:
|
||||
dir_contents = list_directory('webview-ui')
|
||||
for name, size in dir_contents:
|
||||
log(f" {name} - {size}")
|
||||
except Exception as e:
|
||||
log(f"Error listing directory: {e}")
|
||||
|
||||
sys.exit(1) # Exit with error code to fail the workflow
|
||||
|
||||
web_cov = extract_webview_coverage_from_file(web_file_path)
|
||||
log(f"PR webview coverage from artifact: {web_cov}%")
|
||||
|
||||
return ext_cov, web_cov
|
||||
|
||||
def process_coverage_workflow(args):
|
||||
"""
|
||||
Process the entire coverage workflow.
|
||||
|
||||
Args:
|
||||
args: Command line arguments
|
||||
"""
|
||||
# Initialize all variables at the start
|
||||
pr_ext_cov = 0.0
|
||||
pr_web_cov = 0.0
|
||||
base_ext_cov = 0.0
|
||||
base_web_cov = 0.0
|
||||
ext_decreased = False
|
||||
ext_diff = 0.0
|
||||
web_decreased = False
|
||||
web_diff = 0.0
|
||||
|
||||
try:
|
||||
# Validate branch name
|
||||
if not is_valid_branch_name(args.base_branch):
|
||||
raise ValueError(f"Invalid base branch name: {args.base_branch}")
|
||||
|
||||
# Check if we're running in GitHub Actions
|
||||
is_github_actions = 'GITHUB_ACTIONS' in os.environ
|
||||
if is_github_actions:
|
||||
log("Running in GitHub Actions environment")
|
||||
|
||||
# Extract PR branch coverage from artifacts (from test job)
|
||||
pr_ext_cov, pr_web_cov = extract_pr_coverage_from_artifacts()
|
||||
|
||||
# Verify PR coverage values
|
||||
if pr_ext_cov == 0.0:
|
||||
log("WARNING: PR extension coverage is 0.0, this may indicate an issue with the coverage report")
|
||||
find_potential_coverage_files()
|
||||
|
||||
if pr_web_cov == 0.0:
|
||||
log("WARNING: PR webview coverage is 0.0, this may indicate an issue with the coverage report")
|
||||
find_potential_coverage_files()
|
||||
|
||||
# Run base branch coverage
|
||||
log(f"=== Running base branch coverage for {args.base_branch} ===")
|
||||
base_ext_cov, base_web_cov = run_branch_coverage(args.base_branch)
|
||||
|
||||
# Verify base coverage values
|
||||
if base_ext_cov == 0.0:
|
||||
log("WARNING: Base extension coverage is 0.0, this may indicate an issue with the coverage report")
|
||||
|
||||
if base_web_cov == 0.0:
|
||||
log("WARNING: Base webview coverage is 0.0, this may indicate an issue with the coverage report")
|
||||
|
||||
# Compare coverage
|
||||
log("=== Comparing extension coverage ===")
|
||||
ext_decreased, ext_diff = compare_coverage(base_ext_cov, pr_ext_cov)
|
||||
|
||||
log("=== Comparing webview coverage ===")
|
||||
web_decreased, web_diff = compare_coverage(base_web_cov, pr_web_cov)
|
||||
|
||||
# Print summary of coverage values
|
||||
log("\n=== Coverage Summary ===")
|
||||
log(f"PR extension coverage: {pr_ext_cov}%")
|
||||
log(f"Base extension coverage: {base_ext_cov}%")
|
||||
log(f"Extension coverage change: {'+' if not ext_decreased else '-'}{ext_diff}%")
|
||||
log(f"PR webview coverage: {pr_web_cov}%")
|
||||
log(f"Base webview coverage: {base_web_cov}%")
|
||||
log(f"Webview coverage change: {'+' if not web_decreased else '-'}{web_diff}%")
|
||||
|
||||
# Generate and output warnings
|
||||
warnings = generate_warnings(
|
||||
base_ext_cov, pr_ext_cov, ext_decreased, ext_diff,
|
||||
base_web_cov, pr_web_cov, web_decreased, web_diff
|
||||
)
|
||||
output_warnings(warnings)
|
||||
|
||||
# Generate comment
|
||||
log("=== Generating comment ===")
|
||||
comment = generate_comment(
|
||||
base_ext_cov, pr_ext_cov, str(ext_decreased).lower(), ext_diff,
|
||||
base_web_cov, pr_web_cov, str(web_decreased).lower(), web_diff
|
||||
)
|
||||
|
||||
# Save comment to file
|
||||
with open("coverage_comment.md", "w") as f:
|
||||
f.write(comment)
|
||||
|
||||
# Post comment if PR number is provided
|
||||
if args.pr_number:
|
||||
log(f"=== Posting comment to PR #{args.pr_number} ===")
|
||||
post_comment("coverage_comment.md", args.pr_number, args.repo, args.token)
|
||||
|
||||
# Output results for GitHub Actions
|
||||
output_github_results(
|
||||
pr_ext_cov, pr_web_cov, base_ext_cov, base_web_cov,
|
||||
ext_decreased, ext_diff, web_decreased, web_diff
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
log(f"ERROR in process_coverage_workflow: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
# Try to output results even if there was an error
|
||||
try:
|
||||
output_github_results(
|
||||
pr_ext_cov, pr_web_cov, base_ext_cov, base_web_cov,
|
||||
ext_decreased, ext_diff, web_decreased, web_diff
|
||||
)
|
||||
except Exception as e2:
|
||||
log(f"ERROR outputting GitHub results: {e2}")
|
||||
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Tests for coverage_check script.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
import subprocess
|
||||
import tempfile
|
||||
from unittest.mock import patch, MagicMock, call, mock_open
|
||||
|
||||
# Add parent directory to path so we can import coverage modules
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
from coverage_check import extract_coverage, compare_coverage, set_verbose, generate_comment, post_comment, set_github_output
|
||||
from coverage_check.util import log, file_exists, get_file_size, list_directory
|
||||
|
||||
|
||||
class TestCoverage(unittest.TestCase):
|
||||
# Class variables to store coverage files
|
||||
temp_dir = None
|
||||
extension_coverage_file = None
|
||||
webview_coverage_file = None
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
"""Set up test environment once for all tests."""
|
||||
# Create temporary directory for test files
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
cls.extension_coverage_file = os.path.join(cls.temp_dir.name, 'extension_coverage.txt')
|
||||
cls.webview_coverage_file = os.path.join(cls.temp_dir.name, 'webview_coverage.txt')
|
||||
|
||||
# Run actual tests to generate coverage reports
|
||||
cls.generate_coverage_reports()
|
||||
|
||||
# Verify files exist and are not empty
|
||||
assert os.path.exists(cls.extension_coverage_file), \
|
||||
f"Extension coverage file {cls.extension_coverage_file} does not exist"
|
||||
assert os.path.getsize(cls.extension_coverage_file) > 0, \
|
||||
f"Extension coverage file {cls.extension_coverage_file} is empty"
|
||||
assert os.path.exists(cls.webview_coverage_file), \
|
||||
f"Webview coverage file {cls.webview_coverage_file} does not exist"
|
||||
assert os.path.getsize(cls.webview_coverage_file) > 0, \
|
||||
f"Webview coverage file {cls.webview_coverage_file} is empty"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
"""Clean up test environment after all tests."""
|
||||
if cls.temp_dir:
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
@classmethod
|
||||
def generate_coverage_reports(cls):
|
||||
"""Generate real coverage reports by running tests."""
|
||||
log("Generating coverage reports (this may take a while)...")
|
||||
|
||||
# Run extension tests with coverage
|
||||
try:
|
||||
# Get absolute paths
|
||||
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
|
||||
webview_dir = os.path.join(root_dir, 'webview-ui')
|
||||
|
||||
# Use xvfb-run on Linux
|
||||
if sys.platform.startswith('linux'):
|
||||
cmd = f"cd {root_dir} && xvfb-run -a npm run test:coverage > {cls.extension_coverage_file} 2>&1"
|
||||
else:
|
||||
cmd = f"cd {root_dir} && npm run test:coverage > {cls.extension_coverage_file} 2>&1"
|
||||
|
||||
log("Running extension tests...")
|
||||
log(f"Command: {cmd}")
|
||||
result = subprocess.run(cmd, shell=True, check=False, capture_output=True, text=True)
|
||||
log(f"Extension tests exit code: {result.returncode}")
|
||||
|
||||
# Run webview tests with coverage
|
||||
log("Running webview tests...")
|
||||
cmd = f"cd {webview_dir} && npm run test:coverage > {cls.webview_coverage_file} 2>&1"
|
||||
log(f"Command: {cmd}")
|
||||
result = subprocess.run(cmd, shell=True, check=False, capture_output=True, text=True)
|
||||
log(f"Webview tests exit code: {result.returncode}")
|
||||
|
||||
# Verify files were created
|
||||
if file_exists(cls.extension_coverage_file):
|
||||
ext_size = get_file_size(cls.extension_coverage_file)
|
||||
log(f"Extension coverage file created: {cls.extension_coverage_file} (size: {ext_size} bytes)")
|
||||
else:
|
||||
log(f"WARNING: Extension coverage file was not created: {cls.extension_coverage_file}")
|
||||
|
||||
if file_exists(cls.webview_coverage_file):
|
||||
web_size = get_file_size(cls.webview_coverage_file)
|
||||
log(f"Webview coverage file created: {cls.webview_coverage_file} (size: {web_size} bytes)")
|
||||
else:
|
||||
log(f"WARNING: Webview coverage file was not created: {cls.webview_coverage_file}")
|
||||
|
||||
log("Coverage reports generation completed.")
|
||||
except Exception as e:
|
||||
log(f"Error generating coverage reports: {e}")
|
||||
import traceback
|
||||
log(traceback.format_exc())
|
||||
|
||||
# Create empty files if tests fail
|
||||
log("Creating fallback coverage files...")
|
||||
with open(cls.extension_coverage_file, 'w') as f:
|
||||
f.write("No coverage data available")
|
||||
with open(cls.webview_coverage_file, 'w') as f:
|
||||
f.write("No coverage data available")
|
||||
|
||||
def test_extract_coverage(self):
|
||||
"""Test extract_coverage function with both extension and webview coverage."""
|
||||
# Check if verbose mode is enabled
|
||||
if '-v' in sys.argv or '--verbose' in sys.argv:
|
||||
set_verbose(True)
|
||||
|
||||
# Verify files exist before testing
|
||||
self.assertTrue(file_exists(self.extension_coverage_file),
|
||||
f"Extension coverage file does not exist: {self.extension_coverage_file}")
|
||||
self.assertTrue(file_exists(self.webview_coverage_file),
|
||||
f"Webview coverage file does not exist: {self.webview_coverage_file}")
|
||||
|
||||
# Log file sizes
|
||||
ext_size = get_file_size(self.extension_coverage_file)
|
||||
web_size = get_file_size(self.webview_coverage_file)
|
||||
log(f"Extension coverage file size: {ext_size} bytes")
|
||||
log(f"Webview coverage file size: {web_size} bytes")
|
||||
|
||||
# Test extension coverage
|
||||
log("Testing extension coverage extraction...")
|
||||
ext_coverage_pct = extract_coverage(self.extension_coverage_file, 'extension')
|
||||
|
||||
# Check that coverage percentage is a float
|
||||
self.assertIsInstance(ext_coverage_pct, float)
|
||||
|
||||
# Check that coverage percentage is between 0 and 100
|
||||
self.assertGreaterEqual(ext_coverage_pct, 0)
|
||||
self.assertLessEqual(ext_coverage_pct, 100)
|
||||
|
||||
# Log coverage percentage for debugging
|
||||
log(f"Extension coverage: {ext_coverage_pct}%")
|
||||
|
||||
# Test webview coverage
|
||||
log("Testing webview coverage extraction...")
|
||||
web_coverage_pct = extract_coverage(self.webview_coverage_file, 'webview')
|
||||
|
||||
# Convert to float if it's an integer
|
||||
if isinstance(web_coverage_pct, int):
|
||||
web_coverage_pct = float(web_coverage_pct)
|
||||
|
||||
# Check that coverage percentage is a float
|
||||
self.assertIsInstance(web_coverage_pct, float)
|
||||
|
||||
# Check that coverage percentage is between 0 and 100
|
||||
self.assertGreaterEqual(web_coverage_pct, 0)
|
||||
self.assertLessEqual(web_coverage_pct, 100)
|
||||
|
||||
# Log coverage percentage for debugging
|
||||
log(f"Webview coverage: {web_coverage_pct}%")
|
||||
|
||||
def test_compare_coverage(self):
|
||||
"""Test compare_coverage function."""
|
||||
# Test with coverage increase
|
||||
decreased, diff = compare_coverage(80, 90)
|
||||
self.assertFalse(decreased)
|
||||
self.assertEqual(diff, 10)
|
||||
|
||||
# Test with coverage decrease
|
||||
decreased, diff = compare_coverage(90, 80)
|
||||
self.assertTrue(decreased)
|
||||
self.assertEqual(diff, 10)
|
||||
|
||||
# Test with no change
|
||||
decreased, diff = compare_coverage(80, 80)
|
||||
self.assertFalse(decreased)
|
||||
self.assertEqual(diff, 0)
|
||||
|
||||
def test_generate_comment(self):
|
||||
"""Test generate_comment function."""
|
||||
comment = generate_comment(
|
||||
80, 90, 'false', 10,
|
||||
70, 75, 'false', 5
|
||||
)
|
||||
|
||||
# Check that comment contains expected sections
|
||||
self.assertIn('Coverage Report', comment)
|
||||
self.assertIn('Extension Coverage', comment)
|
||||
self.assertIn('Webview Coverage', comment)
|
||||
self.assertIn('Overall Assessment', comment)
|
||||
|
||||
# Check that comment contains coverage percentages
|
||||
self.assertIn('Base branch: 80%', comment)
|
||||
self.assertIn('PR branch: 90%', comment)
|
||||
self.assertIn('Base branch: 70%', comment)
|
||||
self.assertIn('PR branch: 75%', comment)
|
||||
|
||||
# Check that comment contains correct assessment
|
||||
self.assertIn('Coverage increased or remained the same', comment)
|
||||
self.assertIn('Test coverage has been maintained or improved', comment)
|
||||
|
||||
@patch('coverage_check.requests.get')
|
||||
@patch('coverage_check.requests.post')
|
||||
@patch('coverage_check.requests.patch')
|
||||
def test_post_comment_new(self, mock_patch, mock_post, mock_get):
|
||||
"""Test post_comment function when creating a new comment."""
|
||||
# Create a temporary comment file
|
||||
comment_file = os.path.join(self.temp_dir.name, 'comment.md')
|
||||
with open(comment_file, 'w') as f:
|
||||
f.write('<!-- COVERAGE_REPORT -->\nTest comment')
|
||||
|
||||
# Mock the API responses
|
||||
mock_get.return_value = MagicMock(status_code=200, json=lambda: [])
|
||||
mock_post.return_value = MagicMock(status_code=201)
|
||||
|
||||
# Test post_comment function
|
||||
post_comment(comment_file, '123', 'owner/repo', 'token')
|
||||
|
||||
# Check that the correct API calls were made
|
||||
mock_get.assert_called_once()
|
||||
mock_post.assert_called_once()
|
||||
mock_patch.assert_not_called()
|
||||
|
||||
@patch('coverage_check.requests.get')
|
||||
@patch('coverage_check.requests.post')
|
||||
@patch('coverage_check.requests.patch')
|
||||
def test_post_comment_update(self, mock_patch, mock_post, mock_get):
|
||||
"""Test post_comment function when updating an existing comment."""
|
||||
# Create a temporary comment file
|
||||
comment_file = os.path.join(self.temp_dir.name, 'comment.md')
|
||||
with open(comment_file, 'w') as f:
|
||||
f.write('<!-- COVERAGE_REPORT -->\nTest comment')
|
||||
|
||||
# Mock the API responses
|
||||
mock_get.return_value = MagicMock(
|
||||
status_code=200,
|
||||
json=lambda: [{'id': 456, 'body': '<!-- COVERAGE_REPORT -->\nOld comment'}]
|
||||
)
|
||||
mock_patch.return_value = MagicMock(status_code=200)
|
||||
|
||||
# Test post_comment function
|
||||
post_comment(comment_file, '123', 'owner/repo', 'token')
|
||||
|
||||
# Check that the correct API calls were made
|
||||
mock_get.assert_called_once()
|
||||
mock_patch.assert_called_once()
|
||||
mock_post.assert_not_called()
|
||||
|
||||
def test_set_github_output(self):
|
||||
"""Test set_github_output function."""
|
||||
# Capture stdout
|
||||
with patch('sys.stdout', new=MagicMock()) as mock_stdout:
|
||||
# Mock environment without GITHUB_OUTPUT
|
||||
with patch.dict('os.environ', {}, clear=True):
|
||||
set_github_output('test_name', 'test_value')
|
||||
|
||||
# Check that the correct output was printed to stdout
|
||||
mock_stdout.assert_has_calls([
|
||||
# GitHub Actions output format (deprecated method)
|
||||
call.write('::set-output name=test_name::test_value\n'),
|
||||
call.flush(),
|
||||
# Human readable format
|
||||
call.write('test_name: test_value\n'),
|
||||
call.flush()
|
||||
], any_order=False)
|
||||
|
||||
# Reset mock for next test
|
||||
mock_stdout.reset_mock()
|
||||
|
||||
# Test with GITHUB_OUTPUT environment variable
|
||||
with patch.dict('os.environ', {'GITHUB_OUTPUT': '/tmp/github_output'}), \
|
||||
patch('builtins.open', mock_open()) as mock_file:
|
||||
set_github_output('test_name', 'test_value')
|
||||
|
||||
# Check that file was written to
|
||||
mock_file.assert_called_once_with('/tmp/github_output', 'a')
|
||||
mock_file().write.assert_called_once_with('test_name=test_value\n')
|
||||
|
||||
# Check that human readable output was printed
|
||||
mock_stdout.assert_has_calls([
|
||||
call.write('test_name: test_value\n'),
|
||||
call.flush()
|
||||
], any_order=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,435 @@
|
||||
name: cli-publish
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 12 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_target:
|
||||
description: "Which publish flow to run"
|
||||
required: true
|
||||
default: "main"
|
||||
type: choice
|
||||
options:
|
||||
- main
|
||||
- nightly
|
||||
git_tag:
|
||||
description: "Existing release tag to publish when publish_target=main, for example cli-v0.1.0"
|
||||
required: false
|
||||
type: string
|
||||
confirm_publish:
|
||||
description: 'Required when publish_target=main. Type "publish" to confirm release publish.'
|
||||
required: false
|
||||
type: string
|
||||
force_nightly_publish:
|
||||
description: "Force nightly publish even with no commits in last 24h"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: .
|
||||
|
||||
jobs:
|
||||
publish-main:
|
||||
name: Publish cline
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
if: |
|
||||
github.repository == 'cline/cline' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.event.inputs.publish_target == 'main' &&
|
||||
github.event.inputs.confirm_publish == 'publish' &&
|
||||
!endsWith(github.actor, '[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.git_tag }}
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: "1.3.13"
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.x"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Verify publish tooling
|
||||
run: |
|
||||
NPM_VERSION=$(npm --version)
|
||||
echo "npm ${NPM_VERSION}"
|
||||
IFS=. read -r major minor patch <<EOF
|
||||
${NPM_VERSION}
|
||||
EOF
|
||||
if [ "$major" -lt 11 ] || { [ "$major" -eq 11 ] && [ "$minor" -lt 5 ]; } || { [ "$major" -eq 11 ] && [ "$minor" -eq 5 ] && [ "$patch" -lt 1 ]; }; then
|
||||
echo "npm 11.5.1 or newer is required for trusted publishing"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Validate release tag
|
||||
id: version
|
||||
env:
|
||||
TAG: ${{ github.event.inputs.git_tag }}
|
||||
run: |
|
||||
if [ -z "$TAG" ]; then
|
||||
echo "git_tag is required when publish_target=main"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! printf "%s\n" "$TAG" | grep -Eq '^cli-v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||
echo "git_tag must look like cli-vX.Y.Z, got: ${TAG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION="${TAG#cli-v}"
|
||||
PACKAGE_VERSION=$(node -p "require('./apps/cli/package.json').version")
|
||||
|
||||
if [ "$PACKAGE_VERSION" != "$VERSION" ]; then
|
||||
echo "apps/cli/package.json version ${PACKAGE_VERSION} does not match ${TAG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! printf "%s\n" "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||
echo "apps/cli/package.json has invalid version: ${VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TAG_COMMIT=$(git rev-parse "${TAG}^{commit}")
|
||||
HEAD_COMMIT=$(git rev-parse HEAD)
|
||||
if [ "$TAG_COMMIT" != "$HEAD_COMMIT" ]; then
|
||||
echo "${TAG} does not point at the checked out commit"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git fetch origin +main:refs/remotes/origin/main
|
||||
if ! git merge-base --is-ancestor "$HEAD_COMMIT" origin/main; then
|
||||
echo "${TAG} is not reachable from origin/main"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build SDK packages
|
||||
run: bun run build:sdk
|
||||
env:
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
|
||||
- name: Run tests
|
||||
run: bun run test
|
||||
|
||||
- name: Build platform binaries
|
||||
run: bun script/build.ts --install-native-variants --skip-sdk-build
|
||||
working-directory: apps/cli
|
||||
env:
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
|
||||
- name: Verify build output
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
EXPECTED=(
|
||||
"@cline/cli-darwin-arm64"
|
||||
"@cline/cli-darwin-x64"
|
||||
"@cline/cli-linux-arm64"
|
||||
"@cline/cli-linux-x64"
|
||||
"@cline/cli-windows-arm64"
|
||||
"@cline/cli-windows-x64"
|
||||
)
|
||||
|
||||
for package_name in "${EXPECTED[@]}"; do
|
||||
dir="apps/cli/dist/${package_name#@cline/}"
|
||||
if [ ! -f "$dir/package.json" ]; then
|
||||
echo "Missing package manifest: $dir/package.json"
|
||||
exit 1
|
||||
fi
|
||||
actual_name=$(node -p "require('./$dir/package.json').name")
|
||||
actual_version=$(node -p "require('./$dir/package.json').version")
|
||||
if [ "$actual_name" != "$package_name" ]; then
|
||||
echo "Expected $package_name, got $actual_name"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$actual_version" != "$VERSION" ]; then
|
||||
echo "Expected $package_name@$VERSION, got $actual_version"
|
||||
exit 1
|
||||
fi
|
||||
ls -lh "$dir/bin/"
|
||||
done
|
||||
|
||||
- name: Publish to NPM with latest tag
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
run: bun script/publish-npm.ts --tag latest
|
||||
working-directory: apps/cli
|
||||
|
||||
- name: Get Previous CLI Tag
|
||||
id: prev_tag
|
||||
env:
|
||||
CURRENT_TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
PREV_TAG=$(git describe --tags --abbrev=0 --match 'cli-v*' "$CURRENT_TAG^" 2>/dev/null || echo "")
|
||||
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get Changelog Entry
|
||||
id: changelog
|
||||
run: |
|
||||
# Grab content between the first "## " header and the next one in apps/cli/CHANGELOG.md
|
||||
CONTENT=$(awk '/^## [0-9]/{if(found) exit; found=1; next} found{print}' apps/cli/CHANGELOG.md)
|
||||
echo "content<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$CONTENT" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ steps.version.outputs.tag }}
|
||||
name: "CLI v${{ steps.version.outputs.version }}"
|
||||
body: |
|
||||
${{ steps.changelog.outputs.content }}
|
||||
|
||||
${{ steps.prev_tag.outputs.prev_tag != '' && format('**Full Changelog**: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, steps.version.outputs.tag) || '' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Summary
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Published cline@${VERSION} to npm with dist-tag 'latest'"
|
||||
echo "Install with: npm install -g cline"
|
||||
|
||||
- name: Post release to Slack
|
||||
uses: slackapi/slack-github-action@v3.0.1
|
||||
with:
|
||||
method: chat.postMessage
|
||||
token: ${{ secrets.SLACK_RELEASE_BOT_TOKEN }}
|
||||
payload: |
|
||||
channel: "C0APVKGGZFC"
|
||||
text: "Cline CLI v${{ steps.version.outputs.version }}"
|
||||
blocks:
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: "Cline CLI v${{ steps.version.outputs.version }}"
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: ${{ toJSON(steps.changelog.outputs.content) }}
|
||||
- type: "context"
|
||||
elements:
|
||||
- type: "mrkdwn"
|
||||
text: "<https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}|View on npm>${{ steps.prev_tag.outputs.prev_tag != '' && format(' | Full Changelog: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, steps.version.outputs.tag) || '' }}"
|
||||
|
||||
publish-nightly:
|
||||
name: Publish cline nightly
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
if: |
|
||||
github.repository == 'cline/cline' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
(
|
||||
github.event_name == 'schedule' ||
|
||||
(
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.event.inputs.publish_target == 'nightly'
|
||||
)
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check for recent commits
|
||||
id: check_commits
|
||||
env:
|
||||
FORCE_PUBLISH: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.force_nightly_publish == 'true' }}
|
||||
run: |
|
||||
if [ "$FORCE_PUBLISH" = "true" ]; then
|
||||
echo "force_nightly_publish enabled, proceeding with publish"
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$(git rev-list --count HEAD --since='24 hours ago')" -eq 0 ]; then
|
||||
echo "No commits in last 24 hours, skipping publish"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Found recent commits, proceeding with publish"
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: "1.3.13"
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.x"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Verify publish tooling
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: |
|
||||
NPM_VERSION=$(npm --version)
|
||||
echo "npm ${NPM_VERSION}"
|
||||
IFS=. read -r major minor patch <<EOF
|
||||
${NPM_VERSION}
|
||||
EOF
|
||||
if [ "$major" -lt 11 ] || { [ "$major" -eq 11 ] && [ "$minor" -lt 5 ]; } || { [ "$major" -eq 11 ] && [ "$minor" -eq 5 ] && [ "$patch" -lt 1 ]; }; then
|
||||
echo "npm 11.5.1 or newer is required for trusted publishing"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun install
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build SDK packages
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun run build:sdk
|
||||
env:
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
|
||||
- name: Run tests
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun run test
|
||||
|
||||
- name: Generate nightly version
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
id: version
|
||||
run: |
|
||||
BASE_VERSION=$(node -p "require('./apps/cli/package.json').version")
|
||||
TIMESTAMP=$(date +%s)
|
||||
VERSION="${BASE_VERSION}-nightly.${TIMESTAMP}"
|
||||
|
||||
echo "Base version: ${BASE_VERSION}"
|
||||
echo "Generated nightly version: ${VERSION}"
|
||||
echo "base_version=${BASE_VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Update nightly package version
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
node -e '
|
||||
const fs = require("node:fs");
|
||||
const path = "apps/cli/package.json";
|
||||
const pkg = JSON.parse(fs.readFileSync(path, "utf8"));
|
||||
pkg.version = process.env.VERSION;
|
||||
fs.writeFileSync(path, `${JSON.stringify(pkg, null, "\t")}\n`);
|
||||
'
|
||||
cat apps/cli/package.json | grep '"version"'
|
||||
|
||||
- name: Build platform binaries
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun script/build.ts --install-native-variants --skip-sdk-build
|
||||
working-directory: apps/cli
|
||||
env:
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
|
||||
- name: Verify build output
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
EXPECTED=(
|
||||
"@cline/cli-darwin-arm64"
|
||||
"@cline/cli-darwin-x64"
|
||||
"@cline/cli-linux-arm64"
|
||||
"@cline/cli-linux-x64"
|
||||
"@cline/cli-windows-arm64"
|
||||
"@cline/cli-windows-x64"
|
||||
)
|
||||
|
||||
for package_name in "${EXPECTED[@]}"; do
|
||||
dir="apps/cli/dist/${package_name#@cline/}"
|
||||
if [ ! -f "$dir/package.json" ]; then
|
||||
echo "Missing package manifest: $dir/package.json"
|
||||
exit 1
|
||||
fi
|
||||
actual_name=$(node -p "require('./$dir/package.json').name")
|
||||
actual_version=$(node -p "require('./$dir/package.json').version")
|
||||
if [ "$actual_name" != "$package_name" ]; then
|
||||
echo "Expected $package_name, got $actual_name"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$actual_version" != "$VERSION" ]; then
|
||||
echo "Expected $package_name@$VERSION, got $actual_version"
|
||||
exit 1
|
||||
fi
|
||||
ls -lh "$dir/bin/"
|
||||
done
|
||||
|
||||
- name: Publish to NPM with nightly tag
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
run: bun script/publish-npm.ts --tag nightly
|
||||
working-directory: apps/cli
|
||||
|
||||
- name: Summary
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Published cline@${VERSION} to npm with dist-tag 'nightly'"
|
||||
echo "Install with: npm install -g cline@nightly"
|
||||
@@ -0,0 +1,100 @@
|
||||
name: ext-jb-test-integration
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: jetbrains-trigger-${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
trigger-integration-test:
|
||||
name: Run Tests
|
||||
runs-on: ubuntu-latest
|
||||
# Auto-run only for trusted PR authors. Anyone else needs a maintainer
|
||||
# to opt their PR in by commenting /test-jetbrains.
|
||||
if: |
|
||||
(github.event_name == 'pull_request_target' &&
|
||||
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.pull_request.author_association)) ||
|
||||
(github.event_name == 'issue_comment' &&
|
||||
github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '/test-jetbrains') &&
|
||||
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association))
|
||||
steps:
|
||||
- name: Generate GitHub App Token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v1
|
||||
with:
|
||||
app-id: ${{ vars.CLINE_JETBRAINS_APP_ID }}
|
||||
private-key: ${{ secrets.CLINE_JETBRAINS_APP_KEY }}
|
||||
owner: cline
|
||||
repositories: intellij-plugin
|
||||
|
||||
- name: Get PR details (for issue_comment trigger)
|
||||
id: pr-details
|
||||
if: github.event_name == 'issue_comment'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
PR_DATA=$(gh api repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
|
||||
echo "head_ref=$(echo "$PR_DATA" | jq -r '.head.ref')" >> $GITHUB_OUTPUT
|
||||
echo "head_sha=$(echo "$PR_DATA" | jq -r '.head.sha')" >> $GITHUB_OUTPUT
|
||||
echo "title=$(echo "$PR_DATA" | jq -r '.title')" >> $GITHUB_OUTPUT
|
||||
echo "html_url=$(echo "$PR_DATA" | jq -r '.html_url')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Sanitize untrusted inputs
|
||||
id: sanitize
|
||||
env:
|
||||
RAW_BRANCH_NAME: ${{ github.event_name == 'pull_request_target' && github.head_ref || steps.pr-details.outputs.head_ref }}
|
||||
RAW_PR_TITLE: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.title || steps.pr-details.outputs.title }}
|
||||
run: |
|
||||
# Sanitize branch name for JSON
|
||||
BRANCH_NAME_JSON=$(jq -n --arg b "$RAW_BRANCH_NAME" '$b')
|
||||
echo "branch_name=$BRANCH_NAME_JSON" >> $GITHUB_OUTPUT
|
||||
|
||||
# Sanitize PR title for JSON
|
||||
PR_TITLE_JSON=$(jq -n --arg t "$RAW_PR_TITLE" '$t')
|
||||
echo "pr_title=$PR_TITLE_JSON" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Trigger IntelliJ Plugin Integration Test
|
||||
env:
|
||||
BRANCH_NAME: ${{ steps.sanitize.outputs.branch_name }}
|
||||
PR_TITLE: ${{ steps.sanitize.outputs.pr_title }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
|
||||
PR_URL: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.html_url || steps.pr-details.outputs.html_url }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer ${{ steps.app-token.outputs.token }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
-H "User-Agent: cline-pr-trigger" \
|
||||
-H "Content-Type: application/json" \
|
||||
https://api.github.com/repos/cline/intellij-plugin/dispatches \
|
||||
-d @- <<EOF
|
||||
{
|
||||
"event_type": "cline-pr-check",
|
||||
"client_payload": {
|
||||
"pr_number": "$PR_NUMBER",
|
||||
"branch_name": $BRANCH_NAME,
|
||||
"action": "${{ github.event.action }}",
|
||||
"sha": "$PR_SHA",
|
||||
"pr_title": $PR_TITLE,
|
||||
"pr_url": "$PR_URL"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
- name: Log trigger details
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
|
||||
run: |
|
||||
echo "Triggered IntelliJ Plugin integration test for:"
|
||||
echo " PR #$PR_NUMBER"
|
||||
echo " Trigger: ${{ github.event_name }}"
|
||||
echo " Action: ${{ github.event.action }}"
|
||||
echo " SHA: $PR_SHA"
|
||||
@@ -0,0 +1,294 @@
|
||||
name: ext-vscode-publish-legacy
|
||||
|
||||
# Publishes the legacy (pre-SDK-migration) VS Code extension from the
|
||||
# `legacy-extension` branch. This branch holds the npm-based 3.89.x codebase,
|
||||
# rolled forward under a 4.0.x version so existing 4.0.0 users still receive
|
||||
# the update. The main `ext-vscode-publish-stable.yml` workflow (bun-based)
|
||||
# stays the path for releasing main once the SDK migration is solid.
|
||||
#
|
||||
# This workflow lives on and is dispatched from `main` (so it satisfies the
|
||||
# default-branch dispatch requirement), but it checks out and builds the
|
||||
# `legacy-extension` branch.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release-type:
|
||||
description: "Choose release type (release or pre-release)"
|
||||
required: true
|
||||
default: "release"
|
||||
type: choice
|
||||
options:
|
||||
- pre-release
|
||||
- release
|
||||
branch:
|
||||
description: "Branch holding the legacy extension code"
|
||||
required: true
|
||||
default: "legacy-extension"
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
checks: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: ext-vscode-publish-legacy-${{ github.event.inputs.branch }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Gate the publish on the legacy branch's own npm-based test suite. We can't
|
||||
# reuse ./.github/workflows/ext-vscode-test.yml here — on main that's the
|
||||
# bun-based suite and it would test main, not the legacy branch — so the
|
||||
# essential quality + test steps are inlined against the checked-out legacy
|
||||
# branch.
|
||||
test:
|
||||
name: Test Legacy Extension
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.branch }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
apps/vscode/package-lock.json
|
||||
apps/vscode/webview-ui/package-lock.json
|
||||
|
||||
- name: Install extension dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: npm --prefix apps/vscode ci
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install webview-ui dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: npm --prefix apps/vscode/webview-ui ci
|
||||
|
||||
- name: Run Quality Checks (lint + typecheck)
|
||||
run: npm run ci:check-all
|
||||
|
||||
- name: Build Tests and Extension
|
||||
id: build_step
|
||||
run: npm run ci:build
|
||||
|
||||
- name: Unit Tests
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
|
||||
run: npm run test:unit
|
||||
|
||||
- name: Extension Integration Tests
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
|
||||
run: xvfb-run -a npm run test:coverage
|
||||
|
||||
- name: Webview Tests
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
|
||||
run: |
|
||||
cd webview-ui
|
||||
npm run test:coverage
|
||||
|
||||
publish:
|
||||
needs: test
|
||||
name: Publish Legacy Extension
|
||||
runs-on: ubuntu-latest
|
||||
environment: publish
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
|
||||
steps:
|
||||
# Check out the legacy branch (NOT main). fetch-depth: 0 + tags so we
|
||||
# can create/push the release tag and compute the previous tag.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.branch }}
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
lfs: true
|
||||
|
||||
- name: Resolve Release Tag
|
||||
id: resolve_tag
|
||||
working-directory: ${{ github.workspace }}
|
||||
env:
|
||||
BRANCH: ${{ github.event.inputs.branch }}
|
||||
run: |
|
||||
# Tag is derived from the package version on the legacy branch.
|
||||
VERSION=$(node -p "require('./apps/vscode/package.json').version")
|
||||
TAG="v$VERSION"
|
||||
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.]+)?$ ]]; then
|
||||
echo "Error: derived tag '$TAG' does not match vX.Y.Z"
|
||||
exit 1
|
||||
fi
|
||||
TAG_REF="refs/tags/$TAG"
|
||||
HEAD_SHA=$(git rev-parse HEAD)
|
||||
|
||||
if git show-ref --verify --quiet "$TAG_REF"; then
|
||||
TAG_SHA=$(git rev-list -n 1 "$TAG_REF^{commit}")
|
||||
if [[ "$TAG_SHA" != "$HEAD_SHA" ]]; then
|
||||
echo "Error: tag '$TAG' already exists at $TAG_SHA, not at branch head ($HEAD_SHA)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Tag '$TAG' already exists at branch head. Continuing."
|
||||
else
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag "$TAG" "$HEAD_SHA"
|
||||
git push origin "$TAG_REF"
|
||||
echo "Created and pushed tag '$TAG' from $BRANCH head $HEAD_SHA."
|
||||
fi
|
||||
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install extension dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: npm --prefix apps/vscode install --include=optional
|
||||
|
||||
- name: Install webview-ui dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: npm --prefix apps/vscode/webview-ui install --include=optional
|
||||
|
||||
- name: Install Publishing Tools
|
||||
run: npm install -g @vscode/vsce ovsx
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Verify Tag Matches Package Version
|
||||
run: |
|
||||
TAG="${{ steps.resolve_tag.outputs.tag }}"
|
||||
VERSION="v${{ steps.get_version.outputs.version }}"
|
||||
if [[ "$TAG" != "$VERSION" ]]; then
|
||||
echo "Error: tag '$TAG' does not match package version '$VERSION'"
|
||||
exit 1
|
||||
fi
|
||||
echo "Tag and package version match: $TAG"
|
||||
|
||||
- name: Verify Changelog Entry
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
EXPECTED_HEADING="## [${{ steps.get_version.outputs.version }}]"
|
||||
FIRST_HEADING=$(grep -m 1 '^## \[' CHANGELOG.md || true)
|
||||
if [[ "$FIRST_HEADING" != "$EXPECTED_HEADING" ]]; then
|
||||
echo "Error: CHANGELOG.md must start with '$EXPECTED_HEADING' before publishing."
|
||||
echo "Current first release heading: ${FIRST_HEADING:-<none>}"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found changelog entry for ${{ steps.get_version.outputs.version }}"
|
||||
|
||||
- name: Verify Marketplace Tokens
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_PAT }}
|
||||
OVSX_PAT: ${{ secrets.OVSX_PAT }}
|
||||
run: |
|
||||
if [[ -z "$VSCE_PAT" ]]; then
|
||||
echo "Error: VSCE_PAT is required to publish the stable VS Code extension."
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "$OVSX_PAT" ]]; then
|
||||
echo "Error: OVSX_PAT is required to publish the stable Open VSX extension."
|
||||
exit 1
|
||||
fi
|
||||
echo "Marketplace publish tokens are configured."
|
||||
|
||||
- name: Package and Publish Extension
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_PAT }}
|
||||
OVSX_PAT: ${{ secrets.OVSX_PAT }}
|
||||
CLINE_ENVIRONMENT: production
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
# OpenTelemetry production defaults (can be overridden at runtime)
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
RELEASE_TYPE: ${{ github.event.inputs.release-type }}
|
||||
run: |
|
||||
# Swap README.marketplace.md into README.md so both the GitHub
|
||||
# release artifact (vsce package below) and the marketplace
|
||||
# publish (npm run publish:marketplace below, which swaps
|
||||
# internally as an idempotent no-op) ship the same README.
|
||||
node scripts/marketplace-readme.mjs swap-in
|
||||
trap 'node scripts/marketplace-readme.mjs restore' EXIT
|
||||
|
||||
# Required to generate the .vsix
|
||||
vsce package --allow-package-secrets sendgrid --out "cline-${{ steps.get_version.outputs.version }}.vsix"
|
||||
|
||||
if [ "$RELEASE_TYPE" = "pre-release" ]; then
|
||||
npm run publish:marketplace:prerelease
|
||||
echo "Successfully published pre-release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
|
||||
else
|
||||
npm run publish:marketplace
|
||||
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
|
||||
fi
|
||||
|
||||
- name: Get Previous Tag
|
||||
id: prev_tag
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
CURRENT_TAG="${{ steps.resolve_tag.outputs.tag }}"
|
||||
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
|
||||
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get Changelog Entry
|
||||
id: changelog
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
# Get content between first ## [ and second ## [
|
||||
CONTENT=$(awk '/^## \[/{if(found) exit; found=1; next} found{print}' CHANGELOG.md)
|
||||
echo "content<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$CONTENT" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ steps.resolve_tag.outputs.tag }}
|
||||
files: "apps/vscode/*.vsix"
|
||||
body: |
|
||||
${{ steps.changelog.outputs.content }}
|
||||
|
||||
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.resolve_tag.outputs.tag }}
|
||||
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Post release to Slack
|
||||
uses: slackapi/slack-github-action@v3.0.1
|
||||
with:
|
||||
method: chat.postMessage
|
||||
token: ${{ secrets.SLACK_RELEASE_BOT_TOKEN }}
|
||||
payload: |
|
||||
channel: "C0APVKGGZFC"
|
||||
text: "Cline ${{ steps.resolve_tag.outputs.tag }} (legacy)"
|
||||
blocks:
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: "*Cline ${{ steps.resolve_tag.outputs.tag }} (legacy)*"
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: ${{ toJSON(steps.changelog.outputs.content) }}
|
||||
- type: "context"
|
||||
elements:
|
||||
- type: "mrkdwn"
|
||||
text: "Full Changelog: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.resolve_tag.outputs.tag }}"
|
||||
@@ -0,0 +1,138 @@
|
||||
name: ext-vscode-publish-nightly
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Every day at 4:00 AM PST (12:00 UTC)
|
||||
- cron: "0 12 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
run-name: "Publish Nightly from ${{ github.ref_name }} @ ${{ github.sha }}"
|
||||
|
||||
# Prevent concurrent publish runs on the same branch. The nightly publish script
|
||||
# generates the extension version from a seconds-resolution timestamp, so parallel
|
||||
# runs on the same ref can collide on the same version and cause publish failures
|
||||
# or inconsistent tagging. Runs on different branches proceed independently.
|
||||
concurrency:
|
||||
group: ext-vscode-publish-nightly-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
if: github.repository == 'cline/cline' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dpc/sdk-migration-simpler-login')
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: ./.github/workflows/ext-vscode-test.yml
|
||||
|
||||
publish:
|
||||
needs: test
|
||||
permissions:
|
||||
contents: write
|
||||
name: Publish Cline (Nightly) Extension
|
||||
if: github.repository == 'cline/cline' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dpc/sdk-migration-simpler-login')
|
||||
runs-on: ubuntu-latest
|
||||
environment: PublishNightly
|
||||
# The VS Code extension's package.json and lockfiles live under apps/vscode/
|
||||
# (the repo root has no package.json). Mirror ext-vscode-test.yml so install
|
||||
# and publish steps run in the correct workspace.
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
|
||||
steps:
|
||||
- name: Checkout selected branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
lfs: true
|
||||
persist-credentials: false
|
||||
|
||||
- name: Show build source
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
echo "Building ref: $GITHUB_REF"
|
||||
echo "Building sha: $GITHUB_SHA"
|
||||
git --no-pager log -1 --oneline
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Node is still REQUIRED in the publish job (not just for install): the publish
|
||||
# scripts run as `node ./scripts/publish-*.mjs` and shell out to `npx ovsx`.
|
||||
# setup-bun does not provide a Node runtime, so keep setup-node here.
|
||||
# Pinned to Node 22 because newer LTS (Node 24 / npm 11) can make vsce's
|
||||
# `npm list` dependency detection fail with ELSPROBLEMS during packaging.
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
# Single root install resolves the whole bun workspace at once (replaces the
|
||||
# per-package `npm ci` steps for apps/vscode + webview-ui).
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; build dist/ before
|
||||
# packaging/publishing the extension.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
# vsce is now a workspace devDependency (on node_modules/.bin), but ovsx is not
|
||||
# vendored and the publish script invokes it via `npx ovsx`, so install ovsx
|
||||
# globally here (npm is available via setup-node). vsce is installed globally
|
||||
# too to preserve the script's existing PATH expectations.
|
||||
- name: Install Publishing Tools
|
||||
run: npm install -g @vscode/vsce ovsx
|
||||
|
||||
- name: Publish Nightly Extension
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_PAT }}
|
||||
OVSX_PAT: ${{ secrets.OVSX_PAT }}
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
CLINE_ENVIRONMENT: production
|
||||
# OpenTelemetry production defaults (can be overridden at runtime)
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
# The script itself runs under `node ./scripts/publish-nightly.mjs`; bun run
|
||||
# just launches it. Node + npm (for `npx ovsx`) are provided by setup-node above.
|
||||
run: bun run publish:marketplace:nightly
|
||||
|
||||
- name: Tag published commit
|
||||
working-directory: ${{ github.workspace }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
SAFE_REF=$(echo "$GITHUB_REF_NAME" | tr '/[:upper:]' '-[:lower:]' | tr -cd 'a-z0-9._-')
|
||||
SHORT_SHA=$(git rev-parse --short=12 HEAD)
|
||||
TIMESTAMP=$(date -u +"%Y%m%d%H%M%S")
|
||||
TAG="nightly-${SAFE_REF}-${TIMESTAMP}-${SHORT_SHA}"
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a "$TAG" -m "Cline Nightly published from ${GITHUB_REF_NAME} at ${GITHUB_SHA}"
|
||||
# Use an explicit HTTPS remote with GH_TOKEN because checkout was run with
|
||||
# persist-credentials: false, so actions/checkout did not persist a git credential helper.
|
||||
git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/${TAG}"
|
||||
|
||||
echo "Tagged published commit: $TAG"
|
||||
@@ -0,0 +1,310 @@
|
||||
name: ext-vscode-publish-stable
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release-type:
|
||||
description: "Choose release type (release or pre-release)"
|
||||
required: true
|
||||
default: "release"
|
||||
type: choice
|
||||
options:
|
||||
- pre-release
|
||||
- release
|
||||
auto_create_tag_from_main:
|
||||
description: "Auto-create and push the provided tag from the tested main commit (recommended)"
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
tag:
|
||||
description: "Tag to publish (required in both modes, e.g., v3.1.2)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
checks: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: ext-vscode-publish-stable-${{ github.event.inputs.tag }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
test:
|
||||
uses: ./.github/workflows/ext-vscode-test.yml
|
||||
|
||||
publish:
|
||||
needs: test
|
||||
name: Publish Extension
|
||||
runs-on: ubuntu-latest
|
||||
environment: publish
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
lfs: true
|
||||
|
||||
- name: Resolve Release Tag
|
||||
id: resolve_tag
|
||||
working-directory: ${{ github.workspace }}
|
||||
env:
|
||||
TAG: ${{ github.event.inputs.tag }}
|
||||
AUTO_CREATE: ${{ github.event.inputs.auto_create_tag_from_main }}
|
||||
run: |
|
||||
TESTED_SHA="${{ github.sha }}"
|
||||
WORKFLOW_REF="${{ github.ref }}"
|
||||
|
||||
if [[ -z "$TAG" ]]; then
|
||||
echo "Error: tag input is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.]+)?$ ]]; then
|
||||
echo "Error: tag must match vX.Y.Z (optionally with -suffix or .suffix)"
|
||||
exit 1
|
||||
fi
|
||||
TAG_REF="refs/tags/$TAG"
|
||||
|
||||
git fetch origin main --tags
|
||||
|
||||
if [[ "$AUTO_CREATE" == "true" ]]; then
|
||||
if [[ "$WORKFLOW_REF" != "refs/heads/main" ]]; then
|
||||
echo "Error: auto-create mode requires dispatching from main (current ref: $WORKFLOW_REF)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Auto-create enabled. Using tested workflow SHA: $TESTED_SHA"
|
||||
|
||||
if ! git merge-base --is-ancestor "$TESTED_SHA" origin/main; then
|
||||
echo "Error: tested SHA $TESTED_SHA is not on origin/main"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if git show-ref --verify --quiet "$TAG_REF"; then
|
||||
TAG_SHA=$(git rev-list -n 1 "$TAG_REF^{commit}")
|
||||
if [[ "$TAG_SHA" != "$TESTED_SHA" ]]; then
|
||||
echo "Error: tag '$TAG' already exists at $TAG_SHA, not at tested SHA ($TESTED_SHA)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Tag '$TAG' already exists at tested SHA. Continuing."
|
||||
else
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag "$TAG" "$TESTED_SHA"
|
||||
git push origin "$TAG_REF"
|
||||
echo "Created and pushed tag '$TAG' from tested SHA $TESTED_SHA."
|
||||
fi
|
||||
else
|
||||
if ! git show-ref --verify --quiet "$TAG_REF"; then
|
||||
echo "Error: tag '$TAG' does not exist in the repository"
|
||||
exit 1
|
||||
fi
|
||||
TAG_SHA=$(git rev-list -n 1 "$TAG_REF^{commit}")
|
||||
if [[ "$TAG_SHA" != "$TESTED_SHA" ]]; then
|
||||
echo "Error: existing tag '$TAG' points to $TAG_SHA, but this workflow tested $TESTED_SHA"
|
||||
echo "Dispatch from the tag ref, or from the exact main commit the tag points to."
|
||||
exit 1
|
||||
fi
|
||||
echo "Using existing tag '$TAG' at tested SHA $TESTED_SHA."
|
||||
fi
|
||||
|
||||
git checkout --detach "$TAG_REF^{commit}"
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
echo "resolved_sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Node is still REQUIRED in the publish job (not just for install): the
|
||||
# publish scripts run as `node scripts/publish-*.mjs`, the version step uses
|
||||
# `node -p`, and `npx ovsx` needs npm. setup-bun does not provide a Node
|
||||
# runtime, so keep setup-node. Pinned to Node 22 because newer LTS
|
||||
# (Node 24 / npm 11) can make vsce's `npm list` detection fail with
|
||||
# ELSPROBLEMS during packaging.
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
# Single root install resolves the whole bun workspace at once (replaces the
|
||||
# per-package `npm install` steps for apps/vscode + webview-ui).
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; build dist/ before
|
||||
# packaging/publishing the extension.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
# vsce is a workspace devDependency (on node_modules/.bin), but ovsx is not
|
||||
# vendored and the publish script invokes it via `npx ovsx`, so install ovsx
|
||||
# globally (npm is available via setup-node). vsce is installed globally too
|
||||
# to preserve the script's existing PATH expectations.
|
||||
- name: Install Publishing Tools
|
||||
run: npm install -g @vscode/vsce ovsx
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Verify Tag Matches Package Version
|
||||
run: |
|
||||
TAG="${{ steps.resolve_tag.outputs.tag }}"
|
||||
VERSION="v${{ steps.get_version.outputs.version }}"
|
||||
if [[ "$TAG" != "$VERSION" ]]; then
|
||||
echo "Error: tag '$TAG' does not match package version '$VERSION'"
|
||||
exit 1
|
||||
fi
|
||||
echo "Tag and package version match: $TAG"
|
||||
|
||||
- name: Verify Changelog Entry
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
EXPECTED_HEADING="## [${{ steps.get_version.outputs.version }}]"
|
||||
FIRST_HEADING=$(grep -m 1 '^## \[' CHANGELOG.md || true)
|
||||
if [[ "$FIRST_HEADING" != "$EXPECTED_HEADING" ]]; then
|
||||
echo "Error: CHANGELOG.md must start with '$EXPECTED_HEADING' before publishing."
|
||||
echo "Current first release heading: ${FIRST_HEADING:-<none>}"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found changelog entry for ${{ steps.get_version.outputs.version }}"
|
||||
|
||||
- name: Verify Marketplace Tokens
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_PAT }}
|
||||
OVSX_PAT: ${{ secrets.OVSX_PAT }}
|
||||
run: |
|
||||
if [[ -z "$VSCE_PAT" ]]; then
|
||||
echo "Error: VSCE_PAT is required to publish the stable VS Code extension."
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "$OVSX_PAT" ]]; then
|
||||
echo "Error: OVSX_PAT is required to publish the stable Open VSX extension."
|
||||
exit 1
|
||||
fi
|
||||
echo "Marketplace publish tokens are configured."
|
||||
|
||||
- name: Get Previous Tag
|
||||
id: prev_tag
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
CURRENT_TAG="${{ steps.resolve_tag.outputs.tag }}"
|
||||
PREV_TAG=$(
|
||||
git tag --merged "$CURRENT_TAG^" --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname \
|
||||
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.]+)?$' \
|
||||
| head -n 1 || true
|
||||
)
|
||||
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get Changelog Entry
|
||||
id: changelog
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: |
|
||||
# Get content between the matching version heading and the next release heading.
|
||||
CONTENT=$(awk -v version="${{ steps.get_version.outputs.version }}" '
|
||||
$0 == "## [" version "]" { found=1; next }
|
||||
found && /^## \[/ { exit }
|
||||
found { print }
|
||||
END { if (!found) exit 1 }
|
||||
' CHANGELOG.md)
|
||||
echo "content<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$CONTENT" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Package and Publish Extension
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_PAT }}
|
||||
OVSX_PAT: ${{ secrets.OVSX_PAT }}
|
||||
CLINE_ENVIRONMENT: production
|
||||
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
|
||||
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
|
||||
# OpenTelemetry production defaults (can be overridden at runtime)
|
||||
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
|
||||
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
|
||||
RELEASE_TYPE: ${{ github.event.inputs.release-type }}
|
||||
run: |
|
||||
# Swap README.marketplace.md into README.md so both the GitHub
|
||||
# release artifact (vsce package below) and the marketplace
|
||||
# publish (npm run publish:marketplace below, which swaps
|
||||
# internally as an idempotent no-op) ship the same README.
|
||||
node scripts/marketplace-readme.mjs swap-in
|
||||
trap 'node scripts/marketplace-readme.mjs restore' EXIT
|
||||
|
||||
# Required to generate the .vsix. --no-dependencies: the extension
|
||||
# is fully esbuild-bundled, and under the bun workspace the @cline/*
|
||||
# deps are symlinks pointing outside the package, so without this vsce
|
||||
# would walk them and pull the whole monorepo into the .vsix.
|
||||
vsce package --no-dependencies --allow-package-secrets sendgrid --out "cline-${{ steps.get_version.outputs.version }}.vsix"
|
||||
|
||||
# These scripts run under `node scripts/publish-marketplace.mjs`;
|
||||
# bun run just launches them. Node + npm (for `npx ovsx`) come from
|
||||
# setup-node above.
|
||||
if [ "$RELEASE_TYPE" = "pre-release" ]; then
|
||||
bun run publish:marketplace:prerelease
|
||||
echo "Successfully published pre-release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
|
||||
else
|
||||
bun run publish:marketplace
|
||||
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
|
||||
fi
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ steps.resolve_tag.outputs.tag }}
|
||||
files: "apps/vscode/*.vsix"
|
||||
body: |
|
||||
${{ steps.changelog.outputs.content }}
|
||||
|
||||
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.resolve_tag.outputs.tag }}
|
||||
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Post release to Slack
|
||||
uses: slackapi/slack-github-action@v3.0.1
|
||||
with:
|
||||
method: chat.postMessage
|
||||
token: ${{ secrets.SLACK_RELEASE_BOT_TOKEN }}
|
||||
payload: |
|
||||
channel: "C0APVKGGZFC"
|
||||
text: "Cline ${{ steps.resolve_tag.outputs.tag }}"
|
||||
blocks:
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: "*Cline ${{ steps.resolve_tag.outputs.tag }}*"
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: ${{ toJSON(steps.changelog.outputs.content) }}
|
||||
- type: "context"
|
||||
elements:
|
||||
- type: "mrkdwn"
|
||||
text: "Full Changelog: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.resolve_tag.outputs.tag }}"
|
||||
@@ -0,0 +1,179 @@
|
||||
name: ext-vscode-test-e2e
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
runs-on: ubuntu-latest
|
||||
name: Detect Changes
|
||||
outputs:
|
||||
e2e: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.e2e == 'true' }}
|
||||
steps:
|
||||
- id: force
|
||||
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||
run: echo "run_all=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.force.outputs.run_all != 'true'
|
||||
|
||||
- uses: dorny/paths-filter@v3
|
||||
if: steps.force.outputs.run_all != 'true'
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
e2e:
|
||||
- 'apps/vscode/src/**'
|
||||
- 'apps/vscode/webview-ui/**'
|
||||
- 'apps/vscode/proto/**'
|
||||
- 'apps/vscode/tests/**'
|
||||
- 'apps/vscode/scripts/**'
|
||||
- 'apps/vscode/standalone/**'
|
||||
- 'apps/vscode/assets/**'
|
||||
- 'apps/vscode/walkthrough/**'
|
||||
- 'apps/vscode/package.json'
|
||||
- 'apps/vscode/webview-ui/package.json'
|
||||
# Root bun lockfile is authoritative for the whole workspace (incl. apps/vscode).
|
||||
- 'bun.lock'
|
||||
# SDK source packages are local workspace symlinks (@cline/*), so SDK changes affect the build.
|
||||
- 'sdk/packages/**'
|
||||
- 'apps/vscode/buf.yaml'
|
||||
- 'apps/vscode/tsconfig*.json'
|
||||
- 'apps/vscode/biome.jsonc'
|
||||
- 'apps/vscode/esbuild.mjs'
|
||||
- 'apps/vscode/bunfig.toml'
|
||||
- 'apps/vscode/.vscode-test.mjs'
|
||||
- 'apps/vscode/.vscodeignore'
|
||||
- 'apps/vscode/playwright*.ts'
|
||||
- '.github/workflows/ext-vscode-test-e2e.yml'
|
||||
|
||||
matrix_prep:
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.e2e == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
steps:
|
||||
- id: set-matrix
|
||||
run: |
|
||||
echo 'matrix=[{"runner":"ubuntu"},{"runner":"windows"},{"runner":"macos"}]' >> $GITHUB_OUTPUT
|
||||
|
||||
e2e:
|
||||
needs: [detect-changes, matrix_prep]
|
||||
if: needs.detect-changes.outputs.e2e == 'true'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJson(needs.matrix_prep.outputs.matrix) }}
|
||||
runs-on: ${{ matrix.runner }}-latest
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Cache Bun's global install cache - keyed on the authoritative root bun.lock.
|
||||
- name: Cache Bun install cache
|
||||
uses: actions/cache@v4
|
||||
id: bun-cache
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-
|
||||
|
||||
# Cache VS Code installation
|
||||
- name: Cache VS Code
|
||||
uses: actions/cache@v4
|
||||
id: vscode-cache
|
||||
with:
|
||||
path: apps/vscode/.vscode-test
|
||||
key: vscode-${{ runner.os }}-stable-${{ hashFiles('apps/vscode/.vscode-test.mjs', 'apps/vscode/package.json') }}
|
||||
restore-keys: |
|
||||
vscode-${{ runner.os }}-stable-
|
||||
|
||||
# Cache Playwright browsers
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: |
|
||||
~/.cache/ms-playwright
|
||||
~/Library/Caches/ms-playwright
|
||||
~/AppData/Local/ms-playwright
|
||||
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
playwright-browsers-${{ runner.os }}-
|
||||
|
||||
# Single root install resolves the entire bun workspace at once (replaces
|
||||
# the per-package `npm ci` steps for apps/vscode + webview-ui).
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; build dist/
|
||||
# before building/packaging the extension for E2E.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
# Force bash: the Windows runner defaults to pwsh, which can't parse this
|
||||
# POSIX test. Git Bash ships on GitHub's windows-latest images.
|
||||
shell: bash
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
# NOTE: vsce is no longer installed globally. @vscode/vsce is a workspace
|
||||
# devDependency of apps/vscode (resolved into node_modules/.bin), and the
|
||||
# `test:e2e:build` script invokes `vsce` via `bun run`, which puts the local
|
||||
# .bin on PATH. No global install needed.
|
||||
|
||||
- name: Install xvfb on Linux
|
||||
if: matrix.runner == 'ubuntu'
|
||||
run: sudo apt-get update && sudo apt-get install -y xvfb
|
||||
|
||||
# Run optimized E2E tests (eliminates redundant builds)
|
||||
- name: Run E2E tests - Linux
|
||||
if: matrix.runner == 'ubuntu'
|
||||
run: xvfb-run -a bun run test:e2e:optimal
|
||||
|
||||
- name: Run E2E tests - Non-Linux
|
||||
if: matrix.runner != 'ubuntu'
|
||||
run: bun run test:e2e:optimal
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ failure() }}
|
||||
with:
|
||||
name: playwright-recordings-${{ matrix.runner }}
|
||||
path: |
|
||||
test-results/playwright/
|
||||
@@ -0,0 +1,428 @@
|
||||
name: ext-vscode-test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_call:
|
||||
|
||||
# Set default permissions for all jobs
|
||||
permissions:
|
||||
contents: read # Needed to check out code
|
||||
pull-requests: read # Needed for changed-file detection on pull requests
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
runs-on: ubuntu-latest
|
||||
name: Detect Changes
|
||||
outputs:
|
||||
vscode: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.vscode == 'true' }}
|
||||
testing_platform: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.testing_platform == 'true' }}
|
||||
steps:
|
||||
- id: force
|
||||
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call'
|
||||
run: echo "run_all=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.force.outputs.run_all != 'true'
|
||||
|
||||
- uses: dorny/paths-filter@v3
|
||||
if: steps.force.outputs.run_all != 'true'
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
vscode:
|
||||
- 'apps/vscode/src/**'
|
||||
- 'apps/vscode/webview-ui/**'
|
||||
- 'apps/vscode/proto/**'
|
||||
- 'apps/vscode/tests/**'
|
||||
- 'apps/vscode/scripts/**'
|
||||
- 'apps/vscode/standalone/**'
|
||||
- 'apps/vscode/assets/**'
|
||||
- 'apps/vscode/walkthrough/**'
|
||||
- 'apps/vscode/package.json'
|
||||
- 'apps/vscode/webview-ui/package.json'
|
||||
# Root bun lockfile is authoritative for the whole workspace (incl. apps/vscode).
|
||||
- 'bun.lock'
|
||||
# SDK source packages are local workspace symlinks (@cline/*), so SDK changes affect the build.
|
||||
- 'sdk/packages/**'
|
||||
- 'apps/vscode/buf.yaml'
|
||||
- 'apps/vscode/tsconfig*.json'
|
||||
- 'apps/vscode/biome.jsonc'
|
||||
- 'apps/vscode/esbuild.mjs'
|
||||
- 'apps/vscode/bunfig.toml'
|
||||
- 'apps/vscode/.vscode-test.mjs'
|
||||
- 'apps/vscode/test-setup.js'
|
||||
- '.github/workflows/ext-vscode-test.yml'
|
||||
testing_platform:
|
||||
- 'apps/vscode/src/**'
|
||||
- 'apps/vscode/proto/**'
|
||||
- 'apps/vscode/standalone/**'
|
||||
- 'apps/vscode/testing-platform/**'
|
||||
- 'apps/vscode/testing-platform/package.json'
|
||||
- 'apps/vscode/tests/specs/**'
|
||||
- 'apps/vscode/package.json'
|
||||
# Root bun lockfile is authoritative for the whole workspace (incl. apps/vscode).
|
||||
- 'bun.lock'
|
||||
# SDK source packages are local workspace symlinks (@cline/*), so SDK changes affect the build.
|
||||
- 'sdk/packages/**'
|
||||
- 'apps/vscode/buf.yaml'
|
||||
- 'apps/vscode/tsconfig*.json'
|
||||
- 'apps/vscode/esbuild.mjs'
|
||||
- 'apps/vscode/.vscodeignore'
|
||||
- 'apps/vscode/scripts/**'
|
||||
- '.github/workflows/ext-vscode-test.yml'
|
||||
|
||||
quality-checks:
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.vscode == 'true' || needs.detect-changes.outputs.testing_platform == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
name: Quality Checks
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Single root install resolves the entire bun workspace (apps/vscode,
|
||||
# webview-ui, testing-platform and the @cline/* SDK symlinks) at once,
|
||||
# so the previous per-package `npm ci` steps collapse into one.
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; their dist/
|
||||
# output must be built before the extension can type-check/compile.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
- name: Run Quality Checks (Parallel)
|
||||
run: bun run ci:check-all
|
||||
|
||||
vscode-test:
|
||||
needs: [detect-changes, quality-checks]
|
||||
if: needs.detect-changes.outputs.vscode == 'true'
|
||||
env:
|
||||
VSCODE_TEST_VERSION: 1.103.0
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: ${{ matrix.os == 'ubuntu-latest' && 'vscode test' || format('vscode test ({0})', matrix.os) }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
working-directory: apps/vscode
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Single root install resolves the entire bun workspace at once (replaces
|
||||
# the per-package `npm ci` steps for apps/vscode + webview-ui).
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; build dist/
|
||||
# before compiling/testing the extension.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
# NOTE: The old `npm config set script-shell bash` step is intentionally
|
||||
# removed. Scripts are now launched with `bun run`, which uses Bun's own
|
||||
# built-in cross-platform shell rather than npm's configured script-shell,
|
||||
# so that npm-specific Windows workaround no longer applies. Bash-dependent
|
||||
# scripts (e.g. scripts/proto-lint.sh, standalone/runclinecore.sh) are
|
||||
# invoked explicitly via `bash ...` from within the package scripts, and
|
||||
# this job's `defaults.run.shell: bash` (Git Bash on Windows) still covers
|
||||
# the workflow `run:` blocks below.
|
||||
|
||||
- name: Cache VS Code test runtime
|
||||
if: runner.os == 'Windows'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .vscode-test
|
||||
key: vscode-test-runtime-${{ runner.os }}-${{ env.VSCODE_TEST_VERSION }}
|
||||
|
||||
# Build the extension and tests (without redundant checks)
|
||||
- name: Build Tests and Extension
|
||||
id: build_step
|
||||
run: bun run ci:build
|
||||
|
||||
- name: Vitest Suites (SDK adapter + model catalog)
|
||||
id: vitest_tests
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
|
||||
# The vitest config sets passWithNoTests: true, so a broken glob/alias
|
||||
# would "pass" with zero tests. Capture output and assert a non-zero
|
||||
# test count to guard against silent skips.
|
||||
run: |
|
||||
set -o pipefail
|
||||
bun run test:vitest 2>&1 | tee vitest-output.log
|
||||
# Strip ANSI color codes before matching — vitest colorizes the
|
||||
# "Tests N passed" summary, so the count is not adjacent to the
|
||||
# "Tests" label in the raw bytes.
|
||||
if ! sed -r 's/\x1b\[[0-9;]*m//g' vitest-output.log | grep -Eq 'Tests[[:space:]]+[0-9]*[1-9][0-9]* (passed|failed)'; then
|
||||
echo "ERROR: vitest reported zero tests (possible silent skip)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Unit Tests (bun) - Linux
|
||||
id: unit_tests_linux
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
|
||||
# The node-side unit suite (.mocharc spec set) now runs under `bun test`
|
||||
# via scripts/run-bun-unit-tests.ts (one isolated bun process per file).
|
||||
# The runner exits non-zero on any failure and prints a final
|
||||
# "Files: N Pass: P Fail: F" summary; assert a non-zero pass count to
|
||||
# guard against an empty glob silently "passing".
|
||||
run: |
|
||||
set -o pipefail
|
||||
bun run test:unit 2>&1 | tee unit-output.log
|
||||
if ! grep -Eq 'Pass:[[:space:]]+[0-9]*[1-9][0-9]*' unit-output.log; then
|
||||
echo "ERROR: bun unit runner reported zero passing tests (possible silent skip)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Unit Tests (bun) - Non-Linux
|
||||
id: unit_tests_non_linux
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
|
||||
run: |
|
||||
bun run test:unit
|
||||
|
||||
- name: Extension Integration Tests - Linux
|
||||
id: integration_tests_linux
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
|
||||
run: xvfb-run -a bun run test:coverage
|
||||
|
||||
- name: Extension Integration Tests - Non-Linux
|
||||
id: integration_tests_non_linux
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
|
||||
run: |
|
||||
for attempt in 1 2 3; do
|
||||
echo "Running extension integration tests (attempt ${attempt}/3)"
|
||||
if bun run test:integration; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$attempt" -eq 3 ]; then
|
||||
echo "Extension integration tests failed after 3 attempts"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Extension integration tests failed; retrying after short delay"
|
||||
sleep 5
|
||||
done
|
||||
|
||||
- name: Webview Tests with Coverage
|
||||
id: webview_tests
|
||||
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
|
||||
run: |
|
||||
cd webview-ui
|
||||
bun run test:coverage
|
||||
|
||||
- name: Save Coverage Reports
|
||||
uses: actions/upload-artifact@v4
|
||||
# Only upload artifacts on Linux - We only need coverage from one OS
|
||||
if: runner.os == 'Linux'
|
||||
with:
|
||||
name: pr-coverage-reports
|
||||
path: |
|
||||
apps/vscode/webview-ui/coverage/lcov.info
|
||||
|
||||
test-platform-integration:
|
||||
needs: [detect-changes, quality-checks]
|
||||
if: needs.detect-changes.outputs.testing_platform == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/vscode
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# Single root install resolves the whole bun workspace, including the
|
||||
# testing-platform package, so the separate per-package `npm ci` steps
|
||||
# (extension + webview-ui + testing-platform) collapse into one.
|
||||
- name: Install workspace dependencies
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# @cline/* are local workspace symlinks to source packages; build dist/
|
||||
# before compiling the standalone core.
|
||||
- name: Build SDK packages
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Assert better-sqlite3 native binary present
|
||||
run: |
|
||||
NODE_FILE="node_modules/better-sqlite3/build/Release/better_sqlite3.node"
|
||||
if [ ! -f "$NODE_FILE" ]; then
|
||||
echo "ERROR: better-sqlite3 native binary missing at apps/vscode/$NODE_FILE"
|
||||
echo "(bun trustedDependencies postinstall likely did not run)"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found better-sqlite3 native binary: $NODE_FILE"
|
||||
|
||||
- name: Download ripgrep binaries
|
||||
run: bun run download-ripgrep
|
||||
|
||||
- name: Compile Standalone
|
||||
run: bun run compile-standalone
|
||||
|
||||
- name: Running testing platform integration spec tests
|
||||
timeout-minutes: 7
|
||||
run: bun run test:tp-orchestrator -- tests/specs/ --count=1 --coverage
|
||||
|
||||
- name: Save Coverage Reports
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: test-platform-integration-core-coverage
|
||||
path: apps/vscode/coverage/**/lcov.info
|
||||
|
||||
# Keep the required "test" check as a tiny aggregate gate instead of the conditional
|
||||
# VS Code matrix. GitHub treats conditionally skipped jobs as successful required
|
||||
# checks, so the gate below preserves the old required check name while making sure
|
||||
# whichever filtered test jobs were selected actually passed.
|
||||
test:
|
||||
needs: [detect-changes, quality-checks, vscode-test, test-platform-integration]
|
||||
if: ${{ !cancelled() }}
|
||||
runs-on: ubuntu-latest
|
||||
name: test
|
||||
steps:
|
||||
- name: Verify selected test jobs
|
||||
env:
|
||||
DETECT_CHANGES_RESULT: ${{ needs.detect-changes.result }}
|
||||
QUALITY_CHECKS_RESULT: ${{ needs.quality-checks.result }}
|
||||
VSCODE_CHANGED: ${{ needs.detect-changes.outputs.vscode }}
|
||||
TESTING_PLATFORM_CHANGED: ${{ needs.detect-changes.outputs.testing_platform }}
|
||||
VSCODE_TEST_RESULT: ${{ needs.vscode-test.result }}
|
||||
TEST_PLATFORM_RESULT: ${{ needs.test-platform-integration.result }}
|
||||
run: |
|
||||
if [ "$DETECT_CHANGES_RESULT" != "success" ]; then
|
||||
echo "detect-changes did not succeed: $DETECT_CHANGES_RESULT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$VSCODE_CHANGED" != "true" ] && [ "$TESTING_PLATFORM_CHANGED" != "true" ]; then
|
||||
echo "No root test paths changed; skipping root test requirements."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$QUALITY_CHECKS_RESULT" != "success" ]; then
|
||||
echo "quality-checks did not succeed: $QUALITY_CHECKS_RESULT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$VSCODE_CHANGED" = "true" ] && [ "$VSCODE_TEST_RESULT" != "success" ]; then
|
||||
echo "vscode-test did not succeed: $VSCODE_TEST_RESULT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$TESTING_PLATFORM_CHANGED" = "true" ] && [ "$TEST_PLATFORM_RESULT" != "success" ]; then
|
||||
echo "test-platform-integration did not succeed: $TEST_PLATFORM_RESULT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Selected root test jobs passed."
|
||||
|
||||
qlty:
|
||||
needs: [detect-changes, quality-checks, vscode-test, test-platform-integration]
|
||||
if: ${{ !cancelled() && needs.quality-checks.result == 'success' && (needs.vscode-test.result == 'success' || needs.vscode-test.result == 'skipped') && (needs.test-platform-integration.result == 'success' || needs.test-platform-integration.result == 'skipped') && (needs.detect-changes.outputs.vscode == 'true' || needs.detect-changes.outputs.testing_platform == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
# Run on PRs to main, pushes to main, and manual dispatches
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download unit tests coverage reports
|
||||
if: needs.detect-changes.outputs.vscode == 'true'
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: pr-coverage-reports
|
||||
path: apps/vscode
|
||||
|
||||
- name: Upload core unit tests coverage to Qlty
|
||||
if: needs.detect-changes.outputs.vscode == 'true'
|
||||
uses: qltysh/qlty-action/coverage@v2
|
||||
with:
|
||||
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
|
||||
# we can merge multiple files if necessary
|
||||
files: |
|
||||
apps/vscode/coverage-unit/lcov.info
|
||||
tag: unit:core
|
||||
|
||||
- name: Upload webview-ui unit tests coverage to Qlty
|
||||
if: needs.detect-changes.outputs.vscode == 'true'
|
||||
uses: qltysh/qlty-action/coverage@v2
|
||||
with:
|
||||
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
|
||||
# we can merge multiple files if necessary
|
||||
files: |
|
||||
apps/vscode/webview-ui/coverage/lcov.info
|
||||
tag: unit:webview-ui
|
||||
add-prefix: webview-ui/
|
||||
|
||||
- name: Download test platform integration core coverage artifact
|
||||
if: needs.detect-changes.outputs.testing_platform == 'true'
|
||||
uses: actions/download-artifact@v4
|
||||
continue-on-error: true
|
||||
id: download-integration-coverage
|
||||
with:
|
||||
name: test-platform-integration-core-coverage
|
||||
path: apps/vscode/integration-core-coverage-reports
|
||||
|
||||
- name: Upload core integration tests coverage to Qlty
|
||||
if: needs.detect-changes.outputs.testing_platform == 'true' && steps.download-integration-coverage.outcome == 'success'
|
||||
uses: qltysh/qlty-action/coverage@v2
|
||||
with:
|
||||
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
|
||||
files: apps/vscode/integration-core-coverage-reports/**/lcov.info
|
||||
tag: integration:core
|
||||
@@ -0,0 +1,65 @@
|
||||
name: repo-label-issues
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const body = context.payload.issue.body || '';
|
||||
const labels = context.payload.issue.labels.map(l => l.name);
|
||||
|
||||
// Check if JetBrains Plugin is selected
|
||||
if (body.match(/###\s*Cline Surface\s*\n+JetBrains Plugin/i)) {
|
||||
if (!labels.includes('JetBrains')) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels: ['JetBrains']
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if VSCode Extension is selected
|
||||
if (body.match(/###\s*Cline Surface\s*\n+VSCode Extension/i)) {
|
||||
if (!labels.includes('VS Code')) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels: ['VS Code']
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if CLI is selected
|
||||
if (body.match(/###\s*Cline Surface\s*\n+CLI/i)) {
|
||||
if (!labels.includes('CLI')) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels: ['CLI']
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if beta version checkbox is checked
|
||||
if (body.includes('- [X] I am using a beta version of Cline') || body.includes('- [x] I am using a beta version of Cline')) {
|
||||
if (!labels.includes('beta')) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels: ['beta']
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# This workflow will only label and/or close 30 issues at a time in order to avoid exceeding a rate limit.
|
||||
# More info: https://docs.github.com/en/actions/use-cases-and-examples/project-management/closing-inactive-issues
|
||||
name: repo-stale-issues
|
||||
on:
|
||||
schedule:
|
||||
- cron: "30 1 * * *"
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 60
|
||||
days-before-issue-close: 14
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "This issue is stale because it has been open for 60 days with no activity."
|
||||
close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale."
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
exempt-issue-labels: "pinned,security"
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,282 @@
|
||||
name: sdk-publish
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Publish channel"
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- nightly
|
||||
- latest
|
||||
default: nightly
|
||||
force_publish:
|
||||
description: "Force publish even if there are no commits in the last 24 hours"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
confirm_publish:
|
||||
description: 'Required when channel=latest. Type "publish" to confirm release publish.'
|
||||
required: false
|
||||
type: string
|
||||
schedule:
|
||||
# Run nightly at 2:00 AM UTC
|
||||
- cron: "0 2 * * *"
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: .
|
||||
|
||||
jobs:
|
||||
test:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/sdk-test.yml
|
||||
|
||||
publish-sdk:
|
||||
needs: test
|
||||
name: Publish SDK Packages
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
if: |
|
||||
github.repository == 'cline/cline' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
(
|
||||
github.event_name != 'workflow_dispatch' ||
|
||||
inputs.channel != 'latest' ||
|
||||
(
|
||||
inputs.confirm_publish == 'publish' &&
|
||||
!endsWith(github.actor, '[bot]')
|
||||
)
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Determine publish channel
|
||||
id: channel
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
INPUT_CHANNEL: ${{ inputs.channel }}
|
||||
run: |
|
||||
# Default to nightly for scheduled runs
|
||||
if [ "$EVENT_NAME" = "schedule" ]; then
|
||||
echo "channel=nightly" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "channel=$INPUT_CHANNEL" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Check for recent commits
|
||||
id: check_commits
|
||||
env:
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
FORCE_PUBLISH: ${{ inputs.force_publish }}
|
||||
run: |
|
||||
# Always publish for latest (production) releases
|
||||
if [ "$CHANNEL" = "latest" ]; then
|
||||
echo "Production release requested, proceeding with publish"
|
||||
echo "skip=false" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$FORCE_PUBLISH" = "true" ]; then
|
||||
echo "force_publish enabled, proceeding with publish"
|
||||
echo "skip=false" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$(git rev-list --count HEAD --since="24 hours ago")" -eq 0 ]; then
|
||||
echo "No commits in last 24 hours, skipping publish"
|
||||
echo "skip=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "Found recent commits, proceeding with publish"
|
||||
echo "skip=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Verify trusted publishing context
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: |
|
||||
if [ -z "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ] || [ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ]; then
|
||||
echo "GitHub OIDC request environment is unavailable. Ensure this job has id-token: write for npm trusted publishing."
|
||||
exit 1
|
||||
fi
|
||||
echo "GitHub OIDC request environment is available for npm trusted publishing."
|
||||
|
||||
- name: Setup Bun
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: "1.3.13"
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.x"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Verify publish tooling
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: |
|
||||
NPM_VERSION=$(npm --version)
|
||||
echo "npm ${NPM_VERSION}"
|
||||
IFS=. read -r major minor patch <<EOF
|
||||
${NPM_VERSION}
|
||||
EOF
|
||||
if [ "$major" -lt 11 ] || { [ "$major" -eq 11 ] && [ "$minor" -lt 5 ]; } || { [ "$major" -eq 11 ] && [ "$minor" -eq 5 ] && [ "$patch" -lt 1 ]; }; then
|
||||
echo "npm 11.5.1 or newer is required for trusted publishing"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun install
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build SDK
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Generate shared version
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
id: version
|
||||
env:
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
run: |
|
||||
BASE_VERSION=$(node -p "require('./sdk/packages/llms/package.json').version")
|
||||
|
||||
if [ "$CHANNEL" = "nightly" ]; then
|
||||
TIMESTAMP=$(date +%s)
|
||||
VERSION="${BASE_VERSION}-nightly.${TIMESTAMP}"
|
||||
else
|
||||
VERSION="$BASE_VERSION"
|
||||
fi
|
||||
|
||||
echo "Base version: $BASE_VERSION"
|
||||
echo "Channel: $CHANNEL"
|
||||
echo "Publish version: $VERSION"
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Update all package versions and lockfile
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: bun sdk/scripts/version.ts "$VERSION"
|
||||
|
||||
- name: Verify publishability
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: bun sdk/scripts/check-publish.ts
|
||||
|
||||
- name: Prepare package tarball directory
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
run: mkdir -p "$RUNNER_TEMP/sdk-npm-packs"
|
||||
|
||||
# Pack with Bun so workspace/catalog protocols are resolved in the tarball,
|
||||
# then publish that tarball with npm so npm trusted publishing can use GitHub OIDC.
|
||||
# Publish sequentially in dependency order: shared → llms → agents → core → sdk
|
||||
- name: Publish @cline/shared
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Publishing @cline/shared@${VERSION} with tag '${CHANNEL}'..."
|
||||
cd sdk/packages/shared
|
||||
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
|
||||
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
|
||||
|
||||
- name: Publish @cline/llms
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Publishing @cline/llms@${VERSION} with tag '${CHANNEL}'..."
|
||||
cd sdk/packages/llms
|
||||
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
|
||||
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
|
||||
|
||||
- name: Publish @cline/agents
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Publishing @cline/agents@${VERSION} with tag '${CHANNEL}'..."
|
||||
cd sdk/packages/agents
|
||||
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
|
||||
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
|
||||
|
||||
- name: Publish @cline/core
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Publishing @cline/core@${VERSION} with tag '${CHANNEL}'..."
|
||||
cd sdk/packages/core
|
||||
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
|
||||
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
|
||||
|
||||
- name: Publish @cline/sdk
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
NPM_CONFIG_PROVENANCE: "true"
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Publishing @cline/sdk@${VERSION} with tag '${CHANNEL}'..."
|
||||
cd sdk/packages/sdk
|
||||
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
|
||||
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
|
||||
|
||||
- name: Create package tags for production publish
|
||||
if: steps.check_commits.outputs.skip != 'true' && steps.channel.outputs.channel == 'latest'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
for PKG in shared llms agents core sdk; do
|
||||
TAG="sdk/${PKG}/v${VERSION}"
|
||||
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
|
||||
echo "Tag already exists locally: ${TAG}"
|
||||
else
|
||||
git tag -a "${TAG}" -m "@cline/${PKG}@${VERSION}"
|
||||
echo "Created tag: ${TAG}"
|
||||
fi
|
||||
|
||||
# Ensure remote has the tag; this is idempotent if tag already exists remotely.
|
||||
git push origin "refs/tags/${TAG}"
|
||||
done
|
||||
|
||||
- name: Summary
|
||||
if: steps.check_commits.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
CHANNEL: ${{ steps.channel.outputs.channel }}
|
||||
run: |
|
||||
echo "Published SDK packages with tag '${CHANNEL}':"
|
||||
echo " - @cline/shared@${VERSION}"
|
||||
echo " - @cline/llms@${VERSION}"
|
||||
echo " - @cline/agents@${VERSION}"
|
||||
echo " - @cline/core@${VERSION}"
|
||||
echo " - @cline/sdk@${VERSION}"
|
||||
if [ "$CHANNEL" = "latest" ]; then
|
||||
echo "Created git tags:"
|
||||
echo " - sdk/shared/v${VERSION}"
|
||||
echo " - sdk/llms/v${VERSION}"
|
||||
echo " - sdk/agents/v${VERSION}"
|
||||
echo " - sdk/core/v${VERSION}"
|
||||
echo " - sdk/sdk/v${VERSION}"
|
||||
fi
|
||||
@@ -0,0 +1,112 @@
|
||||
name: sdk-test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "sdk/**"
|
||||
- ".github/workflows/sdk-test.yml"
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "sdk/**"
|
||||
- ".github/workflows/sdk-test.yml"
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: .
|
||||
|
||||
jobs:
|
||||
quality-checks:
|
||||
runs-on: ubuntu-latest
|
||||
name: Quality Checks
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: "1.3.13"
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Typecheck
|
||||
run: |
|
||||
bun run build:sdk
|
||||
bun run -F @cline/cli build
|
||||
bun run types
|
||||
|
||||
- name: Lint & Format
|
||||
run: bun run lint
|
||||
|
||||
test:
|
||||
needs: quality-checks
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
node-version: "24.x"
|
||||
- os: windows-latest
|
||||
node-version: "24.x"
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: Test (${{ matrix.os }}, Node ${{ matrix.node-version }})
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: "1.3.13"
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build SDK
|
||||
id: build_sdk_step
|
||||
run: bun run build:sdk
|
||||
|
||||
- name: Build CLI
|
||||
id: build_cli_step
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' }}
|
||||
run: bun -F @cline/cli build
|
||||
|
||||
- name: Run Tests
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os != 'windows-latest' }}
|
||||
run: bun run test
|
||||
|
||||
- name: Run SDK Tests (Windows)
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'windows-latest' }}
|
||||
run: bun -F './sdk/packages/**' test
|
||||
|
||||
- name: Smoke test SQLite under Node
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && matrix.os != 'windows-latest' }}
|
||||
timeout-minutes: 10
|
||||
run: bun sdk/scripts/ci-node-smoke.ts
|
||||
|
||||
- name: Run TUI e2e tests
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'ubuntu-latest' && matrix.node-version == '24.x' }}
|
||||
run: bun -F @cline/cli test:e2e:cli:tui
|
||||
|
||||
- name: Verify packages are publishable
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'ubuntu-latest' && matrix.node-version == '24.x' }}
|
||||
run: bun sdk/scripts/check-publish.ts
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
out
|
||||
dist
|
||||
dist-standalone
|
||||
node_modules
|
||||
tmp
|
||||
.vscode-test/
|
||||
*.vsix
|
||||
|
||||
.DS_Store
|
||||
.idea
|
||||
.husky/_/
|
||||
|
||||
pnpm-lock.yaml
|
||||
|
||||
.clineignore
|
||||
.cline/enterprise
|
||||
.cline/remote-config
|
||||
**/.cline/remote-config
|
||||
.venv
|
||||
.actrc
|
||||
CLAUDE.local.md
|
||||
|
||||
apps/vscode/webview-ui/src/**/*.js
|
||||
apps/vscode/webview-ui/src/**/*.js.map
|
||||
|
||||
# Ignore coverage directories and files
|
||||
coverage
|
||||
coverage-unit
|
||||
.nyc_output
|
||||
# But don't ignore the coverage scripts in .github/scripts/
|
||||
!.github/scripts/coverage/
|
||||
|
||||
*evals.env
|
||||
.env
|
||||
.secrets
|
||||
.github/act/.secrets
|
||||
|
||||
.worktrees
|
||||
|
||||
## Generated files ##
|
||||
apps/vscode/src/generated/
|
||||
apps/vscode/src/shared/proto/
|
||||
apps/vscode/webview-ui/src/services/grpc-client.ts
|
||||
*.tsbuildinfo
|
||||
|
||||
# E2E Tests
|
||||
test-results
|
||||
|
||||
/.github/act
|
||||
/pkg
|
||||
.secrets
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Smoke test results (generated)
|
||||
evals/smoke-tests/results/
|
||||
|
||||
.tui-test
|
||||
secrets.json
|
||||
tui-traces
|
||||
tests/**/cache
|
||||
|
||||
# Backup created by scripts/marketplace-readme.mjs while publishing.
|
||||
# Should never be committed: only exists if a publish aborts mid-swap.
|
||||
.README.github.bak
|
||||
|
||||
# Tauri generated code
|
||||
apps/*/src-tauri/gen
|
||||
apps/*/src-tauri/bin
|
||||
apps/examples/*/src-tauri/gen
|
||||
apps/examples/*/src-tauri/bin
|
||||
# Tauri UI test snapshots
|
||||
apps/*/src/tests/.tui-test
|
||||
apps/*/src/tests/tui-traces
|
||||
apps/vscode/webview-ui/src/**/*.js
|
||||
apps/vscode/webview-ui/src/**/*.js.map
|
||||
|
||||
|
||||
# SDK Session files / User data
|
||||
.cline/data
|
||||
.cline/tmp
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
.cline/**/managed.json
|
||||
.cline/**/bundle.json
|
||||
apps/vscode/tsconfig.test.generated.json
|
||||
.next/dev/static
|
||||
**/src-tauri/target/debug/.fingerprint
|
||||
apps/examples/desktop-app/src-tauri/target
|
||||
apps/examples/desktop-app/webview/.next
|
||||
|
||||
# Next.js generated type shim (churns between dev and build)
|
||||
apps/examples/desktop-app/webview/next-env.d.ts
|
||||
@@ -0,0 +1,4 @@
|
||||
title = "Cline SDK secret scanning"
|
||||
|
||||
[extend]
|
||||
useDefault = true
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "evals/cline-bench"]
|
||||
path = evals/cline-bench
|
||||
url = https://github.com/cline/cline-bench.git
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"strictness": 2,
|
||||
"triggerOnUpdates": true,
|
||||
"statusCheck": true,
|
||||
"rules": [
|
||||
{
|
||||
"id": "sdk-tool-handler-telemetry",
|
||||
"rule": "Any new tool handler added to packages/agents/src or packages/core/src that performs a user-visible action (writes files, executes commands, modifies state, calls external APIs) must include a call to captureToolUsage() from packages/core/src/services/telemetry/core-events.ts, or emit a task.tool_used event via telemetry.capture(). Pure read-only helpers and getters are exempt. When in doubt, prefer instrumentation.",
|
||||
"scope": [
|
||||
"sdk/packages/agents/src/**",
|
||||
"sdk/packages/core/src/**"
|
||||
],
|
||||
"severity": "high"
|
||||
},
|
||||
{
|
||||
"id": "sdk-session-lifecycle-telemetry",
|
||||
"rule": "New session start, end, or state-transition code paths in packages/core/src must call the appropriate typed helper from packages/core/src/services/telemetry/core-events.ts (captureTaskCreated, captureTaskCompleted, captureConversationTurnEvent, captureTokenUsage, etc.). Do not inline raw telemetry.capture() calls for session lifecycle events — always use the typed helper, which guarantees a consistent payload shape.",
|
||||
"scope": [
|
||||
"sdk/packages/core/src/cline-core/**",
|
||||
"sdk/packages/core/src/runtime/**"
|
||||
],
|
||||
"severity": "high"
|
||||
},
|
||||
{
|
||||
"id": "sdk-no-raw-event-strings",
|
||||
"rule": "All telemetry event name strings must be sourced from CORE_TELEMETRY_EVENTS in packages/core/src/services/telemetry/core-events.ts. If a PR introduces a string literal in a telemetry.capture(), telemetry.captureRequired(), or recordCounter()/recordHistogram()/recordGauge() call that does not reference CORE_TELEMETRY_EVENTS, flag it. New events must be added to CORE_TELEMETRY_EVENTS first, with a typed capture helper created alongside them.",
|
||||
"scope": [
|
||||
"sdk/packages/core/src/**",
|
||||
"sdk/packages/agents/src/**",
|
||||
"apps/cli/src/**",
|
||||
"apps/vscode/src/**"
|
||||
],
|
||||
"severity": "medium"
|
||||
},
|
||||
{
|
||||
"id": "sdk-auth-telemetry-completeness",
|
||||
"rule": "Any new OAuth or authentication provider added under packages/core/src/auth must emit all four lifecycle events using the typed helpers from core-events.ts: captureAuthStarted (at flow entry), captureAuthSucceeded + identifyAccount (on token success), captureAuthFailed (on error), and captureAuthLoggedOut (on token invalidation or explicit logout). Flag PRs that introduce a new auth flow file without all four. Cross-reference packages/core/src/auth/cline.ts and packages/core/src/auth/codex.ts as canonical examples.",
|
||||
"scope": [
|
||||
"sdk/packages/core/src/auth/**"
|
||||
],
|
||||
"severity": "high"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"path": "sdk/packages/core/src/services/telemetry/core-events.ts",
|
||||
"description": "Single source of truth for all telemetry event names (CORE_TELEMETRY_EVENTS) and their typed capture helper functions. Every PR touching telemetry must be evaluated against this catalog. New events must be defined here first."
|
||||
},
|
||||
{
|
||||
"path": "sdk/packages/shared/src/services/telemetry.ts",
|
||||
"description": "ITelemetryService interface definition. Defines the contract all telemetry implementations must satisfy (capture, captureRequired, recordCounter, recordHistogram, recordGauge, flush, dispose)."
|
||||
},
|
||||
{
|
||||
"path": "sdk/packages/core/src/services/telemetry/TelemetryService.ts",
|
||||
"description": "Reference implementation of ITelemetryService used by all hosts. Multi-adapter fan-out service that forwards events to OpenTelemetry."
|
||||
},
|
||||
{
|
||||
"path": "sdk/packages/core/src/services/telemetry/OpenTelemetryProvider.ts",
|
||||
"description": "OpenTelemetry-backed provider that wires logs/metrics/traces exporters. Contains createConfiguredTelemetryService and createConfiguredTelemetryHandle, the canonical factories every host should use."
|
||||
},
|
||||
{
|
||||
"path": "sdk/ARCHITECTURE.md",
|
||||
"description": "Architecture reference. Telemetry design decisions and completion semantics (submit_and_exit anchoring) are documented here. Use as ground truth for design intent."
|
||||
},
|
||||
{
|
||||
"path": "sdk/AGENTS.md",
|
||||
"description": "Package boundary rules. Telemetry runtime services live in @cline/core; @cline/agents must not own stateful telemetry. Use to evaluate whether a telemetry change is being made in the correct package."
|
||||
}
|
||||
]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user