From 99d861f92649f3bb792627861094ab86296aa2fd Mon Sep 17 00:00:00 2001 From: Yash Dewasthale Date: Thu, 19 Nov 2026 12:58:59 +0530 Subject: [PATCH] fix(nova): separate GitHub branch discovery from local worktrees Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../server/src/nova/workspaces/README.md | 21 ++ .../server/src/nova/workspaces/git.test.ts | 59 +++- .../server/src/nova/workspaces/git.ts | 96 ++++++- .../server/src/nova/workspaces/server.test.ts | 20 ++ .../server/src/nova/workspaces/server.ts | 6 + .../[projectId]/branches/route.test.ts | 45 +++ .../[projectId]/branches/route.ts | 23 ++ .../[sessionId]/source-file/route.test.ts | 48 ++++ .../sessions/[sessionId]/source-file/route.ts | 23 ++ apps/web/app/api/nova/sessions/route.ts | 7 +- apps/web/modules/nova-web/api.ts | 19 +- .../components/git-workspace-controls.tsx | 27 +- .../components/git-workspace-toolbar.tsx | 271 +++++++++++++----- apps/web/modules/nova-web/git-workspace.ts | 15 + apps/web/modules/nova-web/local-workspace.ts | 4 +- apps/web/modules/nova-web/nova-app.tsx | 30 +- .../web/modules/nova-web/use-git-workspace.ts | 47 ++- .../nova-web/workspace-discovery.test.ts | 111 +++++++ .../modules/nova-web/workspace-discovery.ts | 27 ++ .../nova/local-projects/github-source.test.ts | 33 +++ .../nova/local-projects/github-source.ts | 20 ++ .../nova/local-projects/github.test.ts | 100 +++++++ .../web/modules/nova/local-projects/github.ts | 79 ++++- apps/web/modules/nova/local-projects/pack.ts | 27 +- .../modules/nova/local-projects/service.ts | 4 +- .../nova/local-projects/worktree-binding.ts | 4 +- .../modules/nova/sandbox/e2b-checkout.test.ts | 23 ++ apps/web/modules/nova/sandbox/e2b-checkout.ts | 5 +- .../nova/sandbox/github-checkout.test.ts | 61 ++++ apps/web/modules/nova/sandbox/service.ts | 23 +- .../nova/sessions/github-source.test.ts | 54 ++++ apps/web/modules/nova/sessions/service.ts | 23 +- apps/web/modules/nova/sessions/turn.ts | 14 +- packages/nova/contracts.ts | 5 + 34 files changed, 1243 insertions(+), 131 deletions(-) create mode 100644 apps/web/app/api/nova/local-projects/[projectId]/branches/route.test.ts create mode 100644 apps/web/app/api/nova/local-projects/[projectId]/branches/route.ts create mode 100644 apps/web/app/api/nova/sessions/[sessionId]/source-file/route.test.ts create mode 100644 apps/web/app/api/nova/sessions/[sessionId]/source-file/route.ts create mode 100644 apps/web/modules/nova-web/workspace-discovery.test.ts create mode 100644 apps/web/modules/nova-web/workspace-discovery.ts create mode 100644 apps/web/modules/nova/local-projects/github-source.test.ts create mode 100644 apps/web/modules/nova/local-projects/github-source.ts create mode 100644 apps/web/modules/nova/local-projects/github.test.ts create mode 100644 apps/web/modules/nova/sandbox/e2b-checkout.test.ts create mode 100644 apps/web/modules/nova/sandbox/github-checkout.test.ts create mode 100644 apps/web/modules/nova/sessions/github-source.test.ts diff --git a/apps/supercode-cli/server/src/nova/workspaces/README.md b/apps/supercode-cli/server/src/nova/workspaces/README.md index a226a508..63c7c242 100644 --- a/apps/supercode-cli/server/src/nova/workspaces/README.md +++ b/apps/supercode-cli/server/src/nova/workspaces/README.md @@ -94,6 +94,7 @@ engine-managed clone location, never a browser-supplied path. | `/lookup` | `{threadId}` | `{workspace}` (or `{workspace:null}`) | | `/clone` | `{repositoryFullName:"owner/name",confirmed:true}` | `{project}` | | `/branches` | `{projectId,fetch?:boolean}` | `{branches}` | +| `/worktrees` | `{projectId}` | `{worktrees}` | | `/ignored-files` | `{projectId}` | `{paths}` (names only, no contents) | | `/create` | `{projectId,threadId,sourceRef,mode,newBranch?,copyIgnored?}` | `{workspace}` | | `/get` | `{workspaceId}` | `{workspace}` | @@ -116,6 +117,26 @@ Branch listing is local unless `fetch:true` explicitly requests a refresh from the configured remotes. Ignored-file listing returns only copy-candidate names for user consent, not file bytes. +`/worktrees` reads Git's actual local `worktree list --porcelain -z` for an +approved project, not browser cache. Each entry contains +`{path,branch,head,main,locked,prunable,workspaceId?,threadId?}`. `branch` is the +short local branch name or null for detached HEAD; `head` is the commit ID +(all zeroes for an unborn branch). `main` identifies Git's primary checkout, +not necessarily the approved project directory. Bare entries have an empty +`head` and null branch. Paths, including spaces and newlines, are preserved. +The companion remains required for local discovery and uses the same pairing, +exact-Origin, Host and project authorization as other routes. + +External linked worktrees, including missing/prunable entries, are discovery +only: listing never registers them, reads their files, or grants write access. +Only an existing, validated engine binding adds `workspaceId` and `threadId`; +stale or ambiguous bindings omit both. Listing does not attach a checkout to a +new thread. Reuse a known thread deliberately, or create a separate worktree. +Discovery is limited to 256 worktrees, 1 MiB of Git output, and 1024 immediate +registry entries; it never scans home directories. Limit failures return 409 +rather than a misleading partial list. Git failures also return a sanitized +409 rather than an empty successful list. + Use `/lookup` after pairing again to recover a thread's existing workspace. Workspace IDs may be persisted as nonsecret browser state; bearer tokens should not be persisted beyond the browser session. Lookup remains authenticated and diff --git a/apps/supercode-cli/server/src/nova/workspaces/git.test.ts b/apps/supercode-cli/server/src/nova/workspaces/git.test.ts index d6e8b261..2dbb6e8d 100644 --- a/apps/supercode-cli/server/src/nova/workspaces/git.test.ts +++ b/apps/supercode-cli/server/src/nova/workspaces/git.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { promisify } from "node:util" -import { NovaWorkspaceGit } from "./git" +import { NovaWorkspaceGit, parseGitWorktrees } from "./git" import type { PublishInput } from "./git" const exec = promisify(execFile) @@ -49,6 +49,63 @@ async function fixture(options: { unborn?: boolean; publishPr?: ConstructorParam const publication = (workspaceId: string, extra: Partial = {}): PublishInput => ({ workspaceId, action: "commit", branch: "feature/test", baseBranch: "main", remote: "origin", message: "selected changes", files: ["a.txt"], ...extra }) describe("NovaWorkspaceGit", () => { + test("discovers real external, detached, locked and missing worktrees without registering them", async () => { + const f = await fixture() + const external = join(f.root, "external tree with spaces\nand newline") + const missing = join(f.root, "missing tree") + await git(f.repo, "worktree", "add", "-b", "external/topic", external) + await git(f.repo, "worktree", "lock", "--reason", "keep this tree", external) + await git(f.repo, "worktree", "add", "--detach", missing) + await fs.rm(missing, { recursive: true }) + const managed = await f.create() + const head = await git(f.repo, "rev-parse", "HEAD") + const trees = await f.engine.worktrees(f.project.id) + expect(trees).toHaveLength(4) + expect(trees[0]).toEqual({ path: f.repo, branch: "main", head, main: true, locked: false, prunable: false }) + expect(trees.find(tree => tree.path === external)).toEqual({ path: external, branch: "external/topic", head, main: false, locked: true, prunable: false }) + expect(trees.find(tree => tree.path === missing)).toEqual({ path: missing, branch: null, head, main: false, locked: false, prunable: true }) + expect(trees.find(tree => tree.path === managed.path)).toMatchObject({ branch: null, workspaceId: managed.id, threadId: managed.threadId }) + expect(await f.engine.lookup("external")).toBeNull() + await expect(f.engine.get(external)).rejects.toThrow("Invalid registry ID") + await expect(f.engine.worktrees("unknown")).rejects.toThrow("Unknown project") + const linkedEngine = new NovaWorkspaceGit({ roots: [external], home: f.home }) + const linkedProject = (await linkedEngine.listProjects())[0]! + const linkedTrees = await linkedEngine.worktrees(linkedProject.id) + expect(linkedTrees[0]?.main).toBe(true) + expect(linkedTrees.find(tree => tree.path === external)?.main).toBe(false) + expect(linkedTrees.every(tree => !tree.workspaceId && !tree.threadId)).toBe(true) + }) + + test("omits stale and ambiguous engine metadata without hiding Git entries", async () => { + const f = await fixture() + const managed = await f.create() + const bindingFile = join(f.home, ".nova/worktrees", "binding-" + managed.id + ".json") + const binding = JSON.parse(await fs.readFile(bindingFile, "utf8")) + await fs.writeFile(bindingFile, JSON.stringify({ ...binding, gitDir: "/stale" })) + expect((await f.engine.worktrees(f.project.id)).find(tree => tree.path === managed.path)?.workspaceId).toBeUndefined() + await fs.rm(managed.path, { recursive: true }) + expect((await f.engine.worktrees(f.project.id)).find(tree => tree.path === managed.path)).toMatchObject({ prunable: true }) + await f.create("current-one", "current") + await f.create("current-two", "current") + await f.create("current-three", "current") + const current = (await f.engine.worktrees(f.project.id))[0]! + expect(current.workspaceId).toBeUndefined() + expect(current.threadId).toBeUndefined() + }) + + test("lists unborn repositories and rejects malformed or oversized NUL porcelain", async () => { + const f = await fixture({ unborn: true }) + expect(await f.engine.worktrees(f.project.id)).toEqual([{ path: f.repo, branch: "main", head: "0".repeat(40), main: true, locked: false, prunable: false }]) + const block = "worktree /safe path\0HEAD " + "a".repeat(40) + "\0detached\0\0" + expect(parseGitWorktrees(block)[0]?.branch).toBeNull() + expect(parseGitWorktrees("worktree /bare\0bare\0\0")[0]?.head).toBe("") + for (const malformed of ["", block.slice(0, -1), block + block, block.replace("/safe path", "relative"), block.replace("detached", "branch refs/heads/main\0detached"), block.replace("detached", "locked"), block.replace("detached", "unknown value"), block.replace("HEAD ", "HEAD not-a-hash")]) { + expect(() => parseGitWorktrees(malformed)).toThrow("Invalid Git worktree listing") + } + expect(() => parseGitWorktrees("x".repeat(1024 * 1024 + 1))).toThrow("discovery limits") + expect(() => parseGitWorktrees(Array.from({ length: 257 }, (_, i) => block.replace("/safe path", "/tree-" + i)).join(""))).toThrow("discovery limits") + }) + test("creates an explicitly requested new working branch without switching the original checkout", async () => { const f = await fixture() const workspace = await f.create("named-worktree", "worktree", { newBranch: "nova/new-feature" }) diff --git a/apps/supercode-cli/server/src/nova/workspaces/git.ts b/apps/supercode-cli/server/src/nova/workspaces/git.ts index a2013bb7..0df6af8f 100644 --- a/apps/supercode-cli/server/src/nova/workspaces/git.ts +++ b/apps/supercode-cli/server/src/nova/workspaces/git.ts @@ -16,13 +16,50 @@ function canonical(path: string): string { } export type Project = { id: string; name: string; path: string; repositoryFullName: string | null; isGit: boolean } export type Branch = { name: string; ref: string; sha: string; remote: boolean; checkedOut: boolean; current: boolean } +export type Worktree = { path: string; branch: string | null; head: string; main: boolean; locked: boolean; prunable: boolean; workspaceId?: string; threadId?: string } +const MAX_WORKTREES = 256 +const MAX_WORKTREE_BYTES = 1024 * 1024 + +export function parseGitWorktrees(output: string): Worktree[] { + const invalid = () => { throw new Error("Invalid Git worktree listing") } + if (Buffer.byteLength(output) > MAX_WORKTREE_BYTES) throw new Error("Git worktree listing exceeds discovery limits") + if (!output || !output.endsWith("\0\0")) return invalid() + const result: Worktree[] = [] + const paths = new Set() + for (const block of output.slice(0, -2).split("\0\0")) { + if (result.length >= MAX_WORKTREES) throw new Error("Git worktree listing exceeds discovery limits") + const fields = block.split("\0") + const first = fields.shift()! + if (!first.startsWith("worktree ")) return invalid() + const path = first.slice(9) + if (!isAbsolute(path) || paths.has(path)) return invalid() + paths.add(path) + const values = new Map() + for (const field of fields) { + const space = field.indexOf(" ") + const key = space < 0 ? field : field.slice(0, space) + const value = space < 0 ? "" : field.slice(space + 1) + if (!["HEAD", "branch", "detached", "bare", "locked", "prunable"].includes(key) || values.has(key)) return invalid() + if (["bare", "detached"].includes(key) && value) return invalid() + values.set(key, value) + } + const head = values.get("HEAD") ?? "" + const branch = values.get("branch") + if (values.has("bare")) { + if (head || branch !== undefined || values.has("detached")) return invalid() + } else if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head) || (branch === undefined) === !values.has("detached")) return invalid() + if (branch !== undefined && (!branch.startsWith("refs/heads/") || branch.length <= 11 || /[\x00-\x20\x7f]/.test(branch))) return invalid() + result.push({ path, branch: branch?.slice(11) ?? null, head, main: result.length === 0, locked: values.has("locked"), prunable: values.has("prunable") }) + } + return result +} export type Workspace = { id: string; projectId: string; threadId: string; path: string; sourceRef: string; baseSha: string; branch: string | null; mode: "current" | "worktree" } export type PublishInput = { workspaceId: string; action: "commit" | "push" | "pr"; branch: string; baseBranch: string; remote: string; message: string; files: string[]; title?: string; body?: string } export type Preview = PublishInput & { id: string; head: string; diff: string; expiresAt: string } type StoredPreview = { preview: Preview; fingerprint: string; remoteHeads: string; indexTree?: string; receipt?: { commitSha: string; branch: string; prUrl?: string }; stage?: "committed" | "attached" | "pushed" | "pr-started" | "done" } type PrPublisher = (input: { cwd: string; branch: string; baseBranch: string; remote: string; title: string; body: string }) => Promise -async function run(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: Buffer, timeout = 30_000) { +async function run(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: Buffer, timeout = 30_000, maxBuffer = 16 * 1024 * 1024) { const config = ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null"] const environment = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LITERAL_PATHSPECS: args[0] === "check-ignore" ? "0" : "1", ...env } const filters = await exec("git", [...config, "-C", cwd, "config", "--name-only", "--get-regexp", "^filter\\."], { env: environment, timeout: 5000, maxBuffer: 1024 * 1024 }).then(result => result.stdout).catch(error => { if (error.code === 1) return ""; throw error }) @@ -30,7 +67,7 @@ async function run(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: const match = key.match(/^filter\.(.+)\.(?:clean|smudge|process|required)$/) if (match) for (const attribute of ["clean", "smudge", "process", "required"]) config.push("-c", "filter." + match[1] + "." + attribute + "=" + (attribute === "required" ? "false" : "")) } - const pending = exec("git", [...config, "-C", cwd, ...args], { env: environment, timeout, maxBuffer: 16 * 1024 * 1024 }) + const pending = exec("git", [...config, "-C", cwd, ...args], { env: environment, timeout, maxBuffer }) pending.child.stdin?.end(input) const result = await pending return result.stdout.replace(/\n$/, "") @@ -167,6 +204,61 @@ export class NovaWorkspaceGit { }) } + async worktrees(projectId: string): Promise { + const project = await this.project(projectId) + if (!project.isGit) return [] + if (await fs.realpath(project.path) !== project.path) throw new Error("Project root or ancestors cannot be symlinks") + let output: string + try { + output = await run(project.path, ["worktree", "list", "--porcelain", "-z"], undefined, undefined, 10_000, MAX_WORKTREE_BYTES) + } catch (error) { + if ((error as { code?: string }).code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") throw new Error("Git worktree listing exceeds discovery limits") + throw error + } + const worktrees = parseGitWorktrees(output) + if (!await exists(this.registry)) return worktrees + const directory = await fs.opendir(this.registry).catch(error => { + if (error.code === "ENOENT") return null + throw error + }) + if (!directory) return worktrees + let entries = 0 + const ambiguous = new Set() + for await (const entry of directory) { + if (++entries > 1024) throw new Error("Workspace registry exceeds discovery limits") + if (!entry.isFile() || !/^[0-9a-f]{32}\.json$/.test(entry.name)) continue + const id = entry.name.slice(0, -5) + const stat = await fs.lstat(join(this.registry, entry.name)) + if (!stat.isFile() || stat.size > 64 * 1024) continue + let workspace: Workspace + try { + const manifest = await this.load(id) + if (manifest.projectId !== projectId || !/^[a-zA-Z0-9_-]{1,128}$/.test(manifest.threadId) || hash(projectId + ":" + manifest.threadId).slice(0, 32) !== id) continue + if (!["current", "worktree"].includes(manifest.mode)) continue + const candidate = worktrees.find(tree => tree.path === manifest.path && !tree.prunable) + if (!candidate) continue + const bindingStat = await fs.lstat(join(this.registry, "binding-" + id + ".json")) + if (!bindingStat.isFile() || bindingStat.size > 64 * 1024) continue + const binding = await this.load("binding-" + id) + if (binding.projectId !== projectId || binding.threadId !== manifest.threadId || binding.mode !== manifest.mode || binding.sourceRef !== manifest.sourceRef) continue + workspace = await this.get(id) + } catch { + continue + } + const tree = worktrees.find(tree => tree.path === workspace.path)! + if (ambiguous.has(tree.path)) continue + if (tree.workspaceId) { + ambiguous.add(tree.path) + delete tree.workspaceId + delete tree.threadId + continue + } + tree.workspaceId = workspace.id + tree.threadId = workspace.threadId + } + return worktrees + } + async fetchBranches(projectId: string): Promise { const project = await this.project(projectId) if (!project.isGit) return [] diff --git a/apps/supercode-cli/server/src/nova/workspaces/server.test.ts b/apps/supercode-cli/server/src/nova/workspaces/server.test.ts index 846328cb..e614b21b 100644 --- a/apps/supercode-cli/server/src/nova/workspaces/server.test.ts +++ b/apps/supercode-cli/server/src/nova/workspaces/server.test.ts @@ -18,6 +18,7 @@ function fixture() { cloneRepository: call("cloneRepository", { id: "cloned-project" }), lookup: call("lookup", { id: "workspace" }), branches: call("branches", ["main"]), + worktrees: call("worktrees", [{ path: "/explicit-root", branch: "main", head: "a".repeat(40), main: true, locked: false, prunable: false }]), fetchBranches: call("fetchBranches", ["main", "origin/topic"]), ignoredFiles: call("ignoredFiles", [".env.local"]), create: call("create", { id: "workspace" }), @@ -47,6 +48,24 @@ function fixture() { } describe("workspace companion protocol", () => { + test("protects discovery with pairing, exact origin and strict project-only input", async () => { + const f = fixture() + expect((await f.post("/worktrees", { projectId: "project" })).status).toBe(401) + const { token } = await f.pair() + expect((await f.post("/worktrees", { projectId: "project" }, token, otherOrigin)).status).toBe(403) + expect((await f.post("/worktrees", { projectId: "project" }, token, origin + "/")).status).toBe(403) + for (const body of [{}, { projectId: "project", path: "/arbitrary" }, { projectId: "project", threadId: "new-thread" }, { projectId: 42 }]) { + expect((await f.post("/worktrees", body, token)).status).toBe(400) + } + expect(f.calls).toEqual([]) + f.service.worktrees = async () => { throw new Error("Unknown project") } + const unknown = await f.post("/worktrees", { projectId: "unknown" }, token) + expect(unknown.status).toBe(409) + expect(await unknown.json()).toEqual({ error: "Unknown project" }) + f.service.worktrees = async () => { throw new Error("private Git stderr") } + expect(await (await f.post("/worktrees", { projectId: "project" }, token)).json()).toEqual({ error: "Workspace operation failed" }) + }) + test("validates explicit project roots and exact origins", () => { expect(approvedWorkspaceOrigin(origin)).toBe(true) expect(approvedWorkspaceOrigin(otherOrigin)).toBe(true) @@ -160,6 +179,7 @@ describe("workspace companion protocol", () => { const cases: [string, unknown, string, unknown[], unknown][] = [ ["lookup", { threadId: "thread" }, "lookup", ["thread"], { workspace: { id: "workspace" } }], ["branches", { projectId: "project" }, "branches", ["project"], { branches: ["main"] }], + ["worktrees", { projectId: "project" }, "worktrees", ["project"], { worktrees: [{ path: "/explicit-root", branch: "main", head: "a".repeat(40), main: true, locked: false, prunable: false }] }], ["branches", { projectId: "project", fetch: false }, "branches", ["project"], { branches: ["main"] }], ["branches", { projectId: "project", fetch: true }, "fetchBranches", ["project"], { branches: ["main", "origin/topic"] }], ["ignored-files", { projectId: "project" }, "ignoredFiles", ["project"], { paths: [".env.local"] }], diff --git a/apps/supercode-cli/server/src/nova/workspaces/server.ts b/apps/supercode-cli/server/src/nova/workspaces/server.ts index bce73145..fcb431cf 100644 --- a/apps/supercode-cli/server/src/nova/workspaces/server.ts +++ b/apps/supercode-cli/server/src/nova/workspaces/server.ts @@ -6,6 +6,10 @@ import { NovaWorkspaceGit } from "./git" const MAX_BODY = 2 * 1024 * 1024 const SESSION_MS = 60 * 60 * 1000 const SAFE_WORKSPACE_ERRORS = new Set([ + "Git worktree listing exceeds discovery limits", + "Workspace registry exceeds discovery limits", + "Invalid Git worktree listing", + "Project root or ancestors cannot be symlinks", "Use a GitHub repository name in owner/name format", "Another repository clone is in progress", "Managed clone destination already exists; no files were overwritten", @@ -90,6 +94,7 @@ export interface WorkspaceService { cloneRepository(repositoryFullName: string): Promise lookup(threadId: string): Promise branches(projectId: string): Promise + worktrees(projectId: string): Promise fetchBranches(projectId: string): Promise ignoredFiles(projectId: string): Promise create(input: CreateWorkspaceInput): Promise @@ -243,6 +248,7 @@ export function startWorkspaceCompanion(options: { return reply({ branches: input.fetch ? await service.fetchBranches(input.projectId) : await service.branches(input.projectId) }) } case "/ignored-files": return reply({ paths: await service.ignoredFiles(projectInput.parse(body).projectId) }) + case "/worktrees": return reply({ worktrees: await service.worktrees(projectInput.parse(body).projectId) }) case "/create": return reply({ workspace: await service.create(createInput.parse(body)) }) case "/get": return reply({ workspace: await service.get(workspaceInput.parse(body).workspaceId) }) case "/files": return reply({ paths: await service.files(workspaceInput.parse(body).workspaceId) }) diff --git a/apps/web/app/api/nova/local-projects/[projectId]/branches/route.test.ts b/apps/web/app/api/nova/local-projects/[projectId]/branches/route.test.ts new file mode 100644 index 00000000..075df0c7 --- /dev/null +++ b/apps/web/app/api/nova/local-projects/[projectId]/branches/route.test.ts @@ -0,0 +1,45 @@ +import { beforeEach, expect, mock, test } from "bun:test" +import { NextRequest } from "next/server" + +let userId: string | null = "u" +let project: { repositoryFullName: string | null } | null = { repositoryFullName: "fork/repo" } +let failure = false +let calls: unknown[] = [] +mock.module("@super/auth/server", () => ({ auth: { api: { getSession: async () => userId ? { user: { id: userId } } : null } } })) +mock.module("next/headers", () => ({ headers: async () => new Headers() })) +mock.module("@/modules/nova/local-projects/service", () => ({ getLocalProject: async (...args: unknown[]) => { calls.push(args); return project } })) +mock.module("@/modules/nova/local-projects/github", () => ({ listGithubBranches: async (...args: unknown[]) => { + calls.push(args) + if (failure) throw new Error("provider credential detail must not escape") + return { branches: [{ name: "trunk", sha: "a".repeat(40), isDefault: true }], defaultBranch: "trunk", truncated: false } +} })) +const { GET } = await import("./route") +const get = () => GET(new NextRequest("http://localhost/api/nova/local-projects/p/branches"), { params: Promise.resolve({ projectId: "p" }) }) +beforeEach(() => { userId = "u"; project = { repositoryFullName: "fork/repo" }; failure = false; calls = [] }) + +test("connected branch discovery authorizes the project without a companion device", async () => { + const response = await get() + expect(response.status).toBe(200) + expect((await response.json()).defaultBranch).toBe("trunk") + expect(calls).toEqual([["u", "p"], ["u", "fork/repo"]]) +}) + +test("unauthenticated and inaccessible projects never enumerate branches", async () => { + userId = null + expect((await get()).status).toBe(401) + expect(calls).toHaveLength(0) + userId = "u" + project = null + expect((await get()).status).toBe(404) + expect(calls).toEqual([["u", "p"]]) +}) + +test("non-GitHub projects and provider errors return safe failures", async () => { + project = { repositoryFullName: null } + expect((await get()).status).toBe(400) + project = { repositoryFullName: "fork/repo" } + failure = true + const response = await get() + expect(response.status).toBe(502) + expect(await response.text()).not.toContain("credential detail") +}) diff --git a/apps/web/app/api/nova/local-projects/[projectId]/branches/route.ts b/apps/web/app/api/nova/local-projects/[projectId]/branches/route.ts new file mode 100644 index 00000000..bfb2ee4a --- /dev/null +++ b/apps/web/app/api/nova/local-projects/[projectId]/branches/route.ts @@ -0,0 +1,23 @@ +import { auth } from "@super/auth/server" +import { headers } from "next/headers" +import { NextRequest, NextResponse } from "next/server" + +import { listGithubBranches } from "@/modules/nova/local-projects/github" +import { getLocalProject } from "@/modules/nova/local-projects/service" + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function GET(_request: NextRequest, context: { params: Promise<{ projectId: string }> }) { + const session = await auth.api.getSession({ headers: await headers() }) + if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) + try { + const { projectId } = await context.params + const project = await getLocalProject(session.user.id, projectId) + if (!project) return NextResponse.json({ error: "Not found" }, { status: 404 }) + if (!project.repositoryFullName) return NextResponse.json({ error: "Project is not connected to GitHub" }, { status: 400 }) + return NextResponse.json(await listGithubBranches(session.user.id, project.repositoryFullName)) + } catch { + return NextResponse.json({ error: "Could not load GitHub branches. Check your connected repository and GitHub authorization." }, { status: 502 }) + } +} diff --git a/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.test.ts b/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.test.ts new file mode 100644 index 00000000..f0db2d29 --- /dev/null +++ b/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.test.ts @@ -0,0 +1,48 @@ +import { beforeEach, expect, mock, test } from "bun:test" +import { NextRequest } from "next/server" +import { z } from "zod" + +let userId: string | null = "u" +let available = true +let failure = false +let calls: unknown[] = [] +mock.module("@super/auth/server", () => ({ auth: { api: { getSession: async () => userId ? { user: { id: userId } } : null } } })) +mock.module("next/headers", () => ({ headers: async () => new Headers() })) +mock.module("@/modules/nova/local-projects/github", () => ({ + githubSourceFilePathSchema: z.string().min(1), + readSessionGithubSourceFile: async (...args: unknown[]) => { + calls.push(args) + if (failure) throw new Error("provider credential detail") + if (!available) return null + return args[2] === undefined ? { paths: ["src/file.ts"], truncated: false } : { path: args[2], text: "pinned" } + }, +})) +const { GET } = await import("./route") +const get = (query = "") => GET(new NextRequest(`http://localhost/api/nova/sessions/s/source-file${query}`), { params: Promise.resolve({ sessionId: "s" }) }) +beforeEach(() => { userId = "u"; available = true; failure = false; calls = [] }) + +test("source-file endpoint returns a pinned index without path and text with path", async () => { + const index = await get() + expect(await index.json()).toEqual({ paths: ["src/file.ts"], truncated: false }) + const file = await get("?path=src%2Ffile.ts") + expect(await file.json()).toEqual({ path: "src/file.ts", text: "pinned" }) + expect(file.headers.get("Cache-Control")).toBe("private, no-store") + expect(calls).toEqual([["u", "s", undefined], ["u", "s", "src/file.ts"]]) +}) + +test("unauthenticated and unavailable sources fail closed", async () => { + userId = null + expect((await get()).status).toBe(401) + expect(calls).toHaveLength(0) + userId = "u" + available = false + expect((await get()).status).toBe(404) + expect((await get("?path=")).status).toBe(400) +}) + +test("provider error details never escape the endpoint", async () => { + failure = true + const response = await get("?path=src/file.ts") + expect(response.status).toBe(502) + expect(await response.text()).not.toContain("credential detail") +}) diff --git a/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.ts b/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.ts new file mode 100644 index 00000000..3c41bd4c --- /dev/null +++ b/apps/web/app/api/nova/sessions/[sessionId]/source-file/route.ts @@ -0,0 +1,23 @@ +import { auth } from "@super/auth/server" +import { headers } from "next/headers" +import { NextRequest, NextResponse } from "next/server" + +import { githubSourceFilePathSchema, readSessionGithubSourceFile } from "@/modules/nova/local-projects/github" + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function GET(request: NextRequest, context: { params: Promise<{ sessionId: string }> }) { + const session = await auth.api.getSession({ headers: await headers() }) + if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) + const path = githubSourceFilePathSchema.optional().safeParse(request.nextUrl.searchParams.get("path") ?? undefined) + if (!path.success) return NextResponse.json({ error: "Invalid source file path" }, { status: 400 }) + try { + const { sessionId } = await context.params + const file = await readSessionGithubSourceFile(session.user.id, sessionId, path.data) + if (!file) return NextResponse.json({ error: "Pinned source file not found" }, { status: 404 }) + return NextResponse.json(file, { headers: { "Cache-Control": "private, no-store" } }) + } catch { + return NextResponse.json({ error: "Could not load pinned GitHub source file. Check repository access and file size." }, { status: 502 }) + } +} diff --git a/apps/web/app/api/nova/sessions/route.ts b/apps/web/app/api/nova/sessions/route.ts index 6497bcac..a23acb96 100644 --- a/apps/web/app/api/nova/sessions/route.ts +++ b/apps/web/app/api/nova/sessions/route.ts @@ -10,6 +10,7 @@ const createSessionSchema = z.object({ mode: z.string().trim().min(1).max(64).optional(), surface: z.enum(["web", "desktop"]).optional(), localProjectId: z.string().trim().min(1).max(64).optional().nullable(), + githubBranch: z.string().min(1).max(255).optional(), parentSessionId: z.string().trim().min(1).max(64).optional(), agentId: z.string().trim().min(1).max(64).optional().nullable(), }) @@ -48,15 +49,15 @@ export async function POST(request: NextRequest) { mode: parsed.data.mode, surface: parsed.data.surface ?? "web", localProjectId: parsed.data.localProjectId, + githubBranch: parsed.data.githubBranch, parentSessionId: parsed.data.parentSessionId, agentId: parsed.data.agentId, }) return NextResponse.json({ session }, { status: 201 }) } catch (error) { - console.error("[api/nova/sessions]", error) return NextResponse.json( - { error: error instanceof Error ? error.message : "Failed to create Nova session" }, - { status: 500 }, + { error: "Could not create session. Check project, branch and GitHub access." }, + { status: 400 }, ) } } diff --git a/apps/web/modules/nova-web/api.ts b/apps/web/modules/nova-web/api.ts index f5ea6ce2..fceac74d 100644 --- a/apps/web/modules/nova-web/api.ts +++ b/apps/web/modules/nova-web/api.ts @@ -108,7 +108,7 @@ export function createAgent(input: { export function createSession( objective: string, - options?: { localProjectId?: string | null; mode?: "agent" | "plan" | "chat"; parentSessionId?: string; agentId?: string }, + options?: { localProjectId?: string | null; mode?: "agent" | "plan" | "chat"; parentSessionId?: string; agentId?: string; githubBranch?: string }, ) { return requestJson<{ session: AgentSessionSummary }>("/api/nova/sessions", { method: "POST", @@ -120,10 +120,27 @@ export function createSession( localProjectId: options?.localProjectId ?? undefined, parentSessionId: options?.parentSessionId, agentId: options?.agentId, + githubBranch: options?.githubBranch, }), }) } +export function listGithubProjectBranches(projectId: string, signal?: AbortSignal) { + return requestJson<{ + branches: Array<{ name: string; sha: string; isDefault: boolean }> + defaultBranch: string + truncated: boolean + }>(`/api/nova/local-projects/${encodeURIComponent(projectId)}/branches`, { signal, cache: "no-store" }) +} + +export function listGithubSourceFiles(sessionId: string, signal?: AbortSignal) { + return requestJson<{ paths: string[]; truncated: boolean }>(`/api/nova/sessions/${encodeURIComponent(sessionId)}/source-file`, { signal, cache: "no-store" }) +} + +export function readGithubSourceFile(sessionId: string, path: string) { + return requestJson<{ path: string; text: string }>(`/api/nova/sessions/${encodeURIComponent(sessionId)}/source-file?path=${encodeURIComponent(path)}`, { cache: "no-store" }) +} + export type LocalProjectDto = { id: string displayName: string diff --git a/apps/web/modules/nova-web/components/git-workspace-controls.tsx b/apps/web/modules/nova-web/components/git-workspace-controls.tsx index bd94de90..70518c47 100644 --- a/apps/web/modules/nova-web/components/git-workspace-controls.tsx +++ b/apps/web/modules/nova-web/components/git-workspace-controls.tsx @@ -18,6 +18,7 @@ import { } from "@/components/ui/dialog" import type { GitWorkspaceState } from "../use-git-workspace" import { GitWorkspaceToolbar } from "./git-workspace-toolbar" +import { matchWorkspaceProject } from "../workspace-discovery" import type { GitBranch as Branch, GitProject, @@ -38,12 +39,14 @@ export function GitWorkspaceControls({ repositoryFullName, onOpenWorkspace, workspaceLabels, + localRootName, }: { state: GitWorkspaceState disabled?: boolean repositoryFullName?: string | null onOpenWorkspace?: (threadId: string) => void workspaceLabels?: Record + localRootName?: string | null }) { const [open, setOpen] = useState(false) const [port, setPort] = useState("47832") @@ -67,15 +70,7 @@ export function GitWorkspaceControls({ async function loadProjects() { const items = await client.projects() setProjects(items) - const selected = - items.find((item) => item.id === choice?.projectId) ?? - items.find( - (item) => - repositoryFullName && - item.repositoryFullName?.toLowerCase() === - repositoryFullName.toLowerCase(), - ) ?? - items[0] + const selected = matchWorkspaceProject(items, { projectId: choice?.projectId, repositoryFullName, rootName: localRootName }) setProjectId(selected?.id ?? "") } @@ -87,15 +82,7 @@ export function GitWorkspaceControls({ .then((items) => { if (!current) return setProjects(items) - const selected = - items.find((item) => item.id === choice?.projectId) ?? - items.find( - (item) => - repositoryFullName && - item.repositoryFullName?.toLowerCase() === - repositoryFullName.toLowerCase(), - ) ?? - items[0] + const selected = matchWorkspaceProject(items, { projectId: choice?.projectId, repositoryFullName, rootName: localRootName }) setProjectId(selected?.id ?? "") }) .catch((cause) => { @@ -104,7 +91,7 @@ export function GitWorkspaceControls({ return () => { current = false } - }, [open, client, choice?.projectId, repositoryFullName]) + }, [open, client, choice?.projectId, repositoryFullName, localRootName]) useEffect(() => { if (!open || !projectId || !client.connected) return @@ -150,7 +137,7 @@ export function GitWorkspaceControls({ const project = projects.find((item) => item.id === projectId) return ( <> - setOpen(true)} onOpenWorkspace={onOpenWorkspace} workspaceLabels={workspaceLabels} /> + setOpen(true)} onOpenWorkspace={onOpenWorkspace} workspaceLabels={workspaceLabels} /> { diff --git a/apps/web/modules/nova-web/components/git-workspace-toolbar.tsx b/apps/web/modules/nova-web/components/git-workspace-toolbar.tsx index 0ec6cd10..1c292f8c 100644 --- a/apps/web/modules/nova-web/components/git-workspace-toolbar.tsx +++ b/apps/web/modules/nova-web/components/git-workspace-toolbar.tsx @@ -22,9 +22,11 @@ import { import { type GitBranch as Branch, type GitProject, - type GitWorkspace, + type LocalGitWorktree, } from "../git-workspace" import type { GitWorkspaceState } from "../use-git-workspace" +import { listGithubProjectBranches } from "../api" +import { matchWorkspaceProject } from "../workspace-discovery" const row = "flex w-full min-w-0 items-center gap-2 rounded px-2 py-2 text-left text-xs text-[#ddd] hover:bg-white/5 disabled:opacity-40" @@ -40,6 +42,7 @@ export function GitWorkspaceToolbar({ onSettings, onOpenWorkspace, workspaceLabels = {}, + localRootName, }: { state: GitWorkspaceState disabled: boolean @@ -47,46 +50,57 @@ export function GitWorkspaceToolbar({ onSettings: () => void onOpenWorkspace?: (threadId: string) => void workspaceLabels?: Record + localRootName?: string | null }) { const [machineOpen, setMachineOpen] = useState(false) const [branchOpen, setBranchOpen] = useState(false) const [existingOpen, setExistingOpen] = useState(false) const [projects, setProjects] = useState([]) - const [branches, setBranches] = useState([]) - const [existing, setExisting] = useState([]) + const [localBranches, setLocalBranches] = useState([]) + const [githubBranches, setGithubBranches] = useState([]) + const [githubDefaultBranch, setGithubDefaultBranch] = useState(null) + const [truncated, setTruncated] = useState(false) + const [loadingBranches, setLoadingBranches] = useState(false) + const [existing, setExisting] = useState([]) + const [loadingWorktrees, setLoadingWorktrees] = useState(false) const [query, setQuery] = useState("") const [worktreeQuery, setWorktreeQuery] = useState("") const [busy, setBusy] = useState(false) const [error, setError] = useState(null) + const [branchError, setBranchError] = useState(null) const { client, choice, workspace, locked } = state const projectId = workspace?.projectId ?? choice?.projectId - const project = projectId - ? projects.find((item) => item.id === projectId) - : (projects.find( - (item) => - repositoryFullName && - item.repositoryFullName?.toLowerCase() === - repositoryFullName.toLowerCase(), - ) ?? (!repositoryFullName ? projects[0] : undefined)) + const project = matchWorkspaceProject(projects, { + projectId, + repositoryFullName, + rootName: localRootName, + }) + const githubMode = Boolean(repositoryFullName && !choice && !workspace) + const branches = githubMode ? githubBranches : localBranches + const connected = client.connected + const [refreshKey, setRefreshKey] = useState(0) useEffect(() => { - if ((!machineOpen && !branchOpen) || !client.connected) return + if (!connected) return let current = true + queueMicrotask(() => { + if (current) { + setProjects([]) + setLocalBranches([]) + } + }) void client .projects() .then(async (items) => { - const selected = projectId - ? items.find((item) => item.id === projectId) - : (items.find( - (item) => - repositoryFullName && - item.repositoryFullName?.toLowerCase() === - repositoryFullName.toLowerCase(), - ) ?? (!repositoryFullName ? items[0] : undefined)) + const selected = matchWorkspaceProject(items, { + projectId, + repositoryFullName, + rootName: localRootName, + }) const refs = selected ? await client.branches(selected.id) : [] if (current) { setProjects(items) - setBranches(refs) + setLocalBranches(refs) setError(null) } }) @@ -96,7 +110,85 @@ export function GitWorkspaceToolbar({ return () => { current = false } - }, [machineOpen, branchOpen, client, projectId, repositoryFullName]) + }, [ + machineOpen, + client, + connected, + projectId, + repositoryFullName, + localRootName, + ]) + + useEffect(() => { + if (!githubMode || !state.webProjectId) return + const controller = new AbortController() + queueMicrotask(() => { + if (controller.signal.aborted) return + setLoadingBranches(true) + setGithubBranches([]) + setGithubDefaultBranch(null) + setBranchError(null) + }) + void listGithubProjectBranches(state.webProjectId, controller.signal) + .then((data) => { + if (controller.signal.aborted) return + setGithubBranches( + data.branches.map((branch) => ({ + name: branch.name, + sha: branch.sha, + ref: `refs/heads/${branch.name}`, + current: branch.isDefault, + checkedOut: false, + remote: true, + })), + ) + setTruncated(data.truncated) + setGithubDefaultBranch(data.defaultBranch) + }) + .catch((cause) => { + if (!controller.signal.aborted) + setBranchError( + cause instanceof Error + ? cause.message + : "GitHub branches could not be loaded", + ) + }) + .finally(() => { + if (!controller.signal.aborted) setLoadingBranches(false) + }) + return () => controller.abort() + }, [githubMode, state.webProjectId, refreshKey]) + + useEffect(() => { + if (!existingOpen || !connected || !project?.id) return + let current = true + queueMicrotask(() => { + if (current) { + setLoadingWorktrees(true) + setExisting([]) + setError(null) + } + }) + void client + .worktrees(project.id) + .then((items) => { + if (current) setExisting(items) + }) + .catch((cause) => { + if (current) + setError( + cause instanceof Error + ? cause.message + : "Worktrees could not be loaded", + ) + }) + .finally(() => { + if (current) setLoadingWorktrees(false) + }) + return () => { + current = false + } + }, [existingOpen, project?.id, connected, client]) function settings() { setMachineOpen(false) @@ -113,11 +205,16 @@ export function GitWorkspaceToolbar({ projectId: project.id, sourceRef: mode === "current" - ? (branches.find((branch) => branch.current)?.ref ?? "") + ? (localBranches.find((branch) => branch.current)?.ref ?? "") : (ref ?? choice?.sourceRef ?? - branches.find((branch) => branch.current)?.ref ?? - branches[0]?.ref ?? + localBranches.find( + (branch) => + branch.name === state.githubBranch || + branch.name === `origin/${state.githubBranch}`, + )?.ref ?? + localBranches.find((branch) => branch.current)?.ref ?? + localBranches[0]?.ref ?? ""), mode, copyIgnored: choice?.copyIgnored ?? false, @@ -129,18 +226,17 @@ export function GitWorkspaceToolbar({ setBranchOpen(false) } - async function openExisting(saved: GitWorkspace) { + async function openExisting(saved: LocalGitWorktree) { + if (!saved.workspaceId || !saved.threadId) return setBusy(true) setError(null) try { - const actual = await client.get(saved.id) + const actual = await client.get(saved.workspaceId) if ( - actual.id !== saved.id || + actual.id !== saved.workspaceId || actual.threadId !== saved.threadId || - actual.projectId !== saved.projectId || - actual.baseSha !== saved.baseSha || - actual.sourceRef !== saved.sourceRef || - actual.mode !== saved.mode + actual.projectId !== project?.id || + actual.path !== saved.path ) throw new Error( "Worktree identity changed; reconnect its original companion", @@ -159,6 +255,7 @@ export function GitWorkspaceToolbar({ workspace?.branch ?? workspace?.sourceRef ?? choice?.sourceRef ?? + (githubMode ? state.githubBranch ?? githubDefaultBranch : null) ?? branches.find((branch) => branch.current)?.ref const branchLabel = source?.replace(/^refs\/(?:heads|remotes)\//, "") || "Choose branch" @@ -235,22 +332,7 @@ export function GitWorkspaceToolbar({ - ))} - {!existing.length && ( + {loadingWorktrees && ( +

+ Loading Git worktrees… +

+ )} + {!existing.length && !loadingWorktrees && connected && (

- No saved worktrees for this project in this browser. + {project + ? "No worktrees found." + : "Choose the matching project in workspace settings; Nova will not use a different folder."}

)} @@ -369,7 +473,12 @@ export function GitWorkspaceToolbar({ type="button" className={row} disabled={locked || (mode === "current" && !branch.current)} - onClick={() => select(mode ?? "worktree", branch.ref)} + onClick={() => { + if (githubMode) { + state.selectGithubBranch(branch.name) + setBranchOpen(false) + } else select(mode ?? "worktree", branch.ref) + }} > {branch.name} @@ -378,17 +487,32 @@ export function GitWorkspaceToolbar({ )} {(workspace ? source === branch.name || source === branch.ref - : (choice?.sourceRef ?? + : ((githubMode && state.githubBranch + ? `refs/heads/${state.githubBranch}` + : choice?.sourceRef) ?? branches.find((item) => item.current)?.ref) === branch.ref) && } ))} - {!branches.length && ( + {loadingBranches && ( +

+ + Loading GitHub branches… +

+ )} + {!branches.length && !loadingBranches && !branchError && (

- {client.connected - ? "No matching project branches. Open workspace settings." - : "Connect this computer to load its branches."} + {githubMode + ? "No branches found in this connected repository." + : client.connected + ? "No matching project branches. Open workspace settings." + : "Connect this computer to load its branches."} +

+ )} + {githubMode && truncated && ( +

+ Branch listing is limited; more branches exist on GitHub.

)} {locked && ( @@ -401,12 +525,20 @@ export function GitWorkspaceToolbar({ + {branchError && ( +

+ {branchError} +

+ )} {error && (

{error} diff --git a/apps/web/modules/nova-web/git-workspace.ts b/apps/web/modules/nova-web/git-workspace.ts index f1803934..1a43ed1c 100644 --- a/apps/web/modules/nova-web/git-workspace.ts +++ b/apps/web/modules/nova-web/git-workspace.ts @@ -40,6 +40,17 @@ export const gitWorkspaceSchema = z.object({ export type GitProject = z.infer export type GitBranch = z.infer export type GitWorkspace = z.infer +export const localGitWorktreeSchema = z.object({ + path: z.string(), + branch: z.string().nullable(), + head: z.string(), + main: z.boolean(), + locked: z.boolean(), + prunable: z.boolean(), + workspaceId: z.string().optional(), + threadId: z.string().optional(), +}) +export type LocalGitWorktree = z.infer export type WorkspaceChoice = { projectId: string mode: "current" | "worktree" @@ -226,6 +237,10 @@ export class GitWorkspaceClient { }) return z.array(gitBranchSchema).parse(data.branches) } + async worktrees(projectId: string) { + const data = await this.request<{ worktrees: unknown }>("/worktrees", { projectId }) + return z.array(localGitWorktreeSchema).parse(data.worktrees) + } async clone(repositoryFullName: string) { const data = await this.request<{ project: unknown }>("/clone", { repositoryFullName, confirmed: true }) return gitProjectSchema.parse(data.project) diff --git a/apps/web/modules/nova-web/local-workspace.ts b/apps/web/modules/nova-web/local-workspace.ts index 454de8cd..d65f89be 100644 --- a/apps/web/modules/nova-web/local-workspace.ts +++ b/apps/web/modules/nova-web/local-workspace.ts @@ -518,7 +518,7 @@ export async function writeLocalWorkspaceFile( path: string, content: string, ): Promise<{ ok: true; path: string } | { ok: false; error: string }> { - if (managedWorkspace) return { ok: false, error: "Apply this thread’s changes through its paired worktree companion" } + if (managedWorkspace) return { ok: false, error: "Apply changes through this thread’s authorized workspace, not the original folder" } try { if (!memoryHandle) { return { ok: false, error: "No local folder linked. Re-open the project folder with write access." } @@ -621,7 +621,7 @@ export async function ensureLocalWorkspaceWritable(): Promise<{ prompted: boolean error?: string }> { - if (managedWorkspace) return { ok: false, prompted: false, error: "Apply this thread’s changes through its paired worktree companion" } + if (managedWorkspace) return { ok: false, prompted: false, error: "Apply changes through this thread’s authorized workspace, not the original folder" } // Already writable if (memoryHandle) { const allowed = await ensureWritePermission(memoryHandle) diff --git a/apps/web/modules/nova-web/nova-app.tsx b/apps/web/modules/nova-web/nova-app.tsx index ca2240ff..58dba17e 100644 --- a/apps/web/modules/nova-web/nova-app.tsx +++ b/apps/web/modules/nova-web/nova-app.tsx @@ -14,6 +14,8 @@ import { listApprovals, listConnectors, listSessions, + listGithubProjectBranches, + readGithubSourceFile, streamTurn, syncSession, type FileProposalDto, @@ -286,7 +288,7 @@ export function NovaApp({ const [references, setReferences] = useState([]) const [localFiles, setLocalFiles] = useState([]) const [localProject, setLocalProject] = useState(null) - const gitWorkspace = useGitWorkspace(user.id, selectedId, localProject?.id ?? null, !embedded && !isAgentChat) + const gitWorkspace = useGitWorkspace(user.id, selectedId, localProject?.id ?? null, !embedded && !isAgentChat, session?.githubSource) const { ensure: ensureGitWorkspace, client: gitClient, requestPublish } = gitWorkspace const [model, setModel] = useState(DEFAULT_NOVA_MODEL) const [provider, setProvider] = useState(DEFAULT_NOVA_PROVIDER) @@ -624,11 +626,15 @@ export function NovaApp({ ) { startTransition(async () => { try { - const projectId = getActiveLocalProjectId() || localProject?.id || null + const projectId = localProject?.id || getActiveLocalProjectId() || null + const githubBranch = !embedded && !gitWorkspace.choice && localProject?.repositoryFullName + ? gitWorkspace.githubBranch ?? (await listGithubProjectBranches(localProject.id)).defaultBranch + : undefined const response = await createSession(objective, { localProjectId: projectId, mode: agentMode || DEFAULT_NOVA_AGENT_MODE, parentSessionId, + githubBranch, }) setSessions((current) => [ response.session, @@ -724,6 +730,8 @@ export function NovaApp({ ? await gitClient.pack(localGitWorkspace, content, opts?.localAttachments ?? []) : isAgentChat ? [] + : localProject?.repositoryFullName || session?.githubSource + ? opts?.localAttachments ?? [] : embedded && getActiveLocalProjectId() !== activeProjectId ? opts?.localAttachments ?? [] : await packLocalProjectForTurn(content, opts?.localAttachments ?? []) @@ -853,7 +861,7 @@ export function NovaApp({ }) // Browsers block write permission without a user gesture — don't auto-apply. // Probe quietly; if write is already granted, apply. Otherwise wait for the button. - if (!embedded && !localGitWorkspace && (opts?.mode ?? agentMode) === "agent") { + if (!embedded && !localGitWorkspace && !session?.githubSource && (opts?.mode ?? agentMode) === "agent") { void applyFileProposalsLocally(event.proposals, { interactive: false }).then((batch) => { if (batch.applied > 0) { setApplyStatus(batch.message) @@ -905,7 +913,7 @@ export function NovaApp({ // Keep workingSteps + workingSince so ThreadView can show the completed process // until the next turn starts (which clears them above). } - }, [embedded, agentMode, effort, isAgentChat, loadSharedState, localProject?.id, machineSize, model, provider, pullSync, setSyncCursor, ensureGitWorkspace, gitClient, requestPublish]) + }, [embedded, agentMode, effort, isAgentChat, loadSharedState, localProject?.id, localProject?.repositoryFullName, session?.githubSource, machineSize, model, provider, pullSync, setSyncCursor, ensureGitWorkspace, gitClient, requestPublish]) // Keep "Thinking for Xs" labels live while reasoning is in flight. useEffect(() => { @@ -1070,7 +1078,7 @@ export function NovaApp({ ) : selectedId && session ? ( gitClient.read(gitWorkspace.workspace!.id, path) : undefined} - workspaceControls={!embedded ? navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/> : undefined} + localProject={gitWorkspace.workspace ? { id: localProject?.id ?? gitWorkspace.workspace.projectId, displayName: gitWorkspace.workspace.path.split(/[\\/]/).pop() ?? "Worktree", rootName: "Worktree", fileCount: gitWorkspace.paths.length, truncated: false, repositoryFullName: localProject?.repositoryFullName ?? null, status: "active", lastUsedAt: null, updatedAt: session.updatedAt, paths: gitWorkspace.paths } : session.githubSource && session.localProject ? { ...session.localProject, paths: gitWorkspace.paths, fileCount: gitWorkspace.paths.length } : localProject ?? session.localProject ?? null} + readWorkspaceFile={gitWorkspace.workspace ? path => gitClient.read(gitWorkspace.workspace!.id, path) : session.githubSource ? async path => (await readGithubSourceFile(session.id, path)).text : undefined} + workspaceControls={!embedded ? navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/> : undefined} onLocalProjectChange={(workspace) => void handleLocalProjectChange(workspace)} onProjectChange={(selection) => void applyProjectSelection(selection)} onManageProjects={() => openSettingsSection("projects")} @@ -1098,6 +1106,10 @@ export function NovaApp({ setApplyStatus("Open the parent thread’s project folder before applying these changes.") return } + if (session.githubSource) { + setApplyStatus("These changes belong to the selected GitHub source. Start a local worktree thread to apply them on this computer; Nova will not write them into an unbound folder.") + return + } setApplyStatus("Granting folder access and applying…") // interactive:true runs inside this click — browser allows write + picker. const managed = !embedded ? await ensureGitWorkspace(selectedId) : null @@ -1171,7 +1183,7 @@ export function NovaApp({ onProjectChange={(selection) => void applyProjectSelection(selection)} onManageProjects={() => openSettingsSection("projects")} localProject={localProject} - workspaceControls={ navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/>} + workspaceControls={ navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/>} /> )} diff --git a/apps/web/modules/nova-web/use-git-workspace.ts b/apps/web/modules/nova-web/use-git-workspace.ts index ca49c996..774bb16a 100644 --- a/apps/web/modules/nova-web/use-git-workspace.ts +++ b/apps/web/modules/nova-web/use-git-workspace.ts @@ -8,7 +8,7 @@ import { type WorkspaceChoice, type PublishInput, } from "./git-workspace" -import { bindLocalWorktree, getLocalWorktreeBinding } from "./api" +import { bindLocalWorktree, getLocalWorktreeBinding, listGithubSourceFiles, readGithubSourceFile } from "./api" import { activateManagedWorkspace } from "./local-workspace" function readSaved(key: string): T | null { @@ -24,23 +24,30 @@ export function useGitWorkspace( sessionId: string | null, projectId: string | null, enabled = true, + githubSource?: { repositoryFullName: string; branch: string; sha: string }, ) { const client = useMemo(() => new GitWorkspaceClient(userId), [userId]) const [revision, setRevision] = useState(0) const [workspace, setWorkspace] = useState(null) const [paths, setPaths] = useState([]) const [choice, setChoice] = useState(null) + const [githubBranch, setGithubBranch] = useState(null) const [publishAction, setPublishAction] = useState< PublishInput["action"] | null >(null) const [bindingError, setBindingError] = useState(null) const selectionKey = `nova:git-selection:${userId}:${projectId ?? "none"}` + const githubSourceSha = githubSource?.sha + const githubRepository = githubSource?.repositoryFullName const threadKey = useCallback( (id: string) => `nova:git-thread:${userId}:${id}`, [userId], ) useEffect(() => { + if (enabled && sessionId && githubSourceSha && githubRepository) { + return activateManagedWorkspace({ projectId, rootName: githubRepository, paths, read: async path => (await readGithubSourceFile(sessionId, path)).text }) + } if (!enabled || !workspace || workspace.threadId !== sessionId) return return activateManagedWorkspace({ projectId, @@ -48,18 +55,32 @@ export function useGitWorkspace( paths, read: (path) => client.read(workspace.id, path), }) - }, [workspace, sessionId, projectId, paths, client, enabled]) + }, [workspace, sessionId, projectId, paths, client, enabled, githubSourceSha, githubRepository]) + + useEffect(() => { + if (!enabled || !sessionId || !githubSourceSha) return + const controller = new AbortController() + queueMicrotask(() => { if (!controller.signal.aborted) { setPaths([]); setBindingError(null) } }) + void listGithubSourceFiles(sessionId, controller.signal).then(result => { + if (!controller.signal.aborted) setPaths(result.paths) + }).catch(cause => { + if (!controller.signal.aborted) setBindingError(cause instanceof Error ? cause.message : "GitHub source files are unavailable") + }) + return () => controller.abort() + }, [enabled, sessionId, githubSourceSha]) useEffect(() => { let current = true - const saved = sessionId + const saved = sessionId && !githubSourceSha ? readSaved(threadKey(sessionId)) : null queueMicrotask(() => { if (!current) return - setChoice(readSaved(selectionKey)) + setChoice(githubSourceSha ? null : readSaved(selectionKey)) + const savedBranch = readSaved(`${selectionKey}:github-branch`) + setGithubBranch(typeof savedBranch === "string" ? savedBranch : null) setWorkspace(saved) - setPaths([]) + if (!githubSourceSha) setPaths([]) setBindingError(null) if (saved && client.connected) void client @@ -68,7 +89,7 @@ export function useGitWorkspace( if (current) setPaths(value) }) .catch(() => {}) - if (sessionId && enabled) + if (sessionId && enabled && !githubSourceSha) void getLocalWorktreeBinding(sessionId) .then(async ({ binding }) => { if (!binding || !current) return @@ -100,7 +121,7 @@ export function useGitWorkspace( return () => { current = false } - }, [selectionKey, sessionId, threadKey, revision, client, enabled]) + }, [selectionKey, sessionId, threadKey, revision, client, enabled, githubSourceSha]) const select = useCallback( (value: WorkspaceChoice | null) => { @@ -164,12 +185,24 @@ export function useGitWorkspace( [client, selectionKey, threadKey], ) + const selectGithubBranch = useCallback((branch: string) => { + if (sessionId) throw new Error("Start a new thread to change its starting branch") + localStorage.setItem(`${selectionKey}:github-branch`, JSON.stringify(branch)) + localStorage.removeItem(selectionKey) + setChoice(null) + setGithubBranch(branch) + }, [selectionKey, sessionId]) + return { client, workspace, paths, choice, select, + githubBranch: githubSource?.branch ?? (sessionId ? null : githubBranch), + githubSource, + selectGithubBranch, + webProjectId: projectId, ensure, bindingError, locked: Boolean(sessionId), diff --git a/apps/web/modules/nova-web/workspace-discovery.test.ts b/apps/web/modules/nova-web/workspace-discovery.test.ts new file mode 100644 index 00000000..2d21bebb --- /dev/null +++ b/apps/web/modules/nova-web/workspace-discovery.test.ts @@ -0,0 +1,111 @@ +import { expect, test } from "bun:test" + +import { createSession, listGithubProjectBranches } from "./api" +import { GitWorkspaceClient, type GitProject } from "./git-workspace" +import { matchWorkspaceProject } from "./workspace-discovery" + +const projects: GitProject[] = [ + { + id: "one", + name: "app", + path: "/first/app", + repositoryFullName: "owner/app", + isGit: true, + }, + { + id: "two", + name: "backend", + path: "/second/backend", + repositoryFullName: "owner/backend", + isGit: true, + }, +] + +test("local discovery matches the selected repository or unique folder instead of the first approved root", () => { + expect( + matchWorkspaceProject(projects, { repositoryFullName: "OWNER/BACKEND" }) + ?.id, + ).toBe("two") + expect(matchWorkspaceProject(projects, { rootName: "backend" })?.id).toBe( + "two", + ) + expect( + matchWorkspaceProject(projects, { repositoryFullName: "owner/missing" }), + ).toBeUndefined() + expect( + matchWorkspaceProject(projects, { rootName: "missing" }), + ).toBeUndefined() + expect( + matchWorkspaceProject(projects, { projectId: "missing" }), + ).toBeUndefined() + expect(matchWorkspaceProject(projects, {})).toBeUndefined() + expect( + matchWorkspaceProject( + [ + ...projects, + { ...projects[1]!, id: "duplicate", path: "/third/backend" }, + ], + { rootName: "backend" }, + ), + ).toBeUndefined() +}) + +test("GitHub branch discovery needs no pairing and selected branch is included in session creation", async () => { + const original = globalThis.fetch + const calls: Array<{ url: string; body?: unknown }> = [] + globalThis.fetch = (async ( + input: string | URL | Request, + init?: RequestInit, + ) => { + calls.push({ + url: String(input), + body: init?.body ? JSON.parse(String(init.body)) : undefined, + }) + if (String(input).endsWith("/branches")) + return Response.json({ + defaultBranch: "trunk", + branches: [ + { name: "trunk", sha: "a".repeat(40), isDefault: true }, + { name: "feature/selected", sha: "b".repeat(40), isDefault: false }, + ], + truncated: false, + }) + return Response.json({ session: { id: "new-thread" } }) + }) as unknown as typeof fetch + try { + expect(new GitWorkspaceClient("unpaired").connected).toBe(false) + expect((await listGithubProjectBranches("project/id")).defaultBranch).toBe( + "trunk", + ) + await createSession("Fix selected branch", { + localProjectId: "project/id", + githubBranch: "feature/selected", + }) + expect(calls.map((call) => call.url)).toEqual([ + "/api/nova/local-projects/project%2Fid/branches", + "/api/nova/sessions", + ]) + expect(calls[1]?.body).toMatchObject({ + githubBranch: "feature/selected", + localProjectId: "project/id", + }) + } finally { + globalThis.fetch = original + } +}) + +test("GitHub authorization failures are reported instead of falling back to local pairing", async () => { + const original = globalThis.fetch + globalThis.fetch = (async () => + Response.json( + { error: "Repository access denied" }, + { status: 403 }, + )) as unknown as typeof fetch + try { + await expect(listGithubProjectBranches("project")).rejects.toThrow( + "Repository access denied", + ) + } finally { + globalThis.fetch = original + } +}) diff --git a/apps/web/modules/nova-web/workspace-discovery.ts b/apps/web/modules/nova-web/workspace-discovery.ts new file mode 100644 index 00000000..21d46ae9 --- /dev/null +++ b/apps/web/modules/nova-web/workspace-discovery.ts @@ -0,0 +1,27 @@ +import type { GitProject } from "./git-workspace" + +export function matchWorkspaceProject( + projects: GitProject[], + selection: { + projectId?: string + repositoryFullName?: string | null + rootName?: string | null + }, +): GitProject | undefined { + if (selection.projectId) + return projects.find((project) => project.id === selection.projectId) + const matches = selection.repositoryFullName + ? projects.filter( + (project) => + project.repositoryFullName?.toLowerCase() === + selection.repositoryFullName?.toLowerCase(), + ) + : selection.rootName + ? projects.filter( + (project) => + project.name === selection.rootName || + project.path.split(/[\\/]/).pop() === selection.rootName, + ) + : projects + return matches.length === 1 ? matches[0] : undefined +} diff --git a/apps/web/modules/nova/local-projects/github-source.test.ts b/apps/web/modules/nova/local-projects/github-source.test.ts new file mode 100644 index 00000000..0d45c962 --- /dev/null +++ b/apps/web/modules/nova/local-projects/github-source.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from "bun:test" + +import { agentSessionSummarySchema } from "@super/nova" +import { assertGithubSourceRepository, githubSourceFromPolicy, githubSourceSchema } from "./github-source" +import { createLocalWorktreeBindingService } from "./worktree-binding" + +const source = { repositoryFullName: "owner/repo", branch: "feature/slashes", sha: "a".repeat(40) } + +test("immutable source requires a repository, branch and actual commit, with no credentials or extras", () => { + expect(githubSourceFromPolicy({ githubSource: source })).toEqual(source) + expect(githubSourceFromPolicy({ mode: "legacy" })).toBeUndefined() + for (const change of [{ repositoryFullName: "https://token@github.com/owner/repo" }, { sha: "main" }, { branch: "" }, { branch: "main\n" }, { token: "secret" }]) { + expect(githubSourceSchema.safeParse({ ...source, ...change }).success).toBe(false) + expect(() => githubSourceFromPolicy({ githubSource: { ...source, ...change } })).toThrow() + } + expect(agentSessionSummarySchema.shape.githubSource.parse(source)).toEqual(source) +}) + +test("a different fork or missing project cannot silently replace the source", () => { + expect(() => assertGithubSourceRepository(source, "OWNER/REPO")).not.toThrow() + expect(() => assertGithubSourceRepository(source, "other/repo")).toThrow("immutable") + expect(() => assertGithubSourceRepository(source, null)).toThrow("immutable") +}) + +test("pinned GitHub sessions cannot acquire a second local source", async () => { + let writes = 0 + const service = createLocalWorktreeBindingService({ agentSession: { + findFirst: async () => ({ policySnapshot: { githubSource: source }, localWorkspaceBinding: null, activeRunId: null, parentSessionId: null }), + updateMany: async () => { writes++; return { count: 1 } }, + } } as never) + await expect(service.bindLocalWorktree("u", "s", { workspaceId: "w", projectId: "p", sourceRef: "main", baseSha: source.sha, mode: "worktree" })).rejects.toThrow("cannot bind") + expect(writes).toBe(0) +}) diff --git a/apps/web/modules/nova/local-projects/github-source.ts b/apps/web/modules/nova/local-projects/github-source.ts new file mode 100644 index 00000000..a3dd970d --- /dev/null +++ b/apps/web/modules/nova/local-projects/github-source.ts @@ -0,0 +1,20 @@ +import { z } from "zod" + +export const githubSourceSchema = z.object({ + repositoryFullName: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/), + branch: z.string().min(1).max(255).refine((value) => !/[\x00-\x20\x7f]/.test(value)), + sha: z.string().regex(/^[a-f0-9]{40}$/), +}).strict() + +export type GithubSource = z.infer + +export function githubSourceFromPolicy(policy: unknown): GithubSource | undefined { + if (!policy || typeof policy !== "object" || !("githubSource" in policy)) return undefined + return githubSourceSchema.parse(policy.githubSource) +} + +export function assertGithubSourceRepository(source: GithubSource, repository: string | null | undefined) { + if (source.repositoryFullName.toLowerCase() !== repository?.toLowerCase()) { + throw new Error("Project repository no longer matches the immutable session source") + } +} diff --git a/apps/web/modules/nova/local-projects/github.test.ts b/apps/web/modules/nova/local-projects/github.test.ts new file mode 100644 index 00000000..df4cbf4e --- /dev/null +++ b/apps/web/modules/nova/local-projects/github.test.ts @@ -0,0 +1,100 @@ +import { beforeEach, expect, mock, test } from "bun:test" + +let connected = true +let pages = 2 +let session: Record | null = null +let content = "pinned" +const calls: Array<{ method: string; input: Record }> = [] +const sha = "b".repeat(40) +const rest = { + repos: { + get: async (input: Record) => { calls.push({ method: "repo", input }); return { data: { default_branch: "trunk" } } }, + listBranches: async (input: Record) => { + calls.push({ method: "branches", input }) + return { data: [{ name: input.page === 1 ? "trunk" : "feature/slashes", commit: { sha } }], headers: { link: Number(input.page) < pages ? '; rel="next"' : undefined } } + }, + getBranch: async (input: Record) => { + calls.push({ method: "branch", input }) + if (input.branch === "deleted") throw new Error("not found") + return { data: { name: input.branch, commit: { sha } } } + }, + getContent: async (input: Record) => { calls.push({ method: "content", input }); return { data: { type: "file", content: Buffer.from(content).toString("base64"), encoding: "base64", size: Buffer.byteLength(content) } } }, + }, + git: { getTree: async (input: Record) => { calls.push({ method: "tree", input }); return { data: { tree: [{ type: "blob", path: "src/pinned.ts" }] } } } }, +} +mock.module("octokit", () => ({ Octokit: class { rest = rest } })) +mock.module("@super/db", () => ({ default: { + repository: { findFirst: async () => connected ? { owner: "fork-owner", name: "repo", fullName: "fork-owner/repo" } : null }, + agentSession: { findFirst: async (input: Record) => { calls.push({ method: "session", input }); return session } }, +} })) +mock.module("@/modules/github/lib/github", () => ({ getGithubTokenForUser: async () => "fixture" })) +const { githubSourceFilePathSchema, listGithubBranches, resolveGithubSource, readSessionGithubSourceFile } = await import("./github") +const { packGithubProjectForTurn } = await import("./pack") + +beforeEach(() => { calls.length = 0; pages = 2; connected = true; session = null; content = "pinned" }) + +test("discovery paginates the connected fork and marks its actual default", async () => { + const result = await listGithubBranches("u", "fork-owner/repo") + expect(result).toEqual({ defaultBranch: "trunk", truncated: false, branches: [{ name: "trunk", sha, isDefault: true }, { name: "feature/slashes", sha, isDefault: false }] }) + expect(calls.filter((call) => call.method === "branches").map((call) => call.input.page)).toEqual([1, 2]) + expect(calls.every((call) => call.input.owner === "fork-owner")).toBe(true) +}) + +test("discovery is bounded and reports truncation", async () => { + pages = 11 + expect((await listGithubBranches("u", "fork-owner/repo")).truncated).toBe(true) + expect(calls.filter((call) => call.method === "branches")).toHaveLength(10) +}) + +test("authorization precedes GitHub calls for both discovery and resolution", async () => { + connected = false + await expect(listGithubBranches("other", "fork-owner/repo")).rejects.toThrow("not connected") + await expect(resolveGithubSource("other", "fork-owner/repo", "feature/slashes")).rejects.toThrow("not connected") + expect(calls).toHaveLength(0) +}) + +test("resolving slash branches freezes their SHA and never falls back on deleted branches", async () => { + expect(await resolveGithubSource("u", "fork-owner/repo", "feature/slashes")).toEqual({ repositoryFullName: "fork-owner/repo", branch: "feature/slashes", sha }) + await expect(resolveGithubSource("u", "fork-owner/repo", "deleted")).rejects.toThrow("not found") + expect(calls.some((call) => call.method === "repo")).toBe(false) +}) + +test("fallback indexes and reads exact commit, discarding original folder text", async () => { + const project = { repositoryFullName: "fork-owner/repo", paths: ["wrong.ts"] } + const source = { repositoryFullName: "fork-owner/repo", branch: "feature/slashes", sha } + const result = await packGithubProjectForTurn("u", project as never, "pinned", [ + { id: "local", kind: "text", name: "src/pinned.ts", size: 5, mediaType: "text/plain", text: "wrong" }, + { id: "requirements", kind: "text", name: "requirements.txt", size: 4, mediaType: "text/plain", text: "spec" }, + ], source) + expect(result.map((file) => file.text)).toEqual(["spec", "pinned"]) + expect(calls.find((call) => call.method === "tree")?.input.tree_sha).toBe(sha) + expect(calls.find((call) => call.method === "content")?.input.ref).toBe(sha) + await expect(packGithubProjectForTurn("u", { repositoryFullName: "upstream/repo" } as never, "", [], source)).rejects.toThrow("immutable") +}) + +test("source file reads require an active owner and matching project, and use the frozen SHA", async () => { + const source = { repositoryFullName: "fork-owner/repo", branch: "feature/slashes", sha } + session = { organizationId: "o", policySnapshot: { githubSource: source }, localProject: { status: "active", userId: "u", organizationId: "o", repositoryFullName: source.repositoryFullName } } + expect(await readSessionGithubSourceFile("u", "s", "src/pinned.ts")).toEqual({ path: "src/pinned.ts", text: "pinned", githubSource: source }) + expect(calls.find((call) => call.method === "content")?.input.ref).toBe(sha) + expect(calls.find((call) => call.method === "session")?.input.where).toEqual({ id: "s", initiatorMembership: { userId: "u", status: "active" }, organization: { memberships: { some: { userId: "u", status: "active" } } } }) + expect(await readSessionGithubSourceFile("u", "s")).toEqual({ paths: ["src/pinned.ts"], truncated: false, githubSource: source }) + expect(calls.find((call) => call.method === "tree")?.input.tree_sha).toBe(sha) + calls.length = 0 + expect(await readSessionGithubSourceFile("other", "s", "src/pinned.ts")).toBeNull() + expect(calls.some((call) => call.method === "content")).toBe(false) + session = null + expect(await readSessionGithubSourceFile("u", "missing", "src/pinned.ts")).toBeNull() +}) + +test("source file reads reject binary, oversized files, repository drift and unsafe paths", async () => { + const source = { repositoryFullName: "fork-owner/repo", branch: "feature/slashes", sha } + session = { organizationId: "o", policySnapshot: { githubSource: source }, localProject: { status: "active", userId: "u", organizationId: "o", repositoryFullName: source.repositoryFullName } } + content = "binary\0file" + await expect(readSessionGithubSourceFile("u", "s", "src/pinned.ts")).rejects.toThrow("bounded text") + content = "x".repeat(65_537) + await expect(readSessionGithubSourceFile("u", "s", "src/pinned.ts")).rejects.toThrow("bounded text") + session.localProject = { status: "active", userId: "u", organizationId: "o", repositoryFullName: "upstream/repo" } + await expect(readSessionGithubSourceFile("u", "s", "src/pinned.ts")).rejects.toThrow("immutable") + for (const path of ["", "/absolute", "../escape", "foo/../escape", "a\\b", ".git/config", "a\n"]) expect(githubSourceFilePathSchema.safeParse(path).success).toBe(false) +}) diff --git a/apps/web/modules/nova/local-projects/github.ts b/apps/web/modules/nova/local-projects/github.ts index a1891d6a..94404f44 100644 --- a/apps/web/modules/nova/local-projects/github.ts +++ b/apps/web/modules/nova/local-projects/github.ts @@ -1,14 +1,53 @@ import { Octokit } from "octokit" +import { z } from "zod" import prisma from "@super/db" import { getGithubTokenForUser } from "@/modules/github/lib/github" import { isReferenceFile } from "@/modules/nova/references/service" import { MAX_PROJECT_PATHS } from "@/modules/nova/local-projects/contracts" import { createLocalProject, listLocalProjects, updateLocalProject } from "@/modules/nova/local-projects/service" +import { assertGithubSourceRepository, githubSourceFromPolicy } from "./github-source" const MAX_FILE_BYTES = 64 * 1024 -async function githubForUser(userId: string) { +export const githubSourceFilePathSchema = z.string().min(1).max(1024).refine((path) => + !path.startsWith("/") && !/[\\\x00-\x1f\x7f]/.test(path) + && !path.split("/").some((part) => !part || part === "." || part === ".." || part === ".git"), +) + +export async function readSessionGithubSourceFile(userId: string, sessionId: string, path?: string) { + if (path !== undefined) githubSourceFilePathSchema.parse(path) + const session = await prisma.agentSession.findFirst({ + where: { + id: sessionId, + initiatorMembership: { userId, status: "active" }, + organization: { memberships: { some: { userId, status: "active" } } }, + }, + include: { localProject: true }, + }) + if (!session) return null + const githubSource = githubSourceFromPolicy(session.policySnapshot) + if (!githubSource) return null + const project = session.localProject + if (!project || project.status !== "active" || project.userId !== userId || project.organizationId !== session.organizationId) return null + assertGithubSourceRepository(githubSource, project.repositoryFullName) + const repo = await connectedGithubRepository(userId, githubSource.repositoryFullName) + const github = await githubForUser(userId) + if (path === undefined) { + const { data: tree } = await github.rest.git.getTree({ owner: repo.owner, repo: repo.name, tree_sha: githubSource.sha, recursive: "true" }) + const paths = (tree.tree ?? []).flatMap((item) => item.type === "blob" && item.path && isReferenceFile(item.path) && (item.size ?? 0) <= MAX_FILE_BYTES ? [item.path] : []) + return { paths: paths.slice(0, MAX_PROJECT_PATHS), truncated: Boolean(tree.truncated) || paths.length > MAX_PROJECT_PATHS, githubSource } + } + const { data } = await github.rest.repos.getContent({ owner: repo.owner, repo: repo.name, path, ref: githubSource.sha }) + if (Array.isArray(data) || data.type !== "file" || !("content" in data) || typeof data.content !== "string" + || data.encoding !== "base64" || data.size > MAX_FILE_BYTES) throw new Error("Source file is not bounded text") + const bytes = Buffer.from(data.content, "base64") + if (bytes.byteLength > MAX_FILE_BYTES || bytes.includes(0)) throw new Error("Source file is not bounded text") + const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes) + return { path, text, githubSource } +} + +export async function githubForUser(userId: string) { try { return new Octokit({ auth: await getGithubTokenForUser(userId), request: { timeout: 20_000 } }) } catch { @@ -26,6 +65,44 @@ async function githubForUser(userId: string) { } } +export async function connectedGithubRepository(userId: string, fullName: string) { + const repo = await prisma.repository.findFirst({ + where: { userId, fullName: { equals: fullName, mode: "insensitive" } }, + select: { owner: true, name: true, fullName: true }, + }) + if (!repo) throw new Error("Repository is not connected to your account") + return repo +} + +export async function listGithubBranches(userId: string, fullName: string) { + const repo = await connectedGithubRepository(userId, fullName) + const github = await githubForUser(userId) + const { data: remote } = await github.rest.repos.get({ owner: repo.owner, repo: repo.name }) + const defaultBranch = remote.default_branch + const branches: Array<{ name: string; sha: string; isDefault: boolean }> = [] + let truncated = false + for (let page = 1; page <= 10; page++) { + const response = await github.rest.repos.listBranches({ owner: repo.owner, repo: repo.name, per_page: 100, page }) + branches.push(...response.data.map((branch) => ({ name: branch.name, sha: branch.commit.sha, isDefault: branch.name === defaultBranch }))) + const hasNext = /rel="next"/.test(response.headers.link ?? "") + if (!hasNext) break + if (page === 10) truncated = true + } + return { branches, defaultBranch, truncated } +} + +export async function resolveGithubSource(userId: string, fullName: string, branch?: string) { + const repo = await connectedGithubRepository(userId, fullName) + const github = await githubForUser(userId) + if (!branch) { + const { data } = await github.rest.repos.get({ owner: repo.owner, repo: repo.name }) + branch = data.default_branch + } + const { data } = await github.rest.repos.getBranch({ owner: repo.owner, repo: repo.name, branch }) + const { githubSourceSchema } = await import("./github-source") + return githubSourceSchema.parse({ repositoryFullName: repo.fullName, branch: data.name, sha: data.commit.sha }) +} + export async function indexGithubRepository( userId: string, fullName: string, diff --git a/apps/web/modules/nova/local-projects/pack.ts b/apps/web/modules/nova/local-projects/pack.ts index 0071309b..ce96b59b 100644 --- a/apps/web/modules/nova/local-projects/pack.ts +++ b/apps/web/modules/nova/local-projects/pack.ts @@ -8,6 +8,8 @@ import { type LocalAttachment, } from "@/modules/nova/attachments/contracts" import type { LocalProjectSummary } from "@/modules/nova/local-projects/contracts" +import { connectedGithubRepository } from "./github" +import { assertGithubSourceRepository, type GithubSource } from "./github-source" import { isLikelyTextProjectPath, MAX_PROJECT_PACK_FILES, @@ -41,17 +43,31 @@ export async function packGithubProjectForTurn( project: LocalProjectSummary, objective: string, existing: LocalAttachment[] = [], + source?: GithubSource, ): Promise { const fullName = project.repositoryFullName + if (source) assertGithubSourceRepository(source, fullName) if (!fullName) return existing const [owner, name] = fullName.split("/") if (!owner || !name) return existing - const paths = (project.paths ?? []).filter(isLikelyTextProjectPath) - if (paths.length === 0) return existing - const github = await githubForUser(userId) - if (!github) return existing + if (!github) { + if (source) throw new Error("GitHub authorization is unavailable") + return existing + } + let paths = (project.paths ?? []).filter(isLikelyTextProjectPath) + if (source) { + await connectedGithubRepository(userId, source.repositoryFullName) + const { data: tree } = await github.rest.git.getTree({ owner, repo: name, tree_sha: source.sha, recursive: "true" }) + paths = (tree.tree ?? []).flatMap((item) => item.type === "blob" && item.path && isLikelyTextProjectPath(item.path) ? [item.path] : []) + project.paths = paths + project.fileCount = paths.length + project.truncated = Boolean(tree.truncated) + const sourcePaths = new Set((tree.tree ?? []).flatMap((item) => item.type === "blob" && item.path ? [item.path] : [])) + existing = existing.filter((file) => !sourcePaths.has(file.name)) + } + if (paths.length === 0) return existing const room = Math.max(0, MAX_PROJECT_PACK_FILES - existing.length) if (room === 0) return existing @@ -69,7 +85,7 @@ export async function packGithubProjectForTurn( const results = await Promise.all( batch.map(async ({ path }) => { try { - const { data } = await github.rest.repos.getContent({ owner, repo: name, path }) + const { data } = await github.rest.repos.getContent({ owner, repo: name, path, ...(source ? { ref: source.sha } : {}) }) if (Array.isArray(data) || data.type !== "file" || !("content" in data) || typeof data.content !== "string") { return null } @@ -86,6 +102,7 @@ export async function packGithubProjectForTurn( text: text.slice(0, MAX_LOCAL_FILE_BYTES), } satisfies LocalAttachment } catch { + if (source) throw new Error("Could not read immutable GitHub source") return null } }), diff --git a/apps/web/modules/nova/local-projects/service.ts b/apps/web/modules/nova/local-projects/service.ts index d37fc3f5..0c5e08b9 100644 --- a/apps/web/modules/nova/local-projects/service.ts +++ b/apps/web/modules/nova/local-projects/service.ts @@ -1,4 +1,5 @@ import prisma from "@super/db" +import { githubSourceFromPolicy } from "./github-source" import { MAX_PROJECT_PATHS, @@ -155,9 +156,10 @@ export async function bindSessionLocalProject( const organizationId = await ensureOrg(userId) const session = await prisma.agentSession.findFirst({ where: { id: sessionId, organizationId }, - select: { id: true, localProjectId: true, parentSessionId: true, localWorkspaceBinding: true, _count: { select: { sideThreads: true } } }, + select: { id: true, localProjectId: true, parentSessionId: true, localWorkspaceBinding: true, policySnapshot: true, _count: { select: { sideThreads: true } } }, }) if (!session) return null + if (githubSourceFromPolicy(session.policySnapshot) && session.localProjectId !== projectId) throw new Error("A GitHub source thread keeps its original project; start a new thread to choose another") if (session.localWorkspaceBinding && session.localProjectId !== projectId) throw new Error("A local worktree thread keeps its original project; start a new thread to choose another") if (session.localProjectId !== projectId && (session.parentSessionId || session._count.sideThreads > 0)) { throw new Error("Threads with side conversations share their original project") diff --git a/apps/web/modules/nova/local-projects/worktree-binding.ts b/apps/web/modules/nova/local-projects/worktree-binding.ts index 08afc223..eaacb4d2 100644 --- a/apps/web/modules/nova/local-projects/worktree-binding.ts +++ b/apps/web/modules/nova/local-projects/worktree-binding.ts @@ -1,5 +1,6 @@ import prisma from "@super/db" import { z } from "zod" +import { githubSourceFromPolicy } from "./github-source" import { Prisma } from "../../../../../packages/db/src/generated" @@ -59,7 +60,7 @@ export function createLocalWorktreeBindingService(repository: BindingRepository) async function read(userId: string, sessionId: string) { const session = await repository.agentSession.findFirst({ where: ownedWhere(userId, sessionId), - select: { localWorkspaceBinding: true, activeRunId: true, parentSessionId: true }, + select: { localWorkspaceBinding: true, activeRunId: true, parentSessionId: true, policySnapshot: true }, }) if (!session) throw new LocalWorktreeBindingError("Session not found", 404) return session @@ -73,6 +74,7 @@ export function createLocalWorktreeBindingService(repository: BindingRepository) async function bindLocalWorktree(userId: string, sessionId: string, input: LocalWorktreeBinding): Promise { const binding = localWorktreeBindingSchema.parse(input) const session = await read(userId, sessionId) + if (githubSourceFromPolicy(session.policySnapshot)) throw new LocalWorktreeBindingError("GitHub source sessions cannot bind a local workspace", 409) if (session.parentSessionId) throw new LocalWorktreeBindingError("Side threads cannot bind a local workspace", 409) if (session.localWorkspaceBinding !== null) { const existing = localWorktreeBindingSchema.parse(session.localWorkspaceBinding) diff --git a/apps/web/modules/nova/sandbox/e2b-checkout.test.ts b/apps/web/modules/nova/sandbox/e2b-checkout.test.ts new file mode 100644 index 00000000..1be658c9 --- /dev/null +++ b/apps/web/modules/nova/sandbox/e2b-checkout.test.ts @@ -0,0 +1,23 @@ +import { expect, spyOn, test } from "bun:test" + +import { checkoutE2B } from "./e2b-checkout" +import type { E2BWorkspace } from "./e2b" + +test("E2B archive request uses the exact commit rather than a branch or default", async () => { + const sha = "a".repeat(40) + const fetchSpy = spyOn(globalThis, "fetch").mockResolvedValue(new Response(new Uint8Array([1, 2, 3]))) + const commands: unknown[] = [] + const workspace = { + sandbox: { files: { write: async () => {} } }, + runBounded: async (...args: unknown[]) => { commands.push(args); return { successful: true } }, + } as unknown as E2BWorkspace + try { + await checkoutE2B(workspace, "fork/repo", "fixture", new AbortController().signal, sha) + expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(`https://api.github.com/repos/fork/repo/tarball/${sha}`) + expect(commands).toHaveLength(2) + await expect(checkoutE2B(workspace, "fork/repo", "fixture", new AbortController().signal, "main")).rejects.toThrow("Invalid") + expect(fetchSpy).toHaveBeenCalledTimes(1) + } finally { + fetchSpy.mockRestore() + } +}) diff --git a/apps/web/modules/nova/sandbox/e2b-checkout.ts b/apps/web/modules/nova/sandbox/e2b-checkout.ts index 3b252e1a..41e76068 100644 --- a/apps/web/modules/nova/sandbox/e2b-checkout.ts +++ b/apps/web/modules/nova/sandbox/e2b-checkout.ts @@ -2,10 +2,11 @@ import type { E2BWorkspace } from "./e2b" import { WORKSPACE } from "./policy" // Fetch the archive in the control plane; no GitHub credential enters the VM. -export async function checkoutE2B(workspace: E2BWorkspace, repository: string, token: string, signal: AbortSignal): Promise { +export async function checkoutE2B(workspace: E2BWorkspace, repository: string, token: string, signal: AbortSignal, sha?: string): Promise { if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new Error("Invalid repository binding") + if (sha !== undefined && !/^[a-f0-9]{40}$/.test(sha)) throw new Error("Invalid GitHub source commit") const boundedSignal = AbortSignal.any([signal, AbortSignal.timeout(90_000)]) - const response = await fetch(`https://api.github.com/repos/${repository}/tarball`, { + const response = await fetch(`https://api.github.com/repos/${repository}/tarball${sha ? `/${sha}` : ""}`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, signal: boundedSignal, redirect: "follow", }) diff --git a/apps/web/modules/nova/sandbox/github-checkout.test.ts b/apps/web/modules/nova/sandbox/github-checkout.test.ts new file mode 100644 index 00000000..d8e893d0 --- /dev/null +++ b/apps/web/modules/nova/sandbox/github-checkout.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, expect, mock, test } from "bun:test" + +const source = { repositoryFullName: "fork/repo", branch: "feature/topic", sha: "a".repeat(40) } +let head = source.sha +let retained: Record | null = null +const commands: string[][] = [] +const updates: Array> = [] +const db = { + $queryRaw: async () => [], + novaSandboxSession: { + count: async () => 0, + findUnique: async () => retained, + create: async () => ({ id: "registry" }), + updateMany: async ({ data }: { data: Record }) => { updates.push(data); return { count: 1 } }, + }, + agentRun: { update: async () => ({}) }, + novaUsageLedger: { upsert: async () => ({}) }, + $transaction: async (fn: (tx: unknown) => unknown): Promise => fn(db), +} +mock.module("@super/db", () => ({ default: db })) +mock.module("@/modules/github/lib/github", () => ({ getGithubTokenForUser: async () => "fixture" })) +mock.module("./billing", () => ({ reserveSandboxCredits: async () => ({ cancel: async () => {}, settle: async () => {} }), recoverSandboxCredits: async () => {} })) +const sandbox = { + update: async () => {}, + stop: async () => {}, + currentSession: () => ({ sessionId: "provider-session" }), + runCommand: async (input: { args: string[] }) => { + commands.push(input.args) + return { + async *logs() { yield { stream: "stdout", data: input.args[0] === "rev-parse" ? head : "" } }, + wait: async () => ({ exitCode: 0 }), + kill: async () => {}, + } + }, +} +mock.module("@vercel/sandbox", () => ({ APIError: class extends Error {}, Sandbox: class { static create = async () => sandbox } })) +const { openSandboxWorkspace } = await import("./service") +const input = () => ({ userId: "u", organizationId: "org", sessionId: "s", runId: "r", repositoryFullName: source.repositoryFullName, githubSource: source, signal: new AbortController().signal }) + +beforeEach(() => { commands.length = 0; updates.length = 0; retained = null; head = source.sha }) + +test("Vercel fetches and detaches at the exact resolved commit", async () => { + const workspace = await openSandboxWorkspace(input()) + expect(commands.some((args) => args.includes("fetch") && args.at(-1) === source.sha)).toBe(true) + expect(commands.some((args) => args.includes("checkout") && args.includes("--detach") && args.at(-1) === source.sha)).toBe(true) + expect(updates.some((data) => data.baseSha === source.sha && data.branch === source.branch)).toBe(true) + await workspace.close() +}) + +test("a mismatched checkout fails instead of running on the default branch", async () => { + head = "b".repeat(40) + await expect(openSandboxWorkspace(input())).rejects.toThrow("could not be prepared") + expect(updates.some((data) => data.status === "running")).toBe(false) +}) + +test("retained workspaces with a different source fail before provider acquisition", async () => { + retained = { id: "registry", expiresAt: new Date(Date.now() + 60_000), baseSha: "b".repeat(40), branch: source.branch } + await expect(openSandboxWorkspace(input())).rejects.toThrow("does not match") + expect(commands).toHaveLength(0) + await expect(openSandboxWorkspace({ ...input(), repositoryFullName: "upstream/repo" })).rejects.toThrow("immutable") +}) diff --git a/apps/web/modules/nova/sandbox/service.ts b/apps/web/modules/nova/sandbox/service.ts index 77cd267d..78550197 100644 --- a/apps/web/modules/nova/sandbox/service.ts +++ b/apps/web/modules/nova/sandbox/service.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto" import { APIError, Sandbox } from "@vercel/sandbox" import { NotFoundError, Sandbox as E2BSandbox } from "e2b" import prisma from "@super/db" +import { assertGithubSourceRepository, githubSourceFromPolicy, githubSourceSchema, type GithubSource } from "@/modules/nova/local-projects/github-source" import { getGithubTokenForUser } from "@/modules/github/lib/github" import { createE2BWorkspace, e2bCredentials, e2bNetwork, E2BWorkspace } from "./e2b" @@ -18,24 +19,28 @@ export async function sandboxEligibility(userId: string, sessionId: string) { const session = await prisma.agentSession.findUnique({ where: { id: sessionId }, include: { localProject: true } }) if (!session || !sandboxEnabled(userId, session.organizationId)) return null const project = session.localProject + const githubSource = githubSourceFromPolicy(session.policySnapshot) + if (githubSource) assertGithubSourceRepository(githubSource, project?.repositoryFullName) if (!project?.repositoryFullName || project.status !== "active") return null const membership = await prisma.organizationMembership.findUnique({ where: { organizationId_userId: { organizationId: session.organizationId, userId } } }) if (membership?.status !== "active" || project.userId !== userId || project.organizationId !== session.organizationId) throw new Error("Cloud workspace access denied") const repository = await prisma.repository.findFirst({ where: { userId, fullName: project.repositoryFullName }, select: { fullName: true } }) if (!repository) throw new Error("Connect the selected GitHub repository before using cloud Agent mode") - return { organizationId: session.organizationId, repositoryFullName: repository.fullName } + return { organizationId: session.organizationId, repositoryFullName: repository.fullName, ...(githubSource ? { githubSource } : {}) } } -type WorkspaceInput = { userId: string; sessionId: string; runId: string; organizationId: string; repositoryFullName: string; machineSize?: MachineSize; signal: AbortSignal } +type WorkspaceInput = { userId: string; sessionId: string; runId: string; organizationId: string; repositoryFullName: string; githubSource?: GithubSource; machineSize?: MachineSize; signal: AbortSignal } export async function openSandboxWorkspace(input: WorkspaceInput) { + const source = input.githubSource ? githubSourceSchema.parse(input.githubSource) : undefined + if (source) assertGithubSourceRepository(source, input.repositoryFullName) const provider = sandboxProvider() const machineSize = validateMachineSelection(input.machineSize) let resources: { cpuCount: number; memoryMB: number } | undefined const credentials = provider === "vercel" ? sandboxCredentials() : (e2bCredentials(), {}) const policy = executionPolicy() const domains = typeof policy === "object" ? Object.keys(policy.allow ?? {}) : [] - const sandboxName = `${provider === "e2b" ? "nova-e2b" : "nova"}-${createHash("sha256").update(JSON.stringify([input.organizationId, input.userId, input.sessionId, input.repositoryFullName])).digest("hex").slice(0, 40)}` + const sandboxName = `${provider === "e2b" ? "nova-e2b" : "nova"}-${createHash("sha256").update(JSON.stringify([input.organizationId, input.userId, input.sessionId, input.repositoryFullName, ...(source ? [source.sha] : [])])).digest("hex").slice(0, 40)}` const now = new Date() // Serialize quota checks across all workspace claims in this organization. const registry = await prisma.$transaction(async (tx) => { @@ -46,6 +51,7 @@ export async function openSandboxWorkspace(input: WorkspaceInput) { if (row?.leaseRunId || row?.status === "recovering") throw new Error("This cloud workspace is busy or awaiting recovery; retry after cleanup") if (row && row.expiresAt <= now) throw new Error("Cloud workspace retention expired; start a new thread to avoid losing prior edits silently") if (row && !row.baseSha) throw new Error("Cloud workspace setup was interrupted; start a new thread") + if (row && source && (row.branch !== source.branch || (provider === "vercel" && row.baseSha !== source.sha))) throw new Error("Cloud workspace source does not match the session") if (row?.baseSha && provider === "e2b" && machineSize !== "default") { if (!row.providerSandboxId) throw new Error("E2B workspace identity is missing") const info = await E2BSandbox.getInfo(row.providerSandboxId, { ...e2bCredentials(), signal: input.signal, requestTimeoutMs: 10_000 }) @@ -109,7 +115,7 @@ export async function openSandboxWorkspace(input: WorkspaceInput) { const token = await getGithubTokenForUser(input.userId) sandbox = await createE2BWorkspace(sandboxName, input.signal, machineSize) await prisma.novaSandboxSession.updateMany({ where: { id: registry.id, leaseRunId: input.runId }, data: { providerSandboxId: sandbox.sandbox.sandboxId } }) - await checkoutE2B(sandbox, input.repositoryFullName, token, input.signal) + await checkoutE2B(sandbox, input.repositoryFullName, token, input.signal, source?.sha) const head = await runBounded(sandbox, "/usr/bin/git", ["rev-parse", "HEAD"], { signal: input.signal }) baseSha = head.stdout.trim() if (!head.successful || !/^[a-f0-9]{40}$/.test(baseSha)) throw new Error("Could not determine checkout base commit") @@ -126,9 +132,16 @@ export async function openSandboxWorkspace(input: WorkspaceInput) { sandbox = await Sandbox.create({ ...credentials, name: sandboxName, image: "vercel/sandbox/universal:latest", resources: { vcpus: 2 }, timeout: VM_MS, persistent: true, snapshotExpiration: RETENTION_MS, keepLastSnapshots: { count: 1 }, networkPolicy: checkoutPolicy(input.repositoryFullName, token), signal: input.signal }) const clone = await runBounded(sandbox, "/usr/bin/git", ["-c", "credential.helper=", "-c", "core.hooksPath=/dev/null", "-c", "filter.lfs.required=false", "-c", "filter.lfs.smudge=", "clone", "--depth=1", "--", `https://github.com/${input.repositoryFullName}.git`, WORKSPACE], { signal: input.signal, cwd: "/vercel/sandbox", timeoutMs: 90_000 }) if (!clone.successful) throw new Error("GitHub checkout failed; check repository access") + if (source) { + const fetched = await runBounded(sandbox, "/usr/bin/git", ["-c", "credential.helper=", "-c", "core.hooksPath=/dev/null", "fetch", "--depth=1", "origin", source.sha], { signal: input.signal, timeoutMs: 90_000 }) + if (!fetched.successful) throw new Error("Pinned GitHub commit is unavailable") + const checked = await runBounded(sandbox, "/usr/bin/git", ["-c", "core.hooksPath=/dev/null", "-c", "filter.lfs.required=false", "-c", "filter.lfs.smudge=", "checkout", "--detach", source.sha], { signal: input.signal }) + if (!checked.successful) throw new Error("Pinned GitHub checkout failed") + } const head = await runBounded(sandbox, "/usr/bin/git", ["rev-parse", "HEAD"], { signal: input.signal }) baseSha = head.stdout.trim() if (!head.successful || !/^[a-f0-9]{40}$/.test(baseSha)) throw new Error("Could not determine checkout base commit") + if (source && baseSha !== source.sha) throw new Error("GitHub checkout did not match the pinned commit") } // No repository-controlled code is executed while the GitHub broker is active. if (sandbox instanceof E2BWorkspace) { @@ -138,7 +151,7 @@ export async function openSandboxWorkspace(input: WorkspaceInput) { assertMachineResources(machineSize, info, Boolean(registry.baseSha)) await sandbox.sandbox.updateNetwork(e2bNetwork(domains), { signal: input.signal }) } else await sandbox.update({ networkPolicy: policy }, { signal: input.signal }) - await prisma.novaSandboxSession.updateMany({ where: { id: registry.id, leaseRunId: input.runId }, data: { baseSha, branch: "default", status: "running", providerSessionId: sandbox instanceof E2BWorkspace ? null : sandbox.currentSession().sessionId } }) + await prisma.novaSandboxSession.updateMany({ where: { id: registry.id, leaseRunId: input.runId }, data: { baseSha, branch: source?.branch ?? "default", status: "running", providerSessionId: sandbox instanceof E2BWorkspace ? null : sandbox.currentSession().sessionId } }) const activeSandbox = sandbox return { provider, diff --git a/apps/web/modules/nova/sessions/github-source.test.ts b/apps/web/modules/nova/sessions/github-source.test.ts new file mode 100644 index 00000000..16016c3b --- /dev/null +++ b/apps/web/modules/nova/sessions/github-source.test.ts @@ -0,0 +1,54 @@ +import { beforeEach, expect, mock, test } from "bun:test" + +const source = { repositoryFullName: "fork/repo", branch: "feature/topic", sha: "a".repeat(40) } +let parent: Record | null = null +let project: Record | null = null +let session: Record = {} +let resolutions: unknown[] = [] +const db = { + organizationMembership: { findUnique: async () => ({ id: "m", status: "active" }) }, + agentSession: { + findFirst: async () => parent, + create: async ({ data }: { data: Record }) => { session = { ...data, id: "s", status: "active", activeRunId: null, updatedAt: new Date() }; return session }, + findUniqueOrThrow: async () => ({ ...session, surfaces: [] }), + }, + webLocalProject: { findFirst: async () => project, update: async () => ({}) }, + sessionSurface: { create: async () => ({ id: "surface" }) }, + agentActivity: { create: async () => ({}) }, + novaAuditEvent: { create: async () => ({}) }, + $transaction: async (fn: (tx: unknown) => unknown): Promise => fn(db), +} +mock.module("@super/db", () => ({ default: db })) +mock.module("@/modules/integrations/lib/org", () => ({ ensureUserOrganization: async () => "org" })) +mock.module("@/modules/nova/local-projects/github", () => ({ resolveGithubSource: async (...args: unknown[]) => { resolutions.push(args); return source } })) +const { createAgentSession } = await import("./service") + +beforeEach(() => { parent = null; project = { id: "p", repositoryFullName: "fork/repo" }; session = {}; resolutions = [] }) + +test("explicit branch resolution is persisted and serialized, not trusted from the client", async () => { + const summary = await createAgentSession({ userId: "u", objective: "work", localProjectId: "p", githubBranch: "feature/topic" }) + expect(resolutions).toEqual([["u", "fork/repo", "feature/topic"]]) + expect(session.policySnapshot).toEqual({ githubSource: source }) + expect(summary.githubSource).toEqual(source) +}) + +test("legacy or companion sessions without a branch remain unpinned", async () => { + expect((await createAgentSession({ userId: "u", objective: "work", localProjectId: "p" })).githubSource).toBeUndefined() + expect(resolutions).toHaveLength(0) +}) + +test("side threads inherit the immutable SHA even if branch head advances", async () => { + parent = { id: "parent", localProjectId: "p", policySnapshot: { githubSource: source } } + expect((await createAgentSession({ userId: "u", objective: "side", parentSessionId: "parent" })).githubSource).toEqual(source) + expect(resolutions).toHaveLength(0) + await expect(createAgentSession({ userId: "u", objective: "side", parentSessionId: "parent", githubBranch: "other" })).rejects.toThrow("inherit") + project = { id: "p", repositoryFullName: "upstream/repo" } + await expect(createAgentSession({ userId: "u", objective: "side", parentSessionId: "parent" })).rejects.toThrow("immutable") +}) + +test("branch selection requires an authorized connected project", async () => { + project = null + await expect(createAgentSession({ userId: "u", objective: "work", localProjectId: "not-owned", githubBranch: "topic" })).rejects.toThrow("connected GitHub project") + await expect(createAgentSession({ userId: "u", objective: "work", githubBranch: "topic" })).rejects.toThrow("connected GitHub project") + expect(resolutions).toHaveLength(0) +}) diff --git a/apps/web/modules/nova/sessions/service.ts b/apps/web/modules/nova/sessions/service.ts index d0b05960..3547bbc2 100644 --- a/apps/web/modules/nova/sessions/service.ts +++ b/apps/web/modules/nova/sessions/service.ts @@ -1,4 +1,6 @@ import prisma from "@super/db" +import { resolveGithubSource } from "@/modules/nova/local-projects/github" +import { assertGithubSourceRepository, githubSourceFromPolicy, type GithubSource } from "@/modules/nova/local-projects/github-source" import { NOVA_CONTRACT_VERSION, type AgentSessionSummary, @@ -38,6 +40,7 @@ function serializeSurface(surface: { } function serializeSession(session: { + policySnapshot?: unknown parentSessionId?: string | null agentId?: string | null id: string @@ -63,6 +66,7 @@ function serializeSession(session: { return { contractVersion: NOVA_CONTRACT_VERSION, id: session.id, + githubSource: githubSourceFromPolicy(session.policySnapshot), agentId: session.agentId ?? null, parentSessionId: session.parentSessionId ?? null, createdAt: session.createdAt?.toISOString(), @@ -182,6 +186,7 @@ export async function createAgentSession(input: { surface?: NovaSurfaceProvider parentSessionId?: string localProjectId?: string | null + githubBranch?: string agentId?: string | null }): Promise { const organizationId = await ensureUserOrganization(input.userId) @@ -189,10 +194,19 @@ export async function createAgentSession(input: { const objective = input.objective.trim() if (!objective) throw new Error("Session objective is required") const surfaceProvider = input.surface === "desktop" ? "desktop" : "web" + let resolvedSource: GithubSource | undefined + if (input.githubBranch && !input.parentSessionId) { + const project = input.localProjectId ? await prisma.webLocalProject.findFirst({ + where: { id: input.localProjectId, userId: input.userId, organizationId, status: "active" }, + select: { repositoryFullName: true }, + }) : null + if (!project?.repositoryFullName) throw new Error("A connected GitHub project is required for branch selection") + resolvedSource = await resolveGithubSource(input.userId, project.repositoryFullName, input.githubBranch) + } return prisma.$transaction(async (tx) => { const parent = input.parentSessionId - ? await tx.agentSession.findFirst({ where: { id: input.parentSessionId, organizationId }, select: { id: true, parentSessionId: true, localProjectId: true, agentId: true, localWorkspaceBinding: true } }) + ? await tx.agentSession.findFirst({ where: { id: input.parentSessionId, organizationId }, select: { id: true, parentSessionId: true, localProjectId: true, agentId: true, localWorkspaceBinding: true, policySnapshot: true } }) : null if (input.parentSessionId && !parent) throw new Error("Parent thread not found") if (parent?.parentSessionId) throw new Error("Create side threads from the main thread") @@ -204,6 +218,8 @@ export async function createAgentSession(input: { } const requestedProjectId = parent ? parent.localProjectId : input.localProjectId let localProjectId: string | null = null + const githubSource = parent ? githubSourceFromPolicy(parent.policySnapshot) : resolvedSource + if (parent && input.githubBranch && input.githubBranch !== githubSource?.branch) throw new Error("Side threads inherit their parent's GitHub source") if (requestedProjectId) { const project = await tx.webLocalProject.findFirst({ where: { @@ -212,10 +228,12 @@ export async function createAgentSession(input: { organizationId, status: "active", }, - select: { id: true }, + select: { id: true, repositoryFullName: true }, }) localProjectId = project?.id ?? null + if (githubSource) assertGithubSourceRepository(githubSource, project?.repositoryFullName) } + if (input.githubBranch && !localProjectId) throw new Error("A connected GitHub project is required for branch selection") const session = await tx.agentSession.create({ data: { @@ -227,6 +245,7 @@ export async function createAgentSession(input: { parentSessionId: parent?.id ?? null, agentId: requestedAgentId, localProjectId, + ...(githubSource ? { policySnapshot: { githubSource } } : {}), }, }) if (localProjectId) { diff --git a/apps/web/modules/nova/sessions/turn.ts b/apps/web/modules/nova/sessions/turn.ts index bb518b60..b9fefbfe 100644 --- a/apps/web/modules/nova/sessions/turn.ts +++ b/apps/web/modules/nova/sessions/turn.ts @@ -37,6 +37,7 @@ import { type FileProposal, } from "@/modules/nova/agent-files/parse-proposals" import { packGithubProjectForTurn } from "@/modules/nova/local-projects/pack" +import { assertGithubSourceRepository, githubSourceFromPolicy } from "@/modules/nova/local-projects/github-source" import { formatLocalProjectContext } from "@/modules/nova/local-projects/service" import { assertWorktreeContext, formatWorktreeContext, type WorktreeContext } from "@/modules/nova/local-projects/worktree-context" import { getLocalWorktreeBinding } from "@/modules/nova/local-projects/worktree-binding" @@ -169,6 +170,7 @@ async function buildTurnContext( where: { id: sessionId }, select: { objective: true, + policySnapshot: true, agentId: true, agent: { select: { name: true, description: true, instructions: true } }, localProject: { @@ -243,6 +245,9 @@ async function buildTurnContext( }) } + const githubSource = githubSourceFromPolicy(session.policySnapshot) + if (githubSource) assertGithubSourceRepository(githubSource, session.localProject?.repositoryFullName) + if (githubSource && session.localProject?.status !== "active") throw new Error("The pinned GitHub project is unavailable") const localProject = session.localProject && session.localProject.status === "active" ? { id: session.localProject.id, @@ -278,7 +283,7 @@ async function buildTurnContext( })), ] - return { objective: session.objective, messages: chatMessages, localProject, agentId: session.agentId } + return { objective: session.objective, messages: chatMessages, localProject, githubSource, agentId: session.agentId } } function harnessContentToText(content: HarnessChatMessage["content"]): string { @@ -555,12 +560,13 @@ export async function* runWebTurn(input: { model: selection.model, } try { - const before = localAttachments.length + const before = context.githubSource ? 0 : localAttachments.length localAttachments = await packGithubProjectForTurn( input.userId, context.localProject, content, localAttachments, + context.githubSource, ) const added = localAttachments.slice(before) if (added.length > 0) { @@ -608,6 +614,7 @@ export async function* runWebTurn(input: { } } } catch (error) { + if (context.githubSource) throw new Error("Could not load the pinned GitHub source; no default branch fallback was used") console.warn("[nova/turn] github project pack failed", error) } } else if (!workspace && localAttachments.length > 0) { @@ -661,6 +668,9 @@ export async function* runWebTurn(input: { if (resolvedReferences.context) { text += `\n\n${resolvedReferences.context}` } + if (context.githubSource) { + text += `\n\nGitHub execution source: ${context.githubSource.repositoryFullName}, branch ${context.githubSource.branch}, pinned commit ${context.githubSource.sha}. Project file reads and cloud checkout use this exact commit, not the current default branch. Unrelated user attachments are additional context, not replacements for this source.` + } if (input.localWorktree) { text += `\n\n${formatWorktreeContext(input.localWorktree)}` } else if (context.localProject && !workspace) { diff --git a/packages/nova/contracts.ts b/packages/nova/contracts.ts index 5f499d3c..07c21f47 100644 --- a/packages/nova/contracts.ts +++ b/packages/nova/contracts.ts @@ -137,6 +137,11 @@ export const agentActivitySchema = z.object({ }) export const agentSessionSummarySchema = z.object({ + githubSource: z.object({ + repositoryFullName: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/), + branch: z.string().min(1).max(255), + sha: z.string().regex(/^[a-f0-9]{40}$/), + }).optional(), contractVersion: z.literal(NOVA_CONTRACT_VERSION), id: z.string().min(1), agentId: z.string().nullable().optional(),