diff --git a/packages/server/src/services/gitea-change-requests.test.ts b/packages/server/src/services/gitea-change-requests.test.ts new file mode 100644 index 0000000000..761249197a --- /dev/null +++ b/packages/server/src/services/gitea-change-requests.test.ts @@ -0,0 +1,1599 @@ +import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { join } from "node:path"; +import pino from "pino"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createAgentMessageDelivery } from "../server/agent/agent-messages/index.js"; +import { AgentBackgroundWorkStore } from "../server/agent/background-work/index.js"; +import { createChangeRequestWatches } from "../server/agent/change-request-watches/index.js"; +import { createChangeRequestRouter } from "./change-request-router.js"; +import type { ChangeRequestSnapshot } from "./change-request-source.js"; +import { createForgeResolver } from "./forge-resolver.js"; +import { describeGiteaChangeRequest, resolveGiteaChangeRequest } from "./gitea-change-requests.js"; +import { + createGiteaService, + TeaAuthenticationError, + type TeaCommandRunner, +} from "./gitea-service.js"; + +const PR2_WORKDIR_NOTE = "cwd-free"; + +function teaHttp( + body: unknown, + options: { status?: string; headers?: Record; headersOnStderr?: boolean } = {}, +): { stdout: string; stderr: string } { + const lines = [`HTTP/1.1 ${options.status ?? "200 OK"}`]; + for (const [key, value] of Object.entries(options.headers ?? {})) { + lines.push(`${key}: ${value}`); + } + const headerBlock = `${lines.join("\r\n")}\r\n\r\n`; + const json = typeof body === "string" ? body : JSON.stringify(body); + if (options.headersOnStderr) { + return { stdout: json, stderr: headerBlock }; + } + return { stdout: `${headerBlock}${json}`, stderr: "" }; +} + +function createFakeTeaRunner( + handler: ( + args: string[], + options: { cwd: string; envOverlay?: Record }, + ) => Promise<{ stdout: string; stderr: string }> | { stdout: string; stderr: string }, +) { + const calls: Array<{ args: string[]; cwd: string }> = []; + const runner: TeaCommandRunner = async (args, options) => { + calls.push({ args: [...args], cwd: options.cwd }); + return await handler(args, options); + }; + return { runner, calls }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("Gitea-family change request URL resolution and description", () => { + it("canonicalizes Gitea, Codeberg, and self-hosted Forgejo PR URLs across tabs, queries, and ports", () => { + expect( + resolveGiteaChangeRequest("https://Codeberg.org/Org/Repo/pulls/042/files?style=split#diff-1"), + ).toBe("https://codeberg.org/org/repo/pulls/42"); + expect(resolveGiteaChangeRequest("https://gitea.com/Alice/App/pulls/7/commits/")).toBe( + "https://gitea.com/alice/app/pulls/7", + ); + expect( + resolveGiteaChangeRequest("https://Forgejo.Example.Org:3000/Team/Tool/pulls/9/checks"), + ).toBe("https://forgejo.example.org:3000/team/tool/pulls/9"); + expect(resolveGiteaChangeRequest("http://gitea.lan:3000/Team/Tool/pulls/3")).toBe( + "http://gitea.lan:3000/team/tool/pulls/3", + ); + }); + + it("maps repository case variants to one watch while preserving the mount path", () => { + const baseUrl = "https://forge.example/Apps/Gitea"; + const canonical = `${baseUrl}/org/repo/pulls/1`; + expect(resolveGiteaChangeRequest(`${baseUrl}/Org/Repo/pulls/1/files`)).toBe(canonical); + expect(resolveGiteaChangeRequest(canonical)).toBe(canonical); + }); + + it("describes cloud and self-hosted PRs with native #N numbering and host when non-default", () => { + expect(describeGiteaChangeRequest("https://codeberg.org/Org/Repo/pulls/42")).toBe( + "Org/Repo #42", + ); + expect(describeGiteaChangeRequest("https://gitea.com/Alice/App/pulls/7")).toBe("Alice/App #7"); + expect(describeGiteaChangeRequest("https://forgejo.example.org:3000/Team/Tool/pulls/9")).toBe( + "forgejo.example.org:3000/Team/Tool #9", + ); + }); + + it("rejects invalid Gitea-family PR URLs", () => { + for (const invalid of [ + "https://codeberg.org/Org/Repo/pull/42", + "https://codeberg.org/Org/Repo/issues/42", + "https://codeberg.org/Org/Repo/pulls/0", + "https://codeberg.org/Org/../pulls/42", + "https://codeberg.org/Org/Repo/pulls/42/unknown", + "http://codeberg.org/Org/Repo/pulls/42", + "http://gitea.com/Org/Repo/pulls/42", + ]) { + expect(() => resolveGiteaChangeRequest(invalid), invalid).toThrow(/pull request URL/i); + } + }); +}); + +describe("Gitea-family ChangeRequestSource polling", () => { + it("refreshes cached inline comments even if the review count stays the same", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const url = `${origin}/org/repo/pulls/1`; + let inlineId = 10; + let closed = false; + let inlineRequests = 0; + const { runner, calls } = createFakeTeaRunner((args) => { + if (args[0] === "login") + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) + return teaHttp({ number: 1, state: closed ? "closed" : "open", head: { sha: "head" } }); + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + if (endpoint.includes("/reviews?")) + return teaHttp([{ id: 5, state: "APPROVED", comments_count: 1 }]); + if (endpoint.endsWith("/reviews/5/comments")) { + inlineRequests += 1; + return teaHttp([{ id: inlineId }]); + } + return teaHttp([]); + }); + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 60_000, + }); + const seen = new Set(); + try { + service.changeRequests!.observe(url, { + knownActivity: () => seen, + async snapshot(snapshot) { + for (const item of snapshot.activity) seen.add(item.id); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(seen.has("inline:10")).toBe(true); + inlineId = 12; + await vi.advanceTimersByTimeAsync(60_000); + expect(seen.has("inline:12")).toBe(false); + expect(inlineRequests).toBe(1); + await vi.advanceTimersByTimeAsync(4 * 60_000); + expect(seen.has("inline:12")).toBe(true); + expect(calls.filter(({ args }) => args.at(-1)?.endsWith("/reviews/5/comments"))).toHaveLength( + 2, + ); + inlineId = 13; + closed = true; + await vi.advanceTimersByTimeAsync(60_000); + expect(seen.has("inline:13")).toBe(true); + } finally { + service.dispose?.(); + } + }); + + it("keeps path-mounted and root tea logins separate", async () => { + vi.useFakeTimers(); + const origin = "https://forge.example"; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { + stdout: JSON.stringify([ + { name: "subpath", url: `${origin}/apps/gitea/` }, + { name: "root", url: `${origin}/` }, + ]), + stderr: "", + }; + } + const endpoint = args.at(-1)!; + if (endpoint === "repos/Org/Repo/pulls/1") { + return teaHttp({ number: 1, state: "open", head: { sha: args[2] } }); + } + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + try { + const source = service.changeRequests!; + const snapshots: ChangeRequestSnapshot[] = []; + source.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots.map(({ headSha }) => headSha)).toEqual(["root"]); + const mountedPr = `${origin}/apps/gitea/Org/Repo/pulls/1`; + expect(source.resolve(`${mountedPr}/files?view=split`)).toBe( + `${origin}/apps/gitea/org/repo/pulls/1`, + ); + source.observe(mountedPr, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots.map(({ headSha }) => headSha)).toEqual(["root", "subpath"]); + } finally { + service.dispose?.(); + } + }); + + it.each(["Gitea page", "Forgejo array", "unrelated run"])( + "correlates Actions jobs from a %s response with the watched run", + async (shape) => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const run = `${origin}/Org/Repo/actions/runs/100`; + const responseRun = shape === "unrelated run" ? `${origin}/Org/Repo/actions/runs/99` : run; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + if (endpoint.includes("/status?")) { + return teaHttp({ + statuses: [ + { id: 1, status: "success", context: "CI / job", target_url: `${run}/jobs/1` }, + ], + }); + } + if (endpoint.includes("/actions/tasks?")) { + return teaHttp({ + workflow_runs: [ + { + id: 55, + name: "job", + head_sha: "head", + status: shape === "unrelated run" ? "success" : "failure", + url: run, + }, + { id: 56, name: "job", head_sha: "head", status: "success", url: run }, + ], + total_count: 2, + }); + } + if (endpoint.includes("/actions/runs/100/jobs?")) { + const jobs = [ + { + id: 201, + name: "job", + status: "completed", + conclusion: "failure", + html_url: `${responseRun}/jobs/0`, + }, + { + id: 202, + name: "job", + status: "completed", + conclusion: "success", + html_url: `${responseRun}/jobs/1`, + }, + ]; + return teaHttp(shape === "Forgejo array" ? jobs : { jobs, total_count: jobs.length }); + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + if (shape === "unrelated run") { + expect(snapshots[0]?.checksState).toBe("passed"); + expect(snapshots[0]?.checks.map(({ url }) => url)).toEqual([`${run}/jobs/1`, run, run]); + } else { + expect(snapshots[0]?.checksState).toBe("failed"); + expect(snapshots[0]?.checks.map(({ state, url }) => [state, url])).toEqual([ + ["failed", `${run}/jobs/0`], + ["passed", `${run}/jobs/1`], + ]); + } + } finally { + service.dispose?.(); + } + }, + ); + + it("refreshes the named tea login when the user changes its destination", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + let changed = false; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") + return { + stdout: JSON.stringify( + changed + ? [ + { name: "old", url: "https://forge.example" }, + { name: "new", url: origin }, + ] + : [{ name: "old", url: origin }], + ), + stderr: "", + }; + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) { + const correct = !changed || args[2] === "new"; + return teaHttp({ + number: 1, + state: correct ? "open" : "closed", + html_url: `${correct ? origin : "https://forge.example"}/Org/Repo/pulls/1`, + head: { sha: correct ? "intended" : "wrong" }, + }); + } + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + return teaHttp([]); + }); + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 10_000, + }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + changed = true; + await vi.advanceTimersByTimeAsync(10_000); + expect(snapshots.map(({ state, headSha }) => [state, headSha])).toEqual([ + ["open", "intended"], + ["open", "intended"], + ]); + } finally { + service.dispose?.(); + } + }); + + it("rejects overlapping status pages before reporting that checks passed", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const firstPage = Array.from({ length: 50 }, (_, id) => ({ id, status: "success" })); + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + if (endpoint.includes("/status?")) { + const statuses = endpoint.includes("page=1") + ? firstPage + : [firstPage[0], { id: 51, status: "success" }]; + return teaHttp({ statuses }, { headers: { "X-Total-Count": "52" } }); + } + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + const errors: unknown[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error: (error) => errors.push(error), + }); + await vi.advanceTimersByTimeAsync(25); + expect(errors).toEqual([ + expect.objectContaining({ message: expect.stringContaining("status pages") }), + ]); + expect(snapshots).toEqual([]); + } finally { + service.dispose?.(); + } + }); + + it.each(["Has been cancelled", "Canceled after 5s"])( + "keeps the canceled job neutral without run details (%s)", + async (description) => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const run = `${origin}/Org/Repo/actions/runs/42`; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + if (endpoint.includes("/status?")) { + return teaHttp({ + statuses: [{ id: 4, status: "failure", description, target_url: `${run}/jobs/2` }], + }); + } + if (endpoint.includes("/actions/tasks?")) { + return teaHttp({ + workflow_runs: [{ id: 53, head_sha: "head", status: "cancelled", url: run }], + total_count: 1, + }); + } + if (endpoint.includes("/actions/runs/42/jobs")) { + return teaHttp({ message: "Not found" }, { status: "404 Not Found" }); + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots[0]?.checksState).toBe("neutral"); + expect(snapshots[0]?.checks.map(({ state }) => state)).toEqual(["neutral", "neutral"]); + } finally { + service.dispose?.(); + } + }, + ); + + it("keeps one check for an Actions job reported as both a commit status and a run task", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const run = `${origin}/Org/Repo/actions/runs/100`; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + } + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) { + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + } + if (endpoint.includes("/status?")) { + return teaHttp({ + statuses: [{ id: 1, status: "failure", context: "build", target_url: `${run}/jobs/21` }], + }); + } + if (endpoint.includes("/actions/tasks?")) { + return teaHttp({ + workflow_runs: [{ id: 55, head_sha: "head", status: "cancelled", url: run }], + total_count: 1, + }); + } + if (endpoint.includes("/actions/runs/100/jobs?")) { + return teaHttp({ + jobs: [ + { + id: 55, + name: "build", + status: "completed", + conclusion: "cancelled", + html_url: `${run}/jobs/21`, + }, + ], + total_count: 1, + }); + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots[0]?.checks).toEqual([ + { id: "action-job:55", name: "build", state: "neutral", url: `${run}/jobs/21` }, + ]); + } finally { + service.dispose?.(); + } + }); + + it("stops admitting queued inline-comment requests after a 429", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const reviews = Array.from({ length: 8 }, (_, index) => ({ + id: index + 1, + state: "APPROVED", + comments_count: 1, + })); + let inlineRequests = 0; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + } + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) { + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + } + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + if (endpoint.includes("/reviews?")) { + return teaHttp(reviews); + } + if (endpoint.includes("/reviews/")) { + inlineRequests += 1; + if (inlineRequests === 1) { + return teaHttp( + { message: "slow down" }, + { + status: "429 Too Many Requests", + headers: { "Retry-After": "60" }, + }, + ); + } + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + const errors: unknown[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error: (error) => errors.push(error), + }); + await vi.advanceTimersByTimeAsync(25); + expect(errors).toHaveLength(1); + expect(inlineRequests).toBeGreaterThan(0); + expect(inlineRequests).toBeLessThanOrEqual(3); + await vi.advanceTimersByTimeAsync(59_999); + expect(inlineRequests).toBeLessThanOrEqual(3); + expect(snapshots).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + expect(snapshots).toHaveLength(1); + } finally { + service.dispose?.(); + } + }); + + it("reads submitted reviews after an empty page filtered by the forge", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const url = `${origin}/Org/Repo/pulls/1`; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + } + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) { + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + } + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + if (endpoint.includes("/reviews?")) { + const page = new URL(endpoint, `${origin}/`).searchParams.get("page"); + const items = page === "2" ? [{ id: 5, state: "APPROVED" }] : []; + return teaHttp(items, { headers: { "X-Total-Count": "2" } }); + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(url, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots[0]?.activity).toEqual([ + { id: "review:5", kind: "review", url: `${url}#pullrequestreview-5` }, + ]); + } finally { + service.dispose?.(); + } + }); + + it("selects the tea login for the exact web origin", async () => { + vi.useFakeTimers(); + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { + stdout: JSON.stringify([ + { name: "custom-port", url: "https://forge.example:3000" }, + { name: "http", url: "http://forge.example" }, + { name: "https", url: "https://forge.example:443" }, + ]), + stderr: "", + }; + } + const endpoint = args.at(-1)!; + if (endpoint === "repos/Org/Repo/pulls/1") { + return teaHttp({ number: 1, state: "open", head: { sha: args[2] } }); + } + if (endpoint.includes("/status?")) return teaHttp({ statuses: [] }); + if (endpoint.includes("/actions/tasks?")) return teaHttp({ workflow_runs: [] }); + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + for (const origin of ["https://forge.example", "http://forge.example"]) { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + } + await vi.advanceTimersByTimeAsync(25); + expect(snapshots.map(({ headSha }) => headSha).sort()).toEqual(["http", "https"]); + } finally { + service.dispose?.(); + } + }); + + it("keeps a sibling's pending status when a task only identifies the run", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const run = `${origin}/Org/Repo/actions/runs/100`; + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + } + const endpoint = args.at(-1)!; + if (endpoint === "repos/Org/Repo/pulls/1") { + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + } + if (endpoint.includes("/status?")) { + return teaHttp({ + statuses: [ + { id: 1, status: "success", context: "build", target_url: `${run}/jobs/0` }, + { id: 2, status: "pending", context: "test", target_url: `${run}/jobs/1` }, + ], + }); + } + if (endpoint.includes("/actions/tasks?")) { + return teaHttp({ + workflow_runs: [{ id: 55, head_sha: "head", status: "success", url: run }], + total_count: 1, + }); + } + if (endpoint.includes("/actions/runs/100/jobs?")) { + return teaHttp({ message: "Not found" }, { status: "404 Not Found" }); + } + return teaHttp([]); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, { + async snapshot(snapshot) { + snapshots.push(snapshot); + }, + error(error) { + throw error; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots).toEqual([ + expect.objectContaining({ + checksState: "pending", + checks: expect.arrayContaining([ + expect.objectContaining({ id: "status:2", state: "pending" }), + expect.objectContaining({ id: "status:1", state: "passed" }), + ]), + }), + ]); + } finally { + service.dispose?.(); + } + }); + + it("holds host slots until failed polls drain their already-started reads", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + let finishFirstReads!: () => void; + let finishLaterReads!: () => void; + const firstReads = new Promise((resolve) => { + finishFirstReads = resolve; + }); + const laterReads = new Promise((resolve) => { + finishLaterReads = resolve; + }); + let actionRequests = 0; + const { runner, calls } = createFakeTeaRunner(async (args) => { + if (args[0] === "login") + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + const endpoint = args.at(-1)!; + const pr = /\/pulls\/(\d+)$/.exec(endpoint); + if (pr) return teaHttp({ number: Number(pr[1]), state: "open", head: { sha: "head" } }); + if (endpoint.includes("/status?")) { + return teaHttp({ message: "oops" }, { status: "500 Internal Server Error" }); + } + if (endpoint.includes("/actions/tasks?")) { + if (!endpoint.includes("page=1")) return teaHttp({ workflow_runs: [], total_count: 3 }); + actionRequests += 1; + await (actionRequests <= 2 ? firstReads : laterReads); + return teaHttp({ + workflow_runs: [{ id: 1, head_sha: "head", status: "running" }], + total_count: 3, + }); + } + throw new Error(`Unexpected endpoint: ${endpoint}`); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const errors: unknown[] = []; + const observer = { + async snapshot() { + throw new Error("Expected the poll to fail"); + }, + error: (error: unknown) => errors.push(error), + }; + try { + for (const number of [1, 2, 3, 4]) { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/${number}`, observer); + } + await vi.advanceTimersByTimeAsync(25); + expect(calls.filter(({ args }) => args.at(-1)?.includes("/actions/tasks?"))).toHaveLength(2); + expect(errors).toEqual([]); + finishFirstReads(); + await vi.advanceTimersByTimeAsync(0); + expect(errors).toHaveLength(2); + expect(actionRequests).toBe(4); + finishLaterReads(); + await vi.advanceTimersByTimeAsync(0); + expect(calls.filter(({ args }) => /actions\/tasks.*page=2/.test(args.at(-1) ?? ""))).toEqual( + [], + ); + expect(errors).toHaveLength(4); + expect(errors).toEqual( + Array.from({ length: 4 }, () => expect.objectContaining({ status: 500 })), + ); + } finally { + finishFirstReads(); + finishLaterReads(); + service.dispose?.(); + } + }); + + it("pauses the host when a sibling request fails before an Actions rate limit arrives", async () => { + vi.useFakeTimers(); + const origin = "https://codeberg.org"; + const { runner, calls } = createFakeTeaRunner(async (args) => { + if (args[0] === "login") { + return { stdout: JSON.stringify([{ name: "cb", url: origin }]), stderr: "" }; + } + const endpoint = args.at(-1)!; + if (endpoint.endsWith("/pulls/1")) { + return teaHttp({ number: 1, state: "open", head: { sha: "head" } }); + } + if (endpoint.includes("/status?")) { + return teaHttp({ message: "oops" }, { status: "500 Internal Server Error" }); + } + if (endpoint.includes("/actions/tasks?")) { + await new Promise((resolve) => setTimeout(resolve, 50)); + return teaHttp( + { message: "slow down" }, + { status: "429 Too Many Requests", headers: { "Retry-After": "60" } }, + ); + } + return teaHttp({ message: "no PR" }, { status: "404 Not Found" }); + }); + const service = createGiteaService({ runner, resolveTeaPath: async () => "tea" }); + const snapshots: ChangeRequestSnapshot[] = []; + const errors: unknown[] = []; + const observer = { + async snapshot(snapshot: ChangeRequestSnapshot) { + snapshots.push(snapshot); + }, + error: (error: unknown) => errors.push(error), + }; + try { + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/1`, observer); + await vi.advanceTimersByTimeAsync(75); + expect(errors[0]).toMatchObject({ status: 500 }); + service.changeRequests!.observe(`${origin}/Org/Repo/pulls/2`, observer); + await vi.advanceTimersByTimeAsync(59_999); + expect(calls.some(({ args }) => args.at(-1)?.endsWith("/pulls/2"))).toBe(false); + expect(snapshots).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + // The first recovery poll hits another 429. The next window must + // let the waiting watch start even though that first poll failed. + expect(calls.some(({ args }) => args.at(-1)?.endsWith("/pulls/2"))).toBe(false); + await vi.advanceTimersByTimeAsync(60_050); + expect(calls.some(({ args }) => args.at(-1)?.endsWith("/pulls/2"))).toBe(true); + } finally { + service.dispose?.(); + } + }); + + it("uses cwd-free tea login list + tea api --login -i, combines statuses + Actions tasks + approval-held runs, and namespaces comments/reviews/inline", async () => { + vi.useFakeTimers(); + const prUrl = "https://codeberg.org/Alice/App/pulls/12"; + const headSha = "sha-111"; + let loginListCalls = 0; + + const { runner, calls } = createFakeTeaRunner((args) => { + if (args[0] === "login" && args[1] === "list") { + loginListCalls += 1; + return { + stdout: JSON.stringify([ + { name: "cb-login", url: "https://codeberg.org", ssh_host: "codeberg.org" }, + ]), + stderr: "", + }; + } + expect(args.slice(0, 4)).toEqual(["api", "--login", "cb-login", "-i"]); + const endpoint = args[4] ?? ""; + if (endpoint === "repos/Alice/App/pulls/12") { + return teaHttp({ + number: 12, + state: "open", + merged: false, + html_url: prUrl, + head: { sha: headSha }, + }); + } + if (endpoint.startsWith(`repos/Alice/App/commits/${headSha}/status`)) { + return teaHttp( + { + state: "pending", + total_count: 3, + statuses: [ + // Native status for run 100 job 501 owns the check result + { + id: 1, + status: "success", + context: "CI / build", + target_url: "https://codeberg.org/Alice/App/actions/runs/100/jobs/501", + }, + // Uncovered pending shadow for cross-repo approval-held run 101 + { + id: 2, + status: "pending", + context: "CI / fork-e2e", + target_url: "https://codeberg.org/Alice/App/actions/runs/101/jobs/502", + }, + // External status with warning -> non-passing failure + { + id: 3, + status: "warning", + context: "external/lint", + target_url: "https://ci.example.com/build/3", + }, + ], + }, + { headersOnStderr: true }, + ); + } + if (endpoint.startsWith("repos/Alice/App/actions/tasks")) { + return teaHttp({ + total_count: 2, + workflow_runs: [ + // Older rerun of build workflow — must be collapsed + { + id: 500, + name: "build", + head_sha: headSha, + run_number: 1, + workflow_id: "ci.yml", + status: "failure", + url: "https://codeberg.org/Alice/App/actions/runs/99/jobs/500", + }, + // Latest rerun of build workflow — passed + { + id: 501, + name: "build", + head_sha: headSha, + run_number: 2, + workflow_id: "ci.yml", + status: "success", + url: "https://codeberg.org/Alice/App/actions/runs/100/jobs/501", + }, + ], + }); + } + if (endpoint.startsWith("repos/Alice/App/actions/runs/100/jobs?")) { + return teaHttp({ + jobs: [ + { + id: 501, + name: "build", + status: "completed", + conclusion: "success", + html_url: "https://codeberg.org/Alice/App/actions/runs/100/jobs/501", + }, + ], + total_count: 1, + }); + } + if (endpoint.startsWith("repos/Alice/App/actions/runs")) { + return teaHttp({ + total_count: 1, + workflow_runs: [ + { + id: 101, + head_sha: headSha, + status: "waiting", + need_approval: false, + pull_requests: [{ head: { repo: { id: 999 } }, base: { repo: { id: 1 } } }], + }, + ], + }); + } + if (endpoint.startsWith("repos/Alice/App/issues/12/comments")) { + return teaHttp([ + { id: 10, type: "comment", html_url: `${prUrl}#issuecomment-10`, body: "Looks good" }, + { id: 11, type: "label", html_url: `${prUrl}#issuecomment-11`, body: "" }, + ]); + } + if (endpoint.startsWith("repos/Alice/App/pulls/12/reviews?")) { + return teaHttp([ + { + id: 20, + state: "APPROVED", + comments_count: 1, + submitted_at: "2026-11-20T06:00:00Z", + html_url: `${prUrl}#pullrequestreview-20`, + }, + { + id: 21, + state: "PENDING", + comments_count: 2, + html_url: `${prUrl}#pullrequestreview-21`, + }, + { + id: 22, + state: "REQUEST_REVIEW", + comments_count: 0, + html_url: `${prUrl}#pullrequestreview-22`, + }, + ]); + } + if (endpoint.startsWith("repos/Alice/App/pulls/12/reviews/20/comments")) { + return teaHttp([ + { + id: 10, // Same numeric id as issue comment 10 — must NOT collide! + html_url: `${prUrl}#issuecomment-999`, + body: "Nit here", + }, + ]); + } + throw new Error(`Unexpected tea endpoint (${PR2_WORKDIR_NOTE}): ${endpoint}`); + }); + + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + resolveRemoteUrl: async () => { + throw new Error("watch must not inspect local git remote"); + }, + watchPollMs: 10_000, + }); + const snapshots: ChangeRequestSnapshot[] = []; + const errors: unknown[] = []; + try { + const release = service.changeRequests!.observe(prUrl, { + async snapshot(s) { + snapshots.push(s); + }, + error(err) { + errors.push(err); + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(errors).toEqual([]); + expect(loginListCalls).toBe(1); + expect(snapshots).toHaveLength(1); + expect(snapshots[0]).toEqual({ + state: "open", + headSha, + checksState: "failed", + checks: [ + { + id: "status:2", + name: "CI / fork-e2e", + state: "pending", + url: "https://codeberg.org/Alice/App/actions/runs/101/jobs/502", + }, + { + id: "status:3", + name: "external/lint", + state: "failed", + url: "https://ci.example.com/build/3", + }, + { + id: "action-job:501", + name: "build", + state: "passed", + url: "https://codeberg.org/Alice/App/actions/runs/100/jobs/501", + }, + ], + reviewDecision: null, + activity: [ + { id: "comment:10", kind: "comment", url: `${prUrl}#issuecomment-10` }, + { id: "review:20", kind: "review", url: `${prUrl}#pullrequestreview-20` }, + { id: "inline:10", kind: "inline comment", url: `${prUrl}#issuecomment-999` }, + ], + }); + expect(calls.some((c) => c.args.includes("reviews/21/comments"))).toBe(false); + release(); + } finally { + service.dispose?.(); + } + }); + + it("inspects HTTP status codes directly instead of trusting exit code 0 (500, 401, 429, missing status)", async () => { + vi.useFakeTimers(); + vi.setSystemTime(1_700_000_000_000); + const prUrl = "https://gitea.com/Org/Repo/pulls/5"; + let step = 0; + let loginLists = 0; + + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + loginLists += 1; + return { + stdout: JSON.stringify([{ name: "gitea-main", url: "https://gitea.com" }]), + stderr: "", + }; + } + step += 1; + // Step 1: exit 0 with HTTP 500 on stdout -> must fail poll + if (step === 1) { + return teaHttp({ message: "boom" }, { status: "500 Internal Server Error" }); + } + // Step 2: exit 0 with NO HTTP status line -> must fail poll + if (step === 2) { + return { stdout: JSON.stringify({ number: 5 }), stderr: "" }; + } + // Step 3: exit 0 with HTTP 401 on stderr -> TeaAuthenticationError + if (step === 3) { + return teaHttp( + { message: "token expired" }, + { status: "401 Unauthorized", headersOnStderr: true }, + ); + } + // Step 4: exit 0 with HTTP 429 + Retry-After: 50 -> pauses host for 50s + if (step === 4) { + return teaHttp( + { message: "slow down" }, + { status: "429 Too Many Requests", headers: { "Retry-After": "50" } }, + ); + } + const endpoint = args[4] ?? ""; + if (endpoint === "repos/Org/Repo/pulls/5") { + return teaHttp({ + number: 5, + state: "open", + merged: false, + html_url: prUrl, + head: { sha: "ok" }, + }); + } + if (endpoint.includes("/status")) { + return teaHttp({ state: "", statuses: [], total_count: 0 }); + } + if (endpoint.includes("/actions/tasks")) { + return teaHttp({ message: "Not Found" }, { status: "404 Not Found" }); + } + return teaHttp([]); + }); + + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 10_000, + }); + const errors: unknown[] = []; + const snapshots: ChangeRequestSnapshot[] = []; + try { + service.changeRequests!.observe(prUrl, { + async snapshot(s) { + snapshots.push(s); + }, + error(err) { + errors.push(err); + }, + }); + + // Step 1: HTTP 500 (exit 0) + await vi.advanceTimersByTimeAsync(25); + expect(errors).toHaveLength(1); + expect(snapshots).toHaveLength(0); + + // Step 2: Missing HTTP status line (after 10s backoff) + await vi.advanceTimersByTimeAsync(10_000); + expect(errors).toHaveLength(2); + + // Step 3: HTTP 401 (after 20s backoff) + await vi.advanceTimersByTimeAsync(20_000); + expect(errors).toHaveLength(3); + expect(errors[2]).toBeInstanceOf(TeaAuthenticationError); + expect(loginLists).toBe(3); + + // Step 4: HTTP 429 (after 40s backoff) -> pauses host 50s + await vi.advanceTimersByTimeAsync(40_000); + expect(errors).toHaveLength(4); + expect(loginLists).toBe(4); + + // Still paused at 49.999s + await vi.advanceTimersByTimeAsync(49_999); + expect(snapshots).toHaveLength(0); + + // Resumes at 50s and succeeds (tolerating 404 on /actions/tasks) + await vi.advanceTimersByTimeAsync(1); + expect(snapshots).toHaveLength(1); + expect(snapshots[0]!.headSha).toBe("ok"); + } finally { + service.dispose?.(); + } + }); + + it("bounds review-comment fan-out, skips unchanged reviews on quiet polls, rejects mid-pagination headSha changes, and treats partial failures as stale", async () => { + vi.useFakeTimers(); + const prUrl = "https://forgejo.example.org/Team/Core/pulls/4"; + let prReads = 0; + let activeReviewFetches = 0; + let maxReviewFetches = 0; + let reviewCommentCalls = 0; + let failReview3 = true; + + const { runner } = createFakeTeaRunner(async (args) => { + if (args[0] === "login") { + return { + stdout: JSON.stringify([{ name: "fj", url: "https://forgejo.example.org" }]), + stderr: "", + }; + } + const endpoint = args[4] ?? ""; + if (endpoint === "repos/Team/Core/pulls/4") { + prReads += 1; + // Poll 1: headSha shifts mid-pagination (read 1 -> sha-a, recheck read 2 -> sha-b) + const sha = prReads === 1 ? "sha-a" : "sha-b"; + return teaHttp({ number: 4, state: "open", merged: false, html_url: prUrl, head: { sha } }); + } + if (endpoint.includes("/commits/sha-a/status") && endpoint.includes("page=1")) { + return teaHttp( + { + state: "pending", + total_count: 1, + statuses: [{ id: 1, status: "pending", context: "c1" }], + }, + { headers: { "X-Total-Count": "2" } }, + ); + } + if (endpoint.includes("/commits/sha-a/status") && endpoint.includes("page=2")) { + return teaHttp( + { + state: "pending", + total_count: 1, + statuses: [{ id: 2, status: "success", context: "c2" }], + }, + { headers: { "X-Total-Count": "2" } }, + ); + } + if (endpoint.includes("/commits/sha-b/status")) { + return teaHttp({ state: "success", total_count: 0, statuses: [] }); + } + if (endpoint.includes("/actions/tasks")) { + return teaHttp({ total_count: 0, workflow_runs: [] }); + } + if (endpoint.includes("/issues/4/comments")) { + return teaHttp([]); + } + if (endpoint.includes("/pulls/4/reviews?")) { + const reviews = []; + for (let id = 1; id <= 5; id += 1) { + reviews.push({ + id, + state: "COMMENT", + comments_count: 1, + submitted_at: "2026-11-20T06:00:00Z", + html_url: `${prUrl}#pullrequestreview-${id}`, + }); + } + return teaHttp(reviews); + } + const reviewMatch = /\/pulls\/4\/reviews\/(\d+)\/comments/.exec(endpoint); + if (reviewMatch) { + const reviewId = Number(reviewMatch[1]); + reviewCommentCalls += 1; + activeReviewFetches += 1; + maxReviewFetches = Math.max(maxReviewFetches, activeReviewFetches); + await Promise.resolve(); + activeReviewFetches -= 1; + if (reviewId === 3 && failReview3) { + failReview3 = false; + return teaHttp({ message: "502" }, { status: "502 Bad Gateway" }); + } + return teaHttp([ + { id: reviewId * 100, html_url: `${prUrl}#issuecomment-${reviewId * 100}` }, + ]); + } + throw new Error(`Unexpected: ${endpoint}`); + }); + + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 10_000, + }); + const snapshots: ChangeRequestSnapshot[] = []; + const errors: Error[] = []; + const seen = new Set(); + try { + service.changeRequests!.observe(prUrl, { + knownActivity: () => seen, + async snapshot(s) { + snapshots.push(s); + for (const a of s.activity) seen.add(a.id); + }, + error(err) { + errors.push(err as Error); + }, + }); + + // Poll 1: fails due to mid-pagination headSha change + await vi.advanceTimersByTimeAsync(25); + expect(snapshots).toHaveLength(0); + expect(errors[0]?.message).toMatch(/changed during pagination/i); + + // Poll 2: review 3 comments returns 502 -> entire poll fails (no partial seenActivity committed) + await vi.advanceTimersByTimeAsync(10_000); + expect(snapshots).toHaveLength(0); + expect(errors).toHaveLength(2); + + // Poll 3: succeeds with bounded review-comment fan-out (<= 3 concurrent) + await vi.advanceTimersByTimeAsync(20_000); + expect(snapshots).toHaveLength(1); + expect(maxReviewFetches).toBeLessThanOrEqual(3); + expect(snapshots[0]!.activity.filter((a) => a.kind === "inline comment")).toHaveLength(5); + const callsAfterBaseline = reviewCommentCalls; + + // Poll 4 (quiet): unchanged reviews are skipped — zero additional review-comment fetches + await vi.advanceTimersByTimeAsync(10_000); + expect(snapshots).toHaveLength(2); + expect(reviewCommentCalls).toBe(callsAfterBaseline); + } finally { + service.dispose?.(); + } + }); + + it("routes gitea.com, codeberg.org, and probed self-hosted forgejo through ChangeRequestRouter", async () => { + const forgeResolver = createForgeResolver({ + probeForge: async (host) => (host === "forgejo.internal" ? "forgejo" : null), + }); + const router = createChangeRequestRouter({ forgeResolver }); + try { + await expect(router.resolve("https://gitea.com/Org/Repo/pulls/3")).resolves.toEqual({ + forge: "gitea", + url: "https://gitea.com/org/repo/pulls/3", + }); + await expect(router.resolve("https://codeberg.org/Org/Repo/pulls/4/files")).resolves.toEqual({ + forge: "codeberg", + url: "https://codeberg.org/org/repo/pulls/4", + }); + await expect( + router.resolve("https://forgejo.internal/Org/Repo/pulls/5/commits"), + ).resolves.toEqual({ + forge: "forgejo", + url: "https://forgejo.internal/org/repo/pulls/5", + }); + expect(router.source("codeberg")?.describe("https://codeberg.org/Org/Repo/pulls/4")).toBe( + "Org/Repo #4", + ); + expect(router.source("forgejo")?.describe("https://forgejo.internal/Org/Repo/pulls/5")).toBe( + "forgejo.internal/Org/Repo #5", + ); + } finally { + forgeResolver.dispose(); + } + }); + + it("keeps blocked need_approval Actions tasks pending and delivers digests across restart via ChangeRequestWatches", async () => { + vi.useFakeTimers(); + const artifacts = join(import.meta.dirname, "../../../../.artifacts"); + await mkdir(artifacts, { recursive: true }); + const home = await mkdtemp(join(artifacts, "gitea-watch-")); + const prUrl = "https://codeberg.org/org/repo/pulls/42"; + let phase = 1; + + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { + stdout: JSON.stringify([{ name: "cb", url: "https://codeberg.org" }]), + stderr: "", + }; + } + const endpoint = args[4] ?? ""; + if (endpoint === "repos/org/repo/pulls/42") { + return teaHttp({ + number: 42, + state: phase >= 3 ? "closed" : "open", + merged: phase >= 3, + html_url: prUrl, + head: { sha: "sha-approval" }, + }); + } + if (endpoint.includes("/commits/sha-approval/status")) { + return teaHttp({ state: "", statuses: [], total_count: 0 }); + } + if (endpoint.includes("/actions/tasks")) { + return teaHttp({ + total_count: 1, + workflow_runs: [ + { + id: 700, + name: "ci", + head_sha: "sha-approval", + run_number: 1, + workflow_id: "ci.yml", + status: phase === 1 ? "blocked" : "success", + url: "https://codeberg.org/Org/Repo/actions/runs/70/jobs/700", + }, + ], + }); + } + if (endpoint.includes("/actions/runs")) { + return teaHttp({ + total_count: 1, + workflow_runs: [ + { + id: 70, + run_number: 1, + head_sha: "sha-approval", + status: "blocked", + need_approval: true, + }, + ], + }); + } + if (endpoint.includes("/issues/42/comments")) { + return teaHttp([]); + } + if (endpoint.includes("/pulls/42/reviews?")) { + return teaHttp( + phase >= 2 + ? [ + { + id: 88, + state: "APPROVED", + comments_count: 1, + submitted_at: "2026-11-20T07:00:00Z", + html_url: `${prUrl}#pullrequestreview-88`, + }, + ] + : [], + ); + } + if (endpoint.includes("/pulls/42/reviews/88/comments")) { + return teaHttp([{ id: 901, html_url: `${prUrl}#issuecomment-901` }]); + } + throw new Error(`Unexpected: ${endpoint}`); + }); + + const createWatchHarness = () => { + const gitea = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 10_000, + }); + const forgeResolver = createForgeResolver({ + createService: (forge) => (forge === "codeberg" ? gitea : null), + }); + const backgroundWork = new AgentBackgroundWorkStore(); + const turns: Array<{ recipientId: string; prompt: string }> = []; + const messages = createAgentMessageDelivery({ + isRunning: () => false, + subscribe: () => () => {}, + async dispatch(request) { + turns.push({ recipientId: request.recipientId, prompt: String(request.prompt) }); + return "turn_started"; + }, + onError(error) { + throw error; + }, + }); + const watches = createChangeRequestWatches({ + router: createChangeRequestRouter({ forgeResolver }), + paseoHome: home, + logger: pino({ enabled: false }), + isActive: async () => true, + messages: () => messages, + backgroundWork, + }); + return { + watches, + backgroundWork, + turns, + async close() { + await watches.close(); + await messages.close(); + forgeResolver.dispose(); + }, + }; + }; + + let harness = createWatchHarness(); + try { + await harness.watches.start(); + const subPromise = harness.watches.subscribe( + "agent-1", + "https://codeberg.org/Org/Repo/pulls/42/files", + ); + await vi.advanceTimersByTimeAsync(25); + const sub = await subPromise; + expect(sub).toMatchObject({ + url: prUrl, + state: "open", + headSha: "sha-approval", + checksState: "pending", + checks: [{ id: "action:700", name: "ci", state: "pending" }], + subscribed: true, + stale: false, + }); + await expect(harness.watches.subscribe("agent-1", prUrl)).resolves.toMatchObject({ + url: prUrl, + }); + expect(harness.backgroundWork.list("agent-1")).toEqual([ + expect.objectContaining({ description: "org/repo #42", kind: "monitor" }), + ]); + const saved = JSON.parse(await readFile(join(home, "change-request-watches.json"), "utf8")); + expect(saved).toEqual([expect.objectContaining({ forge: "codeberg", url: prUrl })]); + + // Restart daemon and verify watch restores and delivers passed checks + review + inline comment + merge + await harness.close(); + phase = 2; + harness = createWatchHarness(); + await harness.watches.start(); + expect(harness.backgroundWork.list("agent-1")).toEqual([ + expect.objectContaining({ description: "org/repo #42", kind: "monitor" }), + ]); + + await vi.advanceTimersByTimeAsync(25); + await vi.waitFor(async () => { + const current = JSON.parse( + await readFile(join(home, "change-request-watches.json"), "utf8"), + ) as Array<{ seenActivity: string[] }>; + expect(current[0]?.seenActivity).toContain("inline:901"); + }); + await vi.advanceTimersByTimeAsync(32_000); + expect(harness.turns).toHaveLength(1); + expect(harness.turns[0]!.prompt).toContain("Checks passed on sha-approval."); + expect(harness.turns[0]!.prompt).toContain(`${prUrl}#pullrequestreview-88`); + expect(harness.turns[0]!.prompt).toContain(`${prUrl}#issuecomment-901`); + + phase = 3; + await vi.advanceTimersByTimeAsync(10_000); + await vi.waitFor(() => expect(harness.backgroundWork.list("agent-1")).toEqual([])); + await vi.advanceTimersByTimeAsync(32_000); + expect(harness.turns).toHaveLength(2); + expect(harness.turns[1]!.prompt).toContain("Change request merged."); + } finally { + await harness.close(); + await rm(home, { recursive: true, force: true }); + } + }); + + it("reads 55 inline review comments in a single request and paginates >50 commit statuses via X-Total-Count", async () => { + vi.useFakeTimers(); + const prUrl = "https://codeberg.org/Org/Repo/pulls/99"; + const headSha = "sha-large"; + let reviewCommentsCalls = 0; + let actionRunsCalls = 0; + + const page1Statuses = []; + for (let i = 1; i <= 50; i += 1) { + page1Statuses.push({ id: i, status: "success", context: `ctx-${i}` }); + } + const page2Statuses = []; + for (let i = 51; i <= 60; i += 1) { + page2Statuses.push({ + id: i, + status: i === 55 ? "failure" : "success", + context: `ctx-${i}`, + }); + } + const fiftyFiveInlineComments = []; + for (let i = 1; i <= 55; i += 1) { + fiftyFiveInlineComments.push({ id: i, html_url: `${prUrl}#issuecomment-${i}` }); + } + + const { runner } = createFakeTeaRunner((args) => { + if (args[0] === "login") { + return { + stdout: JSON.stringify([{ name: "cb", url: "https://codeberg.org" }]), + stderr: "", + }; + } + const endpoint = args[4] ?? ""; + if (endpoint === "repos/Org/Repo/pulls/99") { + return teaHttp({ + number: 99, + state: "open", + merged: false, + html_url: prUrl, + head: { sha: headSha }, + }); + } + if (endpoint.includes(`/commits/${headSha}/status`) && endpoint.includes("page=1")) { + // Real Gitea sets body `total_count` to the page length (50) and puts 60 in X-Total-Count. + return teaHttp( + { state: "success", total_count: 50, statuses: page1Statuses }, + { headers: { "X-Total-Count": "60" } }, + ); + } + if (endpoint.includes(`/commits/${headSha}/status`) && endpoint.includes("page=2")) { + return teaHttp( + { state: "failure", total_count: 10, statuses: page2Statuses }, + { headers: { "X-Total-Count": "60" } }, + ); + } + if (endpoint.includes("/actions/tasks")) { + return teaHttp({ total_count: 0, workflow_runs: [] }); + } + if (endpoint.includes("/actions/runs")) { + actionRunsCalls += 1; + return teaHttp({ total_count: 0, workflow_runs: [] }); + } + if (endpoint.includes("/issues/99/comments")) { + return teaHttp([]); + } + if (endpoint.includes("/pulls/99/reviews?")) { + return teaHttp([ + { + id: 7, + state: "COMMENT", + comments_count: 55, + submitted_at: "2026-11-20T08:00:00Z", + html_url: `${prUrl}#pullrequestreview-7`, + }, + ]); + } + if (endpoint === "repos/Org/Repo/pulls/99/reviews/7/comments") { + reviewCommentsCalls += 1; + return teaHttp(fiftyFiveInlineComments); + } + throw new Error(`Unexpected: ${endpoint}`); + }); + + const service = createGiteaService({ + runner, + resolveTeaPath: async () => "tea", + watchPollMs: 10_000, + }); + const snapshots: ChangeRequestSnapshot[] = []; + try { + const release = service.changeRequests!.observe(prUrl, { + async snapshot(s) { + snapshots.push(s); + }, + error(err) { + throw err; + }, + }); + await vi.advanceTimersByTimeAsync(25); + expect(snapshots).toHaveLength(1); + expect(actionRunsCalls).toBe(0); + expect(reviewCommentsCalls).toBe(1); + expect(snapshots[0]!.checks).toHaveLength(60); + expect(snapshots[0]!.checksState).toBe("failed"); + expect(snapshots[0]!.activity.filter((a) => a.kind === "inline comment")).toHaveLength(55); + release(); + } finally { + service.dispose?.(); + } + }); +}); diff --git a/packages/server/src/services/gitea-change-requests.ts b/packages/server/src/services/gitea-change-requests.ts new file mode 100644 index 0000000000..e4e919d7e7 --- /dev/null +++ b/packages/server/src/services/gitea-change-requests.ts @@ -0,0 +1,936 @@ +import pLimit from "p-limit"; +import { z } from "zod"; +import { normalizeHost } from "@getpaseo/protocol/git-remote"; +import { + ChangeRequestRateLimitError, + createPerHostChangeRequestPoller, + type PerHostReadContext, + parseCliHttpResponse, + parseRetryAfterMs, +} from "./change-request-poller.js"; +import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js"; +import { + findTeaLoginNameForBaseUrl, + getGiteaActionTaskName, + GITEA_ACTION_MAX_PAGES, + GITEA_ACTION_PAGE_LIMIT, + GiteaActionsListResponseSchema, + GiteaCombinedCommitStatusSchema, + latestGiteaActionTasksByWorkflow, + parseGiteaActionTasks, + type GiteaActionTask, + type GiteaCommitStatus, +} from "./gitea-checks.js"; + +const GITEA_CLOUD_HOSTS = new Set(["gitea.com", "codeberg.org"]); +const GITEA_PR_TABS = new Set(["commits", "files", "checks"]); +const GITEA_PAGE_SIZE = GITEA_ACTION_PAGE_LIMIT; +const GITEA_REVIEW_COMMENT_CONCURRENCY = 3; +const GITEA_REVIEW_COMMENTS_TTL_MS = 5 * 60_000; +const GITEA_ACTION_RUN_LOOKUP_LIMIT = 5; + +const checkUrlSchema = z.url({ protocol: /^https?$/ }); + +const giteaWatchPrSchema = z + .object({ + number: z.number(), + state: z.string(), + merged: z.boolean().optional(), + merged_at: z.string().nullable().optional(), + html_url: z.string().optional(), + head: z + .object({ + sha: z.string(), + }) + .passthrough(), + }) + .passthrough(); + +const giteaIssueCommentSchema = z + .object({ + id: z.number(), + html_url: z.string().optional(), + type: z.string().optional(), + }) + .passthrough(); + +const giteaReviewSchema = z + .object({ + id: z.number(), + state: z.string(), + comments_count: z.number().optional().default(0), + submitted_at: z.string().nullable().optional(), + updated_at: z.string().nullable().optional(), + html_url: z.string().optional(), + }) + .passthrough(); + +const giteaReviewCommentSchema = z + .object({ + id: z.number(), + html_url: z.string().optional(), + }) + .passthrough(); + +const giteaActionJobSchema = z.object({ + id: z.number(), + name: z.string(), + status: z.string(), + conclusion: z.string().nullable().optional(), + html_url: z.string().nullable().optional(), +}); + +const giteaActionJobsPageSchema = z.union([ + z.object({ + jobs: z + .array(giteaActionJobSchema) + .nullable() + .transform((jobs) => jobs ?? []), + total_count: z.number(), + }), + // Forgejo returns the complete job list as an array. + z.array(giteaActionJobSchema), +]); + +type GiteaActionJob = z.infer; + +type GiteaWatchPr = z.infer; +type GiteaReview = z.infer; + +interface GiteaPullRequestIdentity { + baseUrl: string; + displayBase: string | null; + owner: string; + repo: string; + number: number; +} + +function invalidGiteaUrl(): never { + throw new Error("Enter a Gitea, Forgejo, or Codeberg pull request URL."); +} + +function parseGiteaUrlOrigin(input: string): { + protocol: "http:" | "https:"; + host: string; + port: string; + hostWithPort: string; + pathname: string; +} { + const trimmed = input.trim(); + if (!trimmed || /\s/.test(trimmed)) invalidGiteaUrl(); + let parsed: URL; + try { + parsed = new URL(trimmed); + } catch { + invalidGiteaUrl(); + } + const protocol = parsed.protocol.toLowerCase(); + if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) { + invalidGiteaUrl(); + } + const host = normalizeHost(parsed.hostname); + if (!host || (GITEA_CLOUD_HOSTS.has(host) && protocol !== "https:")) { + invalidGiteaUrl(); + } + return { + protocol: protocol as "http:" | "https:", + host, + port: parsed.port, + hostWithPort: parsed.port ? `${host}:${parsed.port}` : host, + pathname: parsed.pathname, + }; +} + +function decodeRepoSegment(raw: string): string { + let decoded: string; + try { + decoded = decodeURIComponent(raw); + } catch { + invalidGiteaUrl(); + } + if ( + !decoded || + decoded === "." || + decoded === ".." || + decoded.includes("/") || + decoded.includes("\\") + ) { + invalidGiteaUrl(); + } + return decoded; +} + +function parseGiteaPullRequestUrl(input: string): GiteaPullRequestIdentity { + const origin = parseGiteaUrlOrigin(input); + const segments = origin.pathname.split("/").filter(Boolean); + + if ( + segments.length >= 5 && + GITEA_PR_TABS.has(segments.at(-1)!.toLowerCase()) && + /^\d+$/.test(segments.at(-2)!) + ) { + segments.pop(); + } + + const rawNumber = segments.pop(); + const number = Number(rawNumber); + const resource = segments.pop(); + const repo = segments.pop(); + const owner = segments.pop(); + if ( + resource?.toLowerCase() !== "pulls" || + !owner || + !repo || + !rawNumber || + !/^\d+$/.test(rawNumber) || + !Number.isInteger(number) || + number < 1 || + number > 2_147_483_647 + ) { + invalidGiteaUrl(); + } + + const path = segments.length ? `/${segments.join("/")}` : ""; + const displayBase = + !path && !origin.port && GITEA_CLOUD_HOSTS.has(origin.host) + ? null + : `${origin.hostWithPort}${path}`; + return { + baseUrl: `${origin.protocol}//${origin.hostWithPort}${path}`, + displayBase, + owner: decodeRepoSegment(owner), + repo: decodeRepoSegment(repo), + number, + }; +} + +export function resolveGiteaChangeRequest(input: string): string { + const { baseUrl, owner, repo, number } = parseGiteaPullRequestUrl(input); + return `${baseUrl}/${owner.toLowerCase()}/${repo.toLowerCase()}/pulls/${number}`; +} + +export function describeGiteaChangeRequest(url: string): string { + const { displayBase, owner, repo, number } = parseGiteaPullRequestUrl(url); + const project = displayBase ? `${displayBase}/${owner}/${repo}` : `${owner}/${repo}`; + return `${project} #${number}`; +} + +function mapGiteaPrState(pr: GiteaWatchPr): ChangeRequestSnapshot["state"] { + if (pr.merged === true || pr.merged_at != null) return "merged"; + const normalized = pr.state.toLowerCase(); + if (normalized === "open") return "open"; + if (normalized === "merged") return "merged"; + return "closed"; +} + +function mapCommitStatusToWatchState( + status: string, +): ChangeRequestSnapshot["checks"][number]["state"] { + switch (status.toLowerCase()) { + case "success": + return "passed"; + case "failure": + case "error": + case "warning": + return "failed"; + case "pending": + case "running": + return "pending"; + default: + return "neutral"; + } +} + +function isCanceledActionStatus(status: GiteaCommitStatus): boolean { + // Actions writes a generic failure state on cancellation, with a distinct + // description in the native job's commit status. + const description = status.description ?? ""; + return description === "Has been cancelled" || description.startsWith("Canceled after "); +} + +function mapActionTaskToWatchState( + status: string, +): ChangeRequestSnapshot["checks"][number]["state"] { + switch (status.toLowerCase()) { + case "success": + return "passed"; + case "failure": + case "failed": + case "error": + return "failed"; + case "cancelled": + case "canceled": + case "skipped": + return "neutral"; + default: + return "pending"; + } +} + +function computeAggregateChecksState( + checks: ChangeRequestSnapshot["checks"], +): ChangeRequestSnapshot["checksState"] { + if (checks.length === 0) return "neutral"; + if (checks.some((check) => check.state === "failed")) return "failed"; + if (checks.some((check) => check.state === "pending")) return "pending"; + if (checks.some((check) => check.state === "passed")) return "passed"; + return "neutral"; +} + +function nativeActionUrl(value: string | null | undefined, origin: string) { + if (!value) return null; + try { + const url = new URL(value, origin); + if (url.origin !== origin) return null; + const match = /^(.*\/actions\/runs\/(\d+))(\/jobs\/\d+)?\/?$/.exec(url.pathname); + if (!match) return null; + const [, run, runId, job] = match; + return { run: run!, runId: runId!, jobUrl: job ? `${origin}${run}${job}` : null }; + } catch { + return null; + } +} + +function combineWatchChecks( + commitStatuses: GiteaCommitStatus[], + actionTasks: GiteaActionTask[], + jobsByRun: ReadonlyMap, + origin: string, +): ChangeRequestSnapshot["checks"] { + const checks: ChangeRequestSnapshot["checks"] = []; + const actionJobs = [...jobsByRun.values()].flat(); + const coveredJobUrls = new Set( + actionJobs.map((job) => nativeActionUrl(job.html_url, origin)?.jobUrl), + ); + + for (const status of commitStatuses) { + const jobUrl = nativeActionUrl(status.target_url, origin)?.jobUrl; + if (jobUrl && coveredJobUrls.has(jobUrl)) continue; + const url = checkUrlSchema.safeParse(status.target_url).data; + checks.push({ + id: `status:${status.id}`, + name: status.context || `status-${status.id}`, + state: + jobUrl && isCanceledActionStatus(status) + ? "neutral" + : mapCommitStatusToWatchState(status.status), + ...(url ? { url } : {}), + }); + } + + for (const job of actionJobs) { + const url = checkUrlSchema.safeParse(job.html_url).data; + checks.push({ + id: `action-job:${job.id}`, + name: job.name, + state: mapActionTaskToWatchState(job.conclusion || job.status), + ...(url ? { url } : {}), + }); + } + + const seenTaskIds = new Set(); + for (const task of actionTasks) { + if (seenTaskIds.has(task.id)) continue; + const address = nativeActionUrl(task.url, origin); + if (address && jobsByRun.has(address.run)) continue; + seenTaskIds.add(task.id); + const url = checkUrlSchema.safeParse(task.url).data; + checks.push({ + id: `action:${task.id}`, + name: getGiteaActionTaskName(task), + state: mapActionTaskToWatchState(task.status), + ...(url ? { url } : {}), + }); + } + + return checks; +} + +function hasNextLinkHeader(headers: ReadonlyMap): boolean { + const link = headers.get("link"); + return link ? /rel=["']?next["']?/i.test(link) : false; +} + +function parseTotalCountHeader(headers: ReadonlyMap): number | null { + const raw = headers.get("x-total-count"); + if (!raw) return null; + const parsed = Number(raw); + return Number.isInteger(parsed) && parsed >= 0 ? parsed : null; +} + +function isSubmittedGiteaReview(review: GiteaReview): boolean { + const state = review.state.trim().toUpperCase(); + return state !== "PENDING" && state !== "REQUEST_REVIEW"; +} + +function parseTeaHttpStreams( + stdout: string, + stderr: string, +): { + status: number | null; + headers: Map; + body: string; +} { + const fromStdout = parseCliHttpResponse(stdout); + if (fromStdout.status !== null) { + return fromStdout; + } + const fromStderr = parseCliHttpResponse(stderr); + if (fromStderr.status !== null) { + return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() }; + } + return { status: null, headers: new Map(), body: stdout.trim() }; +} + +class TeaHttpStatusError extends Error { + readonly status: number; + + constructor(status: number, message: string) { + super(message); + this.name = "TeaHttpStatusError"; + this.status = status; + } +} + +function isOptionalEndpointStatus(error: unknown): boolean { + return ( + error instanceof TeaHttpStatusError && + (error.status === 403 || error.status === 404 || error.status === 501) + ); +} + +type TeaApiGet = ( + endpoint: string, + schema: z.ZodType, +) => Promise<{ data: T; headers: ReadonlyMap }>; + +interface TeaPollApi { + get: TeaApiGet; + all( + reads: T, + ): Promise<{ -readonly [Key in keyof T]: Awaited }>; +} + +interface CachedReviewComments { + count: number; + fetchedAt: number; + items: ChangeRequestSnapshot["activity"]; +} + +export interface CreateGiteaChangeRequestSourceOptions { + runCommand( + args: string[], + options: { cwd: string; envOverlay?: Record }, + ): Promise<{ stdout: string; stderr: string }>; + createAuthError(stderr: string): Error; + createCommandError(params: { + args: string[]; + cwd: string; + exitCode: number | null; + stderr: string; + stdout?: string; + }): Error; + now?: () => number; + pollIntervalMs?: number; + initialDelayMs?: number; +} + +export function createGiteaChangeRequestSource( + options: CreateGiteaChangeRequestSourceOptions, +): ChangeRequestSource & { dispose(): void } { + const now = options.now ?? Date.now; + const cachedReviewCommentsByUrl = new Map>(); + const reviewCommentLimit = pLimit(GITEA_REVIEW_COMMENT_CONCURRENCY); + + async function resolveLogin(baseUrl: string): Promise { + const result = await options.runCommand(["login", "list", "-o", "json"], { + cwd: process.cwd(), + }); + const loginName = findTeaLoginNameForBaseUrl(result.stdout, baseUrl); + if (!loginName) { + throw options.createAuthError(`No tea login configured for ${baseUrl}`); + } + return loginName; + } + + function parseJsonBody(params: { + args: string[]; + cwd: string; + body: string; + schema: z.ZodType; + }): T { + let data: unknown; + try { + data = JSON.parse(params.body); + } catch { + throw options.createCommandError({ + args: params.args, + cwd: params.cwd, + exitCode: null, + stderr: `tea did not return valid JSON (${params.body.length} bytes)`, + }); + } + const parsed = params.schema.safeParse(data); + if (!parsed.success) { + throw options.createCommandError({ + args: params.args, + cwd: params.cwd, + exitCode: null, + stderr: `tea JSON did not match the expected schema: ${parsed.error.message}`, + }); + } + return parsed.data; + } + + function bindTeaApi(context: PerHostReadContext, loginName: string): TeaPollApi { + let active = true; + + const get: TeaApiGet = async (endpoint, schema) => { + if (!active || !context.isObserved()) throw new Error("Change request observation ended"); + context.assertHostAvailable(); + const args = ["api", "--login", loginName, "-i", endpoint]; + const cwd = process.cwd(); + const result = await options.runCommand(args, { cwd }); + const parsed = parseTeaHttpStreams(result.stdout, result.stderr); + const nowMs = now(); + + // tea api can exit 0 on an HTTP failure, so always check the status line. + if (parsed.status === null) { + throw options.createCommandError({ + args, + cwd, + exitCode: 0, + stderr: "tea api -i did not return an HTTP status line", + stdout: result.stdout, + }); + } + if (parsed.status === 429) { + const resetAtMs = parseRetryAfterMs(parsed.headers, nowMs, { + forceOnMissing: true, + defaultPauseMs: 60_000, + })!; + context.pauseHost(resetAtMs); + throw new ChangeRequestRateLimitError({ host: context.host, resetAtMs }); + } + if (parsed.status === 401) { + throw options.createAuthError(parsed.body || "401 Unauthorized"); + } + if (parsed.status < 200 || parsed.status >= 300) { + throw new TeaHttpStatusError( + parsed.status, + `Gitea API returned HTTP ${parsed.status} for ${endpoint}: ${parsed.body}`.trim(), + ); + } + + const proactivePause = parseRetryAfterMs(parsed.headers, nowMs); + if (proactivePause !== null) context.deferPollsUntil(proactivePause); + + const data = parseJsonBody({ args, cwd, body: parsed.body, schema }); + return { data, headers: parsed.headers }; + }; + + return { + get, + all(reads) { + return Promise.all(reads).catch(async (error: unknown) => { + // Stop admitting reads from this poll and hold its host slot until + // requests already sent (including late rate limits) settle. + active = false; + await Promise.allSettled(reads); + throw error; + }); + }, + }; + } + + async function teaApiGetAllPages(params: { + get: TeaApiGet; + endpoint: string; + itemSchema: z.ZodType; + }): Promise { + const items: T[] = []; + const schema = z.array(params.itemSchema); + let minPageSize = 1; + for (let page = 1; ; page += 1) { + const sep = params.endpoint.includes("?") ? "&" : "?"; + const { data, headers } = await params.get( + `${params.endpoint}${sep}page=${page}&limit=${GITEA_PAGE_SIZE}`, + schema, + ); + items.push(...data); + if (headers.has("link")) { + if (hasNextLinkHeader(headers)) continue; + break; + } + + const totalCount = parseTotalCountHeader(headers); + if (totalCount !== null) { + // Gitea can cap limit below the requested value and filter pending + // reviews after pagination. The largest page is a lower bound on + // the number of records advanced on every page. + minPageSize = Math.max(minPageSize, data.length); + if (page * minPageSize < totalCount) continue; + break; + } + if (data.length < GITEA_PAGE_SIZE) break; + } + + return items; + } + + async function readCommitStatuses(params: { + get: TeaApiGet; + repoPrefix: string; + headSha: string; + isObserved(): boolean; + }): Promise<{ statuses: GiteaCommitStatus[]; pagesRead: number }> { + const statuses: GiteaCommitStatus[] = []; + const seenIds = new Set(); + let page = 1; + let pagesRead = 0; + + while (true) { + if (!params.isObserved()) return { statuses, pagesRead }; + const response = await params.get( + `${params.repoPrefix}/commits/${encodeURIComponent(params.headSha)}/status?limit=${GITEA_PAGE_SIZE}&page=${page}`, + GiteaCombinedCommitStatusSchema, + ); + pagesRead += 1; + const pageStatuses = response.data.statuses; + if (pageStatuses.length === 0) break; + for (const status of pageStatuses) { + if (seenIds.has(status.id)) { + throw new Error("Gitea commit status pages overlap. Retry the poll."); + } + seenIds.add(status.id); + statuses.push(status); + } + + // Gitea sets body `total_count` to the current page length; the full total + // lives only in the `X-Total-Count` response header. + const headerTotal = parseTotalCountHeader(response.headers); + if (headerTotal !== null) { + if (statuses.length >= headerTotal) break; + page += 1; + continue; + } + if (hasNextLinkHeader(response.headers) || pageStatuses.length >= GITEA_PAGE_SIZE) { + page += 1; + continue; + } + break; + } + + return { statuses, pagesRead }; + } + + async function readBoundedActionTasks(params: { + get: TeaApiGet; + repoPrefix: string; + isObserved(): boolean; + }): Promise<{ items: unknown[]; pagesRead: number }> { + const items: unknown[] = []; + let fetched = 0; + let pagesRead = 0; + + for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) { + if (!params.isObserved()) return { items, pagesRead }; + let response: { data: z.infer }; + try { + response = await params.get( + `${params.repoPrefix}/actions/tasks?limit=${GITEA_PAGE_SIZE}&page=${page}`, + GiteaActionsListResponseSchema, + ); + } catch (error) { + if (page === 1 && isOptionalEndpointStatus(error)) { + return { items: [], pagesRead: 0 }; + } + throw error; + } + pagesRead += 1; + const runs = response.data.workflow_runs; + if (runs.length === 0) break; + fetched += runs.length; + items.push(...runs); + if (response.data.total_count !== undefined && fetched >= response.data.total_count) break; + } + + return { items, pagesRead }; + } + + async function readActionJobs(params: { + get: TeaApiGet; + origin: string; + repoPrefix: string; + tasks: GiteaActionTask[]; + statuses: GiteaCommitStatus[]; + }): Promise> { + // Commit statuses identify a job URL. Tasks identify a run, so only a job + // list can establish coverage when both sources report the same run. + const statusRuns = new Set(); + for (const status of params.statuses) { + const address = nativeActionUrl(status.target_url, params.origin); + if (address?.jobUrl) statusRuns.add(address.run); + } + const runs = new Map(); + for (const task of params.tasks) { + const address = nativeActionUrl(task.url, params.origin); + if (address && statusRuns.has(address.run)) runs.set(address.run, address.runId); + } + const jobsByRun = new Map(); + for (const [run, runId] of [...runs].slice(0, GITEA_ACTION_RUN_LOOKUP_LIMIT)) { + const endpoint = `${params.repoPrefix}/actions/runs/${runId}/jobs`; + const jobs = new Map(); + for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) { + try { + const { data } = await params.get( + `${endpoint}?limit=${GITEA_PAGE_SIZE}&page=${page}`, + giteaActionJobsPageSchema, + ); + const items = Array.isArray(data) ? data : data.jobs; + const totalCount = Array.isArray(data) ? data.length : data.total_count; + if (!items.length) break; + // The browser run number and API ID differ on some versions. Keep + // the original sources if any job belongs to another run. + if (items.some((job) => nativeActionUrl(job.html_url, params.origin)?.run !== run)) { + break; + } + for (const job of items) jobs.set(job.id, job); + if (jobs.size >= totalCount) { + jobsByRun.set(run, [...jobs.values()]); + break; + } + } catch (error) { + if (page === 1 && isOptionalEndpointStatus(error)) break; + throw error; + } + } + } + return jobsByRun; + } + + async function readChecks(params: { + api: TeaPollApi; + origin: string; + repoPrefix: string; + prEndpoint: string; + headSha: string; + isObserved(): boolean; + }): Promise { + const { get, all } = params.api; + const [statusResult, tasksResult] = await all([ + readCommitStatuses({ ...params, get }), + readBoundedActionTasks({ ...params, get }), + ]); + if (!params.isObserved()) { + throw new Error("Change request observation ended"); + } + + const matchingTasks = parseGiteaActionTasks(tasksResult.items).filter( + (task) => task.head_sha === params.headSha, + ); + const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks); + + const jobsByRun = await readActionJobs({ + ...params, + get, + tasks: latestTasks, + statuses: statusResult.statuses, + }); + if (statusResult.pagesRead > 1 || tasksResult.pagesRead > 1 || jobsByRun.size > 0) { + const { data: recheck } = await get(params.prEndpoint, giteaWatchPrSchema); + if (recheck.head.sha !== params.headSha) { + throw new Error("The pull request head changed during pagination."); + } + } + + return combineWatchChecks(statusResult.statuses, latestTasks, jobsByRun, params.origin); + } + + async function readActivity(params: { + url: string; + api: TeaPollApi; + repoPrefix: string; + number: number; + prWebUrl: string; + terminal: boolean; + knownActivity(): ReadonlySet | undefined; + isObserved(): boolean; + }): Promise { + const { get, all } = params.api; + const [comments, reviews] = await all([ + teaApiGetAllPages({ + get, + endpoint: `${params.repoPrefix}/issues/${params.number}/comments`, + itemSchema: giteaIssueCommentSchema, + }), + teaApiGetAllPages({ + get, + endpoint: `${params.repoPrefix}/pulls/${params.number}/reviews`, + itemSchema: giteaReviewSchema, + }), + ]); + if (!params.isObserved()) { + throw new Error("Change request observation ended"); + } + + const activity: ChangeRequestSnapshot["activity"] = []; + for (const comment of comments) { + if (comment.type !== undefined && comment.type !== "comment") continue; + activity.push({ + id: `comment:${comment.id}`, + kind: "comment", + url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`, + }); + } + + const submittedReviews = reviews.filter(isSubmittedGiteaReview); + for (const review of submittedReviews) { + activity.push({ + id: `review:${review.id}`, + kind: "review", + url: review.html_url || `${params.prWebUrl}#pullrequestreview-${review.id}`, + }); + } + + const known = params.knownActivity(); + let reviewCache = cachedReviewCommentsByUrl.get(params.url); + if (!reviewCache) { + reviewCache = new Map(); + cachedReviewCommentsByUrl.set(params.url, reviewCache); + } + + const staleBefore = now() - GITEA_REVIEW_COMMENTS_TTL_MS; + const reviewsNeedingFetch = submittedReviews.filter((review) => { + if (review.comments_count <= 0) return false; + const cached = reviewCache.get(review.id); + if ( + !params.terminal && + cached && + cached.fetchedAt > staleBefore && + cached.count === review.comments_count && + cached.items.every((item) => known?.has(item.id)) + ) { + return false; + } + return true; + }); + + // Gitea's review-comments endpoint returns all comments for a review in one + // response and ignores page/limit, so fetch it once without a pagination loop. + const fetchedGroups = await all( + reviewsNeedingFetch.map((review) => + reviewCommentLimit(async () => { + if (!params.isObserved()) { + return { reviewId: review.id, count: review.comments_count, items: [] }; + } + const { data: inlineComments } = await get( + `${params.repoPrefix}/pulls/${params.number}/reviews/${review.id}/comments`, + z.array(giteaReviewCommentSchema), + ); + const items: ChangeRequestSnapshot["activity"] = inlineComments.map((comment) => ({ + id: `inline:${comment.id}`, + kind: "inline comment", + url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`, + })); + return { reviewId: review.id, count: review.comments_count, items }; + }), + ), + ); + if (!params.isObserved()) { + throw new Error("Change request observation ended"); + } + + const fetchedAt = now(); + for (const group of fetchedGroups) { + reviewCache.set(group.reviewId, { count: group.count, fetchedAt, items: group.items }); + } + for (const review of submittedReviews) { + if (review.comments_count <= 0) continue; + const cached = reviewCache.get(review.id); + if (cached) { + activity.push(...cached.items); + } + } + + return activity; + } + + async function readPullRequest(context: PerHostReadContext): Promise { + const identity = parseGiteaPullRequestUrl(context.url); + const { baseUrl, owner, repo, number } = identity; + const loginName = await resolveLogin(baseUrl); + const api = bindTeaApi(context, loginName); + const repoPrefix = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`; + const prEndpoint = `${repoPrefix}/pulls/${number}`; + + const { data: pr } = await api.get(prEndpoint, giteaWatchPrSchema); + if (!pr.head.sha) { + throw new Error(`Gitea pull request #${number} did not include a head commit SHA.`); + } + const prWebUrl = pr.html_url || context.url; + const address = parseGiteaPullRequestUrl(prWebUrl); + if ( + address.baseUrl !== baseUrl || + address.owner.toLowerCase() !== owner.toLowerCase() || + address.repo.toLowerCase() !== repo.toLowerCase() || + address.number !== number || + pr.number !== number + ) { + throw new Error("Tea returned a pull request that does not match the watch URL."); + } + + const checks = await readChecks({ + api, + origin: context.host, + repoPrefix, + prEndpoint, + headSha: pr.head.sha, + isObserved: context.isObserved, + }); + const state = mapGiteaPrState(pr); + const activity = await readActivity({ + url: context.url, + api, + repoPrefix, + number, + prWebUrl, + terminal: state !== "open", + knownActivity: context.knownActivity, + isObserved: context.isObserved, + }); + + return { + state, + headSha: pr.head.sha, + checksState: computeAggregateChecksState(checks), + checks, + reviewDecision: null, + activity, + }; + } + + const poller = createPerHostChangeRequestPoller({ + hostOf: (url) => new URL(url).origin, + read: readPullRequest, + now, + pollIntervalMs: options.pollIntervalMs, + initialDelayMs: options.initialDelayMs, + }); + + return { + resolve: resolveGiteaChangeRequest, + describe: describeGiteaChangeRequest, + observe(url, callbacks) { + const release = poller.observe(url, callbacks); + return () => { + cachedReviewCommentsByUrl.delete(url); + release(); + }; + }, + dispose() { + cachedReviewCommentsByUrl.clear(); + poller.dispose(); + }, + }; +} diff --git a/packages/server/src/services/gitea-checks.ts b/packages/server/src/services/gitea-checks.ts new file mode 100644 index 0000000000..9b00c38a30 --- /dev/null +++ b/packages/server/src/services/gitea-checks.ts @@ -0,0 +1,253 @@ +import { z } from "zod"; +import { normalizeHost } from "@getpaseo/protocol/git-remote"; + +// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds +// the sweep to the 250 most recent Actions tasks. +export const GITEA_ACTION_PAGE_LIMIT = 50; +export const GITEA_ACTION_MAX_PAGES = 5; + +const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid"; + +export const GiteaLoginSchema = z + .object({ + name: z.string().optional(), + url: z.string().optional(), + ssh_host: z.string().optional(), + }) + .passthrough(); + +export const GiteaCommitStatusSchema = z + .object({ + id: z.number(), + status: z.string(), + target_url: z.string().nullable().optional(), + description: z.string().nullable().optional(), + url: z.string().nullable().optional(), + context: z.string().optional().default(""), + creator: z.unknown().nullable().optional(), + }) + .passthrough(); + +export const GiteaCombinedCommitStatusSchema = z + .object({ + state: z.string().optional().default(""), + sha: z.string().optional(), + total_count: z.number().optional(), + statuses: z + .array(GiteaCommitStatusSchema) + .nullable() + .optional() + .transform((value) => value ?? []), + }) + .passthrough(); + +export const GiteaActionTaskSchema = z + .object({ + id: z.number(), + name: z.string().nullable().optional(), + head_branch: z.string().nullable().optional(), + head_sha: z.string(), + run_number: z.number().optional(), + event: z.string().nullable().optional(), + display_title: z.string().nullable().optional(), + status: z.string(), + need_approval: z.boolean().optional().default(false), + workflow_id: z.string().nullable().optional(), + url: z.string().nullable().optional(), + created_at: z.string().nullable().optional(), + run_started_at: z.string().nullable().optional(), + }) + .passthrough(); + +// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)` +// so one malformed task (missing id/status/head_sha) drops only itself instead of +// throwing out the whole page and zeroing every Actions check for the PR. +export const GiteaActionsListResponseSchema = z + .object({ + workflow_runs: z + .array(z.unknown()) + .nullable() + .optional() + .transform((value) => value ?? []), + total_count: z.number().optional(), + }) + .passthrough(); + +export type GiteaCommitStatus = z.infer; +export type GiteaCombinedCommitStatus = z.infer; +export type GiteaActionTask = z.infer; + +export function getGiteaActionTaskName(task: GiteaActionTask): string { + return task.name || task.display_title || task.workflow_id || `actions-${task.id}`; +} + +export function getUrlOrigin(value: string | null | undefined): string | null { + if (!value) return null; + try { + return new URL(value).origin; + } catch { + return null; + } +} + +export function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null { + if (!value) return null; + try { + const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN); + const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/); + return match?.[1] ? Number.parseInt(match[1], 10) : null; + } catch { + return null; + } +} + +function isNativeActionJobUrl( + targetUrl: string | null | undefined, + nativeOrigins: ReadonlySet, + nativeRunIds: ReadonlySet, +): boolean { + if (!targetUrl) return false; + try { + const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN); + if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false; + if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false; + const runId = getGiteaActionRunIdFromUrl(targetUrl); + return runId !== null && nativeRunIds.has(runId); + } catch { + return false; + } +} + +// A "shadow" is the commit status Gitea synthesizes to mirror one of its own +// Actions jobs; keeping both would double-report every job. Detection is purely +// structural: Gitea always creates these statuses with a target_url of the form +// "/jobs/" (services/actions/commit_status.go upstream), so a +// status is a shadow exactly when its URL points at a job of a run we actually +// fetched from the Actions API. Anything else - external CI, URL-less statuses, +// contexts that merely look like " / ()" - is kept. +export function isGiteaActionShadowStatus( + status: GiteaCommitStatus, + nativeOrigins: ReadonlySet, + nativeRunIds: ReadonlySet, +): boolean { + return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds); +} + +function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string { + if (task.workflow_id) { + return `workflow\u0000${task.workflow_id}`; + } + // Instances that omit workflow_id (older Gitea/Forgejo payloads) still need + // reruns of the same job collapsed to the latest execution, so fall back to + // the job name before treating the task as its own group. + const name = task.name || task.display_title; + if (name) { + return `name\u0000${name}`; + } + return `task\u0000${getGiteaActionExecutionIdentity(task)}`; +} + +function getGiteaActionExecutionIdentity(task: GiteaActionTask): string { + if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`; + const runId = getGiteaActionRunIdFromUrl(task.url); + if (runId !== null) return `run-id\u0000${runId}`; + if (task.url) return `url\u0000${task.url}`; + return `task\u0000${task.id}`; +} + +function parseGiteaActionTaskTime(task: GiteaActionTask): number { + const timestamp = task.created_at ?? task.run_started_at ?? null; + if (!timestamp) { + return 0; + } + const time = Date.parse(timestamp); + return Number.isNaN(time) ? 0 : time; +} + +function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number { + const leftRunNumber = left.run_number ?? 0; + const rightRunNumber = right.run_number ?? 0; + if (leftRunNumber !== rightRunNumber) { + return leftRunNumber - rightRunNumber; + } + + const leftTime = parseGiteaActionTaskTime(left); + const rightTime = parseGiteaActionTaskTime(right); + if (leftTime !== rightTime) { + return leftTime - rightTime; + } + + return left.id - right.id; +} + +export function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] { + const tasks: GiteaActionTask[] = []; + for (const raw of rawTasks) { + const parsed = GiteaActionTaskSchema.safeParse(raw); + if (parsed.success) { + tasks.push(parsed.data); + } + } + return tasks; +} + +/** + * Keep all sibling tasks from the latest execution of each workflow. + * Per docs/forge-providers.md, ambiguous same-run tasks are preserved because + * display names are not stable job identities and `/actions/tasks` omits rerun + * attempt numbers. + */ +export function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] { + const latestExecutions = new Map(); + for (const task of tasks) { + const identity = getGiteaActionWorkflowIdentity(task); + const current = latestExecutions.get(identity); + if (!current || compareGiteaActionTaskRecency(current, task) < 0) { + latestExecutions.set(identity, task); + } + } + return tasks.filter((task) => { + const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task)); + return ( + latest !== undefined && + getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest) + ); + }); +} + +function parseTeaLogins(stdout: string): z.infer[] { + try { + return z.array(GiteaLoginSchema).safeParse(JSON.parse(stdout)).data ?? []; + } catch { + return []; + } +} + +export function findTeaLoginNameForBaseUrl(stdout: string, baseUrl: string): string | null { + const match = parseTeaLogins(stdout).find((login) => { + if (!login.name || !login.url) return false; + try { + const url = new URL(login.url); + return `${url.origin}${url.pathname.replace(/\/+$/, "")}` === baseUrl; + } catch { + return false; + } + }); + return match?.name ?? null; +} + +export function findTeaLoginNameForHost(stdout: string, host: string): string | null { + const targetHost = normalizeHost(host); + const match = parseTeaLogins(stdout).find((login) => { + const candidates = [login.ssh_host, login.name]; + if (login.url) { + try { + candidates.push(new URL(login.url).hostname); + } catch { + // ignore malformed login url + } + } + return candidates.some((candidate) => candidate && normalizeHost(candidate) === targetHost); + }); + return match?.name ?? null; +} diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index f974d05693..507c827591 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -61,6 +61,23 @@ import type { SearchIssuesAndPrsOptions, SearchResult, } from "./forge-service.js"; +import { + findTeaLoginNameForHost, + getGiteaActionRunIdFromUrl, + getGiteaActionTaskName, + getUrlOrigin, + GITEA_ACTION_MAX_PAGES, + GITEA_ACTION_PAGE_LIMIT, + GiteaActionsListResponseSchema, + GiteaCombinedCommitStatusSchema, + isGiteaActionShadowStatus, + latestGiteaActionTasksByWorkflow, + parseGiteaActionTasks, + type GiteaActionTask, + type GiteaCombinedCommitStatus, + type GiteaCommitStatus, +} from "./gitea-checks.js"; +import { createGiteaChangeRequestSource } from "./gitea-change-requests.js"; import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js"; const TEA_ENV = { @@ -77,10 +94,6 @@ const reviewCommentsLimit = pLimit(REVIEW_COMMENTS_FAN_OUT_CONCURRENCY); // short cache, each poll re-derives the PR head SHA from scratch (branch name + // PR lookup + PR view). The TTL keeps a new push visible within one poll cycle. const CURRENT_PR_HEAD_SHA_CACHE_TTL_MS = 30_000; -// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds -// the sweep to the 250 most recent Actions tasks. -const GITEA_ACTION_PAGE_LIMIT = 50; -const GITEA_ACTION_MAX_PAGES = 5; // PullRequestFlowAGit in forgejo models/issues/pull.go const GITEA_PULL_REQUEST_FLOW_AGIT = 1; @@ -142,6 +155,8 @@ export interface CreateGiteaServiceOptions { resolveRemoteUrl?: (cwd: string) => Promise; resolveCurrentBranch?: (cwd: string) => Promise; now?: () => number; + watchPollMs?: number; + watchInitialDelayMs?: number; } /** @@ -180,14 +195,6 @@ const GiteaIssueListItemSchema = z }) .passthrough(); -const GiteaLoginSchema = z - .object({ - name: z.string().optional(), - url: z.string().optional(), - ssh_host: z.string().optional(), - }) - .passthrough(); - const GiteaUserSchema = z .object({ login: z.string().optional(), @@ -288,55 +295,6 @@ const GiteaCurrentPullRequestApiSchema = z }) .passthrough(); -const GiteaCommitStatusSchema = z - .object({ - id: z.number(), - status: z.string(), - target_url: z.string().nullable().optional(), - description: z.string().nullable().optional(), - url: z.string().nullable().optional(), - context: z.string().optional().default(""), - creator: z.unknown().nullable().optional(), - }) - .passthrough(); - -const GiteaCombinedCommitStatusSchema = z - .object({ - state: z.string().optional().default(""), - sha: z.string().optional(), - total_count: z.number().optional(), - statuses: z.array(GiteaCommitStatusSchema).optional().default([]), - }) - .passthrough(); - -const GiteaActionTaskSchema = z - .object({ - id: z.number(), - name: z.string().nullable().optional(), - head_branch: z.string().nullable().optional(), - head_sha: z.string(), - run_number: z.number().optional(), - event: z.string().nullable().optional(), - display_title: z.string().nullable().optional(), - status: z.string(), - need_approval: z.boolean().optional().default(false), - workflow_id: z.string().nullable().optional(), - url: z.string().nullable().optional(), - created_at: z.string().nullable().optional(), - run_started_at: z.string().nullable().optional(), - }) - .passthrough(); - -// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)` -// so one malformed task (missing id/status/head_sha) drops only itself instead of -// throwing out the whole page and zeroing every Actions check for the PR. -const GiteaActionsListResponseSchema = z - .object({ - workflow_runs: z.array(z.unknown()).optional().default([]), - total_count: z.number().optional(), - }) - .passthrough(); - const GiteaActionRunPullRequestRefSchema = z .object({ repo: z.object({ id: z.number().optional() }).passthrough().nullable().optional(), @@ -410,9 +368,6 @@ type GiteaPrListItem = z.infer; type GiteaIssueListItem = z.infer; type GiteaPullRequestView = z.infer; type GiteaCurrentPullRequestApi = z.infer; -type GiteaCommitStatus = z.infer; -type GiteaCombinedCommitStatus = z.infer; -type GiteaActionTask = z.infer; type GiteaIssueComment = z.infer; type GiteaReview = z.infer; type GiteaReviewComment = z.infer; @@ -797,10 +752,6 @@ function deriveGiteaActionRequiredRunIds(runs: unknown[], sha: string): Set(); - for (const task of tasks) { - const identity = getGiteaActionWorkflowIdentity(task); - const current = latestExecutions.get(identity); - if (!current || compareGiteaActionTaskRecency(current, task) < 0) { - latestExecutions.set(identity, task); - } - } - return tasks.filter((task) => { - const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task)); - return ( - latest !== undefined && - getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest) - ); - }); -} - -function getUrlOrigin(value: string | null | undefined): string | null { - if (!value) return null; - try { - return new URL(value).origin; - } catch { - return null; - } -} - -const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid"; - -function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null { - if (!value) return null; - try { - const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN); - const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/); - return match?.[1] ? Number.parseInt(match[1], 10) : null; - } catch { - return null; - } -} - -function isNativeActionJobUrl( - targetUrl: string | null | undefined, - nativeOrigins: ReadonlySet, - nativeRunIds: ReadonlySet, -): boolean { - if (!targetUrl) return false; - try { - const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN); - if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false; - if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false; - const runId = getGiteaActionRunIdFromUrl(targetUrl); - return runId !== null && nativeRunIds.has(runId); - } catch { - return false; - } -} - -// A "shadow" is the commit status Gitea synthesizes to mirror one of its own -// Actions jobs; keeping both would double-report every job. Detection is purely -// structural: Gitea always creates these statuses with a target_url of the form -// "/jobs/" (services/actions/commit_status.go upstream), so a -// status is a shadow exactly when its URL points at a job of a run we actually -// fetched from the Actions API. Anything else - external CI, URL-less statuses, -// contexts that merely look like " / ()" - is kept. -function isGiteaActionShadowStatus( - status: GiteaCommitStatus, - nativeOrigins: ReadonlySet, - nativeRunIds: ReadonlySet, -): boolean { - return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds); -} - function combineGiteaChecks( commitStatuses: GiteaCommitStatus[], actionTasks: GiteaActionTask[], @@ -1219,32 +1040,6 @@ export async function probeGiteaHost(host: string): Promise { } } -function findTeaLoginNameForHost(stdout: string, host: string): string | null { - let data: unknown; - try { - data = JSON.parse(stdout); - } catch { - return null; - } - const parsed = z.array(GiteaLoginSchema).safeParse(data); - if (!parsed.success) { - return null; - } - const target = host.toLowerCase(); - const match = parsed.data.find((login) => { - const candidates = [login.ssh_host, login.name]; - if (login.url) { - try { - candidates.push(new URL(login.url).hostname); - } catch { - // ignore malformed login url - } - } - return candidates.some((candidate) => candidate?.toLowerCase() === target); - }); - return match?.name ?? null; -} - function hostHasLogin(stdout: string, host: string): boolean { return findTeaLoginNameForHost(stdout, host) !== null; } @@ -1409,19 +1204,35 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For const now = options.now ?? Date.now; const currentPrHeadShaCache = new Map(); - async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise { + async function runRaw( + args: string[], + runOptions: TeaCommandRunnerOptions, + ): Promise { const teaPath = await resolveTea(); if (!teaPath) { throw new TeaCliMissingError(); } try { - const result = await runner(args, runOptions); - return result.stdout.trim(); + return await runner(args, runOptions); } catch (error) { throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd }); } } + async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise { + const result = await runRaw(args, runOptions); + return result.stdout.trim(); + } + + const changeRequests = createGiteaChangeRequestSource({ + runCommand: runRaw, + createAuthError: (stderr) => new TeaAuthenticationError({ stderr }), + createCommandError: (params) => new TeaCommandError(params), + now, + pollIntervalMs: options.watchPollMs, + initialDelayMs: options.watchInitialDelayMs, + }); + function runJsonParse( args: string[], runOptions: TeaCommandRunnerOptions, @@ -2359,6 +2170,8 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For return notSupported("disablePullRequestAutoMerge"); }, + changeRequests, + invalidate(input: { cwd: string }): void { const prefix = `${input.cwd}:`; for (const key of currentPrHeadShaCache.keys()) { @@ -2367,5 +2180,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For } } }, + + dispose(): void { + changeRequests.dispose(); + }, }; }