Compare commits

..

2 Commits

Author SHA1 Message Date
Dax Raad
54edc4ec31 ci test 2025-04-21 20:07:54 -04:00
Dax Raad
60d159afc1 sync 2025-04-21 20:01:44 -04:00
20 changed files with 218 additions and 387 deletions

View File

@@ -4,7 +4,7 @@ on:
workflow_dispatch:
push:
branches:
- main
- dev
concurrency: ${{ github.workflow }}-${{ github.ref }}
@@ -19,17 +19,30 @@ jobs:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- run: |
npm config set //registry.npmjs.org/:_authToken $NODE_AUTH_TOKEN
npm whoami
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: git fetch --force --tags
- uses: actions/setup-go@v5
with:
go-version: ">=1.23.2"
cache: true
cache-dependency-path: go.sum
- run: go mod download
- name: Go Mod
run: go mod download
# TODO remove temporary workaround
- run: bun i --frozen-lockfile
- run: git reset --hard
- run: cd platform && bun tsc --noEmit
- run: ./platform/scripts/build
- uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser

View File

@@ -3,6 +3,8 @@ name: release
on:
workflow_dispatch:
push:
branches:
- opencode
tags:
- "*"
@@ -25,16 +27,13 @@ jobs:
- uses: actions/setup-go@v5
with:
go-version: ">=1.23.2"
cache: true
cache-dependency-path: go.sum
- run: go mod download
- uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.HOMEBREW_GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUR_KEY: ${{ secrets.AUR_KEY }}

View File

@@ -4,6 +4,7 @@ before:
hooks:
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- darwin
@@ -30,18 +31,11 @@ checksum:
snapshot:
name_template: "0.0.0-{{ .Timestamp }}"
aurs:
- name: opencode
homepage: "https://github.com/opencode-ai/opencode"
description: "terminal based agent that can build anything"
maintainers:
- "kujtimiihoxha <kujtimii.h@gmail.com>"
license: "MIT"
- homepage: "https://github.com/opencode-ai/opencode"
description: "Deploy anything"
private_key: "{{ .Env.AUR_KEY }}"
git_url: "ssh://aur@aur.archlinux.org/opencode-bin.git"
provides:
- opencode
conflicts:
- opencode
git_url: "ssh://aur@aur.archlinux.org/opencode.git"
license: "MIT"
package: |-
install -Dm755 ./opencode "${pkgdir}/usr/bin/opencode"
brews:
@@ -49,7 +43,7 @@ brews:
owner: opencode-ai
name: homebrew-tap
nfpms:
- maintainer: kujtimiihoxha
- maintainer: opencode
description: terminal based agent that can build anything
formats:
- deb

View File

@@ -1,4 +1,4 @@
# OpenCode
# OpenCode
> **⚠️ Early Development Notice:** This project is in early development and is not yet ready for production use. Features may change, break, or be incomplete. Use at your own risk.

View File

@@ -15,7 +15,6 @@ import (
"github.com/kujtimiihoxha/opencode/internal/logging"
"github.com/kujtimiihoxha/opencode/internal/pubsub"
"github.com/kujtimiihoxha/opencode/internal/tui"
"github.com/kujtimiihoxha/opencode/internal/version"
zone "github.com/lrstanley/bubblezone"
"github.com/spf13/cobra"
)
@@ -32,10 +31,6 @@ to assist developers in writing, debugging, and understanding code directly from
cmd.Help()
return nil
}
if cmd.Flag("version").Changed {
fmt.Println(version.Version)
return nil
}
// Load the config
debug, _ := cmd.Flags().GetBool("debug")
@@ -252,7 +247,6 @@ func Execute() {
func init() {
rootCmd.Flags().BoolP("help", "h", false, "Help")
rootCmd.Flags().BoolP("version", "v", false, "Version")
rootCmd.Flags().BoolP("debug", "d", false, "Debug")
rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
}

180
install
View File

@@ -1,180 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
APP=opencode
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
ORANGE='\033[38;2;255;140;0m'
NC='\033[0m' # No Color
requested_version=${VERSION:-}
os=$(uname -s | tr '[:upper:]' '[:lower:]')
if [[ "$os" == "darwin" ]]; then
os="mac"
fi
arch=$(uname -m)
if [[ "$arch" == "aarch64" ]]; then
arch="arm64"
fi
filename="$APP-$os-$arch.tar.gz"
case "$filename" in
*"-linux-"*)
[[ "$arch" == "x86_64" || "$arch" == "arm64" || "$arch" == "i386" ]] || exit 1
;;
*"-mac-"*)
[[ "$arch" == "x86_64" || "$arch" == "arm64" ]] || exit 1
;;
*)
echo "${RED}Unsupported OS/Arch: $os/$arch${NC}"
exit 1
;;
esac
INSTALL_DIR=$HOME/.opencode/bin
mkdir -p "$INSTALL_DIR"
if [ -z "$requested_version" ]; then
url="https://github.com/opencode-ai/opencode/releases/latest/download/$filename"
specific_version=$(curl -s https://api.github.com/repos/opencode-ai/opencode/releases/latest | awk -F'"' '/"tag_name": "/ {gsub(/^v/, "", $4); print $4}')
if [[ $? -ne 0 ]]; then
echo "${RED}Failed to fetch version information${NC}"
exit 1
fi
else
url="https://github.com/opencode-ai/opencode/releases/download/v${requested_version}/$filename"
specific_version=$requested_version
fi
print_message() {
local level=$1
local message=$2
local color=""
case $level in
info) color="${GREEN}" ;;
warning) color="${YELLOW}" ;;
error) color="${RED}" ;;
esac
echo -e "${color}${message}${NC}"
}
check_version() {
if command -v opencode >/dev/null 2>&1; then
opencode_path=$(which opencode)
## TODO: check if version is installed
# installed_version=$(opencode version)
installed_version="0.0.1"
installed_version=$(echo $installed_version | awk '{print $2}')
if [[ "$installed_version" != "$specific_version" ]]; then
print_message info "Installed version: ${YELLOW}$installed_version."
else
print_message info "Version ${YELLOW}$specific_version${GREEN} already installed"
exit 0
fi
fi
}
download_and_install() {
print_message info "Downloading ${ORANGE}opencode ${GREEN}version: ${YELLOW}$specific_version ${GREEN}..."
mkdir -p opencodetmp && cd opencodetmp
curl -# -L $url | tar xz
mv opencode $INSTALL_DIR
cd .. && rm -rf opencodetmp
}
check_version
download_and_install
add_to_path() {
local config_file=$1
local command=$2
if [[ -w $config_file ]]; then
echo -e "\n# opencode" >> "$config_file"
echo "$command" >> "$config_file"
print_message info "Successfully added ${ORANGE}opencode ${GREEN}to \$PATH in $config_file"
else
print_message warning "Manually add the directory to $config_file (or similar):"
print_message info " $command"
fi
}
XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
current_shell=$(basename "$SHELL")
case $current_shell in
fish)
config_files="$HOME/.config/fish/config.fish"
;;
zsh)
config_files="$HOME/.zshrc $HOME/.zshenv $XDG_CONFIG_HOME/zsh/.zshrc $XDG_CONFIG_HOME/zsh/.zshenv"
;;
bash)
config_files="$HOME/.bashrc $HOME/.bash_profile $HOME/.profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile"
;;
ash)
config_files="$HOME/.ashrc $HOME/.profile /etc/profile"
;;
sh)
config_files="$HOME/.ashrc $HOME/.profile /etc/profile"
;;
*)
# Default case if none of the above matches
config_files="$HOME/.bashrc $HOME/.bash_profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile"
;;
esac
config_file=""
for file in $config_files; do
if [[ -f $file ]]; then
config_file=$file
break
fi
done
if [[ -z $config_file ]]; then
print_message error "No config file found for $current_shell. Checked files: ${config_files[@]}"
exit 1
fi
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
case $current_shell in
fish)
add_to_path "$config_file" "fish_add_path $INSTALL_DIR"
;;
zsh)
add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
;;
bash)
add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
;;
ash)
add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
;;
sh)
add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
;;
*)
print_message warning "Manually add the directory to $config_file (or similar):"
print_message info " export PATH=$INSTALL_DIR:\$PATH"
;;
esac
fi
if [ -n "${GITHUB_ACTIONS-}" ] && [ "${GITHUB_ACTIONS}" == "true" ]; then
echo "$INSTALL_DIR" >> $GITHUB_PATH
print_message info "Added $INSTALL_DIR to \$GITHUB_PATH"
fi

View File

@@ -177,7 +177,6 @@ func configureViper() {
viper.SetConfigType("json")
viper.AddConfigPath("$HOME")
viper.AddConfigPath(fmt.Sprintf("$XDG_CONFIG_HOME/%s", appName))
viper.AddConfigPath(fmt.Sprintf("$HOME/.config/%s", appName))
viper.SetEnvPrefix(strings.ToUpper(appName))
viper.AutomaticEnv()
}
@@ -200,25 +199,14 @@ func setDefaults(debug bool) {
// 1. Anthropic
// 2. OpenAI
// 3. Google Gemini
// 4. Groq
// 5. AWS Bedrock
// 4. AWS Bedrock
func setProviderDefaults() {
// Anthropic configuration
if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
viper.SetDefault("providers.anthropic.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.Claude37Sonnet)
viper.SetDefault("agents.task.model", models.Claude37Sonnet)
viper.SetDefault("agents.title.model", models.Claude37Sonnet)
return
}
// OpenAI configuration
if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
viper.SetDefault("providers.openai.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.GPT41)
viper.SetDefault("agents.task.model", models.GPT41Mini)
viper.SetDefault("agents.title.model", models.GPT41Mini)
return
// Groq configuration
if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
viper.SetDefault("providers.groq.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.QWENQwq)
viper.SetDefault("agents.task.model", models.QWENQwq)
viper.SetDefault("agents.title.model", models.QWENQwq)
}
// Google Gemini configuration
@@ -227,24 +215,29 @@ func setProviderDefaults() {
viper.SetDefault("agents.coder.model", models.Gemini25)
viper.SetDefault("agents.task.model", models.Gemini25Flash)
viper.SetDefault("agents.title.model", models.Gemini25Flash)
return
}
// Groq configuration
if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
viper.SetDefault("providers.groq.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.QWENQwq)
viper.SetDefault("agents.task.model", models.QWENQwq)
viper.SetDefault("agents.title.model", models.QWENQwq)
return
// OpenAI configuration
if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
viper.SetDefault("providers.openai.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.GPT41)
viper.SetDefault("agents.task.model", models.GPT41Mini)
viper.SetDefault("agents.title.model", models.GPT41Mini)
}
// Anthropic configuration
if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
viper.SetDefault("providers.anthropic.apiKey", apiKey)
viper.SetDefault("agents.coder.model", models.Claude37Sonnet)
viper.SetDefault("agents.task.model", models.Claude37Sonnet)
viper.SetDefault("agents.title.model", models.Claude37Sonnet)
}
// AWS Bedrock configuration
if hasAWSCredentials() {
viper.SetDefault("agents.coder.model", models.BedrockClaude37Sonnet)
viper.SetDefault("agents.task.model", models.BedrockClaude37Sonnet)
viper.SetDefault("agents.title.model", models.BedrockClaude37Sonnet)
return
}
}

View File

@@ -96,19 +96,19 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
// Determine server type for specialized handling
serverName := getServerNameFromContext(ctx)
logging.Debug("Server type detected", "serverName", serverName)
// Check if this server has sent file watchers
hasFileWatchers := len(watchers) > 0
// For servers that need file preloading, we'll use a smart approach
if shouldPreloadFiles(serverName) || !hasFileWatchers {
go func() {
startTime := time.Now()
filesOpened := 0
// Determine max files to open based on server type
maxFilesToOpen := 50 // Default conservative limit
switch serverName {
case "typescript", "typescript-language-server", "tsserver", "vtsls":
// TypeScript servers benefit from seeing more files
@@ -117,17 +117,17 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
// Java servers need to see many files for project model
maxFilesToOpen = 200
}
// First, open high-priority files
highPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)
filesOpened += highPriorityFilesOpened
if cnf.DebugLSP {
logging.Debug("Opened high-priority files",
logging.Debug("Opened high-priority files",
"count", highPriorityFilesOpened,
"serverName", serverName)
}
// If we've already opened enough high-priority files, we might not need more
if filesOpened >= maxFilesToOpen {
if cnf.DebugLSP {
@@ -137,9 +137,9 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
}
return
}
// For the remaining slots, walk the directory and open matching files
err := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
@@ -199,10 +199,10 @@ func (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watc
func (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {
cnf := config.Get()
filesOpened := 0
// Define patterns for high-priority files based on server type
var patterns []string
switch serverName {
case "typescript", "typescript-language-server", "tsserver", "vtsls":
patterns = []string{
@@ -256,7 +256,7 @@ func (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName
"**/.editorconfig",
}
}
// For each pattern, find and open matching files
for _, pattern := range patterns {
// Use doublestar.Glob to find files matching the pattern (supports ** patterns)
@@ -267,17 +267,17 @@ func (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName
}
continue
}
for _, match := range matches {
// Convert relative path to absolute
fullPath := filepath.Join(w.workspacePath, match)
// Skip directories and excluded files
info, err := os.Stat(fullPath)
if err != nil || info.IsDir() || shouldExcludeFile(fullPath) {
continue
}
// Open the file
if err := w.client.OpenFile(ctx, fullPath); err != nil {
if cnf.DebugLSP {
@@ -289,17 +289,17 @@ func (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName
logging.Debug("Opened high-priority file", "path", fullPath)
}
}
// Add a small delay to prevent overwhelming the server
time.Sleep(20 * time.Millisecond)
// Limit the number of files opened per pattern
if filesOpened >= 5 && (serverName != "java" && serverName != "jdtls") {
break
}
}
}
return filesOpened
}
@@ -310,16 +310,16 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
// Store the watcher in the context for later use
ctx = context.WithValue(ctx, "workspaceWatcher", w)
// If the server name isn't already in the context, try to detect it
if _, ok := ctx.Value("serverName").(string); !ok {
serverName := getServerNameFromContext(ctx)
ctx = context.WithValue(ctx, "serverName", serverName)
}
serverName := getServerNameFromContext(ctx)
logging.Debug("Starting workspace watcher", "workspacePath", workspacePath, "serverName", serverName)
// Register handler for file watcher registrations from the server
lsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {
w.AddRegistrations(ctx, id, watchers)
@@ -414,11 +414,7 @@ func (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath str
case event.Op&fsnotify.Create != 0:
// Already handled earlier in the event loop
// Just send the notification if needed
info, err := os.Stat(event.Name)
if err != nil {
logging.Error("Error getting file info", "path", event.Name, "error", err)
return
}
info, _ := os.Stat(event.Name)
if !info.IsDir() && watchKind&protocol.WatchCreate != 0 {
w.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))
}
@@ -686,7 +682,7 @@ func getServerNameFromContext(ctx context.Context) string {
if serverName, ok := ctx.Value("serverName").(string); ok && serverName != "" {
return strings.ToLower(serverName)
}
// Otherwise, try to extract server name from the client command path
if w, ok := ctx.Value("workspaceWatcher").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {
path := strings.ToLower(w.client.Cmd.Path)
@@ -869,7 +865,7 @@ func (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {
if watched, _ := w.isPathWatched(path); watched {
// Get server name for specialized handling
serverName := getServerNameFromContext(ctx)
// Check if the file is a high-priority file that should be opened immediately
// This helps with project initialization for certain language servers
if isHighPriorityFile(path, serverName) {
@@ -885,7 +881,7 @@ func (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {
// For non-high-priority files, we'll use different strategies based on server type
if shouldPreloadFiles(serverName) {
// For servers that benefit from preloading, open files but with limits
// Check file size - for preloading we're more conservative
if info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files
if cnf.DebugLSP {
@@ -893,13 +889,13 @@ func (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {
}
return
}
// Check file extension for common source files
ext := strings.ToLower(filepath.Ext(path))
// Only preload source files for the specific language
shouldOpen := false
switch serverName {
case "typescript", "typescript-language-server", "tsserver", "vtsls":
shouldOpen = ext == ".ts" || ext == ".js" || ext == ".tsx" || ext == ".jsx"
@@ -917,7 +913,7 @@ func (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {
// For unknown servers, be conservative
shouldOpen = false
}
if shouldOpen {
// Don't need to check if it's already open - the client.OpenFile handles that
if err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {
@@ -947,13 +943,13 @@ func isHighPriorityFile(path string, serverName string) bool {
fileName == "main.js"
case "gopls":
// For Go, we want to open go.mod files immediately
return fileName == "go.mod" ||
return fileName == "go.mod" ||
fileName == "go.sum" ||
// Also open main.go files
fileName == "main.go"
case "rust-analyzer":
// For Rust, we want to open Cargo.toml files immediately
return fileName == "Cargo.toml" ||
return fileName == "Cargo.toml" ||
fileName == "Cargo.lock" ||
// Also open lib.rs and main.rs
fileName == "lib.rs" ||

View File

@@ -21,9 +21,12 @@ type editorCmp struct {
textarea textarea.Model
}
type EditorKeyMaps struct {
type FocusEditorMsg bool
type focusedEditorKeyMaps struct {
Send key.Binding
OpenEditor key.Binding
Blur key.Binding
}
type bluredEditorKeyMaps struct {
@@ -32,10 +35,29 @@ type bluredEditorKeyMaps struct {
OpenEditor key.Binding
}
var editorMaps = EditorKeyMaps{
var focusedKeyMaps = focusedEditorKeyMaps{
Send: key.NewBinding(
key.WithKeys("enter", "ctrl+s"),
key.WithHelp("enter", "send message"),
key.WithKeys("ctrl+s"),
key.WithHelp("ctrl+s", "send message"),
),
Blur: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "focus messages"),
),
OpenEditor: key.NewBinding(
key.WithKeys("ctrl+e"),
key.WithHelp("ctrl+e", "open editor"),
),
}
var bluredKeyMaps = bluredEditorKeyMaps{
Send: key.NewBinding(
key.WithKeys("ctrl+s", "enter"),
key.WithHelp("ctrl+s/enter", "send message"),
),
Focus: key.NewBinding(
key.WithKeys("i"),
key.WithHelp("i", "focus editor"),
),
OpenEditor: key.NewBinding(
key.WithKeys("ctrl+e"),
@@ -66,9 +88,6 @@ func openEditor() tea.Cmd {
if err != nil {
return util.ReportError(err)
}
if len(content) == 0 {
return util.ReportWarn("Message is empty")
}
os.Remove(tmpfile.Name())
return SendMsg{
Text: string(content),
@@ -87,6 +106,7 @@ func (m *editorCmp) send() tea.Cmd {
value := m.textarea.Value()
m.textarea.Reset()
m.textarea.Blur()
if value == "" {
return nil
}
@@ -105,28 +125,32 @@ func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.session = msg
}
return m, nil
case tea.KeyMsg:
if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
return m, nil
case FocusEditorMsg:
if msg {
m.textarea.Focus()
return m, tea.Batch(textarea.Blink, util.CmdHandler(EditorFocusMsg(true)))
}
if key.Matches(msg, editorMaps.OpenEditor) {
case tea.KeyMsg:
if key.Matches(msg, focusedKeyMaps.OpenEditor) {
if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
return m, util.ReportWarn("Agent is working, please wait...")
}
return m, openEditor()
}
// Handle Enter key
if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
value := m.textarea.Value()
if len(value) > 0 && value[len(value)-1] == '\\' {
// If the last character is a backslash, remove it and add a newline
m.textarea.SetValue(value[:len(value)-1] + "\n")
return m, nil
} else {
// Otherwise, send the message
return m, m.send()
}
// if the key does not match any binding, return
if m.textarea.Focused() && key.Matches(msg, focusedKeyMaps.Send) {
return m, m.send()
}
if !m.textarea.Focused() && key.Matches(msg, bluredKeyMaps.Send) {
return m, m.send()
}
if m.textarea.Focused() && key.Matches(msg, focusedKeyMaps.Blur) {
m.textarea.Blur()
return m, util.CmdHandler(EditorFocusMsg(false))
}
if !m.textarea.Focused() && key.Matches(msg, bluredKeyMaps.Focus) {
m.textarea.Focus()
return m, tea.Batch(textarea.Blink, util.CmdHandler(EditorFocusMsg(true)))
}
}
m.textarea, cmd = m.textarea.Update(msg)
@@ -151,7 +175,13 @@ func (m *editorCmp) GetSize() (int, int) {
func (m *editorCmp) BindingKeys() []key.Binding {
bindings := []key.Binding{}
bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
if m.textarea.Focused() {
bindings = append(bindings, layout.KeyMapToSlice(focusedKeyMaps)...)
} else {
bindings = append(bindings, layout.KeyMapToSlice(bluredKeyMaps)...)
}
bindings = append(bindings, layout.KeyMapToSlice(m.textarea.KeyMap)...)
return bindings
}

View File

@@ -14,6 +14,7 @@ import (
"github.com/kujtimiihoxha/opencode/internal/message"
"github.com/kujtimiihoxha/opencode/internal/pubsub"
"github.com/kujtimiihoxha/opencode/internal/session"
"github.com/kujtimiihoxha/opencode/internal/tui/layout"
"github.com/kujtimiihoxha/opencode/internal/tui/styles"
"github.com/kujtimiihoxha/opencode/internal/tui/util"
)
@@ -25,6 +26,7 @@ type cacheItem struct {
type messagesCmp struct {
app *app.App
width, height int
writingMode bool
viewport viewport.Model
session session.Session
messages []message.Message
@@ -36,32 +38,6 @@ type messagesCmp struct {
}
type renderFinishedMsg struct{}
type MessageKeys struct {
PageDown key.Binding
PageUp key.Binding
HalfPageUp key.Binding
HalfPageDown key.Binding
}
var messageKeys = MessageKeys{
PageDown: key.NewBinding(
key.WithKeys("pgdown"),
key.WithHelp("f/pgdn", "page down"),
),
PageUp: key.NewBinding(
key.WithKeys("pgup"),
key.WithHelp("b/pgup", "page up"),
),
HalfPageUp: key.NewBinding(
key.WithKeys("ctrl+u"),
key.WithHelp("ctrl+u", "½ page up"),
),
HalfPageDown: key.NewBinding(
key.WithKeys("ctrl+d", "ctrl+d"),
key.WithHelp("ctrl+d", "½ page down"),
),
}
func (m *messagesCmp) Init() tea.Cmd {
return tea.Batch(m.viewport.Init(), m.spinner.Tick)
}
@@ -69,7 +45,8 @@ func (m *messagesCmp) Init() tea.Cmd {
func (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case EditorFocusMsg:
m.writingMode = bool(msg)
case SessionSelectedMsg:
if msg.ID != m.session.ID {
cmd := m.SetSession(msg)
@@ -83,17 +60,13 @@ func (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.rendering = false
return m, nil
case tea.KeyMsg:
if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
u, cmd := m.viewport.Update(msg)
m.viewport = u
cmds = append(cmds, cmd)
}
case renderFinishedMsg:
m.rendering = false
m.viewport.GotoBottom()
case tea.KeyMsg:
if m.writingMode {
return m, nil
}
case pubsub.Event[message.Message]:
needsRerender := false
if msg.Type == pubsub.CreatedEvent {
@@ -149,6 +122,10 @@ func (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
u, cmd := m.viewport.Update(msg)
m.viewport = u
cmds = append(cmds, cmd)
spinner, cmd := m.spinner.Update(msg)
m.spinner = spinner
cmds = append(cmds, cmd)
@@ -349,24 +326,22 @@ func (m *messagesCmp) working() string {
func (m *messagesCmp) help() string {
text := ""
if m.app.CoderAgent.IsBusy() {
if m.writingMode {
text += lipgloss.JoinHorizontal(
lipgloss.Left,
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render("press "),
styles.BaseStyle.Foreground(styles.Forground).Bold(true).Render("esc"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" to exit cancel"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" to exit writing mode"),
)
} else {
text += lipgloss.JoinHorizontal(
lipgloss.Left,
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render("press "),
styles.BaseStyle.Foreground(styles.Forground).Bold(true).Render("enter"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" to send the message,"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" write"),
styles.BaseStyle.Foreground(styles.Forground).Bold(true).Render(" \\"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" and enter to add a new line"),
styles.BaseStyle.Foreground(styles.Forground).Bold(true).Render("i"),
styles.BaseStyle.Foreground(styles.ForgroundDim).Bold(true).Render(" to start writing"),
)
}
return styles.BaseStyle.
Width(m.width).
Render(text)
@@ -423,26 +398,18 @@ func (m *messagesCmp) SetSession(session session.Session) tea.Cmd {
}
func (m *messagesCmp) BindingKeys() []key.Binding {
return []key.Binding{
m.viewport.KeyMap.PageDown,
m.viewport.KeyMap.PageUp,
m.viewport.KeyMap.HalfPageUp,
m.viewport.KeyMap.HalfPageDown,
}
bindings := layout.KeyMapToSlice(m.viewport.KeyMap)
return bindings
}
func NewMessagesCmp(app *app.App) tea.Model {
s := spinner.New()
s.Spinner = spinner.Pulse
vp := viewport.New(0, 0)
vp.KeyMap.PageUp = messageKeys.PageUp
vp.KeyMap.PageDown = messageKeys.PageDown
vp.KeyMap.HalfPageUp = messageKeys.HalfPageUp
vp.KeyMap.HalfPageDown = messageKeys.HalfPageDown
return &messagesCmp{
app: app,
writingMode: true,
cachedContent: make(map[string]cacheItem),
viewport: vp,
viewport: viewport.New(0, 0),
spinner: s,
}
}

View File

@@ -28,7 +28,7 @@ const (
assistantMessageType
toolMessageType
maxResultHeight = 10
maxResultHeight = 15
)
var diffStyle = diff.NewStyleConfig(diff.WithShowHeader(false), diff.WithShowHunkHeader(false))
@@ -148,7 +148,7 @@ func renderAssistantMessage(
content = "*Finished without output*"
}
content = renderMessage(content, false, true, width, info...)
content = renderMessage(content, false, msg.ID == focusedUIMessageId, width, info...)
messages = append(messages, uiMessage{
ID: msg.ID,
messageType: assistantMessageType,

View File

@@ -116,18 +116,13 @@ func (m *sidebarCmp) sessionSection() string {
func (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {
stats := ""
if additions > 0 && removals > 0 {
additions := styles.BaseStyle.Foreground(styles.Green).PaddingLeft(1).Render(fmt.Sprintf("+%d", additions))
removals := styles.BaseStyle.Foreground(styles.Red).PaddingLeft(1).Render(fmt.Sprintf("-%d", removals))
content := lipgloss.JoinHorizontal(lipgloss.Left, additions, removals)
stats = styles.BaseStyle.Width(lipgloss.Width(content)).Render(content)
stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d additions and %d removals", additions, removals))
} else if additions > 0 {
additions := fmt.Sprintf(" %s", styles.BaseStyle.PaddingLeft(1).Foreground(styles.Green).Render(fmt.Sprintf("+%d", additions)))
stats = styles.BaseStyle.Width(lipgloss.Width(additions)).Render(additions)
stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d additions", additions))
} else if removals > 0 {
removals := fmt.Sprintf(" %s", styles.BaseStyle.PaddingLeft(1).Foreground(styles.Red).Render(fmt.Sprintf("-%d", removals)))
stats = styles.BaseStyle.Width(lipgloss.Width(removals)).Render(removals)
stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d removals", removals))
}
filePathStr := styles.BaseStyle.Render(filePath)
filePathStr := styles.BaseStyle.Foreground(styles.Forground).Render(filePath)
return styles.BaseStyle.
Width(m.width).

View File

@@ -190,6 +190,7 @@ func (c *commandDialogCmp) View() string {
styles.BaseStyle.Width(maxWidth).Render(""),
styles.BaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, commandItems...)),
styles.BaseStyle.Width(maxWidth).Render(""),
styles.BaseStyle.Width(maxWidth).Padding(0, 1).Foreground(styles.ForgroundDim).Render("↑/k: up ↓/j: down enter: select esc: cancel"),
)
return styles.BaseStyle.Padding(1, 2).
@@ -243,3 +244,4 @@ func NewCommandDialogCmp() CommandDialog {
selectedCommandID: "",
}
}

View File

@@ -62,7 +62,7 @@ func (h *helpCmp) render() string {
var (
pairs []string
width int
rows = 10 - 2
rows = 14 - 2
)
for i := 0; i < len(bindings); i += rows {
var (

View File

@@ -46,8 +46,8 @@ func (k initDialogKeyMap) ShortHelp() []key.Binding {
key.WithHelp("enter", "confirm"),
),
key.NewBinding(
key.WithKeys("esc", "q"),
key.WithHelp("esc/q", "cancel"),
key.WithKeys("esc"),
key.WithHelp("esc", "cancel"),
),
key.NewBinding(
key.WithKeys("y", "n"),
@@ -114,7 +114,6 @@ func (m InitDialogCmp) View() string {
Padding(1, 1).
Render("Would you like to initialize this project?")
maxWidth = min(maxWidth, m.width-10)
yesStyle := styles.BaseStyle
noStyle := styles.BaseStyle
@@ -145,6 +144,12 @@ func (m InitDialogCmp) View() string {
Padding(1, 0).
Render(buttons)
help := styles.BaseStyle.
Width(maxWidth).
Padding(0, 1).
Foreground(styles.ForgroundDim).
Render("tab/←/→: toggle y/n: yes/no enter: confirm esc: cancel")
content := lipgloss.JoinVertical(
lipgloss.Left,
title,
@@ -153,6 +158,7 @@ func (m InitDialogCmp) View() string {
question,
buttons,
styles.BaseStyle.Width(maxWidth).Render(""),
help,
)
return styles.BaseStyle.Padding(1, 2).

View File

@@ -67,8 +67,8 @@ var permissionsKeys = permissionsMapping{
key.WithHelp("a", "allow"),
),
AllowSession: key.NewBinding(
key.WithKeys("s"),
key.WithHelp("s", "allow for session"),
key.WithKeys("A"),
key.WithHelp("A", "allow for session"),
),
Deny: key.NewBinding(
key.WithKeys("d"),
@@ -171,7 +171,7 @@ func (p *permissionDialogCmp) renderButtons() string {
}
allowButton := allowStyle.Padding(0, 1).Render("Allow (a)")
allowSessionButton := allowSessionStyle.Padding(0, 1).Render("Allow for session (s)")
allowSessionButton := allowSessionStyle.Padding(0, 1).Render("Allow for session (A)")
denyButton := denyStyle.Padding(0, 1).Render("Deny (d)")
content := lipgloss.JoinHorizontal(
@@ -375,6 +375,9 @@ func (p *permissionDialogCmp) render() string {
contentFinal = p.renderDefaultContent()
}
// Add help text
helpText := styles.BaseStyle.Width(p.width - 4).Padding(0, 1).Foreground(styles.ForgroundDim).Render("←/→/tab: switch options a: allow A: allow for session d: deny enter/space: confirm")
content := lipgloss.JoinVertical(
lipgloss.Top,
title,
@@ -382,7 +385,8 @@ func (p *permissionDialogCmp) render() string {
headerContent,
contentFinal,
buttons,
styles.BaseStyle.Render(strings.Repeat(" ", p.width-4)),
styles.BaseStyle.Render(strings.Repeat(" ", p.width - 4)),
helpText,
)
return styles.BaseStyle.

View File

@@ -122,8 +122,6 @@ func (s *sessionDialogCmp) View() string {
}
}
maxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow
// Limit height to avoid taking up too much screen space
maxVisibleSessions := min(10, len(s.sessions))
@@ -171,6 +169,7 @@ func (s *sessionDialogCmp) View() string {
styles.BaseStyle.Width(maxWidth).Render(""),
styles.BaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),
styles.BaseStyle.Width(maxWidth).Render(""),
styles.BaseStyle.Width(maxWidth).Padding(0, 1).Foreground(styles.ForgroundDim).Render("↑/k: up ↓/j: down enter: select esc: cancel"),
)
return styles.BaseStyle.Padding(1, 2).
@@ -224,3 +223,4 @@ func NewSessionDialogCmp() SessionDialog {
selectedSessionID: "",
}
}

View File

@@ -15,11 +15,12 @@ import (
var ChatPage PageID = "chat"
type chatPage struct {
app *app.App
editor layout.Container
messages layout.Container
layout layout.SplitPaneLayout
session session.Session
app *app.App
editor layout.Container
messages layout.Container
layout layout.SplitPaneLayout
session session.Session
editingMode bool
}
type ChatKeyMap struct {
@@ -33,8 +34,8 @@ var keyMap = ChatKeyMap{
key.WithHelp("ctrl+n", "new session"),
),
Cancel: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "cancel"),
key.WithKeys("ctrl+x"),
key.WithHelp("ctrl+x", "cancel"),
),
}
@@ -64,6 +65,8 @@ func (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
p.session = msg
case chat.EditorFocusMsg:
p.editingMode = bool(msg)
case tea.KeyMsg:
switch {
case key.Matches(msg, keyMap.NewSession):
@@ -133,7 +136,11 @@ func (p *chatPage) View() string {
func (p *chatPage) BindingKeys() []key.Binding {
bindings := layout.KeyMapToSlice(keyMap)
bindings = append(bindings, p.messages.BindingKeys()...)
if p.editingMode {
bindings = append(bindings, p.editor.BindingKeys()...)
} else {
bindings = append(bindings, p.messages.BindingKeys()...)
}
return bindings
}
@@ -148,9 +155,10 @@ func NewChatPage(app *app.App) tea.Model {
layout.WithBorder(true, false, false, false),
)
return &chatPage{
app: app,
editor: editorContainer,
messages: messagesContainer,
app: app,
editor: editorContainer,
messages: messagesContainer,
editingMode: true,
layout: layout.NewSplitPane(
layout.WithLeftPanel(messagesContainer),
layout.WithBottomPanel(editorContainer),

View File

@@ -30,7 +30,7 @@ type keyMap struct {
var keys = keyMap{
Logs: key.NewBinding(
key.WithKeys("ctrl+l"),
key.WithHelp("ctrl+l", "logs"),
key.WithHelp("ctrl+L", "logs"),
),
Quit: key.NewBinding(
@@ -49,7 +49,7 @@ var keys = keyMap{
Commands: key.NewBinding(
key.WithKeys("ctrl+k"),
key.WithHelp("ctrl+k", "commands"),
key.WithHelp("ctrl+K", "commands"),
),
}
@@ -95,6 +95,8 @@ type appModel struct {
showInitDialog bool
initDialog dialog.InitDialogCmp
editingMode bool
}
func (a appModel) Init() tea.Cmd {
@@ -162,6 +164,8 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
a.initDialog.SetSize(msg.Width, msg.Height)
return a, tea.Batch(cmds...)
case chat.EditorFocusMsg:
a.editingMode = bool(msg)
// Status
case util.InfoMsg:
s, cmd := a.status.Update(msg)
@@ -224,6 +228,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
a.app.Permissions.GrantPersistant(msg.Permission)
case dialog.PermissionDeny:
a.app.Permissions.Deny(msg.Permission)
cmd = util.CmdHandler(chat.FocusEditorMsg(true))
}
a.showPermissions = false
return a, cmd
@@ -355,7 +360,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
a.showHelp = !a.showHelp
return a, nil
case key.Matches(msg, helpEsc):
if a.app.CoderAgent.IsBusy() {
if !a.editingMode {
if a.showQuit {
return a, nil
}
@@ -472,7 +477,7 @@ func (a appModel) View() string {
)
}
if !a.app.CoderAgent.IsBusy() {
if a.editingMode {
a.status.SetHelpMsg("ctrl+? help")
} else {
a.status.SetHelpMsg("? help")
@@ -489,7 +494,7 @@ func (a appModel) View() string {
if a.currentPage == page.LogsPage {
bindings = append(bindings, logsKeyReturnKey)
}
if !a.app.CoderAgent.IsBusy() {
if !a.editingMode {
bindings = append(bindings, helpEsc)
}
a.help.SetBindings(bindings)
@@ -580,6 +585,7 @@ func New(app *app.App) tea.Model {
permissions: dialog.NewPermissionDialogCmp(),
initDialog: dialog.NewInitDialogCmp(),
app: app,
editingMode: true,
commands: []dialog.Command{},
pages: map[page.PageID]tea.Model{
page.ChatPage: page.NewChatPage(app),

View File

@@ -1,3 +1,7 @@
#!/usr/bin/env bash
set -e
export DOCKER_PUSH=true
./platform/scripts/build
goreleaser build --clean --snapshot --skip validate
cd sdk/js
bun run release