diff --git a/docs/ipc.md b/docs/ipc.md index de4b2045..32f4ed26 100644 --- a/docs/ipc.md +++ b/docs/ipc.md @@ -35,7 +35,7 @@ explicit project overrides. See [customizations.md](customizations.md). - **Linux desktop entry**: `desktop_integration_status` / `desktop_integration_add` / `desktop_integration_remove` (all async + `spawn_blocking`; add/remove shell out to `update-desktop-database`, `gtk-update-icon-cache` and `xdg-mime`). They write `~/.local/share/applications/termic.desktop` and a 256px icon under `~/.local/share/icons/hicolor/`, which is what gives an AppImage a launcher entry AND a `termic://` handler: macOS and Windows get the scheme from the bundle and the installer, an AppImage has no install step, so without this a deep link on Linux has nowhere to go. `available` is driven by `$APPIMAGE` (absolute and still on disk), NOT by `target_os`, so a `.deb`, a dev build and every other platform answer `available: false` through the same path rather than the command being absent; `src-tauri/src/linux_desktop.rs` compiles everywhere on purpose so its desktop-entry format tests run on the machine they are written on. `integrated` is re-read from the filesystem on every call and never cached: the user can delete the entry and Gear Lever or AppImageLauncher can write one. The entry carries `X-AppImage-Integrate=false` so those tools do not add a second one. It does NOT move the AppImage: `Exec=` points wherever the file already is, and moving someone's file (and then having to rewrite the entry to match) is AppImageLauncher's job, not ours. - **Forge rate ledger** (`forge_rate.rs`, `forge::gh_api`): `forge_rate_status { probe }` (async + `spawn_blocking`) -> `RateStatus[]`, one per GitHub host: `buckets` (`graphql`, `core`), each with GitHub's `window` (`limit/remaining/used/reset_at`, account-wide, so it includes agents and the user's terminal; null when unknown or past its reset), termic's own `spent` / `estimated` / `cap` for the last hour and `by_feature`, plus `paused` (`{ until, kind: "limited" | "floor" | "budget" }`, worded by the webview) when background polling on that host is held. `probe: true` first seeds hosts with no current window from `GET /rate_limit`, which does not count against the primary limit. Every change also arrives as `termic://forge-rate-changed` with the same payload, throttled to one per 2s except when any host's pause starts, ends or moves, which always goes out. New GitHub reads go through `forge::gh_api` / `gh_graphql` (`gh api --hostname H --include`), which feed the ledger from the headers and the GraphQL `rateLimit` object, and refuse without spawning while GitHub's own refusal stands (plus termic's budget for `background` calls); the older `gh pr` / `gh issue` calls report no cost and are charged as 1-point estimates (not when `gh` failed on auth, since nothing was sent). A lookup GitHub refused answers status `rate-limited` (PR card, issue and PR pickers, Todos lists) with `retry_at` (epoch seconds, that host's), which the webview words itself (`lookupMessage` in `forgeRate.ts`) rather than showing Rust's English message; `retry_at` is null on every other status. A pulled `forge_rate_status` that resolves after a pushed event is dropped. Budget rules: [performance.md](performance.md#forge-budget-github-api). -- **Batched forge reads** (one GraphQL query per GitHub host instead of one `gh` subprocess per task or per project; budget in [performance.md](performance.md#forge-budget-github-api)): `task_pr_status_batch { ids }` (async + `spawn_blocking`) -> `(PrLookup & { id })[]`, always background work. A GitHub task whose record has a PR url joins one aliased `repository.pullRequest` query per host (`forge::PR_BATCH_MAX` = 50 per query); a closed PR, a task whose live branch is not the PR head (`forge::branch_matches_pr`, which also accepts the `pr-` / `pr--` fork checkouts), a PR the query cannot see, and every non-GitHub task take the per-task `pr_lookup_at`. A host whose gate closes (checked per chunk, inside `gh_api`) is skipped from there on and its tasks left OUT of the answer, so the caller keeps its entry. A missing CLI or signed-out `gh` answers each task with `cli-missing` / `cli-unauthed`; any other failure leaves the chunk out for a pass and, if it fails again, falls back per task within that budget. An open PR whose head is not the task's branch is looked up by branch at most every three minutes per task (else the batch's answer stands). The webview drops a batch answer that lands behind a refresh in flight or one that landed since, and keeps a good lookup over an `error` / `rate-limited` answer while still stamping the attempt (`batchLanding`). Every per-task lookup a pass starts shares one budget of eight, and each task gets one at most every three minutes, so a PR the query cannot see (deleted repo) does not cost a subprocess every pass; an answer whose url is not the PR asked is not trusted. `task_pr_status { id, background }`, `task_member_pr_status { id, background }` and `task_pr_comments { id, background }` take `background` as REQUIRED, so a new caller has to choose; with it set they answer `null` without calling anything while the task's (or any member's) GitHub host is paused (`forge::background_held`). The TS side has `taskPrStatusBackground` / `taskMemberPrStatusBackground` / `taskPrCommentsBackground` for the pollers; the plain wrappers send `background: false`. The identity is persisted exactly as `task_pr_status` does (`persist_pr_identity`). `project_forge_lists { queries: { projectId, kind: "issues" | "prs", scope, limit }[] }` (async + `spawn_blocking`) -> `(IssueLookup | PrPickList)[]` in `queries` order, each answer shaped for its own `kind`: GitHub lists on one host go out as queries of up to `forge::LISTS_BATCH_MAX` = 30 lists (`forge::github_lists`; repo-wide lists as `repository` aliases, personal ones as `search` aliases with `repo:` qualifiers chunked under GitHub's 256-character limit, split back out by `nameWithOwner` and capped at each list's limit), the rest (GitLab, Azure, no forge, a limit over 100, an owner or repo outside GitHub's `[A-Za-z0-9._-]` charset, or a failed GitHub query) take the per-project path on three threads, except a query GitHub refused on a limit, whose lists (and the host's later chunks) each answer `rate-limited`, and a query past the output cap, which is split in half and asked again (one list still too large answers `error`). `forge::tests::live_github_batch_queries_parse` is an ignored test that runs both queries against the signed-in `gh`. +- **Batched forge reads** (one GraphQL query per GitHub host instead of one `gh` subprocess per task or per project; budget in [performance.md](performance.md#forge-budget-github-api)): `task_pr_status_batch { ids }` (async + `spawn_blocking`) -> `(PrLookup & { id })[]`, always background work. A GitHub task whose record has a PR url joins one aliased `repository.pullRequest` query per host (`forge::PR_BATCH_MAX` = 50 per query); a `merged` or `closed` PR whose live branch is still that PR's head branch (`branch == pr.head`, leaving fork review aliases like `pr--` pinned) scans newer candidates on that branch via a lightweight paginated GraphQL query (`forge::github_branch_pr_replacements_batch`, up to `forge::PR_REPLACEMENT_BATCH_MAX` = 15 per query, throttled by Rust's three-minute `RECHECK_SECS` gate alongside the frontend's three-minute `SETTLED_BATCH_STALE_MS` settled batch cadence while per-task forges wait hourly in `SETTLED_STALE_MS`), hydrates only selected replacements, keeps the old PR if none exists (or if the checkout moved/detached), and omits the entry on failure or rate refusal so the frontend keeps its existing display without advancing into the hourly backoff; an open PR whose live branch is not the PR head, a PR the query cannot see, and every non-GitHub task take the per-task `pr_lookup_at`. A host whose gate closes (checked per chunk, inside `gh_api`) is skipped from there on and its tasks left OUT of the answer, so the caller keeps its entry. A missing CLI or signed-out `gh` answers each task with `cli-missing` / `cli-unauthed`; any other failure leaves the chunk out for a pass and, if it fails again, falls back per task within that budget. An open PR whose head is not the task's branch is looked up by branch at most every three minutes per task (else the batch's answer stands). The webview drops a batch answer that lands behind a refresh in flight or one that landed since, and keeps a good lookup over an `error` / `rate-limited` answer while still stamping the attempt (`batchLanding`). Every per-task lookup a pass starts shares one budget of eight, and each task gets one at most every three minutes, so a PR the query cannot see (deleted repo) does not cost a subprocess every pass; an answer whose url is not the PR asked is not trusted. `task_pr_status { id, background }`, `task_member_pr_status { id, background }` and `task_pr_comments { id, background }` take `background` as REQUIRED, so a new caller has to choose; with it set they answer `null` without calling anything while the task's (or any member's) GitHub host is paused (`forge::background_held`). The TS side has `taskPrStatusBackground` / `taskMemberPrStatusBackground` / `taskPrCommentsBackground` for the pollers; the plain wrappers send `background: false`. The identity is persisted exactly as `task_pr_status` does (`persist_pr_identity`), under a lock that ignores stale snapshots whose PR was already replaced on disk. `project_forge_lists { queries: { projectId, kind: "issues" | "prs", scope, limit }[] }` (async + `spawn_blocking`) -> `(IssueLookup | PrPickList)[]` in `queries` order, each answer shaped for its own `kind`: GitHub lists on one host go out as queries of up to `forge::LISTS_BATCH_MAX` = 30 lists (`forge::github_lists`; repo-wide lists as `repository` aliases, personal ones as `search` aliases with `repo:` qualifiers chunked under GitHub's 256-character limit, split back out by `nameWithOwner` and capped at each list's limit), the rest (GitLab, Azure, no forge, a limit over 100, an owner or repo outside GitHub's `[A-Za-z0-9._-]` charset, or a failed GitHub query) take the per-project path on three threads, except a query GitHub refused on a limit, whose lists (and the host's later chunks) each answer `rate-limited`, and a query past the output cap, which is split in half and asked again (one list still too large answers `error`). `forge::tests::live_github_batch_queries_parse` is an ignored test that runs both queries against the signed-in `gh`. - **Change summaries**: `task_diff` (async + `spawn_blocking`) returns the whole unified diff plus its counts, for the compare view. `task_diff_stat` returns the COUNTS ONLY and is what a list view must use: `task_diff` also ships the full diff text and spawns one `git diff --no-index` per untracked file, so a board polling every visible card would fork that many processes on a timer. The lean one runs exactly two git processes per repo (a `--numstat` against the merge-base, and one `ls-files --others`) and counts new files' lines by READING them, skipping binaries (a NUL in the first 8KB, git's own probe) and anything over 2MB. That line count is therefore an estimate and is documented as one at every layer: a file with no trailing newline is one short. The file counts are exact. Multi-repo tasks sum the host worktree and every WORKTREE member; a `repo_root` member is the project's live checkout, shared with every other task and with whatever the user is doing by hand, so counting it would attribute someone else's uncommitted edit to an agent. Consumed through `src/store/diffStat.ts`, which is demand-driven rather than a poller (see docs/ui.md). - **Pasted images**: `clipboard_image_save` (async + `spawn_blocking`) takes the image bytes as the **raw request body** (`invoke(cmd, uint8array)` → `tauri::ipc::Request` / `InvokeBody::Raw`), not as a JSON array of numbers, which for a 3 MB screenshot is the difference between one copy and several million. It sniffs the format from the MAGIC BYTES (PNG/JPEG/GIF/WebP) rather than trusting a caller-supplied extension, writes `pasted--<8 hex>.` into `$TMPDIR/termic-attachments/clipboard/` (`attachments_dir`, shared with dropped-file staging, and NOT the data dir, which Seatbelt denies outright), prunes anything there older than 7 days, and returns the absolute path. It exists because an image paste cannot reach an agent any other way: xterm.js sends only text down the PTY, and in Docker mode the agent is a Linux process whose clipboard reader shells out to xclip/wl-paste with no route to the Mac's pasteboard. `TerminalPane`'s capture-phase `paste` listener PASTES the returned path in the image's place (via `term.paste()`, so it arrives bracketed and claude reads the file into a real `[Image #N]` attachment instead of echoing a path), backslash-escaped by the same `shellEscapePath` a dragged-in file uses. It fires for DOCKER tasks only: everywhere else the agent reads the Mac clipboard itself and already gets the real image. Docker mounts that directory READ-ONLY at the identical absolute path, so the pasted string resolves inside the container. diff --git a/e2e/specs/git.e2e.ts b/e2e/specs/git.e2e.ts index fca3c4ad..1fd948f9 100644 --- a/e2e/specs/git.e2e.ts +++ b/e2e/specs/git.e2e.ts @@ -2390,6 +2390,7 @@ describe("pr card (#21)", () => { }); await waitForText("Merged"); await waitForTextGone("Changes requested"); + await waitVisible("[data-testid='pr-create-new']"); await browser.waitUntil( () => browser.execute( diff --git a/src-tauri/src/forge.rs b/src-tauri/src/forge.rs index 22cbf45e..ddac3418 100644 --- a/src-tauri/src/forge.rs +++ b/src-tauri/src/forge.rs @@ -927,7 +927,7 @@ fn azure_whoami(bin: &str, org: &str) -> String { /// Normalized PR/MR snapshot — the union of what `gh pr view --json` and /// `glab mr view -F json` report, flattened to what the PR card renders. -#[derive(Clone, Debug, Serialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct PrStatus { pub provider: String, pub number: u64, @@ -1028,13 +1028,29 @@ fn classify_stderr(provider: &str, err: &str) -> ForgeError { /// deleted after a merge, which breaks by-branch lookup on GitLab). /// Ok(None) = the CLI worked and there is genuinely no PR yet. pub fn pr_status(provider: &str, cwd: &Path, number: Option) -> Result, ForgeError> { + pr_status_with_hint(provider, cwd, number, None) +} + +/// Live PR/MR status for the task's current branch, carrying `old_number` as a +/// source-ownership / monotonicity hint when resolving a branch after a prior +/// PR/MR settled or when multiple active PRs/MRs share a branch name. +pub fn pr_status_for_branch(provider: &str, cwd: &Path, old_number: Option) -> Result, ForgeError> { + pr_status_with_hint(provider, cwd, None, old_number) +} + +fn pr_status_with_hint( + provider: &str, + cwd: &Path, + number: Option, + old_number: Option, +) -> Result, ForgeError> { // reprobe, not the cache: a CLI installed mid-session must resolve on // the next call, not after the next detect() pass (which the user // reaches only via Settings or a card hint). let bin = reprobe_bin(cli_for_provider(provider)).ok_or(ForgeError::CliMissing(cli_for_provider(provider)))?; match provider { - GITLAB => gitlab_mr_status(&bin, cwd, number), - AZURE => azure_pr_status(&bin, cwd, number), + GITLAB => gitlab_mr_status(&bin, cwd, number, old_number), + AZURE => azure_pr_status(&bin, cwd, number, old_number), _ => github_pr_status(&bin, cwd, number), } } @@ -1109,7 +1125,11 @@ pub const PR_BATCH_MAX: usize = 50; /// The same fields `github_pr_status` asks `gh pr view` for, in GraphQL. /// The rollup is the head commit's, which is what gh reads too. +/// `isCrossRepository` + `headRepositoryOwner` identify fork ownership so a +/// same-branch replacement lookup never adopts a stranger's fork PR that +/// shares a branch name. const PR_STATUS_SELECTION: &str = "number url title state isDraft reviewDecision baseRefName headRefName \ +isCrossRepository headRepositoryOwner { login } \ latestReviews(first: 20) { nodes { state } } \ commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes { \ __typename ... on CheckRun { status conclusion } ... on StatusContext { state } } } } } } }"; @@ -1160,24 +1180,258 @@ fn normalize_graphql_pr(pr: &serde_json::Value) -> serde_json::Value { v } +/// One answered PR in a batch plus the fork-ownership fields needed when a +/// settled PR checks for a same-branch replacement without adopting another +/// contributor's fork PR that shares the branch name. +#[derive(Clone, Debug, PartialEq)] +pub struct PrBatchItem { + pub status: PrStatus, + pub cross_repository: bool, + pub head_owner: Option, +} + +/// One settled task's branch to check for a newer PR on the same branch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BranchReplacementRef { + pub owner: String, + pub repo: String, + pub branch: String, + pub old_number: u64, + pub old_cross_repository: bool, + pub old_head_owner: Option, +} + +/// Maximum aliases per page when scanning settled branches for replacements. +pub const PR_REPLACEMENT_BATCH_MAX: usize = 15; + +/// Lightweight fields fetched while scanning candidate PRs on a branch; full +/// checks/reviews are hydrated afterwards for selected replacements only. +const PR_REPLACEMENT_SCAN_SELECTION: &str = + "number state headRefName isCrossRepository headRepositoryOwner { login }"; +const PR_REPLACEMENT_PAGE_SIZE: usize = 20; +const MAX_REPLACEMENT_PAGES: usize = 5; + +/// Outcome of scanning one settled PR's branch for a newer same-branch PR. +#[derive(Clone, Debug, PartialEq)] +pub enum ReplacementOutcome { + KeepOld, + Replace(PrStatus), + Retry, +} + /// The answer to a batch, in `refs` order. None for a PR the query could /// not see (deleted repo, wrong number, no access): one bad alias does not /// fail the rest. +#[cfg(test)] fn parse_pr_batch(data: &serde_json::Value, n: usize) -> Vec> { + parse_pr_batch_items(data, n) + .into_iter() + .map(|o| o.map(|i| i.status)) + .collect() +} + +fn parse_pr_batch_items(data: &serde_json::Value, n: usize) -> Vec> { (0..n).map(|i| { let pr = &data[format!("p{i}")]["pullRequest"]; - pr.is_object().then(|| github_pr_status_from(&normalize_graphql_pr(pr))) + pr.is_object().then(|| PrBatchItem { + status: github_pr_status_from(&normalize_graphql_pr(pr)), + cross_repository: pr["isCrossRepository"].as_bool().unwrap_or(false), + head_owner: pr["headRepositoryOwner"]["login"].as_str().map(str::to_string), + }) }).collect() } -/// Status for up to `PR_BATCH_MAX` PRs on one host, in one query. -pub fn github_pr_status_batch(host: &str, feature: &'static str, refs: &[PrRef]) -> Result>, ForgeError> { +/// Status (with fork metadata) for up to `PR_BATCH_MAX` PRs on one host. +pub fn github_pr_status_batch_meta( + host: &str, + feature: &'static str, + refs: &[PrRef], +) -> Result>, ForgeError> { if refs.is_empty() { return Ok(Vec::new()); } // The background poller's call, always: it waits out termic's budget too. let ans = gh_graphql(host, feature, true, &pr_batch_selection(refs))?; - Ok(parse_pr_batch(&ans.data, refs.len())) + Ok(parse_pr_batch_items(&ans.data, refs.len())) +} + +/// Status for up to `PR_BATCH_MAX` PRs on one host, in one query. +#[cfg(test)] +pub fn github_pr_status_batch(host: &str, feature: &'static str, refs: &[PrRef]) -> Result>, ForgeError> { + Ok(github_pr_status_batch_meta(host, feature, refs)? + .into_iter() + .map(|o| o.map(|i| i.status)) + .collect()) +} + +fn branch_replacement_page_selection(items: &[(usize, &BranchReplacementRef, Option<&str>)]) -> String { + items.iter().map(|(idx, r, cursor)| { + let after = cursor.map_or_else(String::new, |c| format!(", after: {}", gql_str(c))); + format!( + "b{idx}: repository(owner: {}, name: {}) {{ pullRequests(headRefName: {}, first: {PR_REPLACEMENT_PAGE_SIZE}{after}, orderBy: {{ field: CREATED_AT, direction: DESC }}) {{ pageInfo {{ hasNextPage endCursor }} nodes {{ {PR_REPLACEMENT_SCAN_SELECTION} }} }} }}", + gql_str(&r.owner), gql_str(&r.repo), gql_str(&r.branch), + ) + }).collect::>().join(" ") +} + +#[derive(Default)] +struct BranchScanAcc { + best_open: Option, + best_newer: Option, + saw_old_or_older: bool, +} + +/// Scan one page of candidate PRs on the same branch (`r.branch`) and matching +/// repo ownership, ignoring older PRs (`<= old_number`) and unrelated forks. +fn scan_branch_replacement_nodes( + nodes: &[serde_json::Value], + r: &BranchReplacementRef, + acc: &mut BranchScanAcc, +) { + for node in nodes { + if !node.is_object() { + continue; + } + let number = node["number"].as_u64().unwrap_or(0); + if number == 0 { + continue; + } + if number <= r.old_number { + acc.saw_old_or_older = true; + continue; + } + let head = node["headRefName"].as_str().unwrap_or(""); + if head != r.branch { + continue; + } + let cross = node["isCrossRepository"].as_bool().unwrap_or(false); + let head_owner = node["headRepositoryOwner"]["login"].as_str(); + let same_origin = if r.old_cross_repository { + cross && r.old_head_owner.as_deref() + .is_some_and(|exp| head_owner.is_some_and(|act| act.eq_ignore_ascii_case(exp))) + } else { + !cross + }; + if !same_origin { + continue; + } + if node["state"].as_str() == Some("OPEN") { + if acc.best_open.map_or(true, |b| number > b) { + acc.best_open = Some(number); + } + } else if acc.best_newer.map_or(true, |b| number > b) { + acc.best_newer = Some(number); + } + } +} + +enum ScanPageOutcome { + Selected(u64), + NextPage(String), + NoneFound, + AliasFailed, +} + +fn eval_branch_replacement_alias( + alias_val: &serde_json::Value, + r: &BranchReplacementRef, + acc: &mut BranchScanAcc, +) -> ScanPageOutcome { + let prs = &alias_val["pullRequests"]; + let Some(nodes) = prs["nodes"].as_array() else { + return ScanPageOutcome::AliasFailed; + }; + scan_branch_replacement_nodes(nodes, r, acc); + if let Some(open) = acc.best_open { + return ScanPageOutcome::Selected(open); + } + let has_next = prs["pageInfo"]["hasNextPage"].as_bool().unwrap_or(false); + let end_cursor = prs["pageInfo"]["endCursor"].as_str().filter(|s| !s.is_empty()); + if has_next && !acc.saw_old_or_older { + if let Some(c) = end_cursor { + return ScanPageOutcome::NextPage(c.to_string()); + } + } + if let Some(newer) = acc.best_newer { + ScanPageOutcome::Selected(newer) + } else { + ScanPageOutcome::NoneFound + } +} + +/// Batched same-branch replacement lookup for settled (`merged` / `closed`) +/// GitHub PRs on one host. Scans lightweight candidates across pages until a +/// matching source is found or older PRs are reached, then hydrates selected +/// candidates via `github_pr_status_batch_meta`. +pub fn github_branch_pr_replacements_batch( + host: &str, + feature: &'static str, + refs: &[BranchReplacementRef], +) -> Result, ForgeError> { + if refs.is_empty() { + return Ok(Vec::new()); + } + let mut outcomes: Vec> = vec![None; refs.len()]; + let mut accs: Vec = (0..refs.len()).map(|_| BranchScanAcc::default()).collect(); + let mut chosen: Vec<(usize, u64)> = Vec::new(); + let mut pending: Vec<(usize, Option)> = (0..refs.len()).map(|i| (i, None)).collect(); + + for page in 0..MAX_REPLACEMENT_PAGES { + if pending.is_empty() { + break; + } + let query_items: Vec<(usize, &BranchReplacementRef, Option<&str>)> = pending + .iter() + .map(|(i, c)| (*i, &refs[*i], c.as_deref())) + .collect(); + let ans = match gh_graphql(host, feature, true, &branch_replacement_page_selection(&query_items)) { + Ok(a) => a, + Err(e) => { + if page == 0 || matches!(e, ForgeError::RateLimited { .. }) { + return Err(e); + } + for (i, _) in pending { + outcomes[i] = Some(ReplacementOutcome::Retry); + } + pending = Vec::new(); + break; + } + }; + let mut next_pending = Vec::new(); + for (i, _) in pending { + match eval_branch_replacement_alias(&ans.data[format!("b{i}")], &refs[i], &mut accs[i]) { + ScanPageOutcome::Selected(n) => chosen.push((i, n)), + ScanPageOutcome::NextPage(c) => next_pending.push((i, Some(c))), + ScanPageOutcome::NoneFound => outcomes[i] = Some(ReplacementOutcome::KeepOld), + ScanPageOutcome::AliasFailed => outcomes[i] = Some(ReplacementOutcome::Retry), + } + } + pending = next_pending; + } + for (i, _) in pending { + if let Some(n) = accs[i].best_open.or(accs[i].best_newer) { + chosen.push((i, n)); + } else { + outcomes[i] = Some(ReplacementOutcome::Retry); + } + } + + for chunk in chosen.chunks(PR_BATCH_MAX) { + let hydrate_refs: Vec = chunk.iter().map(|(i, num)| PrRef { + owner: refs[*i].owner.clone(), + repo: refs[*i].repo.clone(), + number: *num, + }).collect(); + let hydrated = github_pr_status_batch_meta(host, feature, &hydrate_refs)?; + for ((idx, num), item) in chunk.iter().zip(hydrated) { + outcomes[*idx] = Some(match item { + Some(it) if it.status.number == *num => ReplacementOutcome::Replace(it.status), + _ => ReplacementOutcome::Retry, + }); + } + } + + Ok(outcomes.into_iter().map(|o| o.unwrap_or(ReplacementOutcome::KeepOld)).collect()) } // ───────────────────────── batched lists (GitHub) ───────────────────────── @@ -1446,7 +1700,81 @@ fn rollup_to_checks(rollup: &serde_json::Value) -> String { if pending { "pending".into() } else { "passing".into() } } -fn gitlab_mr_status(bin: &str, cwd: &Path, number: Option) -> Result, ForgeError> { +fn gitlab_open_mrs_api_target(branch: &str, server_repo: Option<&str>) -> Result<(Option, String), ForgeError> { + let encoded: String = percent_encoding::utf8_percent_encode(branch, percent_encoding::NON_ALPHANUMERIC).collect(); + let suffix = format!("merge_requests?state=opened&source_branch={encoded}&order_by=created_at&sort=desc&per_page=20"); + if let Some(repo_url) = server_repo { + let host = host_of_remote(repo_url) + .ok_or_else(|| ForgeError::Other(format!("cannot parse GitLab host from {repo_url}")))?; + let project = path_of_remote(repo_url) + .ok_or_else(|| ForgeError::Other(format!("cannot parse GitLab project path from {repo_url}")))?; + let enc_proj: String = percent_encoding::utf8_percent_encode(&project, percent_encoding::NON_ALPHANUMERIC).collect(); + return Ok((Some(host), format!("projects/{enc_proj}/{suffix}"))); + } + Ok((None, format!("projects/:id/{suffix}"))) +} + +fn gitlab_mr_source_project(bin: &str, cwd: &Path, iid: u64, server_repo: Option<&str>) -> Option { + let num_s = iid.to_string(); + let mut args = vec!["mr", "view", &num_s, "--output", "json"]; + if let Some(repo) = server_repo { + args.extend(["-R", repo]); + } + let o = run(bin, &args, Some(cwd)).ok().filter(|o| o.status.success())?; + let v: serde_json::Value = serde_json::from_slice(&o.stdout).ok()?; + v["source_project_id"].as_u64() +} + +fn pick_gitlab_branch_mr_iid( + list: &[serde_json::Value], + old_number: Option, + expected_source_project: Option, +) -> Option { + let mut eligible: Vec<(u64, &serde_json::Value)> = list.iter() + .filter_map(|m| m["iid"].as_u64().filter(|&iid| iid > 0).map(|iid| (iid, m))) + .filter(|(iid, _)| old_number.map_or(true, |old| *iid > old)) + .collect(); + if let Some(src) = expected_source_project { + eligible.retain(|(_, m)| m["source_project_id"].as_u64() == Some(src)); + } else if eligible.iter().any(|(_, m)| m["source_project_id"].is_u64() && m["source_project_id"] == m["target_project_id"]) { + // Without a known prior MR, prefer upstream same-repo MRs when fork MRs also match the branch name. + eligible.retain(|(_, m)| m["source_project_id"].is_u64() && m["source_project_id"] == m["target_project_id"]); + } + eligible.into_iter().map(|(iid, _)| iid).max() +} + +/// Newest open MR iid for `branch`, used when `glab mr view` reports multiple +/// open MRs on the same source branch. +fn gitlab_newest_open_mr_iid( + bin: &str, + cwd: &Path, + branch: &str, + server_repo: Option<&str>, + old_number: Option, +) -> Result, ForgeError> { + let (host, path) = gitlab_open_mrs_api_target(branch, server_repo)?; + let mut args = vec!["api"]; + if let Some(h) = host.as_deref() { + args.extend(["--hostname", h]); + } + args.push(path.as_str()); + let o = run(bin, &args, Some(cwd)).map_err(|e| ForgeError::Other(e.to_string()))?; + if !o.status.success() { + return Err(classify_failure(GITLAB, &o)); + } + let v: serde_json::Value = serde_json::from_slice(&o.stdout) + .map_err(|e| ForgeError::Other(format!("glab returned unparseable JSON: {e}")))?; + let list = v.as_array().map(Vec::as_slice).unwrap_or(&[]); + let distinct_sources: HashSet = list.iter().filter_map(|m| m["source_project_id"].as_u64()).collect(); + let expected_src = if distinct_sources.len() > 1 { + old_number.and_then(|old| gitlab_mr_source_project(bin, cwd, old, server_repo)) + } else { + None + }; + Ok(pick_gitlab_branch_mr_iid(list, old_number, expected_src)) +} + +fn gitlab_mr_status(bin: &str, cwd: &Path, number: Option, old_number: Option) -> Result, ForgeError> { // A folder on a server: name the branch and the repo (glab has no // checkout here to read them from), as github_pr_status does. let server = server_branch(cwd); @@ -1465,10 +1793,39 @@ fn gitlab_mr_status(bin: &str, cwd: &Path, number: Option) -> Result