Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/wizard-commit-hooks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@taskless/cli": patch
---

The installer's offer to commit the Taskless files no longer looks hung while your git hooks run. git now runs in your terminal exactly as if you had typed `git commit`, so hook output, prompts and interactive displays (lefthook, husky, pre-commit) show as they would normally, and the installer says the hooks are running before it starts. When the commit does not go through, because a hook refused it or you pressed Ctrl-C, the installer asks whether to try again, commit without running git hooks, or leave the commit to you. It never skips your hooks unless you choose to, and the install and the onboarding prompt survive either way. A cancelled install now tells you to run `npx @taskless/cli` with no arguments to try again, instead of `init`, which installs without prompts and never reopens the installer.
77 changes: 70 additions & 7 deletions packages/cli/src/install/uncommitted.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { execFile, spawn } from "node:child_process";
import process from "node:process";

import { CANONICAL_DIR, type InstallPlan } from "./install";
import { renderNoticeBox } from "./notice-box";
Expand Down Expand Up @@ -120,22 +121,84 @@ export async function getUncommittedInstallNotice(
);
}

/** How a commit the wizard ran turned out. */
export type CommitResult =
| { ok: true }
/**
* `interrupted` when the person pressed Ctrl-C. `error` carries git's words
* only when they were captured, which a commit's never are: the commit
* writes to the terminal, so its output is already on screen.
*/
| { ok: false; interrupted: boolean; error?: string };

/**
* Commit exactly `paths`, and nothing else the person had staged.
*
* `git commit -- <paths>` records only those paths, so an unrelated change
* already in the index stays staged and out of this commit. The person's own
* hooks and signing configuration run as they would for any commit; a hook
* that refuses, or a merge in progress, comes back as git's own words.
* hooks and signing configuration run as they would for any commit, unless
* `skipHooks` is set, which the person chooses explicitly and only after a
* commit with hooks did not go through.
*
* git gets the terminal itself, exactly as if the person had typed
* `git commit`. Hooks (lefthook, husky, pre-commit) can run for minutes or
* draw a prompt, and with git's output captured the wizard sat on a blank
* screen that read as a hang. Piping the output through would show it, but a
* hook that checks for a terminal would then drop its colors and its
* interactive display. Interactive hooks read their answers from `/dev/tty`
* themselves, since git gives `pre-commit` no stdin, and the wizard holds no
* prompt open while git runs.
*
* Ctrl-C stops the commit, not the wizard. The terminal delivers SIGINT to
* git and its hooks as well as to this process, so git stops on its own; this
* process only has to not die with it, or the install loses the lines that
* say what to do next. A second Ctrl-C does end the wizard, for a hook that
* will not stop.
*/
export async function commitInstall(
cwd: string,
paths: readonly string[],
message: string
): Promise<{ ok: true } | { ok: false; error: string }> {
message: string,
options: { skipHooks?: boolean } = {}
): Promise<CommitResult> {
const added = await run(cwd, ["add", "--", ...paths]);
if (!added.ok) return added;
return run(cwd, ["commit", "--quiet", "-m", message, "--", ...paths]);
if (!added.ok) return { ok: false, interrupted: false, error: added.error };
return runInTerminal(cwd, [
"commit",
"--quiet",
...(options.skipHooks ? ["--no-verify"] : []),
"-m",
message,
"--",
...paths,
]);
}

function runInTerminal(cwd: string, args: string[]): Promise<CommitResult> {
let interrupted = false;
const onInterrupt = () => {
interrupted = true;
};
// `once`, so only the first Ctrl-C is absorbed. A hook that ignores SIGINT
// would otherwise leave no way out: a second press finds no handler and
// terminates the process, which is what pressing it twice should do. The
// install is already on disk either way.
process.once("SIGINT", onInterrupt);
return new Promise<CommitResult>((resolve) => {
const child = spawn("git", args, { cwd, stdio: "inherit" });
child.on("error", (error) => {
resolve({ ok: false, interrupted, error: error.message });
});
child.on("close", (code, signal) => {
resolve(
code === 0
? { ok: true }
: { ok: false, interrupted: interrupted || signal === "SIGINT" }
);
});
}).finally(() => {
process.off("SIGINT", onInterrupt);
});
}

function git(cwd: string, args: string[]): Promise<string | undefined> {
Expand Down
6 changes: 4 additions & 2 deletions packages/cli/src/wizard/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ export async function runWizard(

const proceed = await renderSummaryAndConfirm(diff, permissionPreview);
if (!proceed) {
cancel(`Install cancelled. Run \`${getCliPrefix()} init\` to try again.`);
cancel(
`Install cancelled. Run \`${getCliPrefix()}\` with no arguments to try again.`
);
cancelledStep = "summary";
return finish({ status: "cancelled" });
}
Expand Down Expand Up @@ -245,7 +247,7 @@ export async function runWizard(
} catch (error) {
if (error instanceof WizardCancelled) {
cancel(
`Wizard cancelled at step "${error.step}". Run \`${getCliPrefix()} init\` to try again.`
`Wizard cancelled at step "${error.step}". Run \`${getCliPrefix()}\` with no arguments to try again.`
);
cancelledStep = error.step;
return finish({ status: "cancelled" });
Expand Down
67 changes: 60 additions & 7 deletions packages/cli/src/wizard/steps/commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,66 @@ export async function promptCommit(
message = written.trim();
}

const result = await commitInstall(cwd, paths, message);
if (result.ok) {
log.success(`Committed the Taskless files: ${message}`);
} else {
log.warn(
`git could not commit the Taskless files:\n${result.error}\nCommit them yourself before you start your agent.`
await commitWithRetry(cwd, paths, message);
return choice;
}

/** What to do after a commit that did not go through. */
type AfterFailure = "retry" | "skip-hooks" | "leave";

/**
* Run the commit, and when it does not go through, ask what to do instead of
* giving up. A hook that refuses or hangs is the usual reason, so committing
* without hooks is offered, but only here and only as the person's choice:
* hooks are the project's rules, and the wizard never waives them on its own.
*/
async function commitWithRetry(
cwd: string,
paths: readonly string[],
message: string
): Promise<void> {
let skipHooks = false;
for (;;) {
// Said before git starts, because nothing else from the wizard is on
// screen while a slow hook runs.
log.info(
skipHooks
? "Committing without running your git hooks."
: "Committing. Your git hooks run now, in this terminal. Press Ctrl-C to stop the commit; the install stays in place."
);
const result = await commitInstall(cwd, paths, message, { skipHooks });
if (result.ok) {
log.success(`Committed the Taskless files: ${message}`);
return;
}

const reason = result.interrupted
? "The commit was stopped."
: result.error === undefined
? "git could not commit the Taskless files. Its output is above."
: `git could not commit the Taskless files:\n${result.error}`;
const options: { value: AfterFailure; label: string; hint?: string }[] = [
{ value: "retry", label: "Try again" },
];
if (!skipHooks) {
options.push({
value: "skip-hooks",
label: "Commit without running git hooks",
hint: "git commit --no-verify",
});
}
options.push({ value: "leave", label: "Leave it, I'll commit myself" });

const next = await select<AfterFailure>({
message: `${reason} What now?`,
options,
});
if (isCancel(next) || next === "leave") {
log.warn(
"Commit the Taskless files yourself before you start your agent."
);
return;
}
if (next === "skip-hooks") skipHooks = true;
}
return choice;
}
102 changes: 92 additions & 10 deletions packages/cli/test/wizard-integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ const clackResponses: {
globalTrust?: boolean | symbol;
commit?: string | symbol;
commitMessage?: string | symbol;
} = {};
/** Answers, in order, to "what now?" after a commit does not go through. */
afterFailure: (string | symbol)[];
} = { afterFailure: [] };

// Every select the wizard asked, in order.
const selectMessages: string[] = [];
Expand Down Expand Up @@ -91,6 +93,9 @@ vi.mock("@clack/prompts", () => ({
groupMultiselect: vi.fn(() => Promise.resolve(clackResponses.locations)),
select: vi.fn(({ message }: { message: string }) => {
selectMessages.push(message);
if (message.endsWith("What now?")) {
return Promise.resolve(clackResponses.afterFailure.shift() ?? "leave");
}
return Promise.resolve(clackResponses.commit);
}),
text: vi.fn(() => Promise.resolve(clackResponses.commitMessage)),
Expand Down Expand Up @@ -145,6 +150,7 @@ beforeEach(async () => {
clackResponses.summary = undefined;
clackResponses.commit = undefined;
clackResponses.commitMessage = undefined;
clackResponses.afterFailure = [];
selectMessages.length = 0;
confirmMessages.length = 0;
confirmDefaults.length = 0;
Expand Down Expand Up @@ -323,6 +329,20 @@ describe("runWizard end-to-end", () => {
expect(await exists(join(cwd, ".claude", "settings.json"))).toBe(false);
});

// `init` is the batch install and never prompts, so sending someone there to
// "try again" left them with no way back into the wizard.
it("sends a cancelled install back to the bare command, not init", async () => {
clackResponses.locations = ["Claude Code"];
clackResponses.summary = false;

const { runWizard } = await import("../src/wizard");
await runWizard({ cwd, globalTrustEnvironment });

const message = cancelSpy.mock.calls[0]?.[0] as string;
expect(message).toContain("with no arguments to try again");
expect(message).not.toMatch(/ init`/);
});

it("previews removing a Taskless rule it never recorded", async () => {
// A stale rule an agent added through the skill's fallback.
const stale = "Bash(npx @taskless/cli@0.12.0 *)";
Expand Down Expand Up @@ -798,6 +818,21 @@ function git(directory: string, ...args: string[]): string {
);
}

async function refusingHook(repo: string, script: string): Promise<void> {
const hook = join(repo, ".git", "hooks", "pre-commit");
await writeFile(hook, `#!/bin/sh\n${script}\n`);
await chmod(hook, 0o755);
}

function hasCommit(repo: string): boolean {
try {
git(repo, "rev-parse", "--verify", "HEAD");
return true;
} catch {
return false;
}
}

/**
* #554: a worktree is built from commits, and the install commits nothing, so
* the wizard offers to make the commit itself. The tests run git with no
Expand Down Expand Up @@ -863,22 +898,69 @@ describe("the wizard's offer to commit the install", () => {
expect(git(cwd, "status", "--porcelain")).toBe("");
});

it("shows git's refusal and still completes when a hook rejects the commit", async () => {
const hook = join(cwd, ".git", "hooks", "pre-commit");
await writeFile(hook, "#!/bin/sh\necho 'hook says no' >&2\nexit 1\n");
await chmod(hook, 0o755);
it("asks what to do when a hook refuses, and still completes when left", async () => {
await refusingHook(cwd, "exit 1");
clackResponses.commit = "default";
clackResponses.afterFailure = ["leave"];

const { runWizard } = await import("../src/wizard");
const result = await runWizard({ cwd, globalTrustEnvironment });

expect(result.status).toBe("completed");
const warning = warnedMessages.find((message) =>
message.includes("git could not commit")
expect(selectMessages).toContain(
"git could not commit the Taskless files. Its output is above. What now?"
);
expect(warnedMessages).toContain(
"Commit the Taskless files yourself before you start your agent."
);
expect(hasCommit(cwd)).toBe(false);
expect(outroSpy).toHaveBeenCalledWith(
"Taskless is installed, but its files are not committed yet."
);
});

it("commits without hooks only when the person chooses it", async () => {
await refusingHook(cwd, "exit 1");
clackResponses.commit = "default";
clackResponses.afterFailure = ["skip-hooks"];

const { runWizard } = await import("../src/wizard");
await runWizard({ cwd, globalTrustEnvironment });

expect(hasCommit(cwd)).toBe(true);
expect(infoMessages).toContain(
"Committing without running your git hooks."
);
});

it("runs the hooks again on a retry", async () => {
// Refuses once, then lets the commit through.
const marker = join(cwd, ".git", "refused-once");
await refusingHook(
cwd,
`if [ ! -f '${marker}' ]; then touch '${marker}'; exit 1; fi`
);
clackResponses.commit = "default";
clackResponses.afterFailure = ["retry"];

const { runWizard } = await import("../src/wizard");
await runWizard({ cwd, globalTrustEnvironment });

expect(hasCommit(cwd)).toBe(true);
expect(
selectMessages.filter((message) => message.endsWith("What now?"))
).toHaveLength(1);
});

it("says the hooks are running before git starts", async () => {
clackResponses.commit = "default";

const { runWizard } = await import("../src/wizard");
await runWizard({ cwd, globalTrustEnvironment });

expect(infoMessages.join("\n")).toContain(
"Your git hooks run now, in this terminal."
);
expect(warning).toContain("hook says no");
expect(warning).toContain("Commit them yourself");
expect(() => git(cwd, "rev-parse", "--verify", "HEAD")).toThrow();
});

it("leaves everything uncommitted when the person will do it", async () => {
Expand Down
Loading