Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/core/src/git-interaction/errorPrompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@ export interface FixWithAgentPrompt {
context: string;
}

export function buildCommitHookErrorPrompt(
command: string,
): FixWithAgentPrompt {
return {
label: `Fix commit failure`,
context: `A \`git commit\` command failed, most likely because a pre-commit hook (e.g. lint, format, type-check, or secret scan) rejected the commit or exited with a non-zero status. The command that failed was:

${command}

The full hook output is below.

Your task is to diagnose the root cause from the output and fix the underlying issue (e.g. lint/format violations, failing checks, missing dependencies) so the commit can succeed.

IMPORTANT:
- Start by reading the output carefully to identify which hook failed and why.
- Fix the underlying issue rather than bypassing the hook. Do NOT use \`--no-verify\` unless the user explicitly asks for it.
- Confirm any destructive actions with the user first.
- Once the issue is resolved, you may retry the commit.`,
};
}

export function buildCreatePrFlowErrorPrompt(
failedStep: CreatePrStep | null,
): FixWithAgentPrompt {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Check, Copy, Sparkle } from "@phosphor-icons/react";
import { buildCommitHookErrorPrompt } from "@posthog/core/git-interaction/errorPrompts";
import { useFixWithAgent } from "@posthog/ui/features/git-interaction/useFixWithAgent";
import { Button, Flex } from "@radix-ui/themes";
import { useState } from "react";

const ICON_SIZE = 12;

/**
* Action footer shown under a failed `git commit` Bash tool call (e.g. a
* pre-commit hook rejected the commit). Lets the user hand the failure output
* to the agent to resolve, or copy it to paste into a new message.
*/
export function CommitFailureActions({
command,
output,
}: {
command: string;
output: string;
}) {
const { canFixWithAgent, fixWithAgent } = useFixWithAgent(() =>
buildCommitHookErrorPrompt(command),
);
const [copied, setCopied] = useState(false);

const handleCopy = async () => {
try {
await navigator.clipboard.writeText(output);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// Clipboard writes can reject when the document isn't focused; ignore.
}
};

return (
<Flex gap="2" justify="end" align="center">
{canFixWithAgent && (
<Button
size="1"
variant="soft"
color="gray"
onClick={() => {
void fixWithAgent(output);
}}
>
<Sparkle size={ICON_SIZE} />
Fix with agent
</Button>
)}
<Button size="1" variant="soft" color="gray" onClick={handleCopy}>
{copied ? <Check size={ICON_SIZE} /> : <Copy size={ICON_SIZE} />}
{copied ? "Copied" : "Copy error"}
</Button>
</Flex>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { ToolCall } from "@posthog/ui/features/sessions/types";
import { Theme } from "@radix-ui/themes";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ExecuteToolView } from "./ExecuteToolView";

vi.mock("./CommitFailureActions", () => ({
CommitFailureActions: ({
command,
output,
}: {
command: string;
output: string;
}) => (
<div
data-testid="commit-failure-actions"
data-command={command}
data-output={output}
/>
),
}));

function makeToolCall(overrides: Partial<ToolCall> = {}): ToolCall {
return {
toolCallId: "tc-1",
title: "bash",
kind: "execute",
status: "completed",
rawInput: {
command: 'git commit -m "test"',
description: "run commit",
},
content: [],
...overrides,
};
}

function textContent(text: string): NonNullable<ToolCall["content"]> {
return [{ type: "content", content: { type: "text", text } }];
}

function renderView(toolCall: ToolCall) {
return render(
<Theme>
<ExecuteToolView toolCall={toolCall} expanded />
</Theme>,
);
}

describe("ExecuteToolView", () => {
it("shows commit failure actions for a git commit failure with hook output", () => {
renderView(
makeToolCall({
status: "failed",
rawInput: { command: 'git commit -m "test"' },
content: textContent(`Exit code 1\n╭───╮\n│ hook: pre-commit │\n╰───╯`),
}),
);

const actions = screen.getByTestId("commit-failure-actions");
expect(actions).toHaveAttribute("data-command", 'git commit -m "test"');
expect(actions).toHaveAttribute(
"data-output",
expect.stringContaining("hook: pre-commit"),
);
});

it("still shows commit failure actions when the tool status is completed but the output has a non-zero exit signal", () => {
renderView(
makeToolCall({
status: "completed",
rawInput: { command: "pre-commit run --all-files" },
content: textContent("exit status 1\npre-commit failed"),
}),
);

expect(screen.getByTestId("commit-failure-actions")).toBeInTheDocument();
});

it("does not show commit failure actions for unrelated failed bash output", () => {
renderView(
makeToolCall({
status: "failed",
rawInput: { command: "git push origin main" },
content: textContent("exit status 1\nnetwork error"),
}),
);

expect(
screen.queryByTestId("commit-failure-actions"),
).not.toBeInTheDocument();
});
});
Comment on lines +50 to +93

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Tests should be parameterised

The three it blocks all exercise the same condition (whether CommitFailureActions is rendered) with different command/output/status combinations. Per project convention, tests like these should be collapsed into a single it.each table. The attribute assertions from the first test can live in a short standalone it if needed.

Context Used: Do not attempt to comment on incorrect alphabetica... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Terminal } from "@phosphor-icons/react";
import { compactHomePath } from "@posthog/shared";
import { CommitFailureActions } from "./CommitFailureActions";
import { ToolRow } from "./ToolRow";
import {
ContentPre,
Expand All @@ -14,6 +15,28 @@ import {
const ANSI_REGEX = new RegExp(`${String.fromCharCode(0x1b)}\\[[0-9;]*m`, "g");
const MAX_COMMAND_LENGTH = 120;

const GIT_COMMIT_COMMAND_REGEX =
/(?:^|[\s;&|(])git(?:\s+-[cC]\s+\S+|\s+-\S+)*\s+commit(?:\s|$)/;

const PRE_COMMIT_COMMAND_REGEX =
/\blefthook\b[\s\S]*?\bpre-commit\b|\bpre-commit\b(?:[\s\S]*?\brun\b|$)|\bhusky\b(?:\s+run\b|[\s\S]*?\bpre-commit\b)|\bovercommit\b[\s\S]*?(?:--run\b|\bpre-commit\b)|\blint-staged\b|[./]*\.(?:git\/hooks|husky)\/pre-commit\b/i;

const PRE_COMMIT_OUTPUT_REGEX =
/hook:\s*pre-commit\b|\blefthook\b.*\b(?:hook|run)\b|\bRunning\s+(?:pre-commit\b.*\bhooks?\b|\bhooks?\b.*\bpre-commit\b)|\[pre-commit\]|\bhusky\b.*\bpre-commit\b/i;

const EXIT_STATUS_SIGNAL_REGEX =
/\b(?:exit\s+(?:status|code)|exited\s+with\s+(?:code|status))[:\s]+(\d+)\b/gi;

function hasNonZeroExitStatusSignal(text: string): boolean {
for (const match of text.matchAll(EXIT_STATUS_SIGNAL_REGEX)) {
const exitCode = Number(match[1]);
if (Number.isFinite(exitCode) && exitCode > 0) {
return true;
}
}
return false;
}

interface ExecuteRawInput {
command?: string;
description?: string;
Expand Down Expand Up @@ -42,6 +65,15 @@ export function ExecuteToolView({
"",
);
const hasOutput = output.trim().length > 0;
const isGitCommitCommand = GIT_COMMIT_COMMAND_REGEX.test(command);
const isPreCommitRunCommand = PRE_COMMIT_COMMAND_REGEX.test(command);
const hasPreCommitSignal = PRE_COMMIT_OUTPUT_REGEX.test(output);
const hasNonZeroExitSignal = hasNonZeroExitStatusSignal(output);
const hasFailureSignal = isFailed || hasNonZeroExitSignal;
const showCommitFailureActions =
hasFailureSignal &&
hasOutput &&
((isGitCommitCommand && hasPreCommitSignal) || isPreCommitRunCommand);

return (
<ToolRow
Expand All @@ -50,7 +82,16 @@ export function ExecuteToolView({
isFailed={isFailed}
wasCancelled={wasCancelled}
defaultOpen={expanded}
content={hasOutput ? <ContentPre>{output}</ContentPre> : undefined}
content={
hasOutput ? (
<>
<ContentPre>{output}</ContentPre>
{showCommitFailureActions && (
<CommitFailureActions command={command} output={output} />
)}
</>
) : undefined
}
>
{description && <ToolTitle>{description}</ToolTitle>}
{command && (
Expand Down