Add auto-generate PR description feature (Vibe Kanban) (#1479)

* I've completed the implementation. Here's a summary of the changes made:

## Summary

### Backend (Rust)

1. **`crates/services/src/services/config/versions/v8.rs`**
   - Added two new config fields:
     - `pr_auto_description_enabled: bool` - defaults to `false`
     - `pr_auto_description_prompt: Option<String>` - defaults to `None`

2. **`crates/server/src/routes/task_attempts.rs`**
   - Added `auto_generate_description: bool` field to `CreateGitHubPrRequest`
   - Added `DEFAULT_PR_DESCRIPTION_PROMPT` constant with the default prompt
   - Added `trigger_pr_description_follow_up()` helper function that:
     - Gets the custom prompt from config or uses default
     - Replaces `{pr_number}` and `{pr_url}` placeholders
     - Triggers a follow-up (or initial if no session) coding agent execution
   - Modified `create_github_pr()` to call the follow-up trigger after successful PR creation

### Frontend (TypeScript/React)

3. **`frontend/src/components/dialogs/tasks/CreatePRDialog.tsx`**
   - Added `autoGenerateDescription` state, initialized from `config.pr_auto_description_enabled`
   - Added checkbox to toggle auto-generate PR description
   - Included `auto_generate_description` in the API call payload

4. **`frontend/src/pages/settings/GeneralSettings.tsx`**
   - Added "Pull Requests" Card section with:
     - Checkbox to enable/disable auto-generate by default
     - Textarea for custom prompt override

5. **Translation files**
   - Added `autoGenerateLabel` to `tasks.json`
   - Added `pullRequests` section to `settings.json`

6. **`shared/types.ts`** - Auto-generated with new types

### Key Features
- Toggle in PR creation dialog, defaulting to the global config setting
- Settings page for configuring default behavior and custom prompt
- Placeholders `{pr_number}` and `{pr_url}` for custom prompts
- Uses the same executor profile as the original task attempt
- Graceful error handling (warns but doesn't fail PR creation if follow-up fails)

* Cleanup script changes for task attempt 46e66dfc-f608-47a4-baca-e38399d2da15

* Done! I've updated the placeholder text in `settings.json` to show the actual default prompt. Now users can see exactly what prompt the AI agent will use by default, and they know what they're customizing when they enter a custom prompt.

The placeholder now shows:
```
Update the GitHub PR that was just created with a better title and description.
The PR number is #{pr_number} and the URL is {pr_url}.

Analyze the changes in this branch and write:
1. A concise, descriptive title that summarizes the changes
2. A detailed description that explains:
   - What changes were made
   - Why they were made (based on the task context)
   - Any important implementation details

Use `gh pr edit` to update the PR.
```

I also updated the helper text to mention the placeholder variables (`{pr_number}` and `{pr_url}`) so users know what variables they can use in their custom prompts.

* Cleanup script changes for task attempt 46e66dfc-f608-47a4-baca-e38399d2da15

* Done! Updated the label to "Ask AI agent to generate a better PR description" as requested.

* All done! The refactoring is complete:

**Summary of changes:**

1. **Created `crates/server/src/routes/task_attempts/pr.rs`** - New submodule containing all PR-related code:
   - Types: `CreateGitHubPrRequest`, `CreatePrError`, `AttachPrResponse`, `PrCommentsResponse`, `GetPrCommentsError`
   - Constants: `DEFAULT_PR_DESCRIPTION_PROMPT`
   - Functions: `trigger_pr_description_follow_up`, `create_github_pr`, `attach_existing_pr`, `get_pr_comments`

2. **Updated `crates/server/src/routes/task_attempts.rs`** - Added `pub mod pr;` and updated router to use `pr::` prefix for PR routes

3. **Updated `crates/server/src/bin/generate_types.rs`** - Fixed all paths to reference `pr::` submodule for the PR-related types

Both backend (cargo check) and frontend (TypeScript) compile successfully, and TypeScript types have been regenerated.

* Cleanup script changes for task attempt 46e66dfc-f608-47a4-baca-e38399d2da15

* Done! I've updated the default PR description prompt in both locations:

1. **`crates/server/src/routes/task_attempts/pr.rs`** - Updated `DEFAULT_PR_DESCRIPTION_PROMPT` constant
2. **`frontend/src/i18n/locales/en/settings.json`** - Updated `pullRequests.customPrompt.placeholder`

The changes are:
- Title should now be postfixed with "(Vibe Kanban)"
- Description should include a note at the end: "This PR was written using [Vibe Kanban](https://vibekanban.com)"

* Done! I've updated `pr_auto_description_enabled` to default to `true` in three places:

1. Added `default_pr_auto_description_enabled()` function that returns `true`
2. Updated the `#[serde(default)]` attribute to use this function
3. Updated the `from_v7_config` migration to set it to `true`
4. Updated the `Default` impl to set it to `true`

* All done! I've added i18n translations for the PR auto-description feature to all supported languages:

**settings.json** - Added `pullRequests` section with:
- `title`, `description`
- `autoDescription.label`, `autoDescription.helper`
- `customPrompt.label`, `customPrompt.placeholder`, `customPrompt.helper`

**tasks.json** - Added `autoGenerateLabel` key

Languages updated:
- Spanish (es)
- Japanese (ja)
- Korean (ko)
- Simplified Chinese (zh-Hans)

* Update frontend/src/i18n/locales/en/tasks.json

Co-authored-by: Gabriel Gordon-Hall <gabriel@bloop.ai>

* Done! I've implemented the UX improvement from the PR review:

1. **Moved the auto-generate checkbox** to the top of the form (above title and description)
2. **Added `disabled` prop** to both the title Input and description Textarea when `autoGenerateDescription` is true
3. **Added greyed-out styling** (`opacity-50 cursor-not-allowed`) to visually indicate the fields are disabled

The new field order is:
1. Auto-generate checkbox
2. Title input (disabled when checked)
3. Description textarea (disabled when checked)
4. Base branch selector
5. Draft checkbox

* All done! I've:

1. **Made `DEFAULT_PR_DESCRIPTION_PROMPT` public** in `pr.rs`

2. **Exported the constant to `shared/types.ts`** via `generate_types.rs`:
   - Imported the constant from the pr module
   - Added code to append `export const DEFAULT_PR_DESCRIPTION_PROMPT = \`...\`;` to the generated types

3. **Updated `GeneralSettings.tsx`** to import and use the constant directly as the placeholder

4. **Removed the duplicate `placeholder` key** from all i18n `settings.json` files (en, es, ja, ko, zh-Hans)

The default prompt is now defined in a single place (the Rust backend) and exported to TypeScript, eliminating duplication across all i18n files.

* Cleanup script changes for task attempt 46e66dfc-f608-47a4-baca-e38399d2da15

* Done! I've implemented the two-step UX for the custom prompt:

1. **Updated `GeneralSettings.tsx`**:
   - Replaced the always-visible textarea with a "Use custom prompt" checkbox
   - When checked, pre-fills the textarea with `DEFAULT_PR_DESCRIPTION_PROMPT`
   - When unchecked, sets `pr_auto_description_prompt` to `null` (reverts to default)
   - Textarea only visible when custom prompt is enabled

2. **Updated i18n files** (all 5 languages):
   - Replaced `label` with `useCustom` key
   - Updated `helper` text to remove "Leave empty to use the default" since that's now handled by the checkbox
   - Added translations:
     - **en**: "Use custom prompt"
     - **es**: "Usar prompt personalizado"
     - **ja**: "カスタムプロンプトを使用"
     - **ko**: "사용자 정의 프롬프트 사용"
     - **zh-Hans**: "使用自定义提示"

* Done! The custom prompt UX has been updated:

- **Textarea is now always visible** showing the current prompt (default or custom)
- **When "Use custom prompt" is unchecked**: textarea shows `DEFAULT_PR_DESCRIPTION_PROMPT` but is disabled/read-only with greyed-out styling
- **When "Use custom prompt" is checked**: textarea becomes editable, pre-filled with the default prompt for customization

This gives users visibility into what prompt will be used even when using the default, while still allowing them to customize it by checking the checkbox.

* Cleanup script changes for task attempt 46e66dfc-f608-47a4-baca-e38399d2da15

* Done! The fix has been applied. Now when the "Use custom prompt" checkbox is checked, users can:
- Clear all the text in the textarea to start from scratch
- The text no longer automatically reverts to the default prompt when emptied

---------

Co-authored-by: Gabriel Gordon-Hall <gabriel@bloop.ai>
This commit is contained in:
Louis Knight-Webb
2025-12-09 12:31:22 +00:00
committed by GitHub
parent d8eeab628c
commit 55ca4d3655
17 changed files with 707 additions and 376 deletions

View File

@@ -1,6 +1,7 @@
use std::{collections::HashMap, env, fs, path::Path};
use schemars::{JsonSchema, Schema, SchemaGenerator, generate::SchemaSettings};
use server::routes::task_attempts::pr::DEFAULT_PR_DESCRIPTION_PROMPT;
use ts_rs::TS;
fn generate_types_content() -> String {
@@ -103,7 +104,7 @@ fn generate_types_content() -> String {
server::routes::shared_tasks::AssignSharedTaskRequest::decl(),
server::routes::tasks::ShareTaskResponse::decl(),
server::routes::tasks::CreateAndStartTaskRequest::decl(),
server::routes::task_attempts::CreateGitHubPrRequest::decl(),
server::routes::task_attempts::pr::CreateGitHubPrRequest::decl(),
server::routes::images::ImageResponse::decl(),
server::routes::images::ImageMetadata::decl(),
server::routes::task_attempts::CreateTaskAttemptBody::decl(),
@@ -113,12 +114,12 @@ fn generate_types_content() -> String {
server::routes::task_attempts::RebaseTaskAttemptRequest::decl(),
server::routes::task_attempts::GitOperationError::decl(),
server::routes::task_attempts::PushError::decl(),
server::routes::task_attempts::CreatePrError::decl(),
server::routes::task_attempts::pr::CreatePrError::decl(),
server::routes::task_attempts::BranchStatus::decl(),
server::routes::task_attempts::RunScriptError::decl(),
server::routes::task_attempts::AttachPrResponse::decl(),
server::routes::task_attempts::PrCommentsResponse::decl(),
server::routes::task_attempts::GetPrCommentsError::decl(),
server::routes::task_attempts::pr::AttachPrResponse::decl(),
server::routes::task_attempts::pr::PrCommentsResponse::decl(),
server::routes::task_attempts::pr::GetPrCommentsError::decl(),
services::services::github::UnifiedPrComment::decl(),
services::services::filesystem::DirectoryEntry::decl(),
services::services::filesystem::DirectoryListResponse::decl(),
@@ -198,7 +199,16 @@ fn generate_types_content() -> String {
.collect::<Vec<_>>()
.join("\n\n");
format!("{HEADER}\n\n{body}")
// Append exported constants
let prompt_escaped = DEFAULT_PR_DESCRIPTION_PROMPT
.replace('\\', "\\\\")
.replace('`', "\\`");
let constants = format!(
"export const DEFAULT_PR_DESCRIPTION_PROMPT = `{}`;",
prompt_escaped
);
format!("{HEADER}\n\n{body}\n\n{constants}")
}
fn generate_json_schema<T: JsonSchema>() -> Result<String, serde_json::Error> {

View File

@@ -2,6 +2,7 @@ pub mod codex_setup;
pub mod cursor_setup;
pub mod gh_cli_setup;
pub mod images;
pub mod pr;
pub mod queue;
pub mod util;
@@ -39,7 +40,7 @@ use serde::{Deserialize, Serialize};
use services::services::{
container::ContainerService,
git::{ConflictOp, GitCliError, GitServiceError, WorktreeResetOptions},
github::{CreatePrRequest, GitHubService, GitHubServiceError, UnifiedPrComment},
github::GitHubService,
};
use sqlx::Error as SqlxError;
use ts_rs::TS;
@@ -67,14 +68,6 @@ pub enum GitOperationError {
RebaseInProgress,
}
#[derive(Debug, Deserialize, Serialize, TS)]
pub struct CreateGitHubPrRequest {
pub title: String,
pub body: Option<String>,
pub target_branch: Option<String>,
pub draft: Option<bool>,
}
#[derive(Debug, Deserialize)]
pub struct TaskAttemptQuery {
pub task_id: Option<Uuid>,
@@ -623,179 +616,6 @@ pub enum PushError {
ForcePushRequired,
}
#[derive(Debug, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum CreatePrError {
GithubCliNotInstalled,
GithubCliNotLoggedIn,
GitCliNotLoggedIn,
GitCliNotInstalled,
TargetBranchNotFound { branch: String },
}
pub async fn create_github_pr(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
Json(request): Json<CreateGitHubPrRequest>,
) -> Result<ResponseJson<ApiResponse<String, CreatePrError>>, ApiError> {
let github_config = deployment.config().read().await.github.clone();
// Get the task attempt to access the stored target branch
let target_branch = request.target_branch.unwrap_or_else(|| {
// Use the stored target branch from the task attempt as the default
// Fall back to config default or "main" only if stored target branch is somehow invalid
if !task_attempt.target_branch.trim().is_empty() {
task_attempt.target_branch.clone()
} else {
github_config
.default_pr_base
.as_ref()
.map_or_else(|| "main".to_string(), |b| b.to_string())
}
});
let pool = &deployment.db().pool;
let task = task_attempt
.parent_task(pool)
.await?
.ok_or(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound))?;
let project = Project::find_by_id(pool, task.project_id)
.await?
.ok_or(ApiError::Project(ProjectError::ProjectNotFound))?;
let workspace_path = ensure_worktree_path(&deployment, &task_attempt).await?;
match deployment
.git()
.check_remote_branch_exists(&project.git_repo_path, &target_branch)
{
Ok(false) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::TargetBranchNotFound {
branch: target_branch.clone(),
},
)));
}
Err(GitServiceError::GitCLI(GitCliError::AuthFailed(_))) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotLoggedIn,
)));
}
Err(GitServiceError::GitCLI(GitCliError::NotAvailable)) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotInstalled,
)));
}
Err(e) => return Err(ApiError::GitService(e)),
Ok(true) => {}
}
// Push the branch to GitHub first
if let Err(e) = deployment
.git()
.push_to_github(&workspace_path, &task_attempt.branch, false)
{
tracing::error!("Failed to push branch to GitHub: {}", e);
match e {
GitServiceError::GitCLI(GitCliError::AuthFailed(_)) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotLoggedIn,
)));
}
GitServiceError::GitCLI(GitCliError::NotAvailable) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotInstalled,
)));
}
_ => return Err(ApiError::GitService(e)),
}
}
let norm_target_branch_name = if matches!(
deployment
.git()
.find_branch_type(&project.git_repo_path, &target_branch)?,
BranchType::Remote
) {
// Remote branches are formatted as {remote}/{branch} locally.
// For PR APIs, we must provide just the branch name.
let remote = deployment
.git()
.get_remote_name_from_branch_name(&workspace_path, &target_branch)?;
let remote_prefix = format!("{}/", remote);
target_branch
.strip_prefix(&remote_prefix)
.unwrap_or(&target_branch)
.to_string()
} else {
target_branch
};
// Create the PR using GitHub service
let pr_request = CreatePrRequest {
title: request.title.clone(),
body: request.body.clone(),
head_branch: task_attempt.branch.clone(),
base_branch: norm_target_branch_name.clone(),
draft: request.draft,
};
// Use GitService to get the remote URL, then create GitHubRepoInfo
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// Use GitHubService to create the PR
let github_service = GitHubService::new()?;
match github_service.create_pr(&repo_info, &pr_request).await {
Ok(pr_info) => {
// Update the task attempt with PR information
if let Err(e) = Merge::create_pr(
pool,
task_attempt.id,
&norm_target_branch_name,
pr_info.number,
&pr_info.url,
)
.await
{
tracing::error!("Failed to update task attempt PR status: {}", e);
}
// Auto-open PR in browser
if let Err(e) = utils::browser::open_browser(&pr_info.url).await {
tracing::warn!("Failed to open PR in browser: {}", e);
}
deployment
.track_if_analytics_allowed(
"github_pr_created",
serde_json::json!({
"task_id": task.id.to_string(),
"project_id": project.id.to_string(),
"attempt_id": task_attempt.id.to_string(),
}),
)
.await;
Ok(ResponseJson(ApiResponse::success(pr_info.url)))
}
Err(e) => {
tracing::error!(
"Failed to create GitHub PR for attempt {}: {}",
task_attempt.id,
e
);
match &e {
GitHubServiceError::GhCliNotInstalled(_) => Ok(ResponseJson(
ApiResponse::error_with_data(CreatePrError::GithubCliNotInstalled),
)),
GitHubServiceError::AuthFailed(_) => Ok(ResponseJson(
ApiResponse::error_with_data(CreatePrError::GithubCliNotLoggedIn),
)),
_ => Err(ApiError::GitHubService(e)),
}
}
}
}
#[derive(serde::Deserialize, TS)]
pub struct OpenEditorRequest {
editor_type: Option<String>,
@@ -1431,185 +1251,6 @@ pub async fn stop_task_attempt_execution(
Ok(ResponseJson(ApiResponse::success(())))
}
#[derive(Debug, Serialize, TS)]
pub struct AttachPrResponse {
pub pr_attached: bool,
pub pr_url: Option<String>,
pub pr_number: Option<i64>,
pub pr_status: Option<MergeStatus>,
}
#[derive(Debug, Serialize, TS)]
pub struct PrCommentsResponse {
pub comments: Vec<UnifiedPrComment>,
}
#[derive(Debug, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum GetPrCommentsError {
NoPrAttached,
GithubCliNotInstalled,
GithubCliNotLoggedIn,
}
pub async fn attach_existing_pr(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
) -> Result<ResponseJson<ApiResponse<AttachPrResponse>>, ApiError> {
let pool = &deployment.db().pool;
// Check if PR already attached
if let Some(Merge::Pr(pr_merge)) =
Merge::find_latest_by_task_attempt_id(pool, task_attempt.id).await?
{
return Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: true,
pr_url: Some(pr_merge.pr_info.url.clone()),
pr_number: Some(pr_merge.pr_info.number),
pr_status: Some(pr_merge.pr_info.status.clone()),
})));
}
// Get project and repo info
let Some(task) = task_attempt.parent_task(pool).await? else {
return Err(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound));
};
let Some(project) = Project::find_by_id(pool, task.project_id).await? else {
return Err(ApiError::Project(ProjectError::ProjectNotFound));
};
let github_service = GitHubService::new()?;
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// List all PRs for branch (open, closed, and merged)
let prs = github_service
.list_all_prs_for_branch(&repo_info, &task_attempt.branch)
.await?;
// Take the first PR (prefer open, but also accept merged/closed)
if let Some(pr_info) = prs.into_iter().next() {
// Save PR info to database
let merge = Merge::create_pr(
pool,
task_attempt.id,
&task_attempt.target_branch,
pr_info.number,
&pr_info.url,
)
.await?;
// Update status if not open
if !matches!(pr_info.status, MergeStatus::Open) {
Merge::update_status(
pool,
merge.id,
pr_info.status.clone(),
pr_info.merge_commit_sha.clone(),
)
.await?;
}
// If PR is merged, mark task as done
if matches!(pr_info.status, MergeStatus::Merged) {
Task::update_status(pool, task.id, TaskStatus::Done).await?;
// Try broadcast update to other users in organization
if let Ok(publisher) = deployment.share_publisher() {
if let Err(err) = publisher.update_shared_task_by_id(task.id).await {
tracing::warn!(
?err,
"Failed to propagate shared task update for {}",
task.id
);
}
} else {
tracing::debug!(
"Share publisher unavailable; skipping remote update for {}",
task.id
);
}
}
Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: true,
pr_url: Some(pr_info.url),
pr_number: Some(pr_info.number),
pr_status: Some(pr_info.status),
})))
} else {
Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: false,
pr_url: None,
pr_number: None,
pr_status: None,
})))
}
}
pub async fn get_pr_comments(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
) -> Result<ResponseJson<ApiResponse<PrCommentsResponse, GetPrCommentsError>>, ApiError> {
let pool = &deployment.db().pool;
// Find the latest merge for this task attempt
let merge = Merge::find_latest_by_task_attempt_id(pool, task_attempt.id).await?;
// Ensure there's an attached PR
let pr_info = match merge {
Some(Merge::Pr(pr_merge)) => pr_merge.pr_info,
_ => {
return Ok(ResponseJson(ApiResponse::error_with_data(
GetPrCommentsError::NoPrAttached,
)));
}
};
// Get project and repo info
let task = task_attempt
.parent_task(pool)
.await?
.ok_or(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound))?;
let project = Project::find_by_id(pool, task.project_id)
.await?
.ok_or(ApiError::Project(ProjectError::ProjectNotFound))?;
let github_service = GitHubService::new()?;
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// Fetch comments from GitHub
match github_service
.get_pr_comments(&repo_info, pr_info.number)
.await
{
Ok(comments) => Ok(ResponseJson(ApiResponse::success(PrCommentsResponse {
comments,
}))),
Err(e) => {
tracing::error!(
"Failed to fetch PR comments for attempt {}, PR #{}: {}",
task_attempt.id,
pr_info.number,
e
);
match &e {
GitHubServiceError::GhCliNotInstalled(_) => Ok(ResponseJson(
ApiResponse::error_with_data(GetPrCommentsError::GithubCliNotInstalled),
)),
GitHubServiceError::AuthFailed(_) => Ok(ResponseJson(
ApiResponse::error_with_data(GetPrCommentsError::GithubCliNotLoggedIn),
)),
_ => Err(ApiError::GitHubService(e)),
}
}
}
}
#[derive(Debug, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
@@ -1814,9 +1455,9 @@ pub fn router(deployment: &DeploymentImpl) -> Router<DeploymentImpl> {
.route("/push/force", post(force_push_task_attempt_branch))
.route("/rebase", post(rebase_task_attempt))
.route("/conflicts/abort", post(abort_conflicts_task_attempt))
.route("/pr", post(create_github_pr))
.route("/pr/attach", post(attach_existing_pr))
.route("/pr/comments", get(get_pr_comments))
.route("/pr", post(pr::create_github_pr))
.route("/pr/attach", post(pr::attach_existing_pr))
.route("/pr/comments", get(pr::get_pr_comments))
.route("/open-editor", post(open_task_attempt_in_editor))
.route("/children", get(get_task_attempt_children))
.route("/stop", post(stop_task_attempt_execution))

View File

@@ -0,0 +1,479 @@
use axum::{Extension, Json, extract::State, response::Json as ResponseJson};
use db::models::{
execution_process::{ExecutionProcess, ExecutionProcessRunReason},
merge::{Merge, MergeStatus},
project::{Project, ProjectError},
task::{Task, TaskStatus},
task_attempt::{TaskAttempt, TaskAttemptError},
};
use deployment::Deployment;
use executors::actions::{
ExecutorAction, ExecutorActionType, coding_agent_follow_up::CodingAgentFollowUpRequest,
coding_agent_initial::CodingAgentInitialRequest,
};
use git2::BranchType;
use serde::{Deserialize, Serialize};
use services::services::{
container::ContainerService,
git::{GitCliError, GitServiceError},
github::{CreatePrRequest, GitHubService, GitHubServiceError, UnifiedPrComment},
};
use ts_rs::TS;
use utils::response::ApiResponse;
use super::util::ensure_worktree_path;
use crate::{DeploymentImpl, error::ApiError};
#[derive(Debug, Deserialize, Serialize, TS)]
pub struct CreateGitHubPrRequest {
pub title: String,
pub body: Option<String>,
pub target_branch: Option<String>,
pub draft: Option<bool>,
#[serde(default)]
pub auto_generate_description: bool,
}
#[derive(Debug, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum CreatePrError {
GithubCliNotInstalled,
GithubCliNotLoggedIn,
GitCliNotLoggedIn,
GitCliNotInstalled,
TargetBranchNotFound { branch: String },
}
#[derive(Debug, Serialize, TS)]
pub struct AttachPrResponse {
pub pr_attached: bool,
pub pr_url: Option<String>,
pub pr_number: Option<i64>,
pub pr_status: Option<MergeStatus>,
}
#[derive(Debug, Serialize, TS)]
pub struct PrCommentsResponse {
pub comments: Vec<UnifiedPrComment>,
}
#[derive(Debug, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum GetPrCommentsError {
NoPrAttached,
GithubCliNotInstalled,
GithubCliNotLoggedIn,
}
pub const DEFAULT_PR_DESCRIPTION_PROMPT: &str = r#"Update the GitHub PR that was just created with a better title and description.
The PR number is #{pr_number} and the URL is {pr_url}.
Analyze the changes in this branch and write:
1. A concise, descriptive title that summarizes the changes, postfixed with "(Vibe Kanban)"
2. A detailed description that explains:
- What changes were made
- Why they were made (based on the task context)
- Any important implementation details
- At the end, include a note: "This PR was written using [Vibe Kanban](https://vibekanban.com)"
Use `gh pr edit` to update the PR."#;
async fn trigger_pr_description_follow_up(
deployment: &DeploymentImpl,
task_attempt: &TaskAttempt,
pr_number: i64,
pr_url: &str,
) -> Result<(), ApiError> {
// Get the custom prompt from config, or use default
let config = deployment.config().read().await;
let prompt_template = config
.pr_auto_description_prompt
.as_deref()
.unwrap_or(DEFAULT_PR_DESCRIPTION_PROMPT);
// Replace placeholders in prompt
let prompt = prompt_template
.replace("{pr_number}", &pr_number.to_string())
.replace("{pr_url}", pr_url);
drop(config); // Release the lock before async operations
// Get executor profile from the latest coding agent process
let executor_profile_id = ExecutionProcess::latest_executor_profile_for_attempt(
&deployment.db().pool,
task_attempt.id,
)
.await?;
// Get latest session ID if one exists
let latest_session_id = ExecutionProcess::find_latest_session_id_by_task_attempt(
&deployment.db().pool,
task_attempt.id,
)
.await?;
// Build the action type (follow-up if session exists, otherwise initial)
let action_type = if let Some(session_id) = latest_session_id {
ExecutorActionType::CodingAgentFollowUpRequest(CodingAgentFollowUpRequest {
prompt,
session_id,
executor_profile_id,
})
} else {
ExecutorActionType::CodingAgentInitialRequest(CodingAgentInitialRequest {
prompt,
executor_profile_id,
})
};
let action = ExecutorAction::new(action_type, None);
deployment
.container()
.start_execution(
task_attempt,
&action,
&ExecutionProcessRunReason::CodingAgent,
)
.await?;
Ok(())
}
pub async fn create_github_pr(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
Json(request): Json<CreateGitHubPrRequest>,
) -> Result<ResponseJson<ApiResponse<String, CreatePrError>>, ApiError> {
let github_config = deployment.config().read().await.github.clone();
// Get the task attempt to access the stored target branch
let target_branch = request.target_branch.unwrap_or_else(|| {
// Use the stored target branch from the task attempt as the default
// Fall back to config default or "main" only if stored target branch is somehow invalid
if !task_attempt.target_branch.trim().is_empty() {
task_attempt.target_branch.clone()
} else {
github_config
.default_pr_base
.as_ref()
.map_or_else(|| "main".to_string(), |b| b.to_string())
}
});
let pool = &deployment.db().pool;
let task = task_attempt
.parent_task(pool)
.await?
.ok_or(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound))?;
let project = Project::find_by_id(pool, task.project_id)
.await?
.ok_or(ApiError::Project(ProjectError::ProjectNotFound))?;
let workspace_path = ensure_worktree_path(&deployment, &task_attempt).await?;
match deployment
.git()
.check_remote_branch_exists(&project.git_repo_path, &target_branch)
{
Ok(false) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::TargetBranchNotFound {
branch: target_branch.clone(),
},
)));
}
Err(GitServiceError::GitCLI(GitCliError::AuthFailed(_))) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotLoggedIn,
)));
}
Err(GitServiceError::GitCLI(GitCliError::NotAvailable)) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotInstalled,
)));
}
Err(e) => return Err(ApiError::GitService(e)),
Ok(true) => {}
}
// Push the branch to GitHub first
if let Err(e) = deployment
.git()
.push_to_github(&workspace_path, &task_attempt.branch, false)
{
tracing::error!("Failed to push branch to GitHub: {}", e);
match e {
GitServiceError::GitCLI(GitCliError::AuthFailed(_)) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotLoggedIn,
)));
}
GitServiceError::GitCLI(GitCliError::NotAvailable) => {
return Ok(ResponseJson(ApiResponse::error_with_data(
CreatePrError::GitCliNotInstalled,
)));
}
_ => return Err(ApiError::GitService(e)),
}
}
let norm_target_branch_name = if matches!(
deployment
.git()
.find_branch_type(&project.git_repo_path, &target_branch)?,
BranchType::Remote
) {
// Remote branches are formatted as {remote}/{branch} locally.
// For PR APIs, we must provide just the branch name.
let remote = deployment
.git()
.get_remote_name_from_branch_name(&workspace_path, &target_branch)?;
let remote_prefix = format!("{}/", remote);
target_branch
.strip_prefix(&remote_prefix)
.unwrap_or(&target_branch)
.to_string()
} else {
target_branch
};
// Create the PR using GitHub service
let pr_request = CreatePrRequest {
title: request.title.clone(),
body: request.body.clone(),
head_branch: task_attempt.branch.clone(),
base_branch: norm_target_branch_name.clone(),
draft: request.draft,
};
// Use GitService to get the remote URL, then create GitHubRepoInfo
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// Use GitHubService to create the PR
let github_service = GitHubService::new()?;
match github_service.create_pr(&repo_info, &pr_request).await {
Ok(pr_info) => {
// Update the task attempt with PR information
if let Err(e) = Merge::create_pr(
pool,
task_attempt.id,
&norm_target_branch_name,
pr_info.number,
&pr_info.url,
)
.await
{
tracing::error!("Failed to update task attempt PR status: {}", e);
}
// Auto-open PR in browser
if let Err(e) = utils::browser::open_browser(&pr_info.url).await {
tracing::warn!("Failed to open PR in browser: {}", e);
}
deployment
.track_if_analytics_allowed(
"github_pr_created",
serde_json::json!({
"task_id": task.id.to_string(),
"project_id": project.id.to_string(),
"attempt_id": task_attempt.id.to_string(),
}),
)
.await;
// Trigger auto-description follow-up if enabled
if request.auto_generate_description
&& let Err(e) = trigger_pr_description_follow_up(
&deployment,
&task_attempt,
pr_info.number,
&pr_info.url,
)
.await
{
tracing::warn!(
"Failed to trigger PR description follow-up for attempt {}: {}",
task_attempt.id,
e
);
}
Ok(ResponseJson(ApiResponse::success(pr_info.url)))
}
Err(e) => {
tracing::error!(
"Failed to create GitHub PR for attempt {}: {}",
task_attempt.id,
e
);
match &e {
GitHubServiceError::GhCliNotInstalled(_) => Ok(ResponseJson(
ApiResponse::error_with_data(CreatePrError::GithubCliNotInstalled),
)),
GitHubServiceError::AuthFailed(_) => Ok(ResponseJson(
ApiResponse::error_with_data(CreatePrError::GithubCliNotLoggedIn),
)),
_ => Err(ApiError::GitHubService(e)),
}
}
}
}
pub async fn attach_existing_pr(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
) -> Result<ResponseJson<ApiResponse<AttachPrResponse>>, ApiError> {
let pool = &deployment.db().pool;
// Check if PR already attached
if let Some(Merge::Pr(pr_merge)) =
Merge::find_latest_by_task_attempt_id(pool, task_attempt.id).await?
{
return Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: true,
pr_url: Some(pr_merge.pr_info.url.clone()),
pr_number: Some(pr_merge.pr_info.number),
pr_status: Some(pr_merge.pr_info.status.clone()),
})));
}
// Get project and repo info
let Some(task) = task_attempt.parent_task(pool).await? else {
return Err(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound));
};
let Some(project) = Project::find_by_id(pool, task.project_id).await? else {
return Err(ApiError::Project(ProjectError::ProjectNotFound));
};
let github_service = GitHubService::new()?;
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// List all PRs for branch (open, closed, and merged)
let prs = github_service
.list_all_prs_for_branch(&repo_info, &task_attempt.branch)
.await?;
// Take the first PR (prefer open, but also accept merged/closed)
if let Some(pr_info) = prs.into_iter().next() {
// Save PR info to database
let merge = Merge::create_pr(
pool,
task_attempt.id,
&task_attempt.target_branch,
pr_info.number,
&pr_info.url,
)
.await?;
// Update status if not open
if !matches!(pr_info.status, MergeStatus::Open) {
Merge::update_status(
pool,
merge.id,
pr_info.status.clone(),
pr_info.merge_commit_sha.clone(),
)
.await?;
}
// If PR is merged, mark task as done
if matches!(pr_info.status, MergeStatus::Merged) {
Task::update_status(pool, task.id, TaskStatus::Done).await?;
// Try broadcast update to other users in organization
if let Ok(publisher) = deployment.share_publisher() {
if let Err(err) = publisher.update_shared_task_by_id(task.id).await {
tracing::warn!(
?err,
"Failed to propagate shared task update for {}",
task.id
);
}
} else {
tracing::debug!(
"Share publisher unavailable; skipping remote update for {}",
task.id
);
}
}
Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: true,
pr_url: Some(pr_info.url),
pr_number: Some(pr_info.number),
pr_status: Some(pr_info.status),
})))
} else {
Ok(ResponseJson(ApiResponse::success(AttachPrResponse {
pr_attached: false,
pr_url: None,
pr_number: None,
pr_status: None,
})))
}
}
pub async fn get_pr_comments(
Extension(task_attempt): Extension<TaskAttempt>,
State(deployment): State<DeploymentImpl>,
) -> Result<ResponseJson<ApiResponse<PrCommentsResponse, GetPrCommentsError>>, ApiError> {
let pool = &deployment.db().pool;
// Find the latest merge for this task attempt
let merge = Merge::find_latest_by_task_attempt_id(pool, task_attempt.id).await?;
// Ensure there's an attached PR
let pr_info = match merge {
Some(Merge::Pr(pr_merge)) => pr_merge.pr_info,
_ => {
return Ok(ResponseJson(ApiResponse::error_with_data(
GetPrCommentsError::NoPrAttached,
)));
}
};
// Get project and repo info
let task = task_attempt
.parent_task(pool)
.await?
.ok_or(ApiError::TaskAttempt(TaskAttemptError::TaskNotFound))?;
let project = Project::find_by_id(pool, task.project_id)
.await?
.ok_or(ApiError::Project(ProjectError::ProjectNotFound))?;
let github_service = GitHubService::new()?;
let repo_info = deployment
.git()
.get_github_repo_info(&project.git_repo_path)?;
// Fetch comments from GitHub
match github_service
.get_pr_comments(&repo_info, pr_info.number)
.await
{
Ok(comments) => Ok(ResponseJson(ApiResponse::success(PrCommentsResponse {
comments,
}))),
Err(e) => {
tracing::error!(
"Failed to fetch PR comments for attempt {}, PR #{}: {}",
task_attempt.id,
pr_info.number,
e
);
match &e {
GitHubServiceError::GhCliNotInstalled(_) => Ok(ResponseJson(
ApiResponse::error_with_data(GetPrCommentsError::GithubCliNotInstalled),
)),
GitHubServiceError::AuthFailed(_) => Ok(ResponseJson(
ApiResponse::error_with_data(GetPrCommentsError::GithubCliNotLoggedIn),
)),
_ => Err(ApiError::GitHubService(e)),
}
}
}
}

View File

@@ -13,6 +13,10 @@ fn default_git_branch_prefix() -> String {
"vk".to_string()
}
fn default_pr_auto_description_enabled() -> bool {
true
}
#[derive(Clone, Debug, Serialize, Deserialize, TS)]
pub struct Config {
pub config_version: String,
@@ -33,6 +37,10 @@ pub struct Config {
pub git_branch_prefix: String,
#[serde(default)]
pub showcases: ShowcaseState,
#[serde(default = "default_pr_auto_description_enabled")]
pub pr_auto_description_enabled: bool,
#[serde(default)]
pub pr_auto_description_prompt: Option<String>,
}
impl Config {
@@ -56,6 +64,8 @@ impl Config {
language: old_config.language,
git_branch_prefix: old_config.git_branch_prefix,
showcases: old_config.showcases,
pr_auto_description_enabled: true,
pr_auto_description_prompt: None,
}
}
@@ -104,6 +114,8 @@ impl Default for Config {
language: UiLanguage::default(),
git_branch_prefix: default_git_branch_prefix(),
showcases: ShowcaseState::default(),
pr_auto_description_enabled: true,
pr_auto_description_prompt: None,
}
}
}