From 2e84ca720eb96e0adda7ce5aa2d51a7631d4fd5e Mon Sep 17 00:00:00 2001 From: loopway-bot Date: Mon, 16 Nov 2026 10:36:55 -0500 Subject: [PATCH 1/2] Add loopway setup: an interactive walk through gh, Claude Code, the bot token and the bot files Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 + README.md | 13 +- docs/developing.md | 1 + packages/cli/package.json | 2 +- packages/cli/src/config.ts | 15 +- packages/cli/src/index.ts | 12 ++ packages/cli/src/setup-io.tsx | 115 ++++++++++++++ packages/cli/src/setup.ts | 223 ++++++++++++++++++++++++++++ packages/cli/test/setup-io.test.tsx | 44 ++++++ packages/cli/test/setup.test.ts | 172 +++++++++++++++++++++ 10 files changed, 600 insertions(+), 3 deletions(-) create mode 100644 packages/cli/src/setup-io.tsx create mode 100644 packages/cli/src/setup.ts create mode 100644 packages/cli/test/setup-io.test.tsx create mode 100644 packages/cli/test/setup.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ef6c36a0..ae401628 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2.1.0 + +### Added + +- `loopway setup`: an interactive walk through what loopway needs, safe to run again. It checks `gh` (and offers `gh auth login`), Claude Code, the bot user's token (checked against GitHub, saved to `~/.loopway/config.json` for you alone) and offers `.loopway/dev.md` and `review.md` here, for the repos you name. It only asks about what is missing and never overwrites a file. See [#556](https://github.com/craftmilldev/loopway/issues/556). + ## 2.0.2 ### Added diff --git a/README.md b/README.md index d39068ce..4f9bc999 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ npm install && npm run build # Node 22+ gh auth login # loopway acts as whoever gh is logged in as ``` -Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`. +After installing, run `loopway setup` (see [Setup](#setup)). Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`. Make a directory to run it from, with a `.loopway/` folder holding one file per bot (`scratch/` inside the checkout is git-ignored): @@ -55,6 +55,17 @@ To run it from a directory outside the checkout, `npm link -w @loopway/cli` puts The first run starts now: it does not replay history. An issue or pull request from before that stays quiet until something happens to it; then, if it is open, it is reported as new, with only what happened since as updates, and its bots start threads. After that it remembers where it got to, so a restart prints nothing twice and picks up what happened while it was stopped. +## Setup + +`loopway setup` is an interactive walk through what loopway needs, in a terminal (it refuses to run without one). Each step checks first and only asks about what is missing, so it is safe to run again on a machine that is already set up: it never overwrites a file you have, and the steps that can be left out say so. + +1. **`gh`**, required. It must be installed and logged in; if it isn't logged in, setup offers to run `gh auth login` for you. It says who you are logged in as. Without a working login it stops. +2. **Claude Code**, which runs the sessions. It checks `claude --version`; if it isn't there, setup says where to get it and carries on. +3. **The bot user**, optional. If `~/.loopway/config.json` has a bot token, setup checks GitHub accepts it and says whose it is. Otherwise it asks for the token of a separate GitHub account (typed as dots, never printed), checks it, refuses your own account's (the bot would comment as you), and saves it as the `github` block with the account's login as `name` and its `users.noreply.github.com` address as `email`. The file is written for you alone (0600) and its other keys are kept. Skipping leaves sessions off. +4. **The bot files**, optional, one each for `.loopway/dev.md` and `.loopway/review.md` in the directory you ran it from. It asks which repos they should watch (guessing from `git remote origin`), warns about one `gh` can't see, and writes the files from the examples under [Bots](#bots-loopway). A file that is already there is left alone. + +It ends by telling you to run `loopway` and assign an issue to yourself. + ## Threads A **thread** is one bot plus the subjects it tracks. The rules are in each bot's front matter (see below), and they are deterministic: diff --git a/docs/developing.md b/docs/developing.md index 4ad2fd23..07d30fe2 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -53,6 +53,7 @@ When CI passes on a push to `main` and `packages/cli` changed since the last `cl | `tui-header.tsx`, `tui-theme.ts` | The header (version, poller status) and the pinned keys; the colors, taken from the billboard | | `tui-log.ts` | The session log as turn blocks, one row per line, and the tool call sentences | | `tui-input.tsx`, `tui-text.ts` | The chat text box (cursor, editing); the thread state and grouping, and the poller's status line | +| `setup.ts`, `setup-io.tsx` | `loopway setup`: the steps (gh, Claude Code, the bot token, the bot files), written against an `Io` interface so tests script the answers and the fake `exec` and `fetch` keep them off the machine and the network; and the real `Io`, one inline [Ink](https://github.com/vadimdemedev/ink) question at a time (`gh auth login` gets the terminal itself) | | `format.ts` | The printed line, and `--json` | `tools/init-scratch.mjs` (`npm run init-scratch`) is a plain Node script, outside the packages; `test/init-scratch.test.ts` runs it in a temp dir. diff --git a/packages/cli/package.json b/packages/cli/package.json index f1cc247f..d8f441ee 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@loopway/cli", - "version": "2.0.2", + "version": "2.1.0", "private": true, "license": "MIT", "description": "loopway: polls GitHub and prints every new subject and every update to one you know.", diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts index b148f97b..55322ad1 100644 --- a/packages/cli/src/config.ts +++ b/packages/cli/src/config.ts @@ -1,4 +1,4 @@ -import { readFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -42,3 +42,16 @@ export async function loadAutoUpdate(home: string, env: NodeJS.ProcessEnv = proc if (env.LOOPWAY_NO_UPDATE) return false; return (await readConfig(home)).auto_update !== false; } + +/** + * Sets the `github` block of config.json and leaves every other key as it was. The file holds a token, so it is + * written for you alone (0600), in a folder made if need be. + */ +export async function saveGitHubConfig(home: string, github: GitHubConfig): Promise { + const config = await readConfig(home); + const block = { ...(config.github as Record | undefined), ...github }; + await mkdir(home, { recursive: true }); + const path = join(home, "config.json"); + await writeFile(path, JSON.stringify({ ...config, github: block }, null, 2) + "\n", { mode: 0o600 }); + await chmod(path, 0o600); // writeFile's mode only applies to a new file +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 9fb78e15..e312ad44 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -8,6 +8,8 @@ import { loadAutoUpdate, loadGitHubConfig, loopwayHome, type GitHubConfig } from import { formatJson, formatLine, formatThread, formatThreadJson, type LoopwayEvent } from "./format.js"; import { ghToken, GitHubSource } from "./github.js"; import { startMcp } from "./mcp.js"; +import { inkIo } from "./setup-io.js"; +import { runSetup } from "./setup.js"; import { Poller } from "./poller.js"; import { Sessions } from "./sessions.js"; import type { Subject } from "./source.js"; @@ -31,10 +33,15 @@ and every update to the ones it knows. Usage: loopway [--no-tui] [--json] [--max N] loopway threads [--json] + loopway setup In a terminal it opens a TUI: the open threads and those closed in the last 3 days. Enter opens a thread, q quits. With --no-tui, --json, or output that isn't a terminal, it prints a plain log instead. +\`loopway setup\` walks you through what loopway needs: gh logged in, Claude Code, the bot user's token (optional) and +.loopway/dev.md and review.md here (optional). It checks each first, only asks about what is missing, and never +overwrites a file. + Each new issue or pull request starts a thread for every bot whose rules ask for it (on: issue, on: pull_request), and every update to it goes on the queue of the open threads that hold it. Each thread's queue goes to a Claude Code session that acts as the bot user and talks back through loopway's own MCP tool. \`loopway threads\` lists the open @@ -92,6 +99,11 @@ async function main(): Promise { } const project = projectDir(); + if (positionals[0] === "setup") { + if (!process.stdout.isTTY || !process.stdin.isTTY) + throw new Error("loopway setup asks questions: run it in a terminal."); + return runSetup({ io: inkIo(), home: loopwayHome(), cwd: project }); + } if (positionals[0] === "threads") return listThreads(stateDir(loopwayHome(), project), values.json); if (positionals.length > 0) throw new Error(`Unknown command "${positionals[0]}". Try loopway --help.`); diff --git a/packages/cli/src/setup-io.tsx b/packages/cli/src/setup-io.tsx new file mode 100644 index 00000000..ec4cb343 --- /dev/null +++ b/packages/cli/src/setup-io.tsx @@ -0,0 +1,115 @@ +import { Box, render, Text, useInput } from "ink"; +import { useState } from "react"; +import { runInherited, type Io } from "./setup.js"; +import { editInput, InputLine, type InputState } from "./tui-input.js"; +import { theme } from "./tui-theme.js"; + +/** Shows one question inline, waits for its answer, and leaves the answered line on screen. */ +function ask(element: (done: (value: T) => void) => React.ReactElement): Promise { + return new Promise((resolve) => { + const app = render( + element((value) => { + app.unmount(); + resolve(value); + }), + ); + }); +} + +export function Choose({ + question, + options, + onDone, +}: { + question: string; + options: { value: string; label: string }[]; + onDone: (value: string) => void; +}) { + const [at, setAt] = useState(0); + const [answered, setAnswered] = useState(false); + useInput((_, key) => { + if (answered) return; + if (key.upArrow) setAt((i) => Math.max(0, i - 1)); + if (key.downArrow) setAt((i) => Math.min(options.length - 1, i + 1)); + if (key.return) { + setAnswered(true); + onDone(options[at]!.value); + } + }); + if (answered) { + return ( + + ? + {question} {options[at]!.label} + + ); + } + return ( + + ? {question} + {options.map((o, i) => ( + + {i === at ? "❯ " : " "} + {o.label} + + ))} + ↑/↓ to move, Enter to choose + + ); +} + +export function Prompt({ + question, + initial = "", + secret, + onDone, +}: { + question: string; + initial?: string; + secret?: boolean; + onDone: (value: string) => void; +}) { + const [state, setState] = useState({ value: initial, cursor: initial.length }); + const [answered, setAnswered] = useState(false); + useInput((input, key) => { + if (answered) return; + if (key.return) { + setAnswered(true); + onDone(state.value); + } else setState((s) => editInput(s, input, key)); + }); + // A token shows as dots, same length, so the cursor and editing behave as with text. + const shown: InputState = secret ? { ...state, value: "•".repeat(state.value.length) } : state; + if (answered) { + return ( + + ? + {question} {secret ? "•".repeat(state.value.length) : state.value} + + ); + } + return ( + + ? {question} + + ❯ + + + + ); +} + +const MARKS = { ok: "✓", warn: "!", fail: "✗" } as const; + +/** The real terminal for `loopway setup`: Ink for the questions, plain lines between them. */ +export function inkIo(): Io { + return { + say: (line, tone) => console.log(tone ? `${MARKS[tone]} ${line}` : line), + choose: (question: string, options: { value: T; label: string }[]) => + ask((onDone) => onDone(v as T)} />), + text: (question, initial) => + ask((onDone) => ), + secret: (question) => ask((onDone) => ), + run: runInherited, + }; +} diff --git a/packages/cli/src/setup.ts b/packages/cli/src/setup.ts new file mode 100644 index 00000000..9cd07d84 --- /dev/null +++ b/packages/cli/src/setup.ts @@ -0,0 +1,223 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { loadGitHubConfig, saveGitHubConfig } from "./config.js"; + +/** What `loopway setup` needs from the terminal. The real one is Ink (setup-io.tsx); tests script it. */ +export interface Io { + say: (line: string, tone?: "ok" | "warn" | "fail") => void; + choose: (question: string, options: { value: T; label: string }[]) => Promise; + text: (question: string, initial?: string) => Promise; + /** Like `text`, but shows dots: for a token. */ + secret: (question: string) => Promise; + /** Runs a command with the terminal handed over (`gh auth login` asks its own questions). Its exit code. */ + run: (command: string, args: string[]) => Promise; +} + +export interface SetupDeps { + io: Io; + /** `~/.loopway`: where the bot's token goes. */ + home: string; + /** Where `.loopway/` is made. */ + cwd: string; + env?: NodeJS.ProcessEnv; + fetch?: typeof globalThis.fetch; + /** A command's output, or undefined when it isn't there or failed. */ + exec?: (command: string, args: string[]) => string | undefined; +} + +const REPO = /^[\w.-]+\/[\w.-]+$/; + +const defaultExec = (command: string, args: string[]) => { + try { + return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + } catch { + return undefined; + } +}; + +/** Runs a command with the terminal inherited. */ +export const runInherited = async (command: string, args: string[]) => + spawnSync(command, args, { stdio: "inherit" }).status ?? 1; + +const bot = (repos: string[], on: string, prompt: string) => + `---\nrepos: [${repos.join(", ")}]\non: ${on}\n---\n\n${prompt}\n`; + +/** The two starter bot files: the ones in the README. */ +export const BOT_FILES = { + "dev.md": (repos: string[]) => + bot( + repos, + "issue", + "You are the dev bot. When an issue is assigned to you, read it, make the change on a branch, run the tests, and open\na pull request that says `Closes #N`. Ask on the issue when something is unclear.", + ), + "review.md": (repos: string[]) => + bot( + repos, + "pull_request", + "You are the review bot. Read the pull request and its diff, check it against the issue it closes, and leave a\nreview. Be specific, and say what you ran.", + ), +}; + +/** `owner/name` from a GitHub remote URL (https or ssh), or undefined. */ +export function repoFromRemote(url: string | undefined): string | undefined { + const match = /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(url ?? ""); + return match?.[1]; +} + +/** + * Walks through what loopway needs: `gh` logged in, Claude Code, the bot user's token, and the bot files. Each step + * checks first and only asks about what is missing; nothing is overwritten, and the steps that can be left out say + * so. Returns the exit code: 1 when a step loopway can't run without was not done. + */ +export async function runSetup(deps: SetupDeps): Promise { + const { io, home, cwd } = deps; + const env = deps.env ?? process.env; + const exec = deps.exec ?? defaultExec; + const api = deps.fetch ?? globalThis.fetch; + const get = (token: string, path: string) => + api(`https://api.github.com${path}`, { + headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "loopway" }, + }).catch(() => undefined); + const who = async (token: string) => { + const res = await get(token, "/user"); + if (!res?.ok) return undefined; + const user = (await res.json()) as { login: string; id: number }; + return user; + }; + + io.say("loopway setup: each step checks first, and only asks about what is missing."); + + // 1. gh, which loopway acts as you through. Required. + if (exec("gh", ["--version"]) === undefined) { + io.say("gh isn't installed. Install it from https://cli.github.com, then run `loopway setup` again.", "fail"); + return 1; + } + // The same order as ghToken (github.ts), but through `exec` so a test never reaches the real gh. + const login = () => env.GH_TOKEN || env.GITHUB_TOKEN || exec("gh", ["auth", "token"]) || undefined; + let token = login(); + if (!token) { + const answer = await io.choose("gh isn't logged in to GitHub.", [ + { value: "login", label: "Log in now (runs `gh auth login`)" }, + { value: "stop", label: "Stop here" }, + ]); + if (answer === "login") { + await io.run("gh", ["auth", "login"]); + token = login(); + } + } + const me = token ? await who(token) : undefined; + if (!token || !me) { + io.say(token ? "GitHub didn't accept the gh login." : "No gh login, and loopway can't run without one.", "fail"); + return 1; + } + io.say(`gh is logged in as ${me.login}.`, "ok"); + + // 2. Claude Code, which runs the sessions. Setup carries on without it: it's only needed to run one. + const claude = exec("claude", ["--version"]); + if (claude === undefined) { + io.say( + "Claude Code isn't on your PATH. Sessions need it: install it from https://claude.com/claude-code. Carrying on.", + "warn", + ); + } else io.say(`Claude Code is installed (${claude}).`, "ok"); + + // 3. The bot user. Optional: without its token loopway watches and queues, but runs no sessions. + const config = await loadGitHubConfig(home); + let botDone = false; + if (config.token) { + const existing = await who(config.token); + if (existing) { + io.say(`The bot user is ${existing.login} (from ${join(home, "config.json")}).`, "ok"); + botDone = true; + } else io.say(`The token in ${join(home, "config.json")} isn't accepted by GitHub.`, "warn"); + } + let skipped = false; + while (!botDone && !skipped) { + const answer = await io.choose( + "A bot user acts on your issues so it isn't you commenting. It's a separate GitHub account with its own token.", + [ + { value: "add", label: "Add the bot's token" }, + { value: "skip", label: "Skip it: loopway will watch and queue, but run no sessions" }, + ], + ); + if (answer === "skip") { + skipped = true; + break; + } + const given = (await io.secret("The bot account's GitHub token (a personal access token with repo scope)")).trim(); + const bot = given ? await who(given) : undefined; + if (!bot) io.say("GitHub didn't accept that token.", "fail"); + else if (bot.login.toLowerCase() === me.login.toLowerCase()) + io.say( + `That token is your own account (${me.login}): the bot would comment as you. Use another account's.`, + "warn", + ); + else { + await saveGitHubConfig(home, { + token: given, + name: bot.login, + email: `${bot.id}+${bot.login}@users.noreply.github.com`, + }); + io.say(`Saved ${bot.login} as the bot user in ${join(home, "config.json")}.`, "ok"); + botDone = true; + } + } + if (skipped) io.say("Skipped the bot user: sessions are off until you add one (run `loopway setup` again).", "warn"); + + // 4. The bot files in .loopway/. Never overwrites one. + const folder = join(cwd, ".loopway"); + const missing: string[] = []; + for (const file of Object.keys(BOT_FILES)) { + const present = await readFile(join(folder, file), "utf8").then( + () => true, + () => false, + ); + if (present) io.say(`.loopway/${file} is already here: left as it is.`, "ok"); + else missing.push(file); + } + const wanted: string[] = []; + for (const file of missing) { + const answer = await io.choose(`Add .loopway/${file} here (${cwd})?`, [ + { value: "yes", label: "Yes" }, + { value: "no", label: "No, skip it" }, + ]); + if (answer === "yes") wanted.push(file); + else io.say(`Skipped .loopway/${file}.`, "warn"); + } + if (wanted.length > 0) { + const repos = await askRepos(io, repoFromRemote(exec("git", ["-C", cwd, "remote", "get-url", "origin"]))); + for (const repo of repos) { + const found = await get(token, `/repos/${repo}`); + if (!found?.ok) + io.say(`Couldn't see ${repo} as ${me.login}: check the name and your access. Using it anyway.`, "warn"); + } + await mkdir(folder, { recursive: true }); + for (const file of wanted) { + const make = BOT_FILES[file as keyof typeof BOT_FILES]; + try { + await writeFile(join(folder, file), make(repos), { flag: "wx" }); // wx: if it showed up meanwhile, keep it + io.say(`Wrote .loopway/${file} for ${repos.join(", ")}.`, "ok"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; + io.say(`.loopway/${file} appeared meanwhile: left as it is.`, "warn"); + } + } + } + + io.say("Done. Run `loopway` here, then create an issue on GitHub and assign it to yourself.", "ok"); + return 0; +} + +/** Asks for `owner/name`, comma separated, until every one is well formed. */ +async function askRepos(io: Io, guess: string | undefined): Promise { + for (;;) { + const answer = await io.text("Which repos should the bots watch? (owner/name, separated by commas)", guess); + const repos = answer + .split(",") + .map((r) => r.trim()) + .filter(Boolean); + if (repos.length > 0 && repos.every((r) => REPO.test(r))) return repos; + io.say(`"${answer}" isn't a list of owner/name.`, "fail"); + } +} diff --git a/packages/cli/test/setup-io.test.tsx b/packages/cli/test/setup-io.test.tsx new file mode 100644 index 00000000..3aa8e080 --- /dev/null +++ b/packages/cli/test/setup-io.test.tsx @@ -0,0 +1,44 @@ +import { render } from "ink-testing-library"; +import { setTimeout as sleep } from "node:timers/promises"; +import { stripVTControlCharacters as plain } from "node:util"; +import { describe, expect, it } from "vitest"; +import { Choose, Prompt } from "../src/setup-io.js"; + +const press = async (app: ReturnType, key: string) => { + app.stdin.write(key); + await sleep(20); +}; + +describe("the setup questions", () => { + it("Choose moves with the arrows and answers with Enter", async () => { + let answer = ""; + const app = render( + (answer = v)} + />, + ); + await sleep(20); + expect(plain(app.lastFrame() ?? "")).toContain("❯ Alpha"); + await press(app, "\u001B[B"); + await press(app, "\r"); + expect(answer).toBe("b"); + app.unmount(); + }); + + it("Prompt edits text, and shows a secret as dots", async () => { + let answer = ""; + const app = render( (answer = v)} />); + await sleep(20); + await press(app, "abc"); + expect(plain(app.lastFrame() ?? "")).toContain("•••"); + expect(plain(app.lastFrame() ?? "")).not.toContain("abc"); + await press(app, "\r"); + expect(answer).toBe("abc"); + app.unmount(); + }); +}); diff --git a/packages/cli/test/setup.test.ts b/packages/cli/test/setup.test.ts new file mode 100644 index 00000000..ff6161d6 --- /dev/null +++ b/packages/cli/test/setup.test.ts @@ -0,0 +1,172 @@ +import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { parseBot } from "../src/bots.js"; +import { repoFromRemote, runSetup, type Io, type SetupDeps } from "../src/setup.js"; + +/** A scripted terminal: answers come off a queue, and everything said and asked is kept. */ +function script(answers: string[]) { + const said: string[] = []; + const asked: string[] = []; + const ran: string[] = []; + const next = (question: string) => { + asked.push(question); + const answer = answers.shift(); + if (answer === undefined) throw new Error(`unexpected question: ${question}`); + return answer; + }; + const io: Io = { + say: (line, tone) => said.push(`${tone ?? "-"} ${line}`), + choose: async (question) => next(question) as never, + text: async (question) => next(question), + secret: async (question) => next(question), + run: async (command, args) => { + ran.push([command, ...args].join(" ")); + return 0; + }, + }; + return { io, said, asked, ran }; +} + +const users: Record = { + mytoken: { login: "me", id: 1 }, + bottoken: { login: "the-bot", id: 77 }, +}; +const repos = new Set(["o/r"]); + +/** GitHub: /user by token, and /repos/ for the repos in `repos`. */ +const fakeFetch = (async (url: string, init: { headers: Record }) => { + const token = init.headers.authorization!.replace("Bearer ", ""); + const path = url.replace("https://api.github.com", ""); + if (path === "/user") { + const user = users[token]; + return user ? Response.json(user) : new Response("{}", { status: 401 }); + } + return new Response("{}", { status: repos.has(path.replace("/repos/", "")) ? 200 : 404 }); +}) as unknown as typeof fetch; + +async function setup(more: Partial = {}, answers: string[] = []) { + const root = await mkdtemp(join(tmpdir(), "loopway-setup-")); + const home = join(root, "home"); + const cwd = join(root, "project"); + await mkdir(cwd, { recursive: true }); + const terminal = script(answers); + const deps: SetupDeps = { + io: terminal.io, + home, + cwd, + env: { GH_TOKEN: "mytoken" }, + fetch: fakeFetch, + exec: (command, args) => + command === "claude" ? "2.1.0 (Claude Code)" : command === "git" ? "git@github.com:o/r.git" : args[0] ? "ok" : "", + ...more, + }; + return { ...terminal, deps, home, cwd, run: () => runSetup(deps) }; +} + +/** gh is installed but has no login; nothing else is there. */ +const onlyGhVersion = (c: string, args: string[]) => (c === "gh" && args[0] === "--version" ? "gh version" : undefined); + +describe("loopway setup", () => { + it("walks a fresh machine: bot token, then both bot files for the guessed repo", async () => { + const t = await setup({}, ["add", "bottoken", "yes", "yes", "o/r"]); + expect(await t.run()).toBe(0); + expect(t.said.join("\n")).toMatch(/gh is logged in as me/); + expect(t.said.join("\n")).toMatch(/Claude Code is installed/); + const config = JSON.parse(await readFile(join(t.home, "config.json"), "utf8")); + expect(config.github).toEqual({ + token: "bottoken", + name: "the-bot", + email: "77+the-bot@users.noreply.github.com", + }); + expect((await stat(join(t.home, "config.json"))).mode & 0o777).toBe(0o600); + for (const [file, on] of [ + ["dev.md", "issue"], + ["review.md", "pull_request"], + ] as const) { + const bot = parseBot(file.slice(0, -3), await readFile(join(t.cwd, ".loopway", file), "utf8")); + expect(bot.repos).toEqual(["o/r"]); + expect(bot.on).toEqual([on]); + } + expect(t.said.join("\n")).not.toContain("bottoken"); // the token is never printed + }); + + it("asks nothing when everything is already set up, and changes nothing", async () => { + const t = await setup(); + await mkdir(join(t.home), { recursive: true }); + await writeFile(join(t.home, "config.json"), JSON.stringify({ auto_update: false, github: { token: "bottoken" } })); + await mkdir(join(t.cwd, ".loopway")); + await writeFile(join(t.cwd, ".loopway", "dev.md"), "mine"); + await writeFile(join(t.cwd, ".loopway", "review.md"), "mine too"); + expect(await t.run()).toBe(0); + expect(t.asked).toEqual([]); + expect(await readFile(join(t.cwd, ".loopway", "dev.md"), "utf8")).toBe("mine"); + expect(JSON.parse(await readFile(join(t.home, "config.json"), "utf8")).auto_update).toBe(false); + }); + + it("lets the bot user and each bot file be skipped", async () => { + // No claude and no git remote, so the repo is asked. + const t2 = await setup( + { env: { GH_TOKEN: "mytoken" }, exec: (c, a) => (c === "gh" && a[0] === "--version" ? "gh version" : undefined) }, + ["skip", "yes", "no", "o/r"], + ); + expect(await t2.run()).toBe(0); + expect(t2.said.join("\n")).toMatch(/warn Claude Code isn't on your PATH/); + expect(t2.said.join("\n")).toMatch(/sessions are off/); + await expect(stat(join(t2.home, "config.json"))).rejects.toThrow(); + await expect(readFile(join(t2.cwd, ".loopway", "dev.md"), "utf8")).resolves.toContain("repos: [o/r]"); + await expect(stat(join(t2.cwd, ".loopway", "review.md"))).rejects.toThrow(); + }); + + it("offers gh auth login when gh has no login, and stops when it is declined or still fails", async () => { + const t = await setup({ env: {}, exec: onlyGhVersion }, ["login"]); + expect(await t.run()).toBe(1); + expect(t.ran).toEqual(["gh auth login"]); + const declined = await setup({ env: {}, exec: onlyGhVersion }, ["stop"]); + expect(await declined.run()).toBe(1); + expect(declined.ran).toEqual([]); + }); + + it("stops when gh isn't installed", async () => { + const t = await setup({ exec: () => undefined }); + expect(await t.run()).toBe(1); + expect(t.said.join("\n")).toMatch(/fail gh isn't installed/); + }); + + it("refuses a bad token and your own account's, and asks again", async () => { + users.mytoken2 = { login: "me", id: 1 }; + const t = await setup({}, ["add", "nonsense", "add", "mytoken2", "skip", "no", "no"]); + expect(await t.run()).toBe(0); + const said = t.said.join("\n"); + expect(said).toMatch(/GitHub didn't accept that token/); + expect(said).toMatch(/your own account \(me\)/); + await expect(stat(join(t.home, "config.json"))).rejects.toThrow(); + }); + + it("replaces a bot token GitHub no longer accepts, and keeps the rest of config.json", async () => { + const t = await setup({}, ["add", "bottoken", "no", "no"]); + await mkdir(t.home, { recursive: true }); + await writeFile(join(t.home, "config.json"), JSON.stringify({ auto_update: false, github: { token: "stale" } })); + expect(await t.run()).toBe(0); + const config = JSON.parse(await readFile(join(t.home, "config.json"), "utf8")); + expect(config.auto_update).toBe(false); + expect(config.github.token).toBe("bottoken"); + }); + + it("asks again for a repo that isn't owner/name, and warns about one it can't see, but still writes", async () => { + const t = await setup({ exec: (c) => (c === "git" ? undefined : "ok") }, ["skip", "yes", "no", "nope", "a/b, c/d"]); + expect(await t.run()).toBe(0); + const said = t.said.join("\n"); + expect(said).toMatch(/"nope" isn't a list of owner\/name/); + expect(said).toMatch(/Couldn't see a\/b/); + expect(await readFile(join(t.cwd, ".loopway", "dev.md"), "utf8")).toContain("repos: [a/b, c/d]"); + }); + + it("reads owner/name from a GitHub remote", () => { + expect(repoFromRemote("git@github.com:craftmilldev/loopway.git")).toBe("craftmilldev/loopway"); + expect(repoFromRemote("https://github.com/craftmilldev/loopway")).toBe("craftmilldev/loopway"); + expect(repoFromRemote("https://example.com/a/b")).toBeUndefined(); + expect(repoFromRemote(undefined)).toBeUndefined(); + }); +}); From ff789b9a060c327dce64d6c90774cb2deb3ffd20 Mon Sep 17 00:00:00 2001 From: loopway-bot Date: Mon, 16 Nov 2026 10:47:15 -0500 Subject: [PATCH 2/2] Keep raw mode on through setup: one Ink app for all questions, so a token is never echoed Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/index.ts | 7 +- packages/cli/src/setup-io.tsx | 197 ++++++++++++++++------------ packages/cli/test/setup-io.test.tsx | 39 ++---- verifications/560.md | 38 ++++++ 4 files changed, 166 insertions(+), 115 deletions(-) create mode 100644 verifications/560.md diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e312ad44..8b7a88c4 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -102,7 +102,12 @@ async function main(): Promise { if (positionals[0] === "setup") { if (!process.stdout.isTTY || !process.stdin.isTTY) throw new Error("loopway setup asks questions: run it in a terminal."); - return runSetup({ io: inkIo(), home: loopwayHome(), cwd: project }); + const io = inkIo(); + try { + return await runSetup({ io, home: loopwayHome(), cwd: project }); + } finally { + await io.close(); + } } if (positionals[0] === "threads") return listThreads(stateDir(loopwayHome(), project), values.json); if (positionals.length > 0) throw new Error(`Unknown command "${positionals[0]}". Try loopway --help.`); diff --git a/packages/cli/src/setup-io.tsx b/packages/cli/src/setup-io.tsx index ec4cb343..2fe1f54b 100644 --- a/packages/cli/src/setup-io.tsx +++ b/packages/cli/src/setup-io.tsx @@ -1,54 +1,23 @@ -import { Box, render, Text, useInput } from "ink"; -import { useState } from "react"; +import { Box, render, Static, Text, useInput } from "ink"; +import { useEffect, useState } from "react"; import { runInherited, type Io } from "./setup.js"; -import { editInput, InputLine, type InputState } from "./tui-input.js"; +import { editInput, emptyInput, InputLine, type InputState } from "./tui-input.js"; import { theme } from "./tui-theme.js"; -/** Shows one question inline, waits for its answer, and leaves the answered line on screen. */ -function ask(element: (done: (value: T) => void) => React.ReactElement): Promise { - return new Promise((resolve) => { - const app = render( - element((value) => { - app.unmount(); - resolve(value); - }), - ); - }); -} +const MARKS = { ok: "✓", warn: "!", fail: "✗" } as const; -export function Choose({ - question, - options, - onDone, -}: { - question: string; - options: { value: string; label: string }[]; - onDone: (value: string) => void; -}) { - const [at, setAt] = useState(0); - const [answered, setAnswered] = useState(false); - useInput((_, key) => { - if (answered) return; - if (key.upArrow) setAt((i) => Math.max(0, i - 1)); - if (key.downArrow) setAt((i) => Math.min(options.length - 1, i + 1)); - if (key.return) { - setAnswered(true); - onDone(options[at]!.value); - } - }); - if (answered) { - return ( - - ? - {question} {options[at]!.label} - - ); - } +/** What is being asked: a choice from a list, or a line of text (dots, for a secret). */ +export type Question = + | { kind: "choose"; question: string; options: { value: string; label: string }[] } + | { kind: "text"; question: string; initial?: string; secret?: boolean }; + +/** The choices, as drawn: the one at `at` is marked. */ +export function Choose({ question, options, at }: { question: string; options: { label: string }[]; at: number }) { return ( ? {question} {options.map((o, i) => ( - + {i === at ? "❯ " : " "} {o.label} @@ -58,36 +27,9 @@ export function Choose({ ); } -export function Prompt({ - question, - initial = "", - secret, - onDone, -}: { - question: string; - initial?: string; - secret?: boolean; - onDone: (value: string) => void; -}) { - const [state, setState] = useState({ value: initial, cursor: initial.length }); - const [answered, setAnswered] = useState(false); - useInput((input, key) => { - if (answered) return; - if (key.return) { - setAnswered(true); - onDone(state.value); - } else setState((s) => editInput(s, input, key)); - }); - // A token shows as dots, same length, so the cursor and editing behave as with text. - const shown: InputState = secret ? { ...state, value: "•".repeat(state.value.length) } : state; - if (answered) { - return ( - - ? - {question} {secret ? "•".repeat(state.value.length) : state.value} - - ); - } +/** The line being typed, as drawn: a secret shows as dots of the same length, so editing behaves as with text. */ +export function Prompt({ question, input, secret }: { question: string; input: InputState; secret?: boolean }) { + const shown = secret ? { ...input, value: "•".repeat(input.value.length) } : input; return ( ? {question} @@ -99,17 +41,106 @@ export function Prompt({ ); } -const MARKS = { ok: "✓", warn: "!", fail: "✗" } as const; +/** What the screen shows: the lines said so far, and the question being asked, if any. */ +class Store { + lines: { id: number; text: string }[] = []; + question?: Question; + answer?: (value: string) => void; + private listeners = new Set<() => void>(); + subscribe(fn: () => void) { + this.listeners.add(fn); + return () => void this.listeners.delete(fn); + } + change(fn: () => void) { + fn(); + for (const l of this.listeners) l(); + } + /** A new array each time: `Static` only looks again when it gets a different one. */ + say(text: string) { + this.change(() => (this.lines = [...this.lines, { id: this.lines.length, text }])); + } +} -/** The real terminal for `loopway setup`: Ink for the questions, plain lines between them. */ -export function inkIo(): Io { +/** + * One app for the whole walk, with one `useInput` for the whole of it. Questions that came and went each with their + * own `useInput` dropped the terminal out of raw mode between them, and a token typed then was echoed as plain text. + */ +function Screen({ store }: { store: Store }) { + const [, tick] = useState(0); + const [at, setAt] = useState(0); + const [input, setInput] = useState(emptyInput); + useEffect(() => store.subscribe(() => tick((n) => n + 1)), [store]); + const q = store.question; + // A new question starts at its first choice, or its initial text. + useEffect(() => { + setAt(0); + const initial = q?.kind === "text" ? (q.initial ?? "") : ""; + setInput({ value: initial, cursor: initial.length }); + }, [q]); + useInput((typed, key) => { + if (!q || !store.answer) return; + if (q.kind === "choose") { + if (key.upArrow) setAt((i) => Math.max(0, i - 1)); + else if (key.downArrow) setAt((i) => Math.min(q.options.length - 1, i + 1)); + else if (key.return) store.answer(q.options[at]!.value); + } else if (key.return) store.answer(input.value); + else setInput((s) => editInput(s, typed, key)); + }); + return ( + <> + {(line) => {line.text}} + {q?.kind === "choose" && } + {q?.kind === "text" && } + + ); +} + +/** + * The real terminal for `loopway setup`: Ink for the questions, with the lines said above them. `close` ends it. + */ +export function inkIo(): Io & { close: () => Promise } { + let store = new Store(); + let app: ReturnType | undefined; + const open = () => (app ??= render()); + const ask = (question: Question) => { + open(); + return new Promise((resolve) => { + store.change(() => { + store.question = question; + store.answer = (value) => { + // The answered question stays on screen as a line. + store.say( + `? ${question.question} ${question.kind === "text" && question.secret ? "•".repeat(value.length) : value}`, + ); + store.change(() => { + store.question = undefined; + store.answer = undefined; + }); + resolve(value); + }; + }); + }); + }; + const close = async () => { + const current = app; + app = undefined; + current?.unmount(); + await current?.waitUntilExit(); + }; return { - say: (line, tone) => console.log(tone ? `${MARKS[tone]} ${line}` : line), - choose: (question: string, options: { value: T; label: string }[]) => - ask((onDone) => onDone(v as T)} />), - text: (question, initial) => - ask((onDone) => ), - secret: (question) => ask((onDone) => ), - run: runInherited, + say: (line, tone) => { + open(); + store.say(tone ? `${MARKS[tone]} ${line}` : line); + }, + choose: ((question, options) => ask({ kind: "choose", question, options })) as Io["choose"], + text: (question, initial) => ask({ kind: "text", question, initial }), + secret: (question) => ask({ kind: "text", question, secret: true }), + // gh auth login asks its own questions: give it the terminal, and start again after it, with a clean screen. + run: async (command, args) => { + await close(); + store = new Store(); + return runInherited(command, args); + }, + close, }; } diff --git a/packages/cli/test/setup-io.test.tsx b/packages/cli/test/setup-io.test.tsx index 3aa8e080..1acadc17 100644 --- a/packages/cli/test/setup-io.test.tsx +++ b/packages/cli/test/setup-io.test.tsx @@ -1,44 +1,21 @@ import { render } from "ink-testing-library"; -import { setTimeout as sleep } from "node:timers/promises"; import { stripVTControlCharacters as plain } from "node:util"; import { describe, expect, it } from "vitest"; import { Choose, Prompt } from "../src/setup-io.js"; -const press = async (app: ReturnType, key: string) => { - app.stdin.write(key); - await sleep(20); -}; - -describe("the setup questions", () => { - it("Choose moves with the arrows and answers with Enter", async () => { - let answer = ""; - const app = render( - (answer = v)} - />, - ); - await sleep(20); - expect(plain(app.lastFrame() ?? "")).toContain("❯ Alpha"); - await press(app, "\u001B[B"); - await press(app, "\r"); - expect(answer).toBe("b"); +describe("the setup questions as drawn", () => { + it("Choose marks the option at the cursor", () => { + const app = render(); + const screen = plain(app.lastFrame() ?? ""); + expect(screen).toContain(" Alpha"); + expect(screen).toContain("❯ Beta"); app.unmount(); }); - it("Prompt edits text, and shows a secret as dots", async () => { - let answer = ""; - const app = render( (answer = v)} />); - await sleep(20); - await press(app, "abc"); + it("Prompt shows a secret as dots", () => { + const app = render(); expect(plain(app.lastFrame() ?? "")).toContain("•••"); expect(plain(app.lastFrame() ?? "")).not.toContain("abc"); - await press(app, "\r"); - expect(answer).toBe("abc"); app.unmount(); }); }); diff --git a/verifications/560.md b/verifications/560.md new file mode 100644 index 00000000..598138f2 --- /dev/null +++ b/verifications/560.md @@ -0,0 +1,38 @@ +# Verification for PR 560: Add `loopway setup` + +Run 2026-11-16 on macOS, with the CLI built from branch `issue-556-loopway-setup` (`packages/cli/dist/index.js`, version 2.1.0), the real `claude` (2.1.325), and `gh` logged in as `loopway-bot` through `GH_TOKEN`. Issue #556 has no "How to test it" steps, so I ran the command the way a person would: in a real pseudo-terminal, typing the keys, in a fresh temp directory (a git repo whose `origin` is `craftmilldev/loopway-sandbox`) with `LOOPWAY_HOME` pointing at an empty temp folder. `setup` only reads from GitHub (`/user`, `/repos/`), so nothing was opened or written in the sandbox repo or anywhere else on GitHub. + +**Bottom line:** the fresh-machine walk ran live: gh and Claude Code were checked, the bot-token step refused a token that is the gh login's own account, the bot step could be skipped, both bot files were offered, the repo was guessed from `origin` and accepted, and `.loopway/dev.md` and `review.md` were written. A second run left both files alone. Not run live: logging in with `gh auth login`, saving a valid token from a different account, and a machine with no `gh` or no `claude` (all three are covered by the automated tests only). The live run found a real bug that the tests could not: see below. + +## Automated + +| Check | Result | +| --- | --- | +| `npm run build` | passes | +| `npm test` | cli 265 passed (17 files), web 41 passed (3 files) | +| `npm run typecheck` | passes | +| `npm run lint` | passes | +| `npm run format:check` | passes | + +`test/setup.test.ts` scripts the terminal and fakes `exec` and `fetch`: a fresh machine end to end (token saved 0600 with the name and noreply email, both files parse with `parseBot`, the token never appears in output); an already-set-up machine (asks nothing, changes nothing); skipping the bot user and a bot file; `gh auth login` offered, declined and still failing; `gh` missing; a bad token and your own account's token refused; a stale saved token replaced with the rest of `config.json` kept; a repo that isn't `owner/name` asked again and one `gh` can't see warned about; remote URL parsing. `test/setup-io.test.tsx` covers how the two question views draw. + +## Live, in a pseudo-terminal + +- Header and checks: `✓ gh is logged in as loopway-bot.` and `✓ Claude Code is installed (2.1.325 (Claude Code)).` +- Bot user, add: I typed the real bot token (the one from `~/.loopway/config.json`). It showed as 40 dots and was never echoed, and the screen said: + `! That token is your own account (loopway-bot): the bot would comment as you. Use another account's.` + Because `gh` here is logged in as the bot, this is the closest live case; a different account's token was not available, so saving one was not run live. It then asked again; I chose skip: `! Skipped the bot user: sessions are off until you add one`. Nothing was written to the temp `config.json`. +- Bot files: `Add .loopway/dev.md here (…)?` yes, `Add .loopway/review.md here (…)?` yes, `Which repos should the bots watch?` came up with `craftmilldev/loopway-sandbox` (guessed from `origin`), Enter accepted it, and `✓ Wrote .loopway/dev.md for craftmilldev/loopway-sandbox.` Both files exist, `review.md` has `repos: [craftmilldev/loopway-sandbox]` and `on: pull_request`. +- Second run in the same directory: `✓ .loopway/dev.md is already here: left as it is.`, and no question about the files. +- Not a terminal (`loopway setup < /dev/null`): `loopway setup asks questions: run it in a terminal.`, exit 1. + +### A bug the live run found, and fixed + +The first live runs echoed the token as plain text while it was being typed, and ignored Enter and arrow keys at times (the arrow showed as `^[[B`). Every question had been its own Ink app, and starting the next one raced the last one's cleanup, which left the terminal out of raw mode. The fix is one Ink app for the whole walk with a single input handler (`packages/cli/src/setup-io.tsx`). I reran the flow above on the fixed code: no echo (a grep of the transcript for the token found nothing) and every key was taken. + +## What I did not check, and what else happened + +- Not run live: `gh auth login` from inside setup, a machine where `gh` or `claude` is missing, and saving a token for a different account (covered by the automated tests only). +- The earlier, buggy runs printed the bot's token (the `loopway-bot` token already in `~/.loopway/config.json`) in my own terminal output before the fix. It should be treated as exposed to this session's logs; rotate it if that matters. +- Other loopways: none touched; setup makes no sandbox issues or PRs, so there was nothing to close. +- Cleanup: the temp directories and driver script were removed; the one transcript kept (with the token redacted) was removed too.