diff --git a/layers/nuxi/README.md b/layers/nuxi/README.md index 38c22d4da..e9253734b 100644 --- a/layers/nuxi/README.md +++ b/layers/nuxi/README.md @@ -84,48 +84,73 @@ Dispatch is restricted to channels listed under `discord.channels.admin`, `.publ ## Pull requests from Slack and Discord -When someone on Slack or in an admin Discord channel gives Nuxi a coding task on nuxt.com, such as a fix, a feature, a content change or a question about the code, Nuxi hands it to the `coder` subagent (`agent/subagents/coder/`). `coder` is a coding agent on Claude Opus 5.5 that delivers its changes as pull requests. It mounts [`@github-tools/eve-extension`](https://github-tools.com/integrations/eve) with the `pr-author` preset, trimmed to what opening a pull request needs. It makes the change on a new `nuxi/*` branch of `nuxt/nuxt.com` with `editFiles`, opens a pull request when it's done, and replies with the link. It never merges. +When someone on Slack or in an admin Discord channel gives Nuxi a coding task on nuxt.com, such as a fix, a feature, a content change or a question about the code, Nuxi hands it to the `coder` subagent (`agent/subagents/coder/`). `coder` is a coding agent on Claude Opus 5.5 that delivers its changes as pull requests. It mounts [`@github-tools/eve-extension`](https://github-tools.com/integrations/eve) with the `pr-author` preset, trimmed to what opening a pull request needs. It clones the repository into its own sandbox, changes and runs the code there, commits the result to a new `nuxi/*` branch, opens a pull request when it's done, and replies with the link. Asked to work on a pull request that is already open, such as a dependency update that conflicts with its base branch, it commits to that pull request's branch instead. It never merges. - **Who:** `coder`'s `agent.ts` returns `null` outside Slack, `discord.channels.admin` channels, and `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, so the web chat, public Discord channels and schedules never see it or its tools. `githubToolsApproval` in `agent/lib/github.ts`, the root agent's `approval` policy, also covers subagents and denies every `github__*` call anywhere else. -- **Where:** `GITHUB_REPOSITORIES` in `agent/lib/github.ts` lists the repositories `coder` works on, which is `nuxt/nuxt.com` for now. `guardrails` refuse any call outside that list and any write outside `nuxi/*` branches. See [Work on another repository](#work-on-another-repository). -- **Approval:** creating the branch, committing and opening the pull request run without asking; a person reviews and merges on GitHub. `updatePullRequest` still asks the person who requested it, with **Approve** and **Deny** buttons in the thread. So does a commit to a branch that already has an open pull request (`githubToolsApproval` in `agent/lib/github.ts`): `coder` can't add to a pull request from another task, or to its own on a follow-up, without a click. The same policy denies a commit that names no branch, or a repository outside the list. It compares repository names without their case, as GitHub does. On Discord, the buttons need the Interactions Endpoint URL from the [Discord setup](#discord-channel). -- **Tools:** `coder` changes code through the GitHub API only. Its sandbox holds a browser and no checkout, see [Browser and captures](#browser-and-captures). `coder/tools/` disables `edit_file` and `write_file`, and keeps `bash` and `read_file` to work on files in the sandbox, such as a capture or a logo. It keeps `web_search` and `web_fetch` to read docs, issues and pages linked in the request. `web_fetch` stays off on the root agent, which serves public chats. +- **Where:** `GITHUB_REPOSITORIES` in `agent/lib/github.ts` lists the repositories `coder` writes to, which is `nuxt/nuxt.com` for now. Every tool that writes reads that list, and the GitHub tools' `guardrails` refuse any call outside it. See [Open Nuxi to more repositories](#open-nuxi-to-more-repositories). +- **Approval:** committing to a new `nuxi/*` branch and opening the pull request run without asking; a person reviews and merges on GitHub. A commit to a branch that already has an open pull request asks the person who requested it, with **Approve** and **Deny** buttons in the thread (`githubToolsApproval` in `agent/lib/github.ts`): `coder` adds nothing to a pull request, its own or someone else's, without a click. So does `updatePullRequest`. The same policy denies a commit that names no branch, or a repository outside the list. It compares repository names without their case, as GitHub does. On Discord, the buttons need the Interactions Endpoint URL from the [Discord setup](#discord-channel). +- **Tools:** `coder` has its own sandbox with a browser, see [Browser and captures](#browser-and-captures), and with what it takes to clone a repository and run it, see [Clone and run the project](#clone-and-run-the-project). It uses eve's `bash`, `read_file`, `edit_file` and `write_file` there. The sandbox holds no credentials, so every write to GitHub goes through a tool that runs in the app, and files reach GitHub through one tool, [`commit_changes`](#clone-and-run-the-project). It keeps `web_search` and `web_fetch` to read docs, issues and pages linked in the request. `web_fetch` stays off on the root agent, which serves public chats. -On Slack, Nuxi first moves the request into a [code channel](https://docs.slack.dev/ai/slack-code) with `tools/open_code_channel.ts`, offered to the same people as `coder`. The channel starts with the thread so far and invites the person who asked. Every message in it reaches Nuxi without a mention, the whole channel is one session, and anyone in it can stop the agent from Slack. This needs **Code Channels** turned on in the `slack/nuxi` and `slack/nuxi-preview` connector settings, which adds the `code_channels:manage` scope and the `message.session` and `agent_session_stopped` events, plus the `groups:read` and `mpim:read` bot scopes. Discord has no equivalent and keeps using threads. +On Slack, `coder` works from the thread or direct message the request arrives in. Nuxi moves the request into a [code channel](https://docs.slack.dev/ai/slack-code) with `tools/open_code_channel.ts`, offered to the same people as `coder`, only when the person asks for one, or for a task that will clearly take many rounds, such as a feature across many files. The channel starts with the thread so far and invites the person who asked. Every message in it reaches Nuxi without a mention, the whole channel is one session, and anyone in it can stop the agent from Slack. This needs **Code Channels** turned on in the `slack/nuxi` and `slack/nuxi-preview` connector settings, which adds the `code_channels:manage` scope and the `message.session` and `agent_session_stopped` events, plus the `groups:read` and `mpim:read` bot scopes. Discord has no equivalent and keeps using threads. -Auth uses the `nuxi-code` GitHub App on the `nuxt` org through the Vercel Connect connector `github/nuxi-code`, connected to every environment of the project. `coder` runs with `actAs: 'caller'`: every call uses the GitHub token of the person who asked, so the branch, commits and pull request are theirs, and GitHub enforces their own access to `nuxt/nuxt.com`. The extension's `attribution` still credits the App: the pull request body ends with "Generated by nuxi-code", and the commits list the App's bot as co-author. The first time someone asks, Nuxi replies with a sign-in button to authorize the App on their GitHub account; the task continues once they have. A person never falls back to the App's own token. Only `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, which has no GitHub user, runs as the App, so local tests act with the App's permissions. `searchCode` is excluded because its free-text query can name another repository, which the `repositories` guardrail can't check. The App needs **Contents** and **Pull requests** (read and write) and **Metadata** (read). +Auth uses the `nuxi-code` GitHub App on the `nuxt` org through the Vercel Connect connector `github/nuxi-code`, connected to every environment of the project. `coder` runs with `actAs: 'caller'`: every call uses the GitHub token of the person who asked, so the branch, commits and pull request are theirs, and GitHub enforces their own access to `nuxt/nuxt.com`. The extension's `attribution` still credits the App: the pull request body ends with "Generated by nuxi-code". The first time someone asks, Nuxi replies with a sign-in button to authorize the App on their GitHub account; the task continues once they have. A person never falls back to the App's own token. Only `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, which has no GitHub user, runs as the App, so local tests act with the App's permissions. `searchCode` is excluded because its free-text query can name another repository, which the `repositories` guardrail can't check. The App needs **Contents** and **Pull requests** (read and write) and **Metadata** (read). ### Browser and captures `coder` has its own sandbox (`coder/sandbox.ts`) with Chromium, [agent-browser](https://agent-browser.dev) and ffmpeg. It uses the sandbox to look at pages, and to produce the images a task needs instead of leaving them to a person. For example, a showcase pull request arrives with its screenshot and logo. A task that only asks for a capture, such as a clip of a page for a Slack reply, opens no pull request. -- **Browser:** `coder/extensions/browser/` mounts [`@agent-browser/eve`](https://www.npmjs.com/package/@agent-browser/eve) as `browser__*`, which opens and operates any public page. The sandbox holds no credentials and no checkout, so `coder` can't run the site or capture its own branch. On Vercel, the sandbox's firewall refuses every connection to a private address (`networkPolicy` in `coder/sandbox.ts`). A local Docker sandbox has no such rule: there, the capture tools only refuse a URL that names a private address. The capture tools drive the same browser, so their calls run one at a time, even when the model asks for several together. +- **Browser:** `coder/extensions/browser/` mounts [`@agent-browser/eve`](https://www.npmjs.com/package/@agent-browser/eve) as `browser__*`, which opens and operates any public page. It also opens `http://localhost:`, the sandbox itself, which is how `coder` captures an app it runs from a clone. The sandbox holds no credentials. On Vercel, the sandbox's firewall refuses every connection to a private address (`networkPolicy` in `coder/sandbox.ts`). A local Docker sandbox has no such rule: there, the capture tools only refuse a URL that names a private address other than the sandbox's own loopback. The capture tools drive the same browser, so their calls run one at a time, even when the model asks for several together. - **`capture_screenshot`:** saves a 2560×1440 WebP, the format of `public/assets/websites/`, and shows the frame to the model. Its `cookies`, `hideElements`, `removeElements`, `scripts` and `delay` options match `screenshotOptions` in `content/showcase.yml`. - **`record_video`:** plays a list of steps with a visible cursor, saves an MP4 without sound, and shows six frames spread over the clip to the model. GitHub plays a video inline only from its own attachments, which is where `publish_media` uploads it. - **`publish_media`:** uploads a capture to GitHub as an attachment of the repository, the upload behind [`gh --attach`](https://docs.github.com/en/github-cli/github-cli/attaching-files-with-github-cli), and returns its link and its Markdown once GitHub serves it. This is how a capture reaches a pull request body, and nothing is written to the repository. An image embeds as `![alt](url)`, and the URL of a clip alone on a line renders as a video player. GitHub serves the link to everyone only once a pull request, an issue or a comment of a public repository embeds it, so the link of a capture that no pull request embeds, such as one made for a Slack reply, can answer 404. GitHub has no way to delete an attachment. -- **`commit_assets`:** commits images to a `nuxi/*` branch, because `editFiles` writes text only. It accepts images of 4 MB at most whose bytes match their extension, which covers a blog cover at 2400x1260. The showcase skill holds its screenshots under 1 MB with a lower `capture_screenshot` `quality`. It uses the same GitHub token as the GitHub tools. Unlike `editFiles`, its commits don't list the App's bot as co-author. Every one of these tools calls `assertCanUseGithubTools`, so they are available to the same people as the GitHub tools. Two skills in `coder/skills/` hold the procedures: `showcase-entry` for a complete showcase entry, and `visual-evidence` for the captures of a pull request. Setup: - **Deploys:** `eve build` installs the browser into a sandbox snapshot once per build, which takes about a minute. Sessions start from that snapshot. -- **Files from the conversation:** eve saves a file attached to a Slack message in the sandbox of the root session, under `/workspace/.eve/attachments/`. `coder` has its own sandbox and receives only the text of its task, so the file crosses in two steps. The root agent calls `share_attachments` (`agent/tools/`, offered to the same people as `coder`) with the attachment paths, which copies the files to a store under the session's id. `coder` then calls `receive_attachments`, which reads the store under the id of its parent session and writes the files to `/workspace/shared/`, each under the directory name eve gave it, where `bash`, `read_file` and `commit_assets` reach them. The model never names a session, so a `coder` only gets the files of the conversation that started it. Up to 5 files of 10 MB per call, kept for an hour. The store (`agent/lib/handoff.ts`) is the Redis of `REDIS_URL`, the one the Discord channel uses, under `nuxi:handoff:*`. Without `REDIS_URL` it is a local temp directory, which only works on one machine: on Vercel the tool fails and names the variable, so set `REDIS_URL` on every environment that should pass files, previews included. +- **Files from the conversation:** eve saves a file attached to a Slack message in the sandbox of the root session, under `/workspace/.eve/attachments/`. `coder` has its own sandbox and receives only the text of its task, so the file crosses in two steps. The root agent calls `share_attachments` (`agent/tools/`, offered to the same people as `coder`) with the attachment paths, which copies the files to a store under the session's id. `coder` then calls `receive_attachments`, which reads the store under the id of its parent session and writes the files to `/workspace/shared/`, each under the directory name eve gave it, where `bash` and `read_file` reach them. The model never names a session, so a `coder` only gets the files of the conversation that started it. Up to 5 files of 10 MB per call, kept for an hour. The store (`agent/lib/handoff.ts`) is the Redis of `REDIS_URL`, the one the Discord channel uses, under `nuxi:handoff:*`. Without `REDIS_URL` it is a local temp directory, which only works on one machine: on Vercel the tool fails and names the variable, so set `REDIS_URL` on every environment that should pass files, previews included. - **Local:** the browser needs Docker running before `pnpm nuxi`. The first browser call builds the sandbox image, which takes about two minutes. Without Docker, eve falls back to just-bash, which runs no native binaries, so the browser and capture tools fail. On Apple Silicon, the Docker sandbox gets no browser, because Chrome for Testing has no Linux arm64 build. - **Attachment token:** `publish_media` needs `NUXI_GITHUB_ATTACHMENTS_PAT` on the eve service, a GitHub personal access token. GitHub accepts the attachment upload from a personal access token only: it answers 404 to the `nuxi-code` installation token and to the token of a person signed in through the App ([cli/cli#14309](https://github.com/cli/cli/issues/14309)). So this tool never uses the token of the person who asked, and every attachment belongs to the token's account. That account needs write access to each repository in `GITHUB_REPOSITORIES`, and a classic token needs the `repo` scope. Use a token of a bot account instead of a person's. Without the variable, the tool reports that it has no token, and the other tools still work. -- **Local GitHub access:** the GitHub tools and `commit_assets` need a linked Vercel project (`vercel link`), because Vercel Connect authenticates with the project's OIDC token. Without it, they fail with `VercelOidcTokenError`. +- **Local GitHub access:** the GitHub tools and `commit_changes` need a linked Vercel project (`vercel link`), because Vercel Connect authenticates with the project's OIDC token. Without it, they fail with `VercelOidcTokenError`. - **Local publishing:** set `NUXI_GITHUB_ATTACHMENTS_PAT` in `.env`. It needs no Vercel project. - **`--no-default-extensions`:** the `dev` script passes this flag to turn off eve's bundled self-modification subagent. That subagent uses a just-bash sandbox, and eve prepares every sandbox when `coder` first opens its own. Preparing it runs `pnpm add just-bash` in `layers/nuxi`, which fails on the ignored build scripts and leaves a stray lockfile. -### Work on another repository +### Clone and run the project -Nothing in `coder`'s tools is specific to `nuxt/nuxt.com`. To let it work on another repository: +`coder` works on a clone of the repository, in its sandbox, so it can search the code, run the project's checks, start its dev server and capture the pages it changed. Nothing here is specific to one project: the sandbox holds the tools, and the `run-project` skill tells `coder` to read how each project installs and runs. -1. Add the repository to `GITHUB_REPOSITORIES` in `agent/lib/github.ts`. The first entry stays the default. -2. Give the `nuxi-code` GitHub App access to the repository, and give the account of `NUXI_GITHUB_ATTACHMENTS_PAT` write access to it. -3. Add a section for it to `coder/instructions.md`, like the `nuxt/nuxt.com` one. Say where its site is deployed, where its images live, and how its pull requests preview. +- **Clone:** `coder` runs `git clone` itself, with `bash`, into `/workspace/repos//`. The sandbox holds no GitHub credentials, so a public repository clones and a private one doesn't, and `git push` reaches nothing. Any public repository clones, so `coder` can run a template or a reproduction linked in an issue. Commits stay limited to `GITHUB_REPOSITORIES`. +- **`code` extension:** `coder/extensions/code.ts` mounts eve's [`code` extension](https://eve.dev/docs/code-extension). It adds eve's instructions for `bash`, `read_file`, `edit_file` and `write_file`, the `code__investigate` and `code__review` skills, and it tells `coder` to read the `AGENTS.md` or `CLAUDE.md` nearest to the files it works on. +- **`commit_changes`:** the only way a file reaches GitHub. It commits what `coder` staged with `git add`, in one commit: added, modified and deleted files, text or binary, so an image is committed like any other file. It reads the staged files out of the sandbox (`agent/lib/clone.ts`) and commits them from the app (`agent/lib/github-files.ts`) with the same token as the GitHub tools, so the person who asked is the author. One commit holds 200 files and 10 MB at most, of regular files: an executable file or a symbolic link is refused, because GitHub would write it as a regular one. +- **Which branch:** a `nuxi/*` branch, or the head branch of an open pull request, and never the default branch. A new branch starts at the commit the clone is at. An existing branch must point to it: the commit sends whole files, so on any other commit it would undo what that commit holds. The clone then moves to that branch at the new commit, so the next call commits only what is staged since. +- **Merge commits:** to resolve the conflict of a pull request, `coder` merges the base branch into the pull request's branch in the clone, resolves and stages, and `commit_changes` makes a commit with both parents. It sends only the files `coder` resolved or changed: the rest already exist on GitHub. +- **Signatures:** a commit with one parent goes through GitHub's `createCommitOnBranch`, which signs it. That mutation can't make a merge commit, so a merge is built with the REST git API and is not signed. A branch rule that requires signed commits refuses it. +- **Why the commit is not made in the sandbox:** eve's git extension has a script for this, `gh-signed-commit`, which runs in the sandbox with a placeholder that the sandbox's firewall replaces with the token. While it runs, any other process of the sandbox can read the placeholder and call GitHub as the person who asked. The sandbox runs code nobody here reviewed, such as an install script or a reproduction from an issue, so the token stays in the app. +- **Running:** the sandbox template (`coder/sandbox.ts`) adds `build-essential`, Corepack and Bun to eve's image, which has Node.js and npm. Corepack's `pnpm` and `yarn` run the version a project pins in `packageManager`. `coder` starts a dev server with `bash`, which leaves a command that outlives its wait running in the background, and opens it at `http://localhost:`. The sandbox has 4 vCPUs and 8 GB. +- **What it can't run:** a project that needs a secret or a service to start. The sandbox holds none, and `coder` is told to say which page or check it could not run. +- **Lifetime:** processes end when eve stops the idle sandbox, five minutes after `coder` replies. Files stay, so a follow-up finds the clone and its `node_modules`, and starts the server again. -`commit_assets` and `publish_media` take the repository as an input, and the `github__*` tools take `owner` and `repo`. +### Open Nuxi to more repositories + +Nothing in `coder` is built for `nuxt/nuxt.com`. Its tools take the repository as an input, its sandbox runs whatever a project asks for, and what it knows about a project comes from the project's own `AGENTS.md` and README. One list decides where it may write: `GITHUB_REPOSITORIES` in `agent/lib/github.ts`. + +- **The list:** an entry is `owner/name`, or `owner/*` for every repository of an account. The first entry is the default of every tool. The GitHub tools' `guardrails`, `commit_changes`, `publish_media` and the approval policy all read it, so a repository outside it is refused before any call reaches GitHub. +- **Whose access:** every write runs with the GitHub token of the person who asked (`actAs: 'caller'`), issued through the `nuxi-code` App. GitHub accepts such a token only where the App is installed and the person has access, with the role the person has there. A wider list therefore gives nobody more than GitHub already gives them: a maintainer does what a maintainer can, and a reader only reads. +- **Never the default branch:** whatever the repository, `commit_changes` writes to a `nuxi/*` branch or to the branch of an open pull request. A change reaches the default branch through a pull request a person merges. + +To add repositories of the Nuxt org: + +1. Add `nuxt/`, or `nuxt/*`, to `GITHUB_REPOSITORIES`. +2. Give the `nuxi-code` App access to them, and give the account of `NUXI_GITHUB_ATTACHMENTS_PAT` write access to them. +3. Put how each one installs and runs in its own `AGENTS.md` or README. Add a section to `coder/instructions.md` only for what those can't hold, like the notes on `nuxt/nuxt.com`. + +Letting people use Nuxi on repositories outside the org, where they installed the App themselves, needs more than a wider list. None of it is built: + +- **Private repositories:** `coder` clones without credentials. A private repository needs a token for the clone. eve's `executeGitHubShell` (`eve/extensions/git/sandbox`) lends one to a single command through the sandbox's firewall. Code in the sandbox can use a lent token while the command runs, so lend a token of the App limited to reading that one repository, not the person's own. +- **Attachments:** `publish_media` uploads with one personal access token, and GitHub refuses App tokens for that upload. That account has no access to someone else's repository, so captures there can't be published this way. +- **Who can ask:** `canUseGithubTools` offers `coder` to the Nuxt team on Slack and in admin Discord channels only. Another audience needs its own rule there, and its own limits on sandbox time. +- **The list itself:** it has no entry for "any repository". With the two points above solved, the check can become "wherever GitHub accepts the person's token", in `allowedRepository`. ## Caller identity diff --git a/layers/nuxi/agent/channels/slack.ts b/layers/nuxi/agent/channels/slack.ts index 7057adbb4..a81b87d1b 100644 --- a/layers/nuxi/agent/channels/slack.ts +++ b/layers/nuxi/agent/channels/slack.ts @@ -56,7 +56,7 @@ export default slackChannel({ credentials: connectSlackCredentials(slackConnectorId()), botName: 'Nuxi', // A code channel is one session for one task, and every message in it reaches Nuxi without a - // mention. `tools/open_code_channel.ts` moves coding requests into one. + // mention. `tools/open_code_channel.ts` opens one when the person asks, or for a task too long for a thread. codeChannels: true, threadContext: { since: 'last-agent-reply' }, onAppMention: dispatchSlackMessage, diff --git a/layers/nuxi/agent/lib/clone.ts b/layers/nuxi/agent/lib/clone.ts new file mode 100644 index 000000000..0b038f903 --- /dev/null +++ b/layers/nuxi/agent/lib/clone.ts @@ -0,0 +1,150 @@ +import { quoteShellArg as quote } from '@agent-browser/eve/sandbox' + +/** + * A clone the coder made in its sandbox with `git clone`, to read, change and run a repository. + * The sandbox holds no GitHub credentials, so a change leaves it through the GitHub API, from the + * app runtime: + * + * the coder edits the files and stages the change with `git add` + * readStagedChanges -> what is staged, as bytes, and the commits it applies to + * commitChanges -> one commit on a branch (`github-files.ts`) + * followCommit -> the clone is on that branch at that commit, so nothing is staged any more + */ + +export const MAX_CHANGED_FILES = 200 +export const MAX_CHANGE_BYTES = 10 * 1024 * 1024 + +/** Inside `.git`, so git never lists it. */ +const STAGED_DIR = '.git/nuxi-staged' +/** Files read at a time, so a commit of many files doesn't open them all at once. */ +const READ_BATCH = 16 +const IRREGULAR_MODES: Record = { 100755: 'an executable file', 120000: 'a symbolic link', 160000: 'a submodule' } + +/** The sandbox methods a clone needs; eve's `SandboxSession` satisfies it. */ +export interface CloneSandbox { + run(options: { command: string, workingDirectory?: string, signal?: AbortSignal }): PromiseLike<{ exitCode: number, stdout: string, stderr: string }> + readBinaryFile(options: { path: string }): PromiseLike +} + +interface Clone { + readonly sandbox: CloneSandbox + /** The root of the clone, such as `/workspace/repos/nuxt/nuxt.com`. */ + readonly directory: string + readonly signal?: AbortSignal +} + +function shellIn({ sandbox, directory, signal }: Clone) { + return async (command: string): Promise => { + const result = await sandbox.run({ command, workingDirectory: directory, signal }) + if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout).trim().slice(-600) || `\`${command.split(' ', 2).join(' ')}\` exited ${result.exitCode}`) + return result.stdout + } +} + +/** Runs `git` in the clone, each argument quoted. */ +function gitIn(clone: Clone) { + const run = shellIn(clone) + return (...args: string[]) => run(`git ${args.map(quote).join(' ')}`) +} + +/** What a commit holds. Every `path` is a repository path, as git names it. */ +export interface Changes { + /** The commit the clone is at, then the commit being merged into it, if a merge is in progress. */ + readonly parents: readonly [base: string, merged?: string] + /** The staged files to send. */ + readonly files: ReadonlyArray<{ readonly path: string, readonly bytes: Uint8Array }> + /** In a merge, the staged files that are the merged commit's own. GitHub has them, so their id is enough. */ + readonly inherited: ReadonlyArray<{ readonly path: string, readonly mode: string, readonly id: string }> + readonly deletions: readonly string[] +} + +/** What is staged and differs from `commit`, from `git diff --raw -z`: `: `, NUL, the path, NUL. */ +async function stagedAgainst(git: ReturnType, commit: string) { + const fields = (await git('diff', '--cached', '--raw', '-z', '--no-renames', '--no-abbrev', commit)).split('\0') + const entries: Array<{ path: string, mode: string, id: string, status: string }> = [] + for (let index = 0; index + 1 < fields.length; index += 2) { + const [, mode = '', , id = '', status = ''] = fields[index]!.split(' ') + entries.push({ path: fields[index + 1]!, mode, id, status }) + } + return entries +} + +/** + * What `git add` staged in the clone of `repository`: added, modified and deleted files. Each file + * is read as git staged it: the bytes `git diff --cached` shows, whatever a process still writing + * does to the file in the working tree. + */ +export async function readStagedChanges({ repository, ...clone }: Clone & { readonly repository: string }): Promise { + const git = gitIn(clone) + const run = shellIn(clone) + + const [root = '', base = ''] = (await git('rev-parse', '--show-toplevel', 'HEAD').catch(() => '')).trim().split('\n') + if (!base || root !== clone.directory.replace(/\/+$/, '')) throw new Error(`${clone.directory} is not the root of a clone. Pass the directory you gave \`git clone\`.`) + // The staged files are whole files of this repository: on another one they would be someone else's code. + const origin = (await git('config', '--get', 'remote.origin.url').catch(() => '')).trim() + if (origin.replace(/\.git$/, '').toLowerCase() !== `https://github.com/${repository}`.toLowerCase()) { + throw new Error(`${clone.directory} is a clone of ${origin || 'no remote'}, not of ${repository}.`) + } + + const merged = (await git('rev-parse', '--verify', '--quiet', 'MERGE_HEAD').catch(() => '')).trim() + const entries = await stagedAgainst(git, 'HEAD') + if (!entries.length) throw new Error(`Nothing is staged in ${clone.directory}. Stage the files of the change with \`git add\`, then call this again. If you committed them with \`git commit\`, undo that commit with \`git reset --soft HEAD~1\` first: it never reaches GitHub.`) + const unmerged = entries.find(entry => entry.status === 'U') + if (unmerged) throw new Error(`"${unmerged.path}" still has a merge conflict. Resolve it, stage the file with \`git add\`, then call this again.`) + + // In a merge, most of what is staged came from the merged commit as it is. Only what differs from + // that commit too is the coder's own: a resolved conflict, or a change made on top of the merge. + const own = merged ? new Set((await stagedAgainst(git, merged)).map(entry => entry.path)) : undefined + const kept = entries.filter(entry => entry.status !== 'D') + const written = own ? kept.filter(entry => own.has(entry.path)) : kept + if (written.length > MAX_CHANGED_FILES) throw new Error(`${written.length} files are staged: a commit holds ${MAX_CHANGED_FILES} at most. Unstage what a build generated with \`git restore --staged\`, or commit in several calls.`) + + // GitHub writes every file sent to it as a regular one, so anything else would arrive changed. + const irregular = written.find(entry => entry.mode !== '100644') + if (irregular) { + const kind = IRREGULAR_MODES[irregular.mode] ?? `a file of mode ${irregular.mode}` + throw new Error(`"${irregular.path}" is ${kind}: this tool commits regular, non-executable files only. Unstage it with \`git restore --staged\` and say so in your reply.`) + } + + const files: Array<{ path: string, bytes: Uint8Array }> = [] + if (written.length) { + // Sizes from git, before any file is read into the app's memory. + const sizes = await run(`printf '%s\\n' ${written.map(entry => quote(entry.id)).join(' ')} | git cat-file --batch-check='%(objectsize)'`) + const total = sizes.trim().split('\n').reduce((sum, size) => sum + Number(size), 0) + if (total > MAX_CHANGE_BYTES) throw new Error(`The staged files weigh ${(total / 1024 / 1024).toFixed(1)} MB: a commit holds ${MAX_CHANGE_BYTES / 1024 / 1024} MB at most. Commit them in several calls.`) + + // A command's output is text, so each staged file goes through a file of its own to stay bytes. + await run(`rm -rf ${STAGED_DIR} && mkdir -p ${STAGED_DIR} && ${written.map(({ id }, index) => `git cat-file blob ${quote(id)} > ${STAGED_DIR}/${index}`).join(' && ')}`) + for (let start = 0; start < written.length; start += READ_BATCH) { + files.push(...await Promise.all(written.slice(start, start + READ_BATCH).map(async ({ path }, offset) => { + const bytes = await clone.sandbox.readBinaryFile({ path: `${root}/${STAGED_DIR}/${start + offset}` }) + if (!bytes) throw new Error(`"${path}" is staged, and could not be read from the clone.`) + return { path, bytes } + }))) + } + await run(`rm -rf ${STAGED_DIR}`) + } + + return { + parents: merged ? [base, merged] : [base], + files, + inherited: own ? kept.filter(entry => !own.has(entry.path)).map(({ path, mode, id }) => ({ path, mode, id })) : [], + deletions: entries.filter(entry => entry.status === 'D').map(entry => entry.path) + } +} + +/** + * Put the clone on `branch` at `commit`, just made there from what was staged. The files and the + * index stay as they are: what was committed now matches `HEAD`, so `git status` lists only what + * was left out, and the next commit holds only what is staged after this one. + */ +export async function followCommit({ branch, commit, ...clone }: Clone & { readonly branch: string, readonly commit: string }): Promise { + const git = gitIn(clone) + await git('fetch', '--quiet', 'origin', `refs/heads/${branch}`) + const fetched = (await git('rev-parse', 'FETCH_HEAD')).trim() + if (fetched !== commit) throw new Error(`\`${branch}\` is at ${fetched.slice(0, 8)}, not at the new commit ${commit.slice(0, 8)}.`) + await git('update-ref', `refs/heads/${branch}`, commit) + await git('symbolic-ref', 'HEAD', `refs/heads/${branch}`) + // A merge that was in progress is that commit now. + await git('merge', '--quit') +} diff --git a/layers/nuxi/agent/lib/github-files.ts b/layers/nuxi/agent/lib/github-files.ts index 0f326c89d..5d1c8971b 100644 --- a/layers/nuxi/agent/lib/github-files.ts +++ b/layers/nuxi/agent/lib/github-files.ts @@ -1,15 +1,10 @@ -import { checkedMediaType } from './media/media-type.js' +import type { Changes } from './clone.js' const API = 'https://api.github.com' -/** Same rule as the `branches` guardrail of the GitHub tools. */ -const BRANCH = /^nuxi\/[a-z0-9][a-z0-9._/-]*$/ -const FILE_PATH = /^[\w.-]+(?:\/[\w.-]+)*$/ - -/** - * A blog cover at 2400x1260 is a PNG of 0.5 to 2.5 MB, and most images of `public/assets/blog` over - * 1 MB are under this. Showcase screenshots are 80 to 350 KB: the skill that makes them holds them to that. - */ -export const MAX_COMMIT_BYTES = 4 * 1024 * 1024 +/** A branch the coder makes for a task. Same rule as the `branches` guardrail of the GitHub tools. */ +const NUXI_BRANCH = /^nuxi\/[a-z0-9][a-z0-9._/-]*$/ +/** Any branch this file puts in a URL. */ +const BRANCH = /^\w[\w./-]*$/ export class GithubRequestError extends Error { constructor(message: string, readonly status: number) { @@ -26,11 +21,11 @@ interface Github { readonly fetchImpl?: typeof fetch } -/** GET `url`, or POST `body` to it: bytes as they are, anything else as JSON. */ -export async function request({ token, fetchImpl = fetch }: Pick, url: string, body?: object): Promise { +/** GET `url`, or send `body` to it: bytes as they are, anything else as JSON. */ +export async function request({ token, fetchImpl = fetch }: Pick, url: string, body?: object, method = body ? 'POST' : 'GET'): Promise { const binary = body instanceof Uint8Array const response = await fetchImpl(url, { - method: body ? 'POST' : 'GET', + method, headers: { accept: 'application/vnd.github+json', authorization: `Bearer ${token}`, @@ -53,67 +48,128 @@ export async function openPullRequestOf({ branch, ...github }: Github & { readon return pulls[0]?.number } -interface CommitInput extends Github { - readonly branch: string - /** A conventional commit: the first line is the headline, the rest the body. */ - readonly message: string - /** `path` is the repository path, such as `public/assets/websites/world-triathlon.webp`. */ - readonly files: ReadonlyArray<{ readonly path: string, readonly bytes: Uint8Array }> +/** The commit `branch` points to, if the branch exists. */ +async function headOf(github: Github, branch: string): Promise { + try { + return (await request<{ object: { sha: string } }>(github, `${API}/repos/${github.repository}/git/ref/heads/${branch}`)).object.sha + } catch (error) { + if (error instanceof GithubRequestError && error.status === 404) return undefined + throw error + } } -const COMMIT_MUTATION = 'mutation ($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid url } } }' - /** - * Commit images to a `nuxi/*` branch in one commit, creating the branch from the default branch - * when it doesn't exist. `github__editFiles` takes text only, so an image can't go through it. - * GitHub signs a `createCommitOnBranch` commit and records the token's owner as its author. + * The branches a commit may go to: a `nuxi/*` branch, which the coder makes for a task, or the + * branch of an open pull request of the repository, which is work in review and where + * `githubToolsApproval` asks the person first. Never the default branch. */ -export async function commitAssets({ branch, message, files, ...github }: CommitInput) { - if (!BRANCH.test(branch) || branch.includes('..')) throw new Error(`Images are committed to a \`nuxi/*\` branch only, not "${branch}".`) - if (!files.length) throw new Error('No files to commit.') - for (const { path, bytes } of files) { - if (!FILE_PATH.test(path) || path.includes('..')) throw new Error(`"${path}" is not a path in the repository.`) - if (checkedMediaType(path, bytes, MAX_COMMIT_BYTES) === 'video/mp4') throw new Error(`"${path}" is a video: only images are committed.`) - } +async function assertCommitBranch(github: Github, branch: string): Promise { + if (!BRANCH.test(branch) || branch.includes('..')) throw new Error(`"${branch}" is not a branch name this tool takes.`) + if (NUXI_BRANCH.test(branch)) return - const repository = `${API}/repos/${github.repository}` - async function headOf(name: string) { - try { - return (await request<{ object: { sha: string } }>(github, `${repository}/git/ref/heads/${name}`)).object.sha - } catch (error) { - if (error instanceof GithubRequestError && error.status === 404) return undefined - throw error - } - } + const [{ default_branch }, pullRequest] = await Promise.all([ + request<{ default_branch: string }>(github, `${API}/repos/${github.repository}`), + openPullRequestOf({ ...github, branch }) + ]) + if (branch === default_branch) throw new Error(`\`${branch}\` is the default branch of ${github.repository}. Commit to a \`nuxi/*\` branch and open a pull request.`) + if (pullRequest === undefined) throw new Error(`\`${branch}\` is not a \`nuxi/*\` branch and has no open pull request. Commit to a \`nuxi/*\` branch, or to the branch of the open pull request the task is about.`) +} - let head = await headOf(branch) - const createdBranch = !head - if (!head) { - const { default_branch } = await request<{ default_branch: string }>(github, repository) - head = await headOf(default_branch) - if (!head) throw new Error(`Could not read the head of ${default_branch}.`) - await request(github, `${repository}/git/refs`, { ref: `refs/heads/${branch}`, sha: head }) - } +/** A path as git lists it: relative, and never into `.git`. */ +function isTrackedPath(path: string): boolean { + return !path.split('/').some(segment => segment === '' || segment === '.' || segment === '..' || segment === '.git') +} - const [headline = '', ...rest] = message.trim().split('\n') +type Commit = Changes & { readonly branch: string, readonly message: string } + +/** + * One commit with one parent, the head of `branch`, through `createCommitOnBranch`: GitHub signs + * it and records the token's owner as its author, and refuses it when the branch moved since. + */ +async function commitOnBranch(github: Github, { branch, message, parents: [head], files, deletions }: Commit): Promise<{ sha: string, url: string }> { + const [headline = '', ...rest] = message.split('\n') const body = rest.join('\n').trim() const { data, errors } = await request<{ data?: { createCommitOnBranch?: { commit?: { oid: string, url: string } } } errors?: Array<{ message?: string }> }>(github, `${API}/graphql`, { - query: COMMIT_MUTATION, + query: 'mutation ($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid url } } }', variables: { input: { branch: { repositoryNameWithOwner: github.repository, branchName: branch }, expectedHeadOid: head, message: body ? { headline, body } : { headline }, - fileChanges: { additions: files.map(({ path, bytes }) => ({ path, contents: Buffer.from(bytes).toString('base64') })) } + fileChanges: { + additions: files.map(({ path, bytes }) => ({ path, contents: Buffer.from(bytes).toString('base64') })), + ...(deletions.length ? { deletions: deletions.map(path => ({ path })) } : {}) + } } } }) const commit = data?.createCommitOnBranch?.commit if (!commit) throw new Error(`GitHub refused the commit: ${errors?.map(error => error.message).join('; ') || 'no reason given'}`) + return { sha: commit.oid, url: commit.url } +} - return { repository: github.repository, branch, createdBranch, commitSha: commit.oid, commitUrl: commit.url, paths: files.map(file => file.path) } +/** + * A merge commit, which `createCommitOnBranch` can't make: it gives a commit one parent. Built + * from its parts instead. GitHub records the token's owner as its author and does not sign it. + */ +async function mergeCommit(github: Github, { message, parents, files, inherited, deletions }: Commit): Promise<{ sha: string, url: string }> { + const git = `${API}/repos/${github.repository}/git` + const { tree: base } = await request<{ tree: { sha: string } }>(github, `${git}/commits/${parents[0]}`) + + // One at a time: GitHub limits writes sent together, and a merge leaves few files of its own. + const written: Array<{ path: string, mode: string, id: string }> = [] + for (const { path, bytes } of files) { + const blob = await request<{ sha: string }>(github, `${git}/blobs`, { content: Buffer.from(bytes).toString('base64'), encoding: 'base64' }) + written.push({ path, mode: '100644', id: blob.sha }) + } + + const tree = await request<{ sha: string }>(github, `${git}/trees`, { + base_tree: base.sha, + tree: [ + ...[...written, ...inherited].map(({ path, mode, id }) => ({ path, mode, type: mode === '160000' ? 'commit' : 'blob', sha: id })), + ...deletions.map(path => ({ path, mode: '100644', type: 'blob', sha: null })) + ] + }) + const commit = await request<{ sha: string, html_url: string }>(github, `${git}/commits`, { message, tree: tree.sha, parents }) + return { sha: commit.sha, url: commit.html_url } +} + +/** + * Commit what was staged in a clone (`clone.ts`) to `branch`, in one commit. A new branch starts + * at the commit the clone is at. An existing one must point to it: the changes are whole files, so + * on any other commit they would undo what it holds. + */ +export async function commitChanges({ token, fetchImpl, repository, ...commit }: Github & Commit) { + const github = { token, fetchImpl, repository } + const { branch, parents: [base, merged], files, deletions } = commit + if (!files.length && !deletions.length && !commit.inherited.length) throw new Error('No changes to commit.') + const stray = [...files, ...commit.inherited].map(file => file.path).concat(deletions).find(path => !isTrackedPath(path)) + if (stray !== undefined) throw new Error(`"${stray}" is not a path in the repository.`) + await assertCommitBranch(github, branch) + + const head = await headOf(github, branch) + if (head && head !== base) { + throw new Error(`\`${branch}\` is at ${head.slice(0, 8)} on GitHub, and the clone is at ${base.slice(0, 8)}. Nothing was committed. Stash your changes, fetch \`${branch}\` and check it out, apply them there, then commit again.`) + } + const refs = `${API}/repos/${repository}/git/refs` + // GitHub answers 422 for a commit it doesn't have: one made in the sandbox with `git commit`. + const unknownCommit = (error: unknown) => { + if (!(error instanceof GithubRequestError && error.status === 422)) throw error + throw new Error(`${error.message}. Nothing was committed. GitHub must have the commit the clone is at, ${base.slice(0, 8)}: undo a commit made in the sandbox with \`git reset --soft\`, then call this again.`) + } + + let created: { sha: string, url: string } + if (merged) { + created = await mergeCommit(github, commit).catch(unknownCommit) + // Not forced: GitHub refuses to move a branch that someone moved since. + await (head ? request(github, `${refs}/heads/${branch}`, { sha: created.sha, force: false }, 'PATCH') : request(github, refs, { ref: `refs/heads/${branch}`, sha: created.sha })) + } else { + if (!head) await request(github, refs, { ref: `refs/heads/${branch}`, sha: base }).catch(unknownCommit) + created = await commitOnBranch(github, commit) + } + return { repository, branch, createdBranch: !head, commitSha: created.sha, commitUrl: created.url, paths: files.map(file => file.path), deleted: [...deletions] } } diff --git a/layers/nuxi/agent/lib/github.ts b/layers/nuxi/agent/lib/github.ts index 55f6b07aa..9732a6e5a 100644 --- a/layers/nuxi/agent/lib/github.ts +++ b/layers/nuxi/agent/lib/github.ts @@ -1,5 +1,6 @@ import { getToken } from '@vercel/connect' import type { ApprovalPolicy } from 'eve/tools/approval' +import { z } from 'zod' import { openPullRequestOf } from './github-files.js' import { isAdminMode } from './identity/admin-mode.js' import { resolveContext, type AuthContext, type Surface } from './identity/context.js' @@ -8,19 +9,46 @@ import { resolveContext, type AuthContext, type Surface } from './identity/conte export const GITHUB_CONNECTOR = 'github/nuxi-code' /** - * The repositories the coder works on, as `owner/name`; the first is the default. To let Nuxi work - * on another one, add it here, give the `nuxi-code` App access to it, and describe it in - * `subagents/coder/instructions.md`. + * The repositories the coder may write to. An entry is `owner/name`, or `owner/*` for every + * repository of that account: the syntax of the GitHub tools' `repositories` guardrail, which reads + * this list too. The first entry names one repository, the default of every tool. + * + * This list is the only thing that holds Nuxi to these repositories. Nothing else in the coder + * names one: its tools take the repository as an input, and every write runs with the GitHub token + * of the person who asked. GitHub accepts that token only where the `nuxi-code` App is installed + * and the person has access, with the role the person has there. So a wider list, such as + * `nuxt/*`, gives nobody more than GitHub already gives them. Whatever the repository, a commit + * goes to a `nuxi/*` branch or to the branch of an open pull request, never to the default branch. */ -export const GITHUB_REPOSITORIES = ['nuxt/nuxt.com'] as const +export const GITHUB_REPOSITORIES: readonly [string, ...string[]] = ['nuxt/nuxt.com'] +export const DEFAULT_REPOSITORY = GITHUB_REPOSITORIES[0] + +const REPOSITORY_PART = /^[\w.-]+$/ /** - * The entry of `GITHUB_REPOSITORIES` that `repository` names, if any. GitHub ignores the case of - * owners and repository names, and so does the `repositories` guardrail of the GitHub tools. + * The repository of `allowed` that `repository` names, with its owner written as the list writes + * it, if any. GitHub ignores the case of owners and repository names, and so does the + * `repositories` guardrail of the GitHub tools. */ -function allowedRepository(repository: unknown) { +export function allowedRepository(repository: unknown, allowed: readonly string[] = GITHUB_REPOSITORIES): string | undefined { if (typeof repository !== 'string') return undefined - return GITHUB_REPOSITORIES.find(allowed => allowed.toLowerCase() === repository.toLowerCase()) + const [owner = '', name = '', ...rest] = repository.split('/') + if (rest.length || !REPOSITORY_PART.test(owner) || !REPOSITORY_PART.test(name) || name === '.' || name === '..') return undefined + for (const entry of allowed) { + const [entryOwner = '', entryName = ''] = entry.split('/') + if (entryOwner.toLowerCase() !== owner.toLowerCase()) continue + if (entryName === '*') return `${entryOwner}/${name}` + if (entryName.toLowerCase() === name.toLowerCase()) return entry + } + return undefined +} + +/** A tool input that names a repository to write to: one the list allows, and the default when omitted. */ +export function repositoryInput(description: string) { + return z.string().max(140) + .refine(repository => allowedRepository(repository) !== undefined, { error: `Not a repository Nuxi works on: ${GITHUB_REPOSITORIES.join(', ')}.` }) + .default(DEFAULT_REPOSITORY) + .describe(description) } const GITHUB_SURFACES = new Set(['slack', 'discord', 'cli']) @@ -49,17 +77,6 @@ export function appToken(repository: string): Promise { }) } -const [DEFAULT_OWNER, DEFAULT_REPO] = GITHUB_REPOSITORIES[0].split('/') - -/** - * The coder's tools that commit to a branch, with the repository each one commits to, read from - * the inputs that tool reads and with its defaults. Both name the branch `branch`. - */ -const COMMIT_TOOLS = new Map>) => unknown>([ - ['github__editFiles', ({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO }) => typeof owner === 'string' && typeof repo === 'string' ? `${owner}/${repo}` : undefined], - ['commit_assets', ({ repository = GITHUB_REPOSITORIES[0] }) => repository] -]) - /** * Whether `branch` has an open pull request: work someone may be reviewing, which the coder may * not have opened. Not knowing counts as yes. @@ -78,9 +95,9 @@ async function hasOpenPullRequest(repository: string, branch: string): Promise/…` for a server you started in the sandbox. Omit to use the page the `browser__*` tools left open, in the state they left it.'), viewport: z.enum(['desktop', 'tablet', 'mobile']).optional().describe('desktop 1280x720 (default), tablet 768x1024 or mobile 390x844'), colorScheme: z.enum(['light', 'dark']).optional().describe('Emulated `prefers-color-scheme`. Omit for the browser\'s default, which is light.'), cookies: z.array(z.string().min(3).max(2000)).max(10).optional().describe('Cookies set before the page opens, as `name=value`, such as a consent cookie. Needs `url`.'), @@ -86,17 +86,26 @@ export interface MediaSandbox { export const PRIVATE_SUBNETS = ['10.0.0.0/8', '100.64.0.0/10', '169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.168.0.0/16', '198.18.0.0/15', '224.0.0.0/3'] const privateAddresses = new BlockList() -// 0/8 and loopback never leave the sandbox, so only the URL check knows them. -for (const subnet of [...PRIVATE_SUBNETS, '0.0.0.0/8', '127.0.0.0/8']) { +// 0/8 never leaves the sandbox, so only the URL check knows it. +for (const subnet of [...PRIVATE_SUBNETS, '0.0.0.0/8']) { const [network = '', prefix] = subnet.split('/') privateAddresses.addSubnet(network, Number(prefix)) } -const LOCAL_NAME = /^(?:localhost|.*\.(?:localhost|local|internal))$/ +const LOCAL_NAME = /\.(?:localhost|local|internal)$/ /** - * Why `raw` can't be captured, or null: public http(s) pages only. It reads the URL and resolves - * nothing, so it stops a mistake with a clear message. A hostname that points to a private address, - * a redirect to one and the `browser__*` tools are the firewall's to refuse. + * The sandbox itself, where a dev server the coder started from a clone answers. Whatever + * listens there runs in the sandbox, which holds no credentials. + */ +function isLoopback(host: string): boolean { + return host === 'localhost' || host === '[::1]' || (isIPv4(host) && host.startsWith('127.')) +} + +/** + * Why `raw` can't be captured, or null: public http(s) pages and the sandbox's own loopback only. + * It reads the URL and resolves nothing, so it stops a mistake with a clear message. A hostname + * that points to a private address, a redirect to one and the `browser__*` tools are the + * firewall's to refuse. */ export function captureUrlError(raw: string): string | null { let url: URL @@ -109,7 +118,8 @@ export function captureUrlError(raw: string): string | null { if (url.username || url.password) return 'URLs with credentials are not captured.' // `localhost.` resolves like `localhost`. const host = url.hostname.toLowerCase().replace(/\.$/, '') - // An IPv6 literal is refused whatever it is. `URL` writes every IPv4 form as dotted decimal. + if (isLoopback(host)) return null + // Any other IPv6 literal is refused whatever it is. `URL` writes every IPv4 form as dotted decimal. if (host.startsWith('[') || LOCAL_NAME.test(host) || (isIPv4(host) && privateAddresses.check(host))) return `"${host}" is a local or private address.` return null } @@ -202,7 +212,7 @@ async function preparePage(run: Runner, request: PageRequest, scale: 1 | 2) { return viewport } -/** The URL of the page the browser shows, refused when it isn't public: the `browser__*` tools, a redirect or a click may have led anywhere. */ +/** The URL of the page the browser shows, refused when it is neither public nor the sandbox's own: the `browser__*` tools, a redirect or a click may have led anywhere. */ async function shownUrl(run: Runner) { const url = (await run.browser<{ url?: string }>('get', 'url'))?.url ?? '' const reason = captureUrlError(url) @@ -287,7 +297,7 @@ async function recording(sandbox: MediaSandbox, request: z.infer {}) await runner(sandbox).shell(`rm -f ${quote(`${base}.webm`)}`).catch(() => {}) throw error diff --git a/layers/nuxi/agent/subagents/coder/agent.ts b/layers/nuxi/agent/subagents/coder/agent.ts index 00b2559b3..898d43c94 100644 --- a/layers/nuxi/agent/subagents/coder/agent.ts +++ b/layers/nuxi/agent/subagents/coder/agent.ts @@ -6,14 +6,17 @@ import { nuxiGatewayOptions, nuxiGatewayTags } from '../../lib/gateway-attributi // see it. eve runs this before every parent model call, hence the per-turn memo: on Discord, // `canUseGithubTools` reads Global Config. The root agent's `approval` and `limits.sessionUsage` // apply here too. `sandbox.ts` gives it a browser, driven by `extensions/browser/` and the capture -// tools in `tools/`, which also turns off eve's file-writing tools: the sandbox holds no checkout, so -// code changes through the GitHub API only, on the repositories in `GITHUB_REPOSITORIES`. It keeps `web_search` and `web_fetch` to read docs and issues. +// tools in `tools/`, and what it takes to clone a repository and run it. It writes to the +// repositories of `GITHUB_REPOSITORIES` only, with the GitHub access of the person who asked. +// The sandbox holds no credentials: a change made in a clone reaches GitHub through +// `commit_changes`, in the app runtime. `extensions/code.ts` mounts eve's coding instructions. +// It keeps `web_search` and `web_fetch` to read docs and issues. export default defineDynamic(async (ctx) => { const auth = ctx.session.auth.current if (!(await ctx.memo(ctx.turn?.id ?? null, () => canUseGithubTools(auth)))) return null return defineAgent({ - description: `Nuxi's coding agent for these GitHub repositories: ${GITHUB_REPOSITORIES.join(', ')}. Hand it any coding task there: a fix, a feature, a content or docs change, a new showcase site or template with its screenshot and logo, or a question about how the code works. It reads and searches the repository and the web. When the task changes files, it makes the change on a new \`nuxi/*\` branch and opens a pull request, with the screenshots and short clips that show the change. Hand it any capture task too: it has the only browser, so only it can open a public page and say what it sees, take a screenshot (\`capture_screenshot\`) or record a short clip (\`record_video\`), and attach each to the repository, which gives it a link (\`publish_media\`). A task that changes no file opens no pull request, and a capture's link opens for everyone only once a pull request embeds it. It does not see this conversation or its attachments, so the message must hold the full task, links or excerpts from the thread, and the name of the person asking. When the task needs a file attached here, such as an image to put on the site, call \`share_attachments\` first and name the file in the message.`, + description: `Nuxi's coding agent for these GitHub repositories: ${GITHUB_REPOSITORIES.join(', ')}. Hand it any coding task there: a fix, a feature, a refactor, a performance or content change, a new showcase site or template with its screenshot and logo, or a question about how the code works. It clones the repository into its own sandbox, where it searches and changes the code, installs the project, runs its dev server, tests and checks, and looks at the running app in a browser. It can also clone and run any other public GitHub repository, such as a reproduction linked in an issue, and it reads the web. When the task changes files, it commits the change to a new \`nuxi/*\` branch and opens a pull request, with the screenshots and short clips of the running app that show the change. When the task says to stop earlier, such as a dry run with no commit or no pull request, it prepares the change in its clone and reports it instead. It can also work on a pull request that is already open, such as resolving its conflict with the base branch: it commits to that pull request's branch once the person approves the commit, and never to the default branch. Hand it any capture task too: it has the only browser, so only it can open a public page, or a page of an app it runs, and say what it sees, take a screenshot (\`capture_screenshot\`) or record a short clip (\`record_video\`), and attach each to the repository, which gives it a link (\`publish_media\`). A task that changes no file opens no pull request, and a capture's link opens for everyone only once a pull request embeds it. It does not see this conversation or its attachments, so the message must hold the full task, the repository it is about when it is not the first of the list, links or excerpts from the thread, and the name of the person asking. When the task needs a file attached here, such as an image to put on the site, call \`share_attachments\` first and name the file in the message.`, model: 'anthropic/claude-opus-5.5', modelOptions: { providerOptions: { diff --git a/layers/nuxi/agent/subagents/coder/extensions/code.ts b/layers/nuxi/agent/subagents/coder/extensions/code.ts new file mode 100644 index 000000000..20283b659 --- /dev/null +++ b/layers/nuxi/agent/subagents/coder/extensions/code.ts @@ -0,0 +1,5 @@ +import code from 'eve/extensions/code' + +// eve's coding instructions for `bash`, `read_file`, `edit_file` and `write_file`, and its +// `code__investigate` and `code__review` skills. No Vercel credentials: the coder deploys nothing. +export default code({}) diff --git a/layers/nuxi/agent/subagents/coder/extensions/github.ts b/layers/nuxi/agent/subagents/coder/extensions/github.ts index 2fe9712df..0145591a2 100644 --- a/layers/nuxi/agent/subagents/coder/extensions/github.ts +++ b/layers/nuxi/agent/subagents/coder/extensions/github.ts @@ -1,17 +1,21 @@ import githubExtension from '@github-tools/eve-extension' -import { GITHUB_CONNECTOR, GITHUB_REPOSITORIES } from '../../../lib/github.js' +import { DEFAULT_REPOSITORY, GITHUB_CONNECTOR, GITHUB_REPOSITORIES } from '../../../lib/github.js' -const [owner, repo] = GITHUB_REPOSITORIES[0].split('/') +const [owner, repo] = DEFAULT_REPOSITORY.split('/') // Mounted under the coder subagent only, so the root agent and its public sessions never list // these tools. `githubToolsApproval` in the root `agent.ts` still gates every call. export default githubExtension({ connector: GITHUB_CONNECTOR, preset: 'pr-author', - // Only what opening a pull request needs. Review-thread and branch-maintenance tools can come later. + // Reading a repository and its pull requests, and opening a pull request. Files reach GitHub + // through `commit_changes` only, from a clone the coder could run: one way to commit, with one + // rule for the branch it goes to. Review-thread tools can come later. exclude: [ + 'createBranch', // `commit_changes` creates the branch it commits to + 'editFiles', + 'createOrUpdateFile', 'deleteBranch', - 'createOrUpdateFile', // `editFiles` commits one or more files in a single commit 'getBranchRules', 'getCollaboratorPermission', // calls run with the asker's own token, so GitHub enforces their role 'updatePullRequestBranch', @@ -22,20 +26,15 @@ export default githubExtension({ 'compareCommits', 'searchCode' // a free-text query: `repositories` can't hold it to the allowed repositories ], - // Calls default to the first repository and are refused outside the list. + // Calls default to the first repository and are refused outside the list, whose syntax is the guardrail's. context: { owner, repo }, - guardrails: { repositories: [...GITHUB_REPOSITORIES], branches: ['nuxi/*'] }, - // Each call runs as the person who asked, so the pull request and its commits are theirs on - // GitHub. Someone who hasn't connected GitHub yet gets a sign-in prompt instead of the App. Only - // `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, which has no GitHub user, runs as the App, for local testing. - // `attribution` (on by default) credits the App with a PR footer and a commit co-author. + guardrails: { repositories: [...GITHUB_REPOSITORIES] }, + // Each call runs as the person who asked, so the pull request is theirs on GitHub. Someone who + // hasn't connected GitHub yet gets a sign-in prompt instead of the App. Only `pnpm nuxi` with + // `NUXI_CLI_ADMIN=1`, which has no GitHub user, runs as the App, for local testing. + // `attribution` (on by default) credits the App with a PR footer. actAs: 'caller', - // Opening a pull request needs no click: the guardrails keep it on a new `nuxi/*` branch of an - // allowed repository, and a person reviews and merges it on GitHub. Editing an existing pull request - // (`updatePullRequest`) still asks. - requireApproval: { - createBranch: 'never', - editFiles: 'never', - createPullRequest: 'never' - } + // Opening a pull request needs no click: it changes no code, and a person reviews and merges it + // on GitHub. Editing an existing pull request (`updatePullRequest`) still asks. + requireApproval: { createPullRequest: 'never' } }) diff --git a/layers/nuxi/agent/subagents/coder/instructions.md b/layers/nuxi/agent/subagents/coder/instructions.md index 4c10a8e81..388535cd5 100644 --- a/layers/nuxi/agent/subagents/coder/instructions.md +++ b/layers/nuxi/agent/subagents/coder/instructions.md @@ -1,16 +1,17 @@ -You are Nuxi's coding agent. You work on the repositories the `github__*` tools accept: `nuxt/nuxt.com`, unless the task names another one they accept. You never see the conversation that asked for the work: work from the message you receive. +You are Nuxi's coding agent. You work on the GitHub repository the task names, and on the default of your tools when it names none. You act with the GitHub access of the person who asked: when GitHub or a tool refuses a repository or a branch, say so instead of looking for another way in. You never see the conversation that asked for the work: work from the message you receive. ## What you work with -- The repository, through the `github__*` tools and `commit_assets`. There is no checkout: you can't run the project, its dev server or its tests. -- A browser in a sandbox. The `browser__*` tools open and operate any public page, `capture_screenshot` and `record_video` capture it and show you the result, and `publish_media` attaches a capture to the repository, which gives it a link for a pull request. +- A sandbox of your own, which holds no GitHub credentials. Clone the repository into it with `bash`, as `git clone --filter=blob:none https://github.com// /workspace/repos//`. There you search and change the code, and you install and run the project: its dev server, its tests, its checks. Load the `run-project` skill before the first install or run. A repository that asks for credentials can't be cloned: say so. +- GitHub. The `github__*` tools read repositories and pull requests, and open a pull request. Files reach GitHub through `commit_changes` only, from a clone: `git push` from the sandbox reaches nothing. +- A browser in the sandbox. The `browser__*` tools open and operate any public page and any page of an app you run in the sandbox, at `http://localhost:`, `capture_screenshot` and `record_video` capture it and show you the result, and `publish_media` attaches a capture to the repository, which gives it a link for a pull request. - Files the conversation shared for the task. When the message names an attached file or a path under `/workspace/shared/`, call `receive_attachments` first: the file is not in the sandbox until that call copies it there. You see no other attachment: when the message counts on a file that `receive_attachments` did not return, reply with that instead of guessing its content. -- `bash` and `read_file`, on the files in the sandbox only: look at an image, read its size, or re-encode it with `ffmpeg`. - `web_search` and `web_fetch`, to read pages the task links to, such as a GitHub issue or a docs page, or to check an API you're unsure of. ## How you work -- Understand the code before you change it. Find the right files with `github__getRepositoryTree` instead of guessing paths, and read every file you change with `github__getFileContent`. +- Understand the code before you change it: clone the repository and search it instead of guessing paths. To only read one or two files, the `github__*` tools are enough. +- Check a code change before you deliver it. Run the checks the project has for what you touched, and for a change to a page, run the app and look at the page. When a check can't run in the sandbox, say so instead of calling the change tested. - When the task is about how a page looks or behaves, open the page and look at it before you read the code. - Keep the change to what was asked, and match the style of the surrounding code and content. - Finish the task. When it needs a file you can produce, such as a screenshot of a site or a logo the site publishes, produce it and commit it instead of listing it as a step for a person. @@ -20,19 +21,23 @@ You are Nuxi's coding agent. You work on the repositories the `github__*` tools ## Delivering a change -- Work on one repository per task, on a new branch named `nuxi/` created from its default branch. Never commit to a branch you did not create for this task. When a branch with the name you want already exists, it belongs to another task: pick another name. A commit to a branch that has an open pull request asks the person to approve it first. -- Commit text files with `github__editFiles` and images with `commit_assets`, in as few commits as the change needs. -- Commit an image someone shared as it is, at the path and in the format the task or the file it replaces calls for. Don't resize or re-encode it unless asked, or unless `commit_assets` refuses its size: then say in the pull request what you changed. -- When the change is done, open a pull request. Title it and its commits with a conventional commit, such as `fix(docs): correct the useFetch example`. In the body, say what changed and why, and credit the person who asked by name. +- Work on one repository per task, on a new branch named `nuxi/`. When a branch with the name you want already exists, it belongs to another task: pick another name. +- When the task is about a pull request that is already open, such as resolving its conflict or answering a review, commit to that pull request's branch instead of a new one: fetch the branch and check it out before you change anything. To resolve a conflict with its base branch, merge the base into it with `git merge --no-commit --no-ff origin/`, resolve, stage and call `commit_changes`. Don't rebase. The person is asked to approve each commit to a branch that has an open pull request. Never commit to any other branch you did not create for this task. +- Put every file of the change in the clone, images included, stage them with `git add` and commit with `commit_changes`, in as few commits as the change needs. Never run `git commit`: `commit_changes` makes the commit on GitHub from what is staged. +- Commit an image someone shared as it is, at the path and in the format the task or the file it replaces calls for. Don't resize or re-encode it unless asked. +- A task that asks for a change asks for its pull request too: when the change is done, open one, unless you committed to a pull request that is already open. Title it and its commits with a conventional commit, such as `fix(docs): correct the useFetch example`. In the body, say what changed and why, and credit the person who asked by name. - Open a draft pull request only when a part of the task is left that you tried and could not do. Name that part and what a person needs to do. -- Never merge, and never edit a pull request you did not open for this task. +- Never merge a pull request, and never edit the title or body of one you did not open for this task. - Reply with the pull request link, a one-line summary of the change, and the URL of every capture you published. -## nuxt/nuxt.com +## Notes on nuxt/nuxt.com + +This section holds what the repository's own files don't say. A repository without a section here has none: its `AGENTS.md` and README are what you go by. The source of nuxt.com. - `https://nuxt.com` serves `main`. - The images the site serves live under `public/assets/`. Screenshots of showcase sites (`websites/.webp`), templates (`templates/.webp`) and video courses (`video-courses/.webp`) are all what `capture_screenshot` saves at its default viewport. +- `pnpm dev` regenerates the types under `.nuxt/` without the `eve` module, and `pnpm test:types` then fails on an unknown `eve` key in `layers/nuxi/nuxt.config.ts`. That failure is not in the code: once the dev server has run, run `pnpm nuxt prepare` before the type check. - The Vercel preview of a pull request redirects to a Vercel sign-in, so you can't open it. - A pull request that only changes files under `content/` gets no Vercel build. It previews at `https://nuxt.com/pull/nuxt.com/` once a maintainer adds the `preview:enabled` label. Open that page only when the request says the label is on. diff --git a/layers/nuxi/agent/subagents/coder/sandbox.ts b/layers/nuxi/agent/subagents/coder/sandbox.ts index e366cfc1c..ac854318e 100644 --- a/layers/nuxi/agent/subagents/coder/sandbox.ts +++ b/layers/nuxi/agent/subagents/coder/sandbox.ts @@ -5,10 +5,11 @@ import { BROWSER_LAUNCH_ARGS, PRIVATE_SUBNETS } from '../../lib/media/capture.js type PrepareSandbox = NonNullable[0]>['prepare']> /** - * Chromium, agent-browser and ffmpeg, installed once per template: every coder session starts with - * a browser that can screenshot and record. It holds no checkout and no credentials. Code still - * changes through the GitHub API, and the tools that publish or commit a capture run in the app - * runtime and read the file out of the sandbox. + * Chromium, agent-browser, ffmpeg and what a JavaScript project needs to install and run, installed + * once per template: every coder session starts with a browser that can screenshot and record, and + * can clone a repository and start its dev server. It holds no credentials: `git clone` reaches + * public repositories and `git push` reaches nothing. Code reaches GitHub through its API only: + * the tools that commit or publish run in the app runtime and read the files out of the sandbox. */ const prepare: PrepareSandbox = async (sandbox) => { // just-bash (`eve dev` without Docker) runs no native binaries: leave it empty, and the capture @@ -33,17 +34,25 @@ const prepare: PrepareSandbox = async (sandbox) => { const configured = await sandbox.run({ command: `mkdir -p "$HOME/.agent-browser" && printf '%s' ${config} > "$HOME/.agent-browser/config.json"` }) if (configured.exitCode !== 0) throw new Error(`Could not write the agent-browser config: ${configured.stderr || configured.stdout}`) - const ffmpeg = await sandbox.run({ command: 'sudo apt-get install -y --no-install-recommends ffmpeg' }) - if (ffmpeg.exitCode !== 0) throw new Error(`Could not install ffmpeg: ${ffmpeg.stderr || ffmpeg.stdout}`) + // `build-essential` is for a dependency that compiles a native module when it has no prebuilt binary. + const packages = await sandbox.run({ command: 'sudo apt-get install -y --no-install-recommends ffmpeg build-essential' }) + if (packages.exitCode !== 0) throw new Error(`Could not install ffmpeg and build-essential: ${packages.stderr || packages.stdout}`) + + // The image has npm only. Corepack's `pnpm` and `yarn` run the version a project pins in + // `packageManager`, downloaded on first use, so no project's choice is baked in here. + const packageManagers = await sandbox.run({ command: 'npm install -g corepack bun && corepack enable' }) + if (packageManagers.exitCode !== 0) throw new Error(`Could not install the package managers: ${packageManagers.stderr || packageManagers.stdout}`) } export const environment = DefaultSandbox.environment({ prepare, vercel: { - // Chromium, a recording and an ffmpeg encode at once. + // Chromium, a recording and an ffmpeg encode at once, or Chromium next to a project's dev + // server. Memory follows at 2 GB per vCPU. resources: { vcpus: 4 }, - // The browser opens any public page and nothing else: the firewall resets a connection to a - // private address, whatever name, redirect or tool led to it. Docker has no such rule. + // The browser and the project's code reach the public internet and the sandbox itself, and + // nothing else: the firewall resets a connection to a private address, whatever name, redirect + // or tool led to it. Docker has no such rule. networkPolicy: { allow: ['*'], subnets: { deny: PRIVATE_SUBNETS } } }, // Don't add `just-bash` to the app's dependencies for a sandbox that can't run a browser anyway. diff --git a/layers/nuxi/agent/subagents/coder/skills/run-project/SKILL.md b/layers/nuxi/agent/subagents/coder/skills/run-project/SKILL.md new file mode 100644 index 000000000..53aa96a12 --- /dev/null +++ b/layers/nuxi/agent/subagents/coder/skills/run-project/SKILL.md @@ -0,0 +1,46 @@ +--- +description: Install and run a cloned project in the sandbox, whatever it is built with. Covers its dev server, tests, lint, type check and build, and opening its pages in the browser. Load it before the first install or run of a task, and when a server you started no longer answers. +--- + +The sandbox is a Linux machine with Node.js, npm, pnpm, Yarn, Bun, git, a C toolchain, ffmpeg and a browser. Install anything else a project needs with `sudo apt-get install -y`. It holds no secrets and no services: no database, no Docker, no account of any kind. + +Every project runs its own way, so read how this one runs before you run it. + +## Read first + +In the clone, read what exists of `AGENTS.md` or `CLAUDE.md`, `README.md`, `CONTRIBUTING.md`, `package.json` (`packageManager`, `scripts`, `engines`, `workspaces`) and `.env.example`. They name the package manager, the commands, and what the app needs to start. + +The lockfile names the package manager when `packageManager` doesn't: `pnpm-lock.yaml` is pnpm, `yarn.lock` is Yarn, `bun.lock` or `bun.lockb` is Bun, `package-lock.json` is npm. `pnpm` and `yarn` run the version the project pins, and download it on first use. + +## Install + +Install with the lockfile as it is: `pnpm install --frozen-lockfile`, `yarn install --immutable` (`--frozen-lockfile` on Yarn 1), `bun install --frozen-lockfile` or `npm ci`. Prefix the command with `CI=1` so nothing waits for an answer. + +- Change the lockfile only when the task adds or updates a dependency. Then run the package manager's own command and commit the lockfile it writes. +- In a monorepo, install at the root, then run the app or package the task is about the way its README shows. + +## Commands that take time + +`bash` waits 60 seconds for a command, or up to 120 with `timeout`. A command still running after that keeps running: the result says `running` and gives a `pid` and an `outputDirectory` that holds `stdout`, `stderr` and, once the command ends, `exit`. Read those files to follow an install, a build or a test run. Don't start the command again. + +## Checks + +Run the checks the project has for what you changed: its lint, its type check and the tests of that area, under the script names in `package.json`. Run the narrowest command that covers your change first, such as one test file or one package, then the wider one when it is quick enough. + +- Fix what your change breaks. Never weaken a test or a lint rule to get a pass. +- A check that fails the same way on the commit you checked out is not yours to fix. Say which one, and that it fails without your change. + +## Run the app + +1. Start the dev script with `bash` and a `timeout` of 5, on a port you choose. Most dev servers take `--port 3000` or `PORT=3000`. The call returns `running` and the server keeps going. +2. Wait for it with `curl -s -o /dev/null -w '%{http_code}' --max-time 90 http://localhost:3000/`. A dev server compiles a page on its first request, which can take a minute. When it doesn't answer, read `stderr` in the output directory. +3. Open `http://localhost:3000/` with the `browser__*` tools, `capture_screenshot` or `record_video`. Write `localhost`, not `0.0.0.0` or the address the server prints. +4. Look at the page your change touches. Read `browser__errors` and the server's `stderr` for errors your change causes. + +- When the app needs environment variables to start, use the values that `.env.example` or the README give for local development. Never invent a credential. When a page needs a service the sandbox doesn't have, say which page you could not check. +- Processes end when your task ends, and the files stay. On a follow-up message, the clone and its `node_modules` are there and the server is not: start it again. +- Stop a server you no longer need with `kill -- -`. Two dev servers at once can use up the sandbox's memory. + +## Say what you ran + +In your reply and in the pull request, name each check you ran with its result, and each one you could not run with the reason. Quote the output of a failure. Never write that the tests pass when you did not run them. diff --git a/layers/nuxi/agent/subagents/coder/skills/showcase-entry/SKILL.md b/layers/nuxi/agent/subagents/coder/skills/showcase-entry/SKILL.md index 43e548aca..7989eb0a0 100644 --- a/layers/nuxi/agent/subagents/coder/skills/showcase-entry/SKILL.md +++ b/layers/nuxi/agent/subagents/coder/skills/showcase-entry/SKILL.md @@ -44,7 +44,7 @@ The frame is good when it shows the site's own homepage, above the fold, with no When the frame is clean, write the options that got you there into the entry's `screenshotOptions`, with the same names (`cookies`, `hideElements`, `removeElements`, `scripts`, `delay`), so a person can regenerate the image later. -Commit it with `commit_assets`, from `/workspace/captures/.webp` to `public/assets/websites/.webp`. Showcase screenshots are 80 to 350 KB. `commit_assets` accepts more, but keep this one under 1 MB: when the capture's `bytes` is higher, capture again with a lower `quality`, such as 60. +Copy it from `/workspace/captures/.webp` to `public/assets/websites/.webp` in the clone. Showcase screenshots are 80 to 350 KB, so keep this one under 1 MB: when the capture's `bytes` is higher, capture again with a lower `quality`, such as 60. ## The logo @@ -58,10 +58,10 @@ The tile uses the logo as a mask and paints it in one colour. Only its shape cou Look at the cleaned logo before you commit it. With `browser__eval` on the site's page, cover the page with a dark `position: fixed` box that holds one element with a white background and `mask: url("data:image/svg+xml,…") center/contain no-repeat`, where the URL is the cleaned markup through `encodeURIComponent`. The tile draws the logo the same way. Call `capture_screenshot` without `url` and compare the shape with the logo in the site's header. A solid block, an empty box or a missing part means the cleaning broke the logo: fix the markup and look again. When the box is empty for the site's original markup too, the page refuses `data:` images: do the same on another public page, such as `https://example.com/`. -Commit the SVG with `github__editFiles`; it is text. +Write the SVG to `public/assets/websites/logos/.svg` in the clone. ## The pull request -- One branch, `nuxi/showcase-`, and a title such as `feat(showcase): add World Triathlon`. +- One branch, `nuxi/showcase-`, one commit with the three files, and a title such as `feat(showcase): add World Triathlon`. - In the body: what the site is in one sentence, the Nuxt evidence with its link, why you picked the `industry`, and the screenshot. Show the screenshot by publishing the same capture with `publish_media` and pasting its Markdown. - Open it ready for review when the three parts are in. Open it as a draft only when you tried and could not produce one of them, and say in the body which one, what you tried, and what a person needs to add. A draft is not the default for a task you did not finish trying. diff --git a/layers/nuxi/agent/subagents/coder/skills/visual-evidence/SKILL.md b/layers/nuxi/agent/subagents/coder/skills/visual-evidence/SKILL.md index fa06462cc..c83e4271b 100644 --- a/layers/nuxi/agent/subagents/coder/skills/visual-evidence/SKILL.md +++ b/layers/nuxi/agent/subagents/coder/skills/visual-evidence/SKILL.md @@ -6,10 +6,11 @@ A reviewer should see what you saw. A sentence that describes a page is not evid ## What you can and can't capture -- **Production**, the deployed default branch of the repository, such as `https://nuxt.com`. Capture it freely: it is the "before" of every change. -- **Your branch**, only when your instructions name a preview of the repository that you can open. The sandbox has no checkout to run, so without such a preview you have no "after" for a code change. Say so in the pull request in one line, and never present a production capture as the result of your change. +- **Your change**, from the app you run in the sandbox: clone the repository, start its dev server (`run-project` skill) and capture `http://localhost:/`. This is the "after" of a code change. +- **The same page without your change**, as the "before". Capture it from the dev server before you edit anything, so both captures come from the same place. When you didn't, capture the deployed site of the repository, if your instructions name one, and say that the two come from different places. - **Any other public page**: a site for the showcase, a template's demo, a page linked in an issue. -- Capture public pages only. Never a dashboard, an admin page, or a page that shows a person's data. +- When the app can't run in the sandbox, you have no "after" for a code change. Say so in the pull request in one line, and never present a capture of the deployed site as the result of your change. +- Capture public pages and pages of an app you run, with the demo data it starts with. Never a dashboard, an admin page, or a page that shows a person's data. ## Still or clip @@ -22,9 +23,9 @@ Look at every capture you get back before you use it, and check that it shows th ## Putting it where people see it -- Call `publish_media` and paste the Markdown it returns into the pull request body, under a short label that says what the capture shows and where it was taken, such as "Before, production, desktop". For a clip, the Markdown is its URL: keep it alone on its line, with a blank line before and after, and it renders as a video player. +- Call `publish_media` and paste the Markdown it returns into the pull request body, under a short label that says what the capture shows and where it was taken, such as "Before, local dev server, desktop". For a clip, the Markdown is its URL: keep it alone on its line, with a blank line before and after, and it renders as a video player. - Put the URL of every published capture in your reply too. A capture opens for everyone only once the pull request embeds it, so open the pull request before you reply. - When the task has no pull request, such as a request to look at a page, say what the capture shows in your reply, give its URL, and say that the link may not open for someone else: nothing on GitHub embeds it. -- Never commit a capture that is evidence to the branch. Only images the site serves go into the repository, with `commit_assets`. +- Never commit a capture that is evidence to the branch. Only images the site serves go into the repository. - When `publish_media` fails, say in the pull request and in your reply that the capture exists but could not be published. Never write "see the screenshot" for an image that is not there. - A change that only adds something has no "before". Don't pair it with an unrelated capture to fill a table. diff --git a/layers/nuxi/agent/subagents/coder/tools/capture_screenshot.ts b/layers/nuxi/agent/subagents/coder/tools/capture_screenshot.ts index 8b27371ea..cdbbffdd3 100644 --- a/layers/nuxi/agent/subagents/coder/tools/capture_screenshot.ts +++ b/layers/nuxi/agent/subagents/coder/tools/capture_screenshot.ts @@ -7,7 +7,7 @@ export default defineTool({ 'Screenshot a web page in the sandbox browser and look at it: the frame comes back as an image.', 'Saves a 2x WebP at /workspace/captures/.webp: 2560x1440 for the default desktop viewport.', 'Use `cookies`, `hideElements`, `removeElements`, `scripts` and `delay` to get a cookie banner, a chat widget or a splash screen out of the frame, then look at the result and call again until the frame is clean.', - 'Pass the returned `path` to `commit_assets` to add the image to a repository, or to `publish_media` to get its link, for evidence in a pull request or your reply.' + 'To add the image to a repository, copy the file at the returned `path` into the clone. To get its link, for evidence in a pull request or your reply, pass the `path` to `publish_media`.' ].join(' '), inputSchema: screenshotRequest, label: { diff --git a/layers/nuxi/agent/subagents/coder/tools/commit_assets.ts b/layers/nuxi/agent/subagents/coder/tools/commit_assets.ts deleted file mode 100644 index 8b7c31949..000000000 --- a/layers/nuxi/agent/subagents/coder/tools/commit_assets.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { defineTool } from 'eve/tools' -import { z } from 'zod' -import { assertCanUseGithubTools, GITHUB_REPOSITORIES } from '../../../lib/github.js' -import { commitAssets } from '../../../lib/github-files.js' -import { withGithubToken } from '../../../lib/github-token.js' - -export default defineTool({ - description: [ - 'Commit images from the sandbox to a `nuxi/*` branch of a repository, in one commit: a showcase screenshot, a template preview, a blog cover or an illustration someone shared (`receive_attachments`).', - '`github__editFiles` writes text only, so this is how a png, jpg, gif or webp reaches a repository, 4 MB each at most. Commit an SVG, which is text, with `github__editFiles`.', - 'The branch is created from the default branch when it does not exist, so this can be the first or a later commit of the task; open the pull request with the GitHub tools.', - 'Never use it for evidence of a change (before and after captures): those go through `publish_media`, not onto the branch.' - ].join(' '), - inputSchema: z.object({ - repository: z.enum(GITHUB_REPOSITORIES).default(GITHUB_REPOSITORIES[0]).describe('Repository to commit to, as `owner/name`'), - branch: z.string().min(6).max(120).describe('The task\'s branch, such as `nuxi/showcase-world-triathlon`'), - message: z.string().trim().min(8).max(1000).describe('A conventional commit message, such as `feat(showcase): add World Triathlon screenshot`'), - files: z.array(z.object({ - from: z.string().min(1).max(300).describe('Sandbox path, such as /workspace/captures/world-triathlon.webp or /workspace/shared/3f2a9c1e/cover.png'), - to: z.string().min(1).max(300).describe('Repository path, such as public/assets/websites/world-triathlon.webp') - })).min(1).max(10) - }), - async execute({ repository, branch, message, files }, ctx) { - await assertCanUseGithubTools(ctx.session.auth.current) - - const sandbox = await ctx.getSandbox() - const images = await Promise.all(files.map(async ({ from, to }) => { - const bytes = await sandbox.readBinaryFile({ path: from }) - if (!bytes) throw new Error(`No file at "${from}" in the sandbox.`) - return { path: to, bytes } - })) - - return withGithubToken(ctx, repository, token => commitAssets({ repository, token, branch, message, files: images })) - }, - // After `execute`, so TypeScript infers `output`. - label: { - start: ({ branch, files }) => `Commit ${files.length === 1 ? files[0]!.to : `${files.length} images`} to ${branch}`, - complete: (_input, output) => `Committed ${output.paths.join(', ')} to ${output.branch}` - } -}) diff --git a/layers/nuxi/agent/subagents/coder/tools/commit_changes.ts b/layers/nuxi/agent/subagents/coder/tools/commit_changes.ts new file mode 100644 index 000000000..f7518492c --- /dev/null +++ b/layers/nuxi/agent/subagents/coder/tools/commit_changes.ts @@ -0,0 +1,44 @@ +import { defineTool } from 'eve/tools' +import { z } from 'zod' +import { followCommit, MAX_CHANGE_BYTES, MAX_CHANGED_FILES, readStagedChanges } from '../../../lib/clone.js' +import { assertCanUseGithubTools, repositoryInput } from '../../../lib/github.js' +import { commitChanges } from '../../../lib/github-files.js' +import { withGithubToken } from '../../../lib/github-token.js' + +export default defineTool({ + description: [ + 'Commit what you staged in a clone to a branch of its repository on GitHub, in one commit: files you added, modified or deleted, text or binary. This is the only way a change reaches GitHub.', + 'Stage the files of the change with `git add` first, and never run `git commit`: the commit is made on GitHub, and the clone then moves to that branch at that commit. Read `git status` before the call, so the commit holds the whole change and nothing a build generated.', + 'The branch is a new `nuxi/*` branch, which starts at the commit the clone is at, or the branch of an open pull request, never the default branch. A branch that exists must be at the commit the clone is at: fetch it and check it out before you change files for it.', + 'To bring another branch into the branch of a pull request, run `git merge --no-commit --no-ff origin/` in the clone, resolve the conflicts, stage them and call this: it makes the merge commit.', + `One commit holds ${MAX_CHANGED_FILES} files of your own and ${MAX_CHANGE_BYTES / 1024 / 1024} MB at most, of regular files only: an executable file or a symbolic link is refused.`, + 'After the commit, `git status` in the clone lists only what you left out or changed since.' + ].join(' '), + inputSchema: z.object({ + repository: repositoryInput('The repository of the clone, as `owner/name`'), + directory: z.string().startsWith('/').max(300).describe('The root of the clone, such as `/workspace/repos/nuxt/nuxt.com`'), + branch: z.string().min(1).max(120).describe('The task\'s branch, such as `nuxi/fix-header-overflow`, or the branch of the open pull request the task is about'), + message: z.string().trim().min(8).max(1000).describe('A conventional commit message, such as `fix(header): keep the menu inside the viewport`') + }), + async execute({ repository, directory, branch, message }, ctx) { + await assertCanUseGithubTools(ctx.session.auth.current) + + const clone = { sandbox: await ctx.getSandbox(), directory, signal: ctx.abortSignal } + const changes = await readStagedChanges({ ...clone, repository }) + // In the app runtime, with the token of the person who asked: the sandbox, which runs the + // project's code, never holds a GitHub token and no request of its own carries one. + const commit = await withGithubToken(ctx, repository, token => commitChanges({ repository, token, branch, message, ...changes })) + + // The commit is on GitHub whatever happens next, so a clone that can't follow it is a note on + // the result, not a failure the model would answer by committing again. + const stale = await followCommit({ ...clone, branch, commit: commit.commitSha }).then(() => undefined, (error: unknown) => ( + `The clone is still at the commit before this one (${error instanceof Error ? error.message : String(error)}). Before another commit to \`${branch}\`, run \`git fetch origin ${branch}\` and \`git reset --soft FETCH_HEAD\` in it.` + )) + return stale ? { ...commit, note: stale } : commit + }, + // After `execute`, so TypeScript infers `output`. + label: { + start: ({ branch }) => `Commit the changes to ${branch}`, + complete: (_input, output) => `Committed ${output.paths.length + output.deleted.length} ${output.paths.length + output.deleted.length === 1 ? 'file' : 'files'} to ${output.branch}` + } +}) diff --git a/layers/nuxi/agent/subagents/coder/tools/edit_file.ts b/layers/nuxi/agent/subagents/coder/tools/edit_file.ts deleted file mode 100644 index 2156acb9c..000000000 --- a/layers/nuxi/agent/subagents/coder/tools/edit_file.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { disableTool } from 'eve/tools' - -export default disableTool() diff --git a/layers/nuxi/agent/subagents/coder/tools/publish_media.ts b/layers/nuxi/agent/subagents/coder/tools/publish_media.ts index a3cf2d156..9d9ecbc23 100644 --- a/layers/nuxi/agent/subagents/coder/tools/publish_media.ts +++ b/layers/nuxi/agent/subagents/coder/tools/publish_media.ts @@ -1,7 +1,7 @@ import { basename } from 'node:path/posix' import { defineTool } from 'eve/tools' import { z } from 'zod' -import { assertCanUseGithubTools, GITHUB_REPOSITORIES } from '../../../lib/github.js' +import { assertCanUseGithubTools, repositoryInput } from '../../../lib/github.js' import { CAPTURES_DIR } from '../../../lib/media/capture.js' import { publishMedia } from '../../../lib/media/publish.js' @@ -11,10 +11,10 @@ export default defineTool({ 'Use it for evidence: paste the `markdown` into the body of a pull request, an issue or a comment of that repository. For an image it is `![alt](url)`. For a clip it is the URL, which renders as a video player when it stands alone on a line with a blank line before and after.', 'GitHub is checked to serve the URL before it is returned. The URL opens for everyone only once a pull request, an issue or a comment of the repository embeds it. Until then, a person who opens it can get a 404.', 'An attachment can\'t be deleted, so publish captures of public pages only, and only the ones you will use.', - 'Not for images the site serves: those are committed to the branch with `commit_assets`.' + 'Not for images the site serves: copy those into the clone and commit them with `commit_changes`.' ].join(' '), inputSchema: z.object({ - repository: z.enum(GITHUB_REPOSITORIES).default(GITHUB_REPOSITORIES[0]).describe('Repository whose pull request, issue or comment will embed the capture, as `owner/name`'), + repository: repositoryInput('Repository whose pull request, issue or comment will embed the capture, as `owner/name`'), path: z.string().min(1).max(300).describe('A `path` that `capture_screenshot` or `record_video` returned, such as /workspace/captures/showcase-after.webp'), alt: z.string().trim().min(1).max(200).describe('What the capture shows, such as `World Triathlon tile on /showcase, hovered`. A clip has no alt text on GitHub, so say it in the label above the clip too.') }), diff --git a/layers/nuxi/agent/subagents/coder/tools/receive_attachments.ts b/layers/nuxi/agent/subagents/coder/tools/receive_attachments.ts index 7ca105a19..9d9e9957c 100644 --- a/layers/nuxi/agent/subagents/coder/tools/receive_attachments.ts +++ b/layers/nuxi/agent/subagents/coder/tools/receive_attachments.ts @@ -6,7 +6,7 @@ import { handoffStore, receiveAttachments, SHARED_DIR } from '../../../lib/hando export default defineTool({ description: [ `Copy the files the conversation shared for this task into the sandbox, under ${SHARED_DIR}: an image to add to the site, a document to work from. Call it when the message names an attached file.`, - 'Returns each file\'s `path` and size. Look at an image with `read_file`, and commit one with `commit_assets`.', + 'Returns each file\'s `path` and size. Look at an image with `read_file`. To commit a file, copy it into the clone.', 'An empty list means nothing was shared: say so in your reply instead of working without the file.' ].join(' '), inputSchema: z.object({}), diff --git a/layers/nuxi/agent/subagents/coder/tools/write_file.ts b/layers/nuxi/agent/subagents/coder/tools/write_file.ts deleted file mode 100644 index 2156acb9c..000000000 --- a/layers/nuxi/agent/subagents/coder/tools/write_file.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { disableTool } from 'eve/tools' - -export default disableTool() diff --git a/layers/nuxi/agent/tools/open_code_channel.ts b/layers/nuxi/agent/tools/open_code_channel.ts index b49693b17..8fa598bad 100644 --- a/layers/nuxi/agent/tools/open_code_channel.ts +++ b/layers/nuxi/agent/tools/open_code_channel.ts @@ -5,8 +5,9 @@ import slack from '../channels/slack.js' import { canUseGithubTools } from '../lib/github.js' import { resolveContext } from '../lib/identity/context.js' -// Slack only, for the people who can use the `coder` subagent: a code channel is where its coding -// work happens, one channel and one session per task. +// Slack only, for the people who can use the `coder` subagent. Opt-in: `coder` works from the thread +// a request arrives in, and a code channel is for the person who asks for one, or for a task too +// long for a thread. export default defineDynamic(async (ctx) => { const auth = ctx.session.auth.current if (resolveContext(auth).surface !== 'slack') return null @@ -14,8 +15,9 @@ export default defineDynamic(async (ctx) => { return defineTool({ description: [ - 'Move this Slack conversation into a new code channel before handing a coding task on nuxt.com to `coder`, such as a fix, a feature, or an investigation with long output.', - 'Answer in place when one message answers the request. Call it once per request; Slack links the new channel here and invites the person who asked, so afterward reply in one short sentence at most and continue the work in the channel.', + 'Move this Slack conversation into a new code channel: a channel of its own for one coding task, where every message reaches you without a mention.', + 'Call it when the person asks for a code channel. Without that request, hand the task to `coder` from this conversation and reply here: that is the place for a fix, a content change, a question about the code or a capture. The one exception is a task that will clearly take many rounds with the person, such as a feature built across many files or a migration: open a channel for it and say why.', + 'Call it once per request. Slack links the new channel here and invites the person who asked, so afterward reply in one short sentence at most and continue the work in the channel.', 'If it returns unavailable, such as when this already is a code channel, or Slack refuses, continue here and quote the reason without guessing its cause. Don\'t call it again for the same request, but do when the person asks you to try again, since the Slack setup may have changed.' ].join(' '), inputSchema: z.object({ diff --git a/test/unit/admin-mode.spec.ts b/test/unit/admin-mode.spec.ts index ef9bb10a8..cf07f3ded 100644 --- a/test/unit/admin-mode.spec.ts +++ b/test/unit/admin-mode.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { isAdminMode } from '../../layers/nuxi/agent/lib/identity/admin-mode' -import { githubToolsApproval } from '../../layers/nuxi/agent/lib/github' +import { allowedRepository, githubToolsApproval, repositoryInput } from '../../layers/nuxi/agent/lib/github' vi.mock('@vercel/connect', () => ({ getToken: vi.fn(async () => 'app-token') })) @@ -119,6 +119,40 @@ describe('isAdminMode', () => { }) }) +describe('the repositories the coder may write to', () => { + const allowed = ['nuxt/nuxt.com', 'nuxt-modules/*'] + + it('allows a listed repository and every repository of a listed account, whatever the case', () => { + expect(allowedRepository('nuxt/nuxt.com', allowed)).toBe('nuxt/nuxt.com') + expect(allowedRepository('Nuxt/Nuxt.com', allowed)).toBe('nuxt/nuxt.com') + expect(allowedRepository('nuxt-modules/i18n', allowed)).toBe('nuxt-modules/i18n') + expect(allowedRepository('Nuxt-Modules/.github', allowed)).toBe('nuxt-modules/.github') + }) + + it.each([ + ['another repository of an account listed for one', 'nuxt/ui'], + ['an account that only starts like a listed one', 'nuxt-modules-evil/i18n'], + ['a listed account as a repository name', 'evil/nuxt-modules'], + ['the pattern itself', 'nuxt-modules/*'], + ['a third segment', 'nuxt-modules/i18n/extra'], + ['a name that climbs', 'nuxt-modules/..'], + ['a name with a query', 'nuxt-modules/i18n?x=1'], + ['no name', 'nuxt-modules/'], + ['no owner', 'nuxt.com'], + ['something that is not text', null] + ])('refuses %s', (_, repository) => { + expect(allowedRepository(repository, allowed)).toBeUndefined() + }) + + it('gives a tool the default repository, and refuses one outside the list before the tool runs', () => { + const input = repositoryInput('Repository to commit to') + + expect(input.parse(undefined)).toBe('nuxt/nuxt.com') + expect(input.parse('Nuxt/nuxt.com')).toBe('Nuxt/nuxt.com') + expect(() => input.parse('nuxt/ui')).toThrow('Not a repository Nuxi works on: nuxt/nuxt.com.') + }) +}) + describe('githubToolsApproval', () => { beforeEach(() => { vi.stubEnv('GLOBAL_CONFIG', 'https://edge-config.vercel.com/ecfg_test?token=test') @@ -152,45 +186,40 @@ describe('githubToolsApproval', () => { it('asks before a commit to a branch that has an open pull request', async () => { githubWithOnePullRequest() - expect(await decide('github__editFiles', slackUser, { branch: 'nuxi/showcase-world-triathlon', message: 'feat(showcase): add World Triathlon' })).toBe('user-approval') - expect(await decide('commit_assets', slackUser, { repository: 'nuxt/nuxt.com', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') + expect(await decide('commit_changes', slackUser, { repository: 'nuxt/nuxt.com', branch: 'nuxi/showcase-world-triathlon', message: 'feat(showcase): add World Triathlon' })).toBe('user-approval') + expect(await decide('commit_changes', slackUser, { branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') }) it('lets a commit to a branch without a pull request through, and looks up nothing for other tools', async () => { const heads = githubWithOnePullRequest() - expect(await decide('github__editFiles', slackUser, { owner: 'nuxt', repo: 'nuxt.com', branch: 'nuxi/showcase-world-triathlon-assets' })).toBeUndefined() - expect(await decide('commit_assets', slackUser, { branch: 'nuxi/showcase-world-triathlon-assets' })).toBeUndefined() - expect(await decide('github__createBranch', slackUser, { branch: 'nuxi/showcase-world-triathlon' })).toBeUndefined() + expect(await decide('commit_changes', slackUser, { branch: 'nuxi/showcase-world-triathlon-assets' })).toBeUndefined() + expect(await decide('github__createPullRequest', slackUser, { head: 'nuxi/showcase-world-triathlon' })).toBeUndefined() expect(await decide('capture_screenshot', slackUser, { name: 'world-triathlon' })).toBeUndefined() - expect(heads).toEqual(['nuxt:nuxi/showcase-world-triathlon-assets', 'nuxt:nuxi/showcase-world-triathlon-assets']) + expect(heads).toEqual(['nuxt:nuxi/showcase-world-triathlon-assets']) }) - it('asks whatever the case of the repository, which GitHub and the guardrails ignore', async () => { + it('asks whatever the case of the repository, which GitHub ignores', async () => { const heads = githubWithOnePullRequest() - expect(await decide('github__editFiles', slackUser, { owner: 'Nuxt', repo: 'nuxt.com', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') - expect(await decide('github__editFiles', slackUser, { repo: 'NUXT.COM', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') - expect(await decide('commit_assets', slackUser, { repository: 'Nuxt/Nuxt.com', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') - expect(heads).toEqual(Array(3).fill('nuxt:nuxi/showcase-world-triathlon')) + expect(await decide('commit_changes', slackUser, { repository: 'Nuxt/Nuxt.com', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') + expect(heads).toEqual(['nuxt:nuxi/showcase-world-triathlon']) }) it('reads the repository where the tool does, so an input the tool ignores can\'t move the lookup', async () => { githubWithOnePullRequest() - expect(await decide('github__editFiles', slackUser, { repository: 'nuxt/ui', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') - expect(await decide('commit_assets', slackUser, { owner: 'nuxt', repo: 'ui', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') + expect(await decide('commit_changes', slackUser, { owner: 'nuxt', repo: 'ui', branch: 'nuxi/showcase-world-triathlon' })).toBe('user-approval') }) it('denies a commit it can\'t place, instead of letting it through unasked', async () => { const heads = githubWithOnePullRequest() const unplaced = { type: 'denied', reason: 'A commit names a branch of one of these repositories: nuxt/nuxt.com.' } - expect(await decide('github__editFiles', slackUser, { owner: 'nuxt', repo: 'ui', branch: 'nuxi/showcase-world-triathlon' })).toEqual(unplaced) - expect(await decide('github__editFiles', slackUser, { owner: null, branch: 'nuxi/showcase-world-triathlon' })).toEqual(unplaced) - expect(await decide('commit_assets', slackUser, { repository: 'nuxt/ui', branch: 'nuxi/showcase-world-triathlon' })).toEqual(unplaced) - expect(await decide('github__editFiles', slackUser, { message: 'docs: fix typo' })).toEqual(unplaced) - expect(await decide('commit_assets', slackUser)).toEqual(unplaced) + expect(await decide('commit_changes', slackUser, { repository: 'nuxt/ui', branch: 'nuxi/showcase-world-triathlon' })).toEqual(unplaced) + expect(await decide('commit_changes', slackUser, { repository: null, branch: 'nuxi/showcase-world-triathlon' })).toEqual(unplaced) + expect(await decide('commit_changes', slackUser, { message: 'docs: fix typo' })).toEqual(unplaced) + expect(await decide('commit_changes', slackUser)).toEqual(unplaced) expect(heads).toEqual([]) }) @@ -198,13 +227,7 @@ describe('githubToolsApproval', () => { vi.stubGlobal('fetch', async () => Response.json({ message: 'Bad credentials' }, { status: 401 })) vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(await decide('github__editFiles', slackUser, { branch: 'nuxi/fix-typo' })).toBe('user-approval') - }) - - it('still denies a commit where GitHub tools are not offered', async () => { - githubWithOnePullRequest() - - expect(await decide('github__editFiles', { issuer: 'discord', principalId: 'discord:U1', principalType: 'user', attributes: { channel_id: 'C_PUBLIC' } }, { branch: 'nuxi/showcase-world-triathlon' })).toEqual(denied) + expect(await decide('commit_changes', slackUser, { branch: 'nuxi/fix-typo' })).toBe('user-approval') }) it('leaves GitHub tools to their own policy for a human on Slack and in an admin Discord channel', async () => { @@ -222,8 +245,8 @@ describe('githubToolsApproval', () => { }) it('denies GitHub tools to a Slack bot and to anonymous web visitors', async () => { - expect(await decide('github__editFiles', { ...slackUser, principalType: 'service', attributes: { user_id: 'B1', author_type: 'bot' } })).toEqual(denied) - expect(await decide('github__editFiles', { issuer: 'nuxt.com', principalId: 'anon', principalType: 'anonymous' })).toEqual(denied) + expect(await decide('github__updatePullRequest', { ...slackUser, principalType: 'service', attributes: { user_id: 'B1', author_type: 'bot' } })).toEqual(denied) + expect(await decide('github__updatePullRequest', { issuer: 'nuxt.com', principalId: 'anon', principalType: 'anonymous' })).toEqual(denied) }) it('leaves other tools alone in public sessions', async () => { diff --git a/test/unit/nuxi-clone.spec.ts b/test/unit/nuxi-clone.spec.ts new file mode 100644 index 000000000..cab4f531f --- /dev/null +++ b/test/unit/nuxi-clone.spec.ts @@ -0,0 +1,344 @@ +import { execFile, execFileSync } from 'node:child_process' +import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { followCommit, MAX_CHANGE_BYTES, readStagedChanges, type CloneSandbox } from '../../layers/nuxi/agent/lib/clone' +import { commitChanges } from '../../layers/nuxi/agent/lib/github-files' + +/** No signing, no hooks and no identity from the machine that runs the tests. */ +const GIT_ENV = { + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_CONFIG_SYSTEM: '/dev/null', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com' +} + +function bash(command: string, cwd: string) { + return new Promise<{ exitCode: number, stdout: string, stderr: string }>((resolve) => { + execFile('bash', ['-c', command], { cwd, env: { ...process.env, ...GIT_ENV }, maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => { + resolve({ exitCode: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr }) + }) + }) +} + +async function sh(command: string, cwd: string): Promise { + const result = await bash(command, cwd) + if (result.exitCode !== 0) throw new Error(`${command}: ${result.stderr || result.stdout}`) + return result.stdout.trim() +} + +/** + * GitHub's API for `acme/app`, answered by git itself in the repository at `origin`: a commit made + * through it is a real commit there, with the tree and the parents git gives it. `calls` lists + * every request, and `pullRequests` the branches that have an open pull request. + */ +function githubOf(origin: string, pullRequests: string[] = []) { + const calls: string[] = [] + let indexes = 0 + const git = (args: string[], options: { input?: Buffer, index?: string } = {}) => execFileSync('git', args, { + cwd: origin, + input: options.input, + stdio: ['pipe', 'pipe', 'ignore'], + env: { ...process.env, ...GIT_ENV, ...(options.index && { GIT_INDEX_FILE: options.index }) } + }).toString().trim() + const attempt = (args: string[]) => { + try { + return git(args) + } catch { + return undefined + } + } + const headOf = (branch: string) => attempt(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]) + const hasCommit = (sha: string) => attempt(['cat-file', '-e', `${sha}^{commit}`]) !== undefined + const blob = (base64: string) => git(['hash-object', '-w', '--stdin'], { input: Buffer.from(base64, 'base64') }) + /** `base` with each entry written over it, or removed from it when it has no `sha`. */ + function tree(base: string, entries: Array<{ path: string, mode: string, sha: string | null }>) { + const index = join(origin, '.git', `api-index-${indexes++}`) + git(['read-tree', base], { index }) + for (const { path, mode, sha } of entries) { + git(sha === null ? ['update-index', '--force-remove', path] : ['update-index', '--add', '--cacheinfo', `${mode},${sha},${path}`], { index }) + } + return git(['write-tree'], { index }) + } + + const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)) + const method = init?.method ?? 'GET' + const path = url.pathname.replace('/repos/acme/app', '') + const body = init?.body ? JSON.parse(String(init.body)) : undefined + calls.push(`${method} ${path}`) + const fail = (status: number, message: string) => Response.json({ message }, { status }) + + if (method === 'GET' && path === '') return Response.json({ default_branch: 'main' }) + if (method === 'GET' && path === '/pulls') return Response.json(pullRequests.some(branch => url.searchParams.get('head') === `acme:${branch}`) ? [{ number: 7 }] : []) + if (method === 'GET' && path.startsWith('/git/ref/heads/')) { + const sha = headOf(path.slice('/git/ref/heads/'.length)) + return sha ? Response.json({ object: { sha } }) : fail(404, 'Not Found') + } + if (method === 'POST' && path === '/git/refs') { + if (!hasCommit(body.sha)) return fail(422, 'Object does not exist') + git(['update-ref', body.ref, body.sha]) + return Response.json({}) + } + if (method === 'PATCH' && path.startsWith('/git/refs/heads/')) { + const ref = path.slice('/git/'.length) + if (body.force !== false || attempt(['merge-base', '--is-ancestor', ref, body.sha]) === undefined) return fail(422, 'Update is not a fast forward') + git(['update-ref', ref, body.sha]) + return Response.json({}) + } + if (method === 'GET' && path.startsWith('/git/commits/')) return Response.json({ tree: { sha: git(['rev-parse', `${path.slice('/git/commits/'.length)}^{tree}`]) } }) + if (method === 'POST' && path === '/git/blobs') return Response.json({ sha: blob(body.content) }) + if (method === 'POST' && path === '/git/trees') return Response.json({ sha: tree(body.base_tree, body.tree) }) + if (method === 'POST' && path === '/git/commits') { + if (!body.parents.every(hasCommit)) return fail(422, 'Parent does not exist') + const sha = git(['commit-tree', body.tree, ...body.parents.flatMap((parent: string) => ['-p', parent]), '-m', body.message]) + return Response.json({ sha, html_url: `https://github.com/acme/app/commit/${sha}` }) + } + if (method === 'POST' && path === '/graphql') { + const { branch: { branchName }, expectedHeadOid, message, fileChanges } = body.variables.input + if (headOf(branchName) !== expectedHeadOid) return Response.json({ errors: [{ message: `Expected branch to point to "${expectedHeadOid}"` }] }) + const written = tree(expectedHeadOid, [ + ...fileChanges.additions.map((file: { path: string, contents: string }) => ({ path: file.path, mode: '100644', sha: blob(file.contents) })), + ...(fileChanges.deletions ?? []).map((file: { path: string }) => ({ path: file.path, mode: '100644', sha: null })) + ]) + const sha = git(['commit-tree', written, '-p', expectedHeadOid, '-m', [message.headline, message.body].filter(Boolean).join('\n\n')]) + git(['update-ref', `refs/heads/${branchName}`, sha]) + return Response.json({ data: { createCommitOnBranch: { commit: { oid: sha, url: `https://github.com/acme/app/commit/${sha}` } } } }) + } + return fail(404, 'Not Found') + }) as typeof fetch + + return { fetchImpl, calls } +} + +const BINARY = new Uint8Array([0x89, 0x50, 0x4E, 0x47, 0x00, 0xFF, 0x0D, 0x0A, 0x00]) + +describe('a clone in the coder\'s sandbox', () => { + let root: string + /** Stands for GitHub: what `https://github.com/acme/app` answers with, and where a commit made through the API lands. */ + let origin: string + /** The clone, as the coder's `git clone https://github.com/acme/app` leaves it. */ + let directory: string + const repository = 'acme/app' + /** Real git and real directories. */ + const sandbox: CloneSandbox = { + run: ({ command, workingDirectory }) => bash(command, workingDirectory ?? root), + readBinaryFile: ({ path }) => readFile(path).then(bytes => new Uint8Array(bytes), () => null) + } + + async function write(path: string, content: string | Uint8Array) { + await mkdir(dirname(join(directory, path)), { recursive: true }) + await writeFile(join(directory, path), content) + } + + const git = (command: string) => sh(`git ${command}`, directory) + const onGithub = (command: string) => sh(`git ${command}`, origin) + const staged = (override: { repository?: string, directory?: string } = {}) => readStagedChanges({ sandbox, repository, directory, ...override }) + const text = (bytes: Uint8Array) => Buffer.from(bytes).toString() + + /** What `commit_changes` does: read what is staged, commit it through GitHub's API, and put the clone on that commit. */ + async function commit(github: ReturnType, branch: string, message = 'fix: change') { + const made = await commitChanges({ repository, token: 'token', fetchImpl: github.fetchImpl, branch, message, ...await staged() }) + await followCommit({ sandbox, directory, branch, commit: made.commitSha }) + return made + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'nuxi-clone-test-')) + origin = join(root, 'origin') + directory = join(root, 'repos', repository) + await mkdir(join(origin, 'app/pages'), { recursive: true }) + await writeFile(join(origin, '.gitignore'), 'node_modules\n.output\n') + await writeFile(join(origin, 'README.md'), '# App\n') + await writeFile(join(origin, 'package.json'), '{\n "dependencies": {\n "nuxt": "4.0.0"\n }\n}\n') + await writeFile(join(origin, 'app/pages/index.vue'), '\n') + await writeFile(join(origin, 'app/pages/old.vue'), '\n') + await writeFile(join(origin, 'run.sh'), '#!/bin/sh\n') + await chmod(join(origin, 'run.sh'), 0o755) + await sh('git init --quiet --initial-branch=main && git add --all && git commit --quiet -m init', origin) + await sh(`git clone --quiet ${origin} ${directory}`, root) + await git(`config url.${origin}.insteadOf https://github.com/${repository}`) + await git(`config remote.origin.url https://github.com/${repository}`) + }) + afterEach(() => rm(root, { recursive: true, force: true })) + + it('reads what was staged, added, modified or deleted, and nothing else', async () => { + await write('app/pages/index.vue', '\n') + await write('app/pages/[slug] copy.vue', '\n') + await write('app/assets/logo.png', BINARY) + await rm(join(directory, 'app/pages/old.vue')) + await write('README.md', '# Left out\n') + await write('node_modules/pkg/index.js', 'ignored') + await git('add --all app') + + const read = await staged() + + expect(read.parents).toEqual([await git('rev-parse HEAD')]) + expect(read.inherited).toEqual([]) + expect(read.deletions).toEqual(['app/pages/old.vue']) + expect(Object.fromEntries(read.files.map(file => [file.path, file.bytes]))).toEqual({ + 'app/assets/logo.png': BINARY, + 'app/pages/[slug] copy.vue': new Uint8Array(Buffer.from('\n')), + 'app/pages/index.vue': new Uint8Array(Buffer.from('\n')) + }) + }) + + it('reads a file as it was staged, whatever was written to it since', async () => { + await write('README.md', '# Staged\n') + await git('add README.md') + await write('README.md', '# Still being written') + + expect((await staged()).files.map(file => [file.path, text(file.bytes)])).toEqual([['README.md', '# Staged\n']]) + }) + + it.each([ + ['nothing is staged', () => write('README.md', '# Not staged\n'), 'Nothing is staged'], + ['an executable file is staged', () => write('run.sh', '#!/bin/sh\necho hi\n'), '"run.sh" is an executable file'], + ['a symbolic link is staged', () => symlink('README.md', join(directory, 'link.md')), '"link.md" is a symbolic link'], + ['the staged files weigh more than a commit holds', () => write('big.bin', new Uint8Array(MAX_CHANGE_BYTES + 1)), 'a commit holds 10 MB at most'] + ])('refuses when %s', async (name, change, message) => { + await change() + if (name !== 'nothing is staged') await git('add --all') + + await expect(staged()).rejects.toThrow(message) + }) + + it('refuses a directory that is not the root of a clone of that repository', async () => { + await write('README.md', '# Changed\n') + await git('add --all') + + await expect(staged({ repository: 'acme/other' })).rejects.toThrow(`is a clone of https://github.com/acme/app, not of acme/other`) + await expect(staged({ directory: join(directory, 'app') })).rejects.toThrow('is not the root of a clone') + await expect(staged({ directory: root })).rejects.toThrow('is not the root of a clone') + await expect(staged({ directory: join(root, 'missing') })).rejects.toThrow('is not the root of a clone') + }) + + it('commits what was staged to a new `nuxi/*` branch, then only what is staged since', async () => { + const github = githubOf(origin) + const cloned = await git('rev-parse HEAD') + await write('app/pages/index.vue', '\n') + await write('app/assets/logo.png', BINARY) + await rm(join(directory, 'app/pages/old.vue')) + await write('README.md', '# Left out\n') + await git('add --all app') + const index = await git('write-tree') + + const first = await commit(github, 'nuxi/home', 'feat(home): new home\n\nWith a logo.') + + expect(first).toEqual({ + repository, + branch: 'nuxi/home', + createdBranch: true, + commitSha: await onGithub('rev-parse nuxi/home'), + commitUrl: `https://github.com/acme/app/commit/${first.commitSha}`, + paths: ['app/assets/logo.png', 'app/pages/index.vue'], + deleted: ['app/pages/old.vue'] + }) + // The commit on GitHub holds the files exactly as git staged them, on top of the cloned commit. + expect(await onGithub(`rev-parse ${first.commitSha}^{tree}`)).toBe(index) + expect(await onGithub(`rev-list --parents -n 1 ${first.commitSha}`)).toBe(`${first.commitSha} ${cloned}`) + expect(await onGithub(`log -1 --format=%B ${first.commitSha}`)).toBe('feat(home): new home\n\nWith a logo.') + expect(await onGithub('rev-parse main')).toBe(cloned) + + // The clone is on that branch at that commit, with what was left out still there to read. + expect(await git('rev-parse HEAD')).toBe(first.commitSha) + expect(await git('rev-parse --abbrev-ref HEAD')).toBe('nuxi/home') + expect(await git('rev-parse main')).toBe(cloned) + expect(await sh('git status --porcelain', directory)).toBe('M README.md') + await expect(staged()).rejects.toThrow('Nothing is staged') + + await git('add README.md') + const second = await commit(github, 'nuxi/home') + + expect(second).toMatchObject({ createdBranch: false, paths: ['README.md'], deleted: [] }) + expect(await onGithub(`rev-list --parents -n 1 ${second.commitSha}`)).toBe(`${second.commitSha} ${first.commitSha}`) + expect(await sh('git status --porcelain', directory)).toBe('') + }) + + it('resolves the conflict of an open pull request with a merge commit on its branch', async () => { + // A dependency update, and a default branch that moved on since: the same line of + // `package.json`, a file it deleted, a file it changed and an executable file it added. + await sh('git checkout --quiet -b renovate/nuxt && sed -i s/4.0.0/5.0.0/ package.json && echo nuxt@5 > lock.txt && git add --all && git commit --quiet -m bump', origin) + await sh('git checkout --quiet main && sed -i s/4.0.0/4.1.0/ package.json && git rm --quiet app/pages/old.vue && echo "# App 2" > README.md && mkdir scripts && cp run.sh scripts/build.sh && git add --all && git commit --quiet -m move', origin) + const [theirs, mainHead] = [await onGithub('rev-parse renovate/nuxt'), await onGithub('rev-parse main')] + const github = githubOf(origin, ['renovate/nuxt']) + + await git('fetch --quiet origin') + await git('checkout --quiet -B renovate/nuxt origin/renovate/nuxt') + expect((await bash('git merge --no-commit --no-ff origin/main', directory)).exitCode).toBe(1) + await expect(staged()).rejects.toThrow('"package.json" still has a merge conflict') + + // Neither side's line, so the file is in neither commit. + await write('package.json', '{\n "dependencies": {\n "nuxt": "5.0.1"\n }\n}\n') + await git('add package.json') + const index = await git('write-tree') + const merge = await commit(github, 'renovate/nuxt', 'chore: merge main into renovate/nuxt') + + // One commit on the pull request's branch, with both parents and the tree git staged. + expect(await onGithub('rev-parse renovate/nuxt')).toBe(merge.commitSha) + expect(await onGithub(`rev-list --parents -n 1 ${merge.commitSha}`)).toBe(`${merge.commitSha} ${theirs} ${mainHead}`) + expect(await onGithub(`rev-parse ${merge.commitSha}^{tree}`)).toBe(index) + expect(await onGithub(`ls-tree ${merge.commitSha} scripts/build.sh`)).toMatch(/^100755 blob /) + expect(await onGithub('rev-parse main')).toBe(mainHead) + // Only the resolved file is sent: GitHub has the files of the merged commit. + expect(merge).toMatchObject({ createdBranch: false, paths: ['package.json'], deleted: ['app/pages/old.vue'] }) + expect(github.calls.filter(call => call === 'POST /git/blobs')).toHaveLength(1) + + // The merge is over in the clone too. + expect(await git('rev-parse HEAD')).toBe(merge.commitSha) + expect(await sh('git status --porcelain', directory)).toBe('') + expect((await bash('git rev-parse --verify --quiet MERGE_HEAD', directory)).exitCode).not.toBe(0) + }) + + it.each([ + ['the default branch', 'main', '`main` is the default branch of acme/app'], + ['a branch that is neither `nuxi/*` nor the branch of an open pull request', 'v3', '`v3` is not a `nuxi/*` branch and has no open pull request'], + ['a new branch outside `nuxi/*`', 'feat/home', 'has no open pull request'], + ['a branch name that climbs', 'nuxi/../main', 'is not a branch name this tool takes'], + ['a branch name that is a path of the API', 'nuxi/x?ref=main', 'is not a branch name this tool takes'] + ])('writes nothing to %s', async (_, branch, message) => { + await onGithub('branch v3') + const github = githubOf(origin, ['renovate/nuxt']) + await write('README.md', '# Changed\n') + await git('add README.md') + + await expect(commit(github, branch)).rejects.toThrow(message) + expect(github.calls.filter(call => !call.startsWith('GET '))).toEqual([]) + expect(await onGithub('rev-parse v3')).toBe(await onGithub('rev-parse main')) + }) + + it('writes nothing to a branch that is not at the commit the clone is at, where whole files would undo its commits', async () => { + await sh('git checkout --quiet -b nuxi/home && echo "# Theirs" > README.md && git commit --quiet -am theirs && git checkout --quiet main', origin) + const head = await onGithub('rev-parse nuxi/home') + const github = githubOf(origin) + await write('app/pages/index.vue', '\n') + await git('add --all') + + await expect(commit(github, 'nuxi/home')).rejects.toThrow(`\`nuxi/home\` is at ${head.slice(0, 8)} on GitHub, and the clone is at ${(await git('rev-parse HEAD')).slice(0, 8)}. Nothing was committed.`) + expect(github.calls.filter(call => !call.startsWith('GET '))).toEqual([]) + expect(await onGithub('rev-parse nuxi/home')).toBe(head) + }) + + it('says what to undo when the clone is at a commit made in the sandbox, which GitHub does not have', async () => { + const github = githubOf(origin) + await write('README.md', '# Committed in the sandbox\n') + await sh('git commit --quiet -am local', directory) + await write('app/pages/index.vue', '\n') + await git('add --all') + + await expect(commit(github, 'nuxi/home')).rejects.toThrow('Nothing was committed. GitHub must have the commit the clone is at') + expect(await bash('git rev-parse --verify --quiet refs/heads/nuxi/home', origin)).toMatchObject({ exitCode: 1 }) + }) + + it('does not follow a branch that is not at the new commit', async () => { + const cloned = await git('rev-parse HEAD') + await onGithub('branch nuxi/elsewhere') + + await expect(followCommit({ sandbox, directory, branch: 'nuxi/elsewhere', commit: 'f'.repeat(40) })).rejects.toThrow('not at the new commit') + expect(await git('rev-parse HEAD')).toBe(cloned) + expect(await git('rev-parse --abbrev-ref HEAD')).toBe('main') + }) +}) diff --git a/test/unit/nuxi-media.spec.ts b/test/unit/nuxi-media.spec.ts index e37f9fc68..792be633c 100644 --- a/test/unit/nuxi-media.spec.ts +++ b/test/unit/nuxi-media.spec.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { captureScreenshot, captureUrlError, hideElementsExpression, parseCookie, recordVideo, removeElementsExpression, stepCommand } from '../../layers/nuxi/agent/lib/media/capture' import { mediaTypeFromPath, sniffMediaType } from '../../layers/nuxi/agent/lib/media/media-type' import { publishMedia } from '../../layers/nuxi/agent/lib/media/publish' -import { commitAssets, MAX_COMMIT_BYTES, openPullRequestOf } from '../../layers/nuxi/agent/lib/github-files' +import { openPullRequestOf } from '../../layers/nuxi/agent/lib/github-files' import { handoffStore, localStore, MAX_SHARED_BYTES, receiveAttachments, shareAttachments, type HandoffStore } from '../../layers/nuxi/agent/lib/handoff' const ascii = (text: string) => [...text].map(char => char.charCodeAt(0)) @@ -40,20 +40,25 @@ describe('captureUrlError', () => { expect(captureUrlError('https://internal.example.com/')).toBeNull() }) + it('accepts a server running in the sandbox itself', () => { + expect(captureUrlError('http://localhost:3000/docs')).toBeNull() + expect(captureUrlError('http://localhost./')).toBeNull() + expect(captureUrlError('http://127.0.0.1:5173/')).toBeNull() + expect(captureUrlError('http://[::1]:3000/')).toBeNull() + }) + it.each([ 'triathlon.org', 'about:blank', 'file:///etc/passwd', 'javascript:alert(1)', 'https://user:pass@example.com/', - 'http://localhost:3000/', - 'http://localhost./', 'http://app.localhost/', 'http://db.internal/', - 'http://127.0.0.1/', - // The URL parser normalises these to 127.0.0.1. - 'http://2130706433/', - 'http://0x7f.1/', + 'http://0.0.0.0:3000/', + // The URL parser normalises these to 10.0.0.1. + 'http://167772161/', + 'http://0xa.1/', 'http://10.1.2.3/', 'http://172.16.0.1/', 'http://172.31.255.255/', @@ -67,7 +72,8 @@ describe('captureUrlError', () => { 'http://192.0.0.8/', 'http://224.0.0.1/', 'http://255.255.255.255/', - 'http://[::1]/' + 'http://[fd00::1]/', + 'http://[::ffff:10.0.0.1]/' ])('rejects %s', (url) => { expect(captureUrlError(url)).toEqual(expect.any(String)) }) @@ -155,7 +161,7 @@ describe('recordVideo', () => { }) it('keeps nothing of a recording whose step leaves the public page', async () => { - const urls = ['https://nuxt.com/', 'http://127.0.0.1:3000/admin'] + const urls = ['https://nuxt.com/', 'http://10.0.0.1:3000/admin'] const commands: string[] = [] const sandbox = { // What the agent-browser CLI prints with `--json`. @@ -166,7 +172,7 @@ describe('recordVideo', () => { readBinaryFile: async () => null } - await expect(recordVideo(sandbox, { name: 'menu', steps: [{ action: 'click', selector: '#admin' }] })).rejects.toThrow('"127.0.0.1" is a local or private address') + await expect(recordVideo(sandbox, { name: 'menu', steps: [{ action: 'click', selector: '#admin' }] })).rejects.toThrow('"10.0.0.1" is a local or private address') expect(commands.some(command => command.includes('record stop'))).toBe(true) expect(commands.at(-1)).toContain('rm -f /workspace/captures/menu.webm') expect(commands.some(command => command.includes('ffmpeg'))).toBe(false) @@ -330,82 +336,6 @@ describe('openPullRequestOf', () => { }) }) -describe('commitAssets', () => { - const API = 'https://api.github.com' - const REFS = `${API}/repos/nuxt/ui/git` - const file = { path: 'public/assets/websites/world-triathlon.webp', bytes: WEBP } - const commit = { oid: 'c0ffee', url: 'https://github.com/nuxt/ui/commit/c0ffee' } - const committed = { [`POST ${API}/graphql`]: { data: { createCommitOnBranch: { commit } } } } - const input = { repository: 'nuxt/ui', token: 'token', branch: 'nuxi/showcase', message: 'feat: add screenshot', files: [file] } - - it('commits onto the head of an existing branch', async () => { - const { fetchImpl, requests } = fakeGithub({ ...committed, [`GET ${REFS}/ref/heads/nuxi/showcase`]: { object: { sha: 'branch-sha' } } }) - const message = 'feat(showcase): add World Triathlon screenshot\n\nCaptured from https://triathlon.org.' - - expect(await commitAssets({ ...input, message, fetchImpl })).toEqual({ - repository: 'nuxt/ui', - branch: 'nuxi/showcase', - createdBranch: false, - commitSha: 'c0ffee', - commitUrl: commit.url, - paths: [file.path] - }) - expect(requests.map(request => request.call)).toEqual([`GET ${REFS}/ref/heads/nuxi/showcase`, `POST ${API}/graphql`]) - expect(JSON.parse(String(requests[1]!.body)).variables.input).toEqual({ - branch: { repositoryNameWithOwner: 'nuxt/ui', branchName: 'nuxi/showcase' }, - expectedHeadOid: 'branch-sha', - message: { headline: 'feat(showcase): add World Triathlon screenshot', body: 'Captured from https://triathlon.org.' }, - fileChanges: { additions: [{ path: file.path, contents: Buffer.from(WEBP).toString('base64') }] } - }) - }) - - it('creates a missing branch from the default branch first', async () => { - const { fetchImpl, requests } = fakeGithub({ - ...committed, - [`GET ${API}/repos/nuxt/ui`]: { default_branch: 'v4' }, - [`GET ${REFS}/ref/heads/v4`]: { object: { sha: 'v4-sha' } }, - [`POST ${REFS}/refs`]: {} - }) - - expect(await commitAssets({ ...input, fetchImpl })).toMatchObject({ createdBranch: true }) - expect(JSON.parse(String(requests[3]!.body))).toEqual({ ref: 'refs/heads/nuxi/showcase', sha: 'v4-sha' }) - expect(JSON.parse(String(requests[4]!.body)).variables.input).toMatchObject({ expectedHeadOid: 'v4-sha', message: { headline: 'feat: add screenshot' } }) - }) - - it('commits a blog cover of 1.5 MB', async () => { - const { fetchImpl, requests } = fakeGithub({ ...committed, [`GET ${REFS}/ref/heads/nuxi/showcase`]: { object: { sha: 'branch-sha' } } }) - const cover = { path: 'public/assets/blog/v4.7.png', bytes: new Uint8Array([...PNG, ...new Uint8Array(1_500_000)]) } - - expect(await commitAssets({ ...input, files: [cover], fetchImpl })).toMatchObject({ paths: [cover.path] }) - expect(JSON.parse(String(requests[1]!.body)).variables.input.fileChanges.additions[0].contents).toBe(Buffer.from(cover.bytes).toString('base64')) - }) - - it('reports why GitHub refused the commit', async () => { - const { fetchImpl } = fakeGithub({ - [`GET ${REFS}/ref/heads/nuxi/showcase`]: { object: { sha: 'branch-sha' } }, - [`POST ${API}/graphql`]: { data: { createCommitOnBranch: null }, errors: [{ message: 'Expected branch to point to "x"' }] } - }) - - await expect(commitAssets({ ...input, fetchImpl })).rejects.toThrow('Expected branch to point to "x"') - }) - - it.each([ - ['the default branch', { branch: 'main' }], - ['a branch that only contains nuxi/', { branch: 'feat/nuxi/x' }], - ['a branch that climbs out of nuxi/', { branch: 'nuxi/../main' }], - ['a path that climbs out of the repository', { files: [{ path: 'public/../../x.webp', bytes: WEBP }] }], - ['a text file', { files: [{ path: '.github/workflows/ci.yml', bytes: TEXT }] }], - ['text renamed to an image', { files: [{ path: 'public/x.webp', bytes: TEXT }] }], - ['a video', { files: [{ path: 'public/demo.mp4', bytes: MP4 }] }], - ['an image over the size limit', { files: [{ path: 'public/x.webp', bytes: new Uint8Array([...WEBP, ...new Uint8Array(MAX_COMMIT_BYTES)]) }] }] - ])('sends nothing to GitHub for %s', async (_, override) => { - const { fetchImpl, requests } = fakeGithub({}) - - await expect(commitAssets({ ...input, ...override, fetchImpl })).rejects.toThrow() - expect(requests).toEqual([]) - }) -}) - describe('attachment hand-off', () => { const ATTACHED = '/workspace/.eve/attachments' let directory: string