Compare commits

..

2 Commits

Author SHA1 Message Date
claude[bot]
1d100f7832 feat: add workflow cancellation detection and update comment
When a workflow is cancelled, the comment now shows "Claude's task was cancelled" 
instead of the generic "Claude encountered an error" message. This provides clearer 
feedback to users about why the workflow stopped.

Changes:
- Add CLAUDE_CANCELLED environment variable using cancelled() function in action.yml
- Implement cancellation detection logic in update-comment-link.ts
- Update comment-logic.ts to show specific cancellation message
- Add comprehensive tests for cancellation handling

Fixes #123

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-04 01:03:26 +00:00
claude[bot]
e0dcb85d34 fix: improve workflow status detection in comment updates
- Changed CLAUDE_SUCCESS check from !== "false" to === "true" for more explicit handling
- This ensures undefined or empty values are treated as failures
- Moved status check before output file parsing to ensure consistent behavior
- Added comprehensive tests for various workflow status scenarios

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-06-04 00:56:28 +00:00
26 changed files with 322 additions and 292 deletions

View File

@@ -29,4 +29,4 @@ jobs:
Be constructive and specific in your feedback. Give inline comments where applicable. Be constructive and specific in your feedback. Give inline comments where applicable.
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff" allowed_tools: "mcp__github__add_pull_request_review_comment"

View File

@@ -70,8 +70,6 @@ jobs:
# NODE_ENV: test # NODE_ENV: test
# DEBUG: true # DEBUG: true
# API_URL: https://api.example.com # API_URL: https://api.example.com
# Optional: limit the number of conversation turns
# max_turns: "5"
``` ```
## Inputs ## Inputs
@@ -80,7 +78,6 @@ jobs:
| --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- | | --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - | | `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - | | `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - |
| `max_turns` | Maximum number of conversation turns Claude can take (limits back-and-forth exchanges) | No | - |
| `timeout_minutes` | Timeout in minutes for execution | No | `30` | | `timeout_minutes` | Timeout in minutes for execution | No | `30` |
| `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - | | `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - |
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - | | `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - |
@@ -314,24 +311,6 @@ You can pass custom environment variables to Claude Code execution using the `cl
The `claude_env` input accepts YAML format where each line defines a key-value pair. These environment variables will be available to Claude Code during execution, allowing it to run tests, build processes, or other commands that depend on specific environment configurations. The `claude_env` input accepts YAML format where each line defines a key-value pair. These environment variables will be available to Claude Code during execution, allowing it to run tests, build processes, or other commands that depend on specific environment configurations.
### Limiting Conversation Turns
You can use the `max_turns` parameter to limit the number of back-and-forth exchanges Claude can have during task execution. This is useful for:
- Controlling costs by preventing runaway conversations
- Setting time boundaries for automated workflows
- Ensuring predictable behavior in CI/CD pipelines
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
max_turns: "5" # Limit to 5 conversation turns
# ... other inputs
```
When the turn limit is reached, Claude will stop execution gracefully. Choose a value that gives Claude enough turns to complete typical tasks while preventing excessive usage.
### Custom Tools ### Custom Tools
By default, Claude only has access to: By default, Claude only has access to:

View File

@@ -1,20 +0,0 @@
# Claude Code GitHub Action Roadmap
Thank you for trying out the beta of our GitHub Action! This document outlines our path to `v1.0`. Items are not necessarily in priority order.
## Path to 1.0
- **Ability to see GitHub Action CI results** - This will enable Claude to look at CI failures and make updates to PRs to fix test failures, lint errors, and the like.
- **Cross-repo support** - Enable Claude to work across multiple repositories in a single session
- **Ability to modify workflow files** - Let Claude update GitHub Actions workflows and other CI configuration files
- **Support for workflow_dispatch and repository_dispatch events** - Dispatch Claude on events triggered via API from other workflows or from other services
- **Ability to disable commit signing** - Option to turn off GPG signing for environments where it's not required. This will enable Claude to use normal `git` bash commands for committing. This will likely become the default behavior once added.
- **Better code review behavior** - Support inline comments on specific lines, provide higher quality reviews with more actionable feedback
- **Support triggering @claude from bot users** - Allow automation and bot accounts to invoke Claude
- **Customizable base prompts** - Full control over Claude's initial context with template variables like `$PR_COMMENTS`, `$PR_FILES`, etc. Users can replace our default prompt entirely while still accessing key contextual data
---
**Note:** This roadmap represents our current vision for reaching `v1.0` and is subject to change based on user feedback and development priorities.
We welcome feedback on these planned features! If you're interested in contributing to any of these features, please open an issue to discuss implementation details with us. We're also open to suggestions for new features not listed here.

View File

@@ -62,10 +62,6 @@ inputs:
required: false required: false
default: "false" default: "false"
max_turns:
description: "Maximum number of conversation turns"
required: false
default: ""
timeout_minutes: timeout_minutes:
description: "Timeout in minutes for execution" description: "Timeout in minutes for execution"
required: false required: false
@@ -87,20 +83,19 @@ runs:
- name: Install Dependencies - name: Install Dependencies
shell: bash shell: bash
run: | run: |
cd ${GITHUB_ACTION_PATH} cd ${{ github.action_path }}
bun install bun install
- name: Prepare action - name: Prepare action
id: prepare id: prepare
shell: bash shell: bash
run: | run: |
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/prepare.ts bun run ${{ github.action_path }}/src/entrypoints/prepare.ts
env: env:
TRIGGER_PHRASE: ${{ inputs.trigger_phrase }} TRIGGER_PHRASE: ${{ inputs.trigger_phrase }}
ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }} ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }}
BASE_BRANCH: ${{ inputs.base_branch }} BASE_BRANCH: ${{ inputs.base_branch }}
ALLOWED_TOOLS: ${{ inputs.allowed_tools }} ALLOWED_TOOLS: ${{ inputs.allowed_tools }}
DISALLOWED_TOOLS: ${{ inputs.disallowed_tools }}
CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }} CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }}
DIRECT_PROMPT: ${{ inputs.direct_prompt }} DIRECT_PROMPT: ${{ inputs.direct_prompt }}
MCP_CONFIG: ${{ inputs.mcp_config }} MCP_CONFIG: ${{ inputs.mcp_config }}
@@ -110,13 +105,12 @@ runs:
- name: Run Claude Code - name: Run Claude Code
id: claude-code id: claude-code
if: steps.prepare.outputs.contains_trigger == 'true' if: steps.prepare.outputs.contains_trigger == 'true'
uses: anthropics/claude-code-base-action@ebd8558e902b3db132e89863de49565fcb9aec46 # v0.0.19 uses: anthropics/claude-code-base-action@1370ac97fbba9bddec20ea2924b5726bf10d8b94 # v0.0.9
with: with:
prompt_file: ${{ runner.temp }}/claude-prompts/claude-prompt.txt prompt_file: /tmp/claude-prompts/claude-prompt.txt
allowed_tools: ${{ env.ALLOWED_TOOLS }} allowed_tools: ${{ env.ALLOWED_TOOLS }}
disallowed_tools: ${{ env.DISALLOWED_TOOLS }} disallowed_tools: ${{ env.DISALLOWED_TOOLS }}
timeout_minutes: ${{ inputs.timeout_minutes }} timeout_minutes: ${{ inputs.timeout_minutes }}
max_turns: ${{ inputs.max_turns }}
model: ${{ inputs.model || inputs.anthropic_model }} model: ${{ inputs.model || inputs.anthropic_model }}
mcp_config: ${{ steps.prepare.outputs.mcp_config }} mcp_config: ${{ steps.prepare.outputs.mcp_config }}
use_bedrock: ${{ inputs.use_bedrock }} use_bedrock: ${{ inputs.use_bedrock }}
@@ -153,7 +147,7 @@ runs:
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always() if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
shell: bash shell: bash
run: | run: |
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/update-comment-link.ts bun run ${{ github.action_path }}/src/entrypoints/update-comment-link.ts
env: env:
REPOSITORY: ${{ github.repository }} REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }} PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}
@@ -166,6 +160,7 @@ runs:
IS_PR: ${{ github.event.issue.pull_request != null || github.event_name == 'pull_request_review_comment' }} IS_PR: ${{ github.event.issue.pull_request != null || github.event_name == 'pull_request_review_comment' }}
BASE_BRANCH: ${{ steps.prepare.outputs.BASE_BRANCH }} BASE_BRANCH: ${{ steps.prepare.outputs.BASE_BRANCH }}
CLAUDE_SUCCESS: ${{ steps.claude-code.outputs.conclusion == 'success' }} CLAUDE_SUCCESS: ${{ steps.claude-code.outputs.conclusion == 'success' }}
CLAUDE_CANCELLED: ${{ cancelled() }}
OUTPUT_FILE: ${{ steps.claude-code.outputs.execution_file || '' }} OUTPUT_FILE: ${{ steps.claude-code.outputs.execution_file || '' }}
TRIGGER_USERNAME: ${{ github.event.comment.user.login || github.event.issue.user.login || github.event.pull_request.user.login || github.event.sender.login || github.triggering_actor || github.actor || '' }} TRIGGER_USERNAME: ${{ github.event.comment.user.login || github.event.issue.user.login || github.event.pull_request.user.login || github.event.sender.login || github.triggering_actor || github.actor || '' }}
PREPARE_SUCCESS: ${{ steps.prepare.outcome == 'success' }} PREPARE_SUCCESS: ${{ steps.prepare.outcome == 'success' }}

View File

@@ -2,7 +2,7 @@
"lockfileVersion": 1, "lockfileVersion": 1,
"workspaces": { "workspaces": {
"": { "": {
"name": "@anthropic-ai/claude-code-action", "name": "claude-pr-action",
"dependencies": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@actions/github": "^6.0.1", "@actions/github": "^6.0.1",

View File

@@ -35,4 +35,4 @@ jobs:
Provide constructive feedback with specific suggestions for improvement. Provide constructive feedback with specific suggestions for improvement.
Use inline comments to highlight specific areas of concern. Use inline comments to highlight specific areas of concern.
# allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff" # allowed_tools: "mcp__github__add_pull_request_review_comment"

View File

@@ -1,5 +1,5 @@
{ {
"name": "@anthropic-ai/claude-code-action", "name": "claude-pr-action",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"scripts": { "scripts": {

View File

@@ -24,7 +24,6 @@ export type { CommonFields, PreparedContext } from "./types";
const BASE_ALLOWED_TOOLS = [ const BASE_ALLOWED_TOOLS = [
"Edit", "Edit",
"MultiEdit",
"Glob", "Glob",
"Grep", "Grep",
"LS", "LS",
@@ -36,35 +35,38 @@ const BASE_ALLOWED_TOOLS = [
]; ];
const DISALLOWED_TOOLS = ["WebSearch", "WebFetch"]; const DISALLOWED_TOOLS = ["WebSearch", "WebFetch"];
export function buildAllowedToolsString(customAllowedTools?: string[]): string { export function buildAllowedToolsString(customAllowedTools?: string): string {
let baseTools = [...BASE_ALLOWED_TOOLS]; let baseTools = [...BASE_ALLOWED_TOOLS];
let allAllowedTools = baseTools.join(","); let allAllowedTools = baseTools.join(",");
if (customAllowedTools && customAllowedTools.length > 0) { if (customAllowedTools) {
allAllowedTools = `${allAllowedTools},${customAllowedTools.join(",")}`; allAllowedTools = `${allAllowedTools},${customAllowedTools}`;
} }
return allAllowedTools; return allAllowedTools;
} }
export function buildDisallowedToolsString( export function buildDisallowedToolsString(
customDisallowedTools?: string[], customDisallowedTools?: string,
allowedTools?: string[], allowedTools?: string,
): string { ): string {
let disallowedTools = [...DISALLOWED_TOOLS]; let disallowedTools = [...DISALLOWED_TOOLS];
// If user has explicitly allowed some hardcoded disallowed tools, remove them from disallowed list // If user has explicitly allowed some hardcoded disallowed tools, remove them from disallowed list
if (allowedTools && allowedTools.length > 0) { if (allowedTools) {
const allowedToolsArray = allowedTools
.split(",")
.map((tool) => tool.trim());
disallowedTools = disallowedTools.filter( disallowedTools = disallowedTools.filter(
(tool) => !allowedTools.includes(tool), (tool) => !allowedToolsArray.includes(tool),
); );
} }
let allDisallowedTools = disallowedTools.join(","); let allDisallowedTools = disallowedTools.join(",");
if (customDisallowedTools && customDisallowedTools.length > 0) { if (customDisallowedTools) {
if (allDisallowedTools) { if (allDisallowedTools) {
allDisallowedTools = `${allDisallowedTools},${customDisallowedTools.join(",")}`; allDisallowedTools = `${allDisallowedTools},${customDisallowedTools}`;
} else { } else {
allDisallowedTools = customDisallowedTools.join(","); allDisallowedTools = customDisallowedTools;
} }
} }
return allDisallowedTools; return allDisallowedTools;
@@ -118,10 +120,8 @@ export function prepareContext(
triggerPhrase, triggerPhrase,
...(triggerUsername && { triggerUsername }), ...(triggerUsername && { triggerUsername }),
...(customInstructions && { customInstructions }), ...(customInstructions && { customInstructions }),
...(allowedTools.length > 0 && { allowedTools: allowedTools.join(",") }), ...(allowedTools && { allowedTools }),
...(disallowedTools.length > 0 && { ...(disallowedTools && { disallowedTools }),
disallowedTools: disallowedTools.join(","),
}),
...(directPrompt && { directPrompt }), ...(directPrompt && { directPrompt }),
...(claudeBranch && { claudeBranch }), ...(claudeBranch && { claudeBranch }),
}; };
@@ -418,7 +418,6 @@ ${
} }
<claude_comment_id>${context.claudeCommentId}</claude_comment_id> <claude_comment_id>${context.claudeCommentId}</claude_comment_id>
<trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username> <trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username>
<trigger_display_name>${githubData.triggerDisplayName ?? context.triggerUsername ?? "Unknown"}</trigger_display_name>
<trigger_phrase>${context.triggerPhrase}</trigger_phrase> <trigger_phrase>${context.triggerPhrase}</trigger_phrase>
${ ${
(eventData.eventName === "issue_comment" || (eventData.eventName === "issue_comment" ||
@@ -504,14 +503,12 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
? ` ? `
- Push directly using mcp__github_file_ops__commit_files to the existing branch (works for both new and existing files). - Push directly using mcp__github_file_ops__commit_files to the existing branch (works for both new and existing files).
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files). - Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
- When pushing changes with this tool and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message. - When pushing changes with this tool and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.`
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"`
: ` : `
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch. - You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
- Push changes directly to the current branch using mcp__github_file_ops__commit_files (works for both new and existing files) - Push changes directly to the current branch using mcp__github_file_ops__commit_files (works for both new and existing files)
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files). - Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
- When pushing changes and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message. - When pushing changes and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"
${ ${
eventData.claudeBranch eventData.claudeBranch
? `- Provide a URL to create a PR manually in this format: ? `- Provide a URL to create a PR manually in this format:
@@ -624,9 +621,7 @@ export async function createPrompt(
claudeBranch, claudeBranch,
); );
await mkdir(`${process.env.RUNNER_TEMP}/claude-prompts`, { await mkdir("/tmp/claude-prompts", { recursive: true });
recursive: true,
});
// Generate the prompt // Generate the prompt
const promptContent = generatePrompt(preparedContext, githubData); const promptContent = generatePrompt(preparedContext, githubData);
@@ -637,18 +632,15 @@ export async function createPrompt(
console.log("======================="); console.log("=======================");
// Write the prompt file // Write the prompt file
await writeFile( await writeFile("/tmp/claude-prompts/claude-prompt.txt", promptContent);
`${process.env.RUNNER_TEMP}/claude-prompts/claude-prompt.txt`,
promptContent,
);
// Set allowed tools // Set allowed tools
const allAllowedTools = buildAllowedToolsString( const allAllowedTools = buildAllowedToolsString(
context.inputs.allowedTools, preparedContext.allowedTools,
); );
const allDisallowedTools = buildDisallowedToolsString( const allDisallowedTools = buildDisallowedToolsString(
context.inputs.disallowedTools, preparedContext.disallowedTools,
context.inputs.allowedTools, preparedContext.allowedTools,
); );
core.exportVariable("ALLOWED_TOOLS", allAllowedTools); core.exportVariable("ALLOWED_TOOLS", allAllowedTools);

View File

@@ -59,7 +59,6 @@ async function run() {
repository: `${context.repository.owner}/${context.repository.repo}`, repository: `${context.repository.owner}/${context.repository.repo}`,
prNumber: context.entityNumber.toString(), prNumber: context.entityNumber.toString(),
isPR: context.isPR, isPR: context.isPR,
triggerUsername: context.actor,
}); });
// Step 8: Setup branch // Step 8: Setup branch
@@ -93,7 +92,6 @@ async function run() {
branch: branchInfo.currentBranch, branch: branchInfo.currentBranch,
additionalMcpConfig, additionalMcpConfig,
claudeCommentId: commentId.toString(), claudeCommentId: commentId.toString(),
allowedTools: context.inputs.allowedTools,
}); });
core.setOutput("mcp_config", mcpConfig); core.setOutput("mcp_config", mcpConfig);
} catch (error) { } catch (error) {

View File

@@ -146,8 +146,12 @@ async function run() {
duration_api_ms?: number; duration_api_ms?: number;
} | null = null; } | null = null;
let actionFailed = false; let actionFailed = false;
let actionCancelled = false;
let errorDetails: string | undefined; let errorDetails: string | undefined;
// Check if the workflow was cancelled
const isCancelled = process.env.CLAUDE_CANCELLED === "true";
// First check if prepare step failed // First check if prepare step failed
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false"; const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR; const prepareError = process.env.PREPARE_ERROR;
@@ -155,8 +159,18 @@ async function run() {
if (!prepareSuccess && prepareError) { if (!prepareSuccess && prepareError) {
actionFailed = true; actionFailed = true;
errorDetails = prepareError; errorDetails = prepareError;
} else if (isCancelled) {
// If the workflow was cancelled, set the cancelled flag
actionCancelled = true;
} else { } else {
// Check for existence of output file and parse it if available // Check if the Claude action failed
// CLAUDE_SUCCESS is set to the result of: steps.claude-code.outputs.conclusion == 'success'
// If the step didn't run or didn't set outputs.conclusion, CLAUDE_SUCCESS will be "false"
// If the step succeeded, CLAUDE_SUCCESS will be "true"
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
// Try to read execution details from output file
try { try {
const outputFile = process.env.OUTPUT_FILE; const outputFile = process.env.OUTPUT_FILE;
if (outputFile) { if (outputFile) {
@@ -179,14 +193,10 @@ async function run() {
} }
} }
} }
// Check if the Claude action failed
const claudeSuccess = process.env.CLAUDE_SUCCESS !== "false";
actionFailed = !claudeSuccess;
} catch (error) { } catch (error) {
console.error("Error reading output file:", error); console.error("Error reading output file:", error);
// If we can't read the file, check for any failure markers // Error reading output file doesn't change the action status
actionFailed = process.env.CLAUDE_SUCCESS === "false"; // We already determined actionFailed based on CLAUDE_SUCCESS
} }
} }
@@ -194,6 +204,7 @@ async function run() {
const commentInput: CommentUpdateInput = { const commentInput: CommentUpdateInput = {
currentBody, currentBody,
actionFailed, actionFailed,
actionCancelled,
executionDetails, executionDetails,
jobUrl, jobUrl,
branchLink, branchLink,

View File

@@ -104,11 +104,3 @@ export const ISSUE_QUERY = `
} }
} }
`; `;
export const USER_QUERY = `
query($login: String!) {
user(login: $login) {
name
}
}
`;

View File

@@ -28,8 +28,8 @@ export type ParsedGitHubContext = {
inputs: { inputs: {
triggerPhrase: string; triggerPhrase: string;
assigneeTrigger: string; assigneeTrigger: string;
allowedTools: string[]; allowedTools: string;
disallowedTools: string[]; disallowedTools: string;
customInstructions: string; customInstructions: string;
directPrompt: string; directPrompt: string;
baseBranch?: string; baseBranch?: string;
@@ -52,14 +52,8 @@ export function parseGitHubContext(): ParsedGitHubContext {
inputs: { inputs: {
triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude", triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude",
assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "", assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "",
allowedTools: (process.env.ALLOWED_TOOLS ?? "") allowedTools: process.env.ALLOWED_TOOLS ?? "",
.split(",") disallowedTools: process.env.DISALLOWED_TOOLS ?? "",
.map((tool) => tool.trim())
.filter((tool) => tool.length > 0),
disallowedTools: (process.env.DISALLOWED_TOOLS ?? "")
.split(",")
.map((tool) => tool.trim())
.filter((tool) => tool.length > 0),
customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "", customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "",
directPrompt: process.env.DIRECT_PROMPT ?? "", directPrompt: process.env.DIRECT_PROMPT ?? "",
baseBranch: process.env.BASE_BRANCH, baseBranch: process.env.BASE_BRANCH,

View File

@@ -1,6 +1,6 @@
import { execSync } from "child_process"; import { execSync } from "child_process";
import type { Octokits } from "../api/client"; import type { Octokits } from "../api/client";
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github"; import { ISSUE_QUERY, PR_QUERY } from "../api/queries/github";
import type { import type {
GitHubComment, GitHubComment,
GitHubFile, GitHubFile,
@@ -18,7 +18,6 @@ type FetchDataParams = {
repository: string; repository: string;
prNumber: string; prNumber: string;
isPR: boolean; isPR: boolean;
triggerUsername?: string;
}; };
export type GitHubFileWithSHA = GitHubFile & { export type GitHubFileWithSHA = GitHubFile & {
@@ -32,7 +31,6 @@ export type FetchDataResult = {
changedFilesWithSHA: GitHubFileWithSHA[]; changedFilesWithSHA: GitHubFileWithSHA[];
reviewData: { nodes: GitHubReview[] } | null; reviewData: { nodes: GitHubReview[] } | null;
imageUrlMap: Map<string, string>; imageUrlMap: Map<string, string>;
triggerDisplayName?: string | null;
}; };
export async function fetchGitHubData({ export async function fetchGitHubData({
@@ -40,7 +38,6 @@ export async function fetchGitHubData({
repository, repository,
prNumber, prNumber,
isPR, isPR,
triggerUsername,
}: FetchDataParams): Promise<FetchDataResult> { }: FetchDataParams): Promise<FetchDataResult> {
const [owner, repo] = repository.split("/"); const [owner, repo] = repository.split("/");
if (!owner || !repo) { if (!owner || !repo) {
@@ -194,12 +191,6 @@ export async function fetchGitHubData({
allComments, allComments,
); );
// Fetch trigger user display name if username is provided
let triggerDisplayName: string | null | undefined;
if (triggerUsername) {
triggerDisplayName = await fetchUserDisplayName(octokits, triggerUsername);
}
return { return {
contextData, contextData,
comments, comments,
@@ -207,27 +198,5 @@ export async function fetchGitHubData({
changedFilesWithSHA, changedFilesWithSHA,
reviewData, reviewData,
imageUrlMap, imageUrlMap,
triggerDisplayName,
}; };
} }
export type UserQueryResponse = {
user: {
name: string | null;
};
};
export async function fetchUserDisplayName(
octokits: Octokits,
login: string,
): Promise<string | null> {
try {
const result = await octokits.graphql<UserQueryResponse>(USER_QUERY, {
login,
});
return result.user.name;
} catch (error) {
console.warn(`Failed to fetch user display name for ${login}:`, error);
return null;
}
}

View File

@@ -45,16 +45,9 @@ export async function setupBranch(
const branchName = prData.headRefName; const branchName = prData.headRefName;
// Determine optimal fetch depth based on PR commit count, with a minimum of 20 // Execute git commands to checkout PR branch (shallow fetch for performance)
const commitCount = prData.commits.totalCount; // Fetch the branch with a depth of 20 to avoid fetching too much history, while still allowing for some context
const fetchDepth = Math.max(commitCount, 20); await $`git fetch origin --depth=20 ${branchName}`;
console.log(
`PR #${entityNumber}: ${commitCount} commits, using fetch depth ${fetchDepth}`,
);
// Execute git commands to checkout PR branch (dynamic depth based on PR size)
await $`git fetch origin --depth=${fetchDepth} ${branchName}`;
await $`git checkout ${branchName}`; await $`git checkout ${branchName}`;
console.log(`Successfully checked out PR branch for PR #${entityNumber}`); console.log(`Successfully checked out PR branch for PR #${entityNumber}`);

View File

@@ -9,6 +9,7 @@ export type ExecutionDetails = {
export type CommentUpdateInput = { export type CommentUpdateInput = {
currentBody: string; currentBody: string;
actionFailed: boolean; actionFailed: boolean;
actionCancelled?: boolean;
executionDetails: ExecutionDetails | null; executionDetails: ExecutionDetails | null;
jobUrl: string; jobUrl: string;
branchLink?: string; branchLink?: string;
@@ -74,6 +75,7 @@ export function updateCommentBody(input: CommentUpdateInput): string {
branchLink, branchLink,
prLink, prLink,
actionFailed, actionFailed,
actionCancelled,
branchName, branchName,
triggerUsername, triggerUsername,
errorDetails, errorDetails,
@@ -112,7 +114,13 @@ export function updateCommentBody(input: CommentUpdateInput): string {
// Build the header // Build the header
let header = ""; let header = "";
if (actionFailed) { if (actionCancelled) {
header = "**Claude's task was cancelled";
if (durationStr) {
header += ` after ${durationStr}`;
}
header += "**";
} else if (actionFailed) {
header = "**Claude encountered an error"; header = "**Claude encountered an error";
if (durationStr) { if (durationStr) {
header += ` after ${durationStr}`; header += ` after ${durationStr}`;

View File

@@ -1,7 +1,6 @@
// Types for GitHub GraphQL query responses // Types for GitHub GraphQL query responses
export type GitHubAuthor = { export type GitHubAuthor = {
login: string; login: string;
name?: string;
}; };
export type GitHubComment = { export type GitHubComment = {

View File

@@ -466,7 +466,6 @@ server.tool(
const octokit = new Octokit({ const octokit = new Octokit({
auth: githubToken, auth: githubToken,
baseUrl: GITHUB_API_URL,
}); });
const isPullRequestReviewComment = const isPullRequestReviewComment =

View File

@@ -1,5 +1,4 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import { GITHUB_API_URL } from "../github/api/config";
type PrepareConfigParams = { type PrepareConfigParams = {
githubToken: string; githubToken: string;
@@ -8,7 +7,6 @@ type PrepareConfigParams = {
branch: string; branch: string;
additionalMcpConfig?: string; additionalMcpConfig?: string;
claudeCommentId?: string; claudeCommentId?: string;
allowedTools: string[];
}; };
export async function prepareMcpConfig( export async function prepareMcpConfig(
@@ -21,17 +19,24 @@ export async function prepareMcpConfig(
branch, branch,
additionalMcpConfig, additionalMcpConfig,
claudeCommentId, claudeCommentId,
allowedTools,
} = params; } = params;
try { try {
const allowedToolsList = allowedTools || []; const baseMcpConfig = {
const hasGitHubMcpTools = allowedToolsList.some((tool) =>
tool.startsWith("mcp__github__"),
);
const baseMcpConfig: { mcpServers: Record<string, unknown> } = {
mcpServers: { mcpServers: {
github: {
command: "docker",
args: [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/anthropics/github-mcp-server:sha-7382253",
],
env: {
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
},
},
github_file_ops: { github_file_ops: {
command: "bun", command: "bun",
args: [ args: [
@@ -47,29 +52,11 @@ export async function prepareMcpConfig(
...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }), ...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }),
GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "", GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
IS_PR: process.env.IS_PR || "false", IS_PR: process.env.IS_PR || "false",
GITHUB_API_URL: GITHUB_API_URL,
}, },
}, },
}, },
}; };
if (hasGitHubMcpTools) {
baseMcpConfig.mcpServers.github = {
command: "docker",
args: [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-e9f748f", // https://github.com/github/github-mcp-server/releases/tag/v0.4.0
],
env: {
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
},
};
}
// Merge with additional MCP config if provided // Merge with additional MCP config if provided
if (additionalMcpConfig && additionalMcpConfig.trim()) { if (additionalMcpConfig && additionalMcpConfig.trim()) {
try { try {

View File

@@ -418,4 +418,48 @@ describe("updateCommentBody", () => {
); );
}); });
}); });
describe("cancellation handling", () => {
it("shows cancellation message when actionCancelled is true", () => {
const input = {
...baseInput,
currentBody: "Claude Code is working…",
actionCancelled: true,
executionDetails: { duration_ms: 30000 }, // 30s
triggerUsername: "test-user",
};
const result = updateCommentBody(input);
expect(result).toContain("**Claude's task was cancelled after 30s**");
expect(result).not.toContain("Claude encountered an error");
expect(result).not.toContain("Claude finished");
});
it("shows cancellation message without duration when duration is missing", () => {
const input = {
...baseInput,
currentBody: "Claude Code is working…",
actionCancelled: true,
triggerUsername: "test-user",
};
const result = updateCommentBody(input);
expect(result).toContain("**Claude's task was cancelled**");
expect(result).not.toContain("after");
});
it("prioritizes cancellation over failure", () => {
const input = {
...baseInput,
currentBody: "Claude Code is working…",
actionCancelled: true,
actionFailed: true, // Both are true, cancellation should take precedence
executionDetails: { duration_ms: 45000 },
};
const result = updateCommentBody(input);
expect(result).toContain("**Claude's task was cancelled after 45s**");
expect(result).not.toContain("Claude encountered an error");
});
});
}); });

View File

@@ -316,7 +316,7 @@ describe("generatePrompt", () => {
expect(prompt).toContain("<trigger_username>johndoe</trigger_username>"); expect(prompt).toContain("<trigger_username>johndoe</trigger_username>");
expect(prompt).toContain( expect(prompt).toContain(
'Use: "Co-authored-by: johndoe <johndoe@users.noreply.github.com>"', "Co-authored-by: johndoe <johndoe@users.noreply.github.com>",
); );
}); });
@@ -652,7 +652,7 @@ describe("buildAllowedToolsString", () => {
}); });
test("should append custom tools when provided", () => { test("should append custom tools when provided", () => {
const customTools = ["Tool1", "Tool2", "Tool3"]; const customTools = "Tool1,Tool2,Tool3";
const result = buildAllowedToolsString(customTools); const result = buildAllowedToolsString(customTools);
// Base tools should be present // Base tools should be present
@@ -683,7 +683,7 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should append custom disallowed tools when provided", () => { test("should append custom disallowed tools when provided", () => {
const customDisallowedTools = ["BadTool1", "BadTool2"]; const customDisallowedTools = "BadTool1,BadTool2";
const result = buildDisallowedToolsString(customDisallowedTools); const result = buildDisallowedToolsString(customDisallowedTools);
// Base disallowed tools should be present // Base disallowed tools should be present
@@ -701,8 +701,8 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should remove hardcoded disallowed tools if they are in allowed tools", () => { test("should remove hardcoded disallowed tools if they are in allowed tools", () => {
const customDisallowedTools = ["BadTool1", "BadTool2"]; const customDisallowedTools = "BadTool1,BadTool2";
const allowedTools = ["WebSearch", "SomeOtherTool"]; const allowedTools = "WebSearch,SomeOtherTool";
const result = buildDisallowedToolsString( const result = buildDisallowedToolsString(
customDisallowedTools, customDisallowedTools,
allowedTools, allowedTools,
@@ -720,7 +720,7 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should remove all hardcoded disallowed tools if they are all in allowed tools", () => { test("should remove all hardcoded disallowed tools if they are all in allowed tools", () => {
const allowedTools = ["WebSearch", "WebFetch", "SomeOtherTool"]; const allowedTools = "WebSearch,WebFetch,SomeOtherTool";
const result = buildDisallowedToolsString(undefined, allowedTools); const result = buildDisallowedToolsString(undefined, allowedTools);
// Both hardcoded disallowed tools should be removed // Both hardcoded disallowed tools should be removed
@@ -732,8 +732,8 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should handle custom disallowed tools when all hardcoded tools are overridden", () => { test("should handle custom disallowed tools when all hardcoded tools are overridden", () => {
const customDisallowedTools = ["BadTool1", "BadTool2"]; const customDisallowedTools = "BadTool1,BadTool2";
const allowedTools = ["WebSearch", "WebFetch"]; const allowedTools = "WebSearch,WebFetch";
const result = buildDisallowedToolsString( const result = buildDisallowedToolsString(
customDisallowedTools, customDisallowedTools,
allowedTools, allowedTools,

View File

@@ -24,19 +24,21 @@ describe("prepareMcpConfig", () => {
processExitSpy.mockRestore(); processExitSpy.mockRestore();
}); });
test("should return base config when no additional config is provided and no allowed_tools", async () => { test("should return base config when no additional config is provided", async () => {
const result = await prepareMcpConfig({ const result = await prepareMcpConfig({
githubToken: "test-token", githubToken: "test-token",
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
"test-token",
);
expect(parsed.mcpServers.github_file_ops.env.GITHUB_TOKEN).toBe( expect(parsed.mcpServers.github_file_ops.env.GITHUB_TOKEN).toBe(
"test-token", "test-token",
); );
@@ -47,60 +49,6 @@ describe("prepareMcpConfig", () => {
); );
}); });
test("should include github MCP server when mcp__github__ tools are allowed", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
"test-token",
);
});
test("should not include github MCP server when only file_ops tools are allowed", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
allowedTools: [
"mcp__github_file_ops__commit_files",
"mcp__github_file_ops__update_claude_comment",
],
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
});
test("should include file_ops server even when no GitHub tools are allowed", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
allowedTools: ["Edit", "Read", "Write"],
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
});
test("should return base config when additional config is empty string", async () => { test("should return base config when additional config is empty string", async () => {
const result = await prepareMcpConfig({ const result = await prepareMcpConfig({
githubToken: "test-token", githubToken: "test-token",
@@ -108,12 +56,11 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: "", additionalMcpConfig: "",
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
expect(consoleWarningSpy).not.toHaveBeenCalled(); expect(consoleWarningSpy).not.toHaveBeenCalled();
}); });
@@ -125,12 +72,11 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: " \n\t ", additionalMcpConfig: " \n\t ",
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
expect(consoleWarningSpy).not.toHaveBeenCalled(); expect(consoleWarningSpy).not.toHaveBeenCalled();
}); });
@@ -154,10 +100,6 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -191,10 +133,6 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -231,13 +169,12 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.customProperty).toBe("custom-value"); expect(parsed.customProperty).toBe("custom-value");
expect(parsed.anotherProperty).toEqual({ nested: "value" }); expect(parsed.anotherProperty).toEqual({ nested: "value" });
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.custom_server).toBeDefined(); expect(parsed.mcpServers.custom_server).toBeDefined();
}); });
@@ -250,14 +187,13 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: invalidJson, additionalMcpConfig: invalidJson,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("Failed to parse additional MCP config:"), expect.stringContaining("Failed to parse additional MCP config:"),
); );
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -270,7 +206,6 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: nonObjectJson, additionalMcpConfig: nonObjectJson,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -280,7 +215,7 @@ describe("prepareMcpConfig", () => {
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("MCP config must be a valid JSON object"), expect.stringContaining("MCP config must be a valid JSON object"),
); );
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -293,7 +228,6 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: nullJson, additionalMcpConfig: nullJson,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -303,7 +237,7 @@ describe("prepareMcpConfig", () => {
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("MCP config must be a valid JSON object"), expect.stringContaining("MCP config must be a valid JSON object"),
); );
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -316,7 +250,6 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: arrayJson, additionalMcpConfig: arrayJson,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -325,7 +258,7 @@ describe("prepareMcpConfig", () => {
expect(consoleInfoSpy).toHaveBeenCalledWith( expect(consoleInfoSpy).toHaveBeenCalledWith(
"Merging additional MCP server configuration with built-in servers", "Merging additional MCP server configuration with built-in servers",
); );
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
// The array will be spread into the config (0: 1, 1: 2, 2: 3) // The array will be spread into the config (0: 1, 1: 2, 2: 3)
expect(parsed[0]).toBe(1); expect(parsed[0]).toBe(1);
@@ -362,13 +295,12 @@ describe("prepareMcpConfig", () => {
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers.server1).toBeDefined(); expect(parsed.mcpServers.server1).toBeDefined();
expect(parsed.mcpServers.server2).toBeDefined(); expect(parsed.mcpServers.server2).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined(); expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_file_ops.command).toBe("overridden"); expect(parsed.mcpServers.github_file_ops.command).toBe("overridden");
expect(parsed.mcpServers.github_file_ops.env.CUSTOM).toBe("value"); expect(parsed.mcpServers.github_file_ops.env.CUSTOM).toBe("value");
expect(parsed.otherConfig.nested.deeply).toBe("value"); expect(parsed.otherConfig.nested.deeply).toBe("value");
@@ -383,7 +315,6 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -403,7 +334,6 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
allowedTools: [],
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);

View File

@@ -11,8 +11,8 @@ const defaultInputs = {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
anthropicModel: "claude-3-7-sonnet-20250219", anthropicModel: "claude-3-7-sonnet-20250219",
allowedTools: [] as string[], allowedTools: "",
disallowedTools: [] as string[], disallowedTools: "",
customInstructions: "", customInstructions: "",
directPrompt: "", directPrompt: "",
useBedrock: false, useBedrock: false,

View File

@@ -62,8 +62,8 @@ describe("checkWritePermissions", () => {
inputs: { inputs: {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
directPrompt: "", directPrompt: "",
}, },

View File

@@ -242,7 +242,7 @@ describe("parseEnvVarsWithContext", () => {
...mockPullRequestCommentContext, ...mockPullRequestCommentContext,
inputs: { inputs: {
...mockPullRequestCommentContext.inputs, ...mockPullRequestCommentContext.inputs,
allowedTools: ["Tool1", "Tool2"], allowedTools: "Tool1,Tool2",
}, },
}); });
const result = prepareContext(contextWithAllowedTools, "12345"); const result = prepareContext(contextWithAllowedTools, "12345");

View File

@@ -30,8 +30,8 @@ describe("checkContainsTrigger", () => {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
directPrompt: "Fix the bug in the login form", directPrompt: "Fix the bug in the login form",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
}, },
}); });
@@ -56,8 +56,8 @@ describe("checkContainsTrigger", () => {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
}, },
}); });
@@ -228,8 +228,8 @@ describe("checkContainsTrigger", () => {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
}, },
}); });
@@ -255,8 +255,8 @@ describe("checkContainsTrigger", () => {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
}, },
}); });
@@ -282,8 +282,8 @@ describe("checkContainsTrigger", () => {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: [], allowedTools: "",
disallowedTools: [], disallowedTools: "",
customInstructions: "", customInstructions: "",
}, },
}); });

View File

@@ -0,0 +1,160 @@
import { describe, test, expect, beforeEach, afterEach } from "bun:test";
describe("update-comment-link workflow status detection", () => {
let originalEnv: NodeJS.ProcessEnv;
beforeEach(() => {
originalEnv = { ...process.env };
});
afterEach(() => {
process.env = originalEnv;
});
test("should detect prepare step failure", () => {
process.env.PREPARE_SUCCESS = "false";
process.env.PREPARE_ERROR = "Failed to fetch issue data";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
let actionFailed = false;
let errorDetails: string | undefined;
if (!prepareSuccess && prepareError) {
actionFailed = true;
errorDetails = prepareError;
}
expect(actionFailed).toBe(true);
expect(errorDetails).toBe("Failed to fetch issue data");
});
test("should detect claude-code step failure when prepare succeeds", () => {
process.env.PREPARE_SUCCESS = "true";
process.env.CLAUDE_SUCCESS = "false";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
let actionFailed = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else {
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(true);
});
test("should detect success when both steps succeed", () => {
process.env.PREPARE_SUCCESS = "true";
process.env.CLAUDE_SUCCESS = "true";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
let actionFailed = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else {
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(false);
});
test("should treat missing CLAUDE_SUCCESS env var as failure", () => {
process.env.PREPARE_SUCCESS = "true";
delete process.env.CLAUDE_SUCCESS;
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
let actionFailed = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else {
// When CLAUDE_SUCCESS is undefined, it's not === "true", so claudeSuccess = false
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(true);
});
test("should handle undefined PREPARE_SUCCESS as success", () => {
delete process.env.PREPARE_SUCCESS;
delete process.env.PREPARE_ERROR;
process.env.CLAUDE_SUCCESS = "true";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
let actionFailed = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else {
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(false);
});
test("should detect cancellation when CLAUDE_CANCELLED is true", () => {
process.env.PREPARE_SUCCESS = "true";
process.env.CLAUDE_SUCCESS = "false";
process.env.CLAUDE_CANCELLED = "true";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
const isCancelled = process.env.CLAUDE_CANCELLED === "true";
let actionFailed = false;
let actionCancelled = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else if (isCancelled) {
actionCancelled = true;
} else {
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(false);
expect(actionCancelled).toBe(true);
});
test("should not detect cancellation when CLAUDE_CANCELLED is false", () => {
process.env.PREPARE_SUCCESS = "true";
process.env.CLAUDE_SUCCESS = "false";
process.env.CLAUDE_CANCELLED = "false";
const prepareSuccess = process.env.PREPARE_SUCCESS !== "false";
const prepareError = process.env.PREPARE_ERROR;
const isCancelled = process.env.CLAUDE_CANCELLED === "true";
let actionFailed = false;
let actionCancelled = false;
if (!prepareSuccess && prepareError) {
actionFailed = true;
} else if (isCancelled) {
actionCancelled = true;
} else {
const claudeSuccess = process.env.CLAUDE_SUCCESS === "true";
actionFailed = !claudeSuccess;
}
expect(actionFailed).toBe(true);
expect(actionCancelled).toBe(false);
});
});