From 75b07e0c629019a4a340cb60fbe3f09bc776c008 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 11:26:22 -0500 Subject: [PATCH 1/5] fix(dg): print dg doctor's forge-v2 row once The row was printed under network (proof-verified) and again under contracts (the recorded ids). The proof-verified row now carries the deployment file as its source and stands alone under contracts; the recorded row is shown only when the live check did not run (fresh install, no deployment, DAPI unreachable). QW-083. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/doctor.rs | 92 +++++++++++++++++++++++++++++++++-------- 1 file changed, 74 insertions(+), 18 deletions(-) diff --git a/crates/dg/src/doctor.rs b/crates/dg/src/doctor.rs index c6e72a6b0..3113be35c 100644 --- a/crates/dg/src/doctor.rs +++ b/crates/dg/src/doctor.rs @@ -174,6 +174,11 @@ struct Section { /// Run every check, apply the safe fixes when `fix` is set, and report. pub async fn run(ctx: &Ctx, fix: bool) -> Result<()> { let identity = check_identity(ctx).await; + let mut network = check_network(ctx).await; + let contracts = contract_rows( + &mut network, + check_contracts(&ctx.target, unchosen_undeployed(ctx)), + ); let mut sections = vec![ Section { title: "toolchain", @@ -185,11 +190,11 @@ pub async fn run(ctx: &Ctx, fix: bool) -> Result<()> { }, Section { title: "network", - checks: check_network(ctx).await, + checks: network, }, Section { title: "contracts", - checks: vec![check_contracts(&ctx.target, unchosen_undeployed(ctx))], + checks: contracts, }, Section { title: "storage", @@ -723,23 +728,34 @@ async fn check_network(ctx: &Ctx) -> Vec { "run it again in a minute (a different node is asked)", ), }); - out.push(check_forge_v2(&client, &ctx.target).await); + out.extend(check_forge_v2(&client, &ctx.target).await); out } +/// The contracts section: one `forge-v2` row (QW-083 printed it under network and again +/// here). The network section's proof-verified row, when it ran, moves here: it says all the +/// recorded row does and whether the contracts are really there. Otherwise (a fresh install, +/// no deployment, a DAPI that could not be reached) the recorded row is all there is. +fn contract_rows(network: &mut Vec, recorded: Check) -> Vec { + match network.iter().position(|c| c.name == "forge-v2") { + Some(i) => vec![network.remove(i)], + None => vec![recorded], + } +} + +/// Where the forge-v2 contract ids for `target` come from. +fn deployment_source(target: &NetworkTarget) -> String { + format!("forge-contracts/deployments/{}.json", target.network.key()) +} + /// The DPNS system contract: its id is fixed by rs-dpp and identical on every network. const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; /// The forge-v2 contracts recorded for this network: each must fetch with a verified proof -/// and be enrolled, as whole contracts, in the recorded contract group. A network -/// with no forge-v2 deployment is reported by the contracts row, so this one only notes it. -async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Check { - let Some(ids) = &target.v2 else { - return Check::ok( - "forge-v2", - format!("not deployed on {} (see contracts)", target.network.key()), - ); - }; +/// and be enrolled, as whole contracts, in the recorded contract group. `None` for a network +/// with no forge-v2 deployment: [`check_contracts`]' row reports that. +async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Option { + let ids = target.v2.as_ref()?; let mut problems = Vec::new(); // forge-community is forge-collab on a deployment that predates the split: checked once let mut contracts = ids.all().to_vec(); @@ -763,12 +779,16 @@ async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Chec Err(e) => problems.push(format!("{label} {id} group lookup failed: {e}")), } } - if problems.is_empty() { + Some(if problems.is_empty() { Check::ok( "forge-v2", format!( - "core={} collab={} community={} proof-verified and enrolled in group {}", - ids.core, ids.collab, ids.community, ids.group + "core={} collab={} community={} proof-verified and enrolled in group {} (source: {})", + ids.core, + ids.collab, + ids.community, + ids.group, + deployment_source(target) ), ) } else { @@ -777,7 +797,7 @@ async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Chec problems.join("; "), "the network may not run protocol 14 yet, or the deployment record is stale", ) - } + }) } /// A fresh install: no flag, `config.toml` or environment chose a network, and the default @@ -812,12 +832,12 @@ fn check_contracts(target: &NetworkTarget, fresh_install: bool) -> Check { Ok(ids) => Check::ok( "forge-v2", format!( - "core={} collab={} community={} group={} (source: forge-contracts/deployments/{}.json)", + "core={} collab={} community={} group={} (source: {})", ids.core, ids.collab, ids.community, ids.group, - target.network.key() + deployment_source(target) ), ), Err(e) => Check::fail( @@ -1416,6 +1436,42 @@ mod tests { assert!(rows.iter().all(|c| c.status == Status::Ok)); } + /// QW-083: the forge-v2 row was printed under network and again under contracts. + #[test] + fn the_forge_v2_row_is_printed_once() { + let recorded = || Check::ok("forge-v2", "core=a (source: deployments/x.json)"); + let proved = Check::ok("forge-v2", "core=a proof-verified and enrolled in group g"); + let mut network = vec![ + Check::ok("dapi", "reachable"), + Check::ok("protocol", "14"), + proved, + ]; + let contracts = contract_rows(&mut network, recorded()); + assert_eq!(contracts.len(), 1); + assert!( + contracts[0].detail.contains("proof-verified"), + "the live row is kept" + ); + let sections = [ + Section { + title: "network", + checks: network, + }, + Section { + title: "contracts", + checks: contracts, + }, + ]; + let out = render_sections(§ions); + assert_eq!(out.matches("forge-v2").count(), 1, "{out}"); + + // No live row (fresh install, no deployment, DAPI down): the recorded one stands. + let mut network = vec![Check::fail("dapi", "could not connect", "retry")]; + let contracts = contract_rows(&mut network, recorded()); + assert!(contracts[0].detail.contains("source:")); + assert_eq!(network.len(), 1); + } + #[test] fn contracts_check_reports_the_deployment_file_as_the_source() { let target = NetworkSettings { From 1316185beb6aa157eb963989210d45061ff8ab2b Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 11:26:22 -0500 Subject: [PATCH 2/5] feat(dg): switch to the branch in dg pr checkout Like gh pr checkout: pr/ is pointed at the PR head and switched to when the working tree has no uncommitted changes; with changes it stays put and prints the git switch hint. Already on pr/, it fast-forwards (git refuses what would lose work) instead of failing on branch -f. JSON gains switched. QW-083. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/main.rs | 3 +- crates/dg/src/pr/mod.rs | 101 ++++++++++++++++++++++++++++++++--- docs/guides/collaborating.md | 2 +- 3 files changed, 96 insertions(+), 10 deletions(-) diff --git a/crates/dg/src/main.rs b/crates/dg/src/main.rs index f0315587f..f95b2ffae 100644 --- a/crates/dg/src/main.rs +++ b/crates/dg/src/main.rs @@ -740,7 +740,8 @@ pub enum PrCommand { #[arg(long)] comments: bool, }, - /// Check out a pull request as branch `pr/`, fetching its head from the source repo. + /// Check out a pull request as branch `pr/`, fetching its head from the source repo, + /// and switch to it (left for `git switch` when there are uncommitted changes). Checkout { /// The repository (`owner/name`). repo: String, diff --git a/crates/dg/src/pr/mod.rs b/crates/dg/src/pr/mod.rs index 8ced75495..77731dfe0 100644 --- a/crates/dg/src/pr/mod.rs +++ b/crates/dg/src/pr/mod.rs @@ -2309,8 +2309,35 @@ async fn checkout(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { )); } let branch = format!("pr/{number}"); - git::git(&cwd, &["branch", "-f", &branch, &head], &[]) - .with_context(|| format!("creating branch {branch} (is it checked out?)"))?; + // Tracked changes only: git refuses a switch that would overwrite an untracked file. + let clean = git::git( + &cwd, + &["status", "--porcelain", "--untracked-files=no"], + &[], + ) + .is_ok_and(|out| out.is_empty()); + let step = checkout_step(git::current_branch(&cwd).as_deref(), &branch, clean); + match step { + CheckoutStep::FastForward => { + git::git(&cwd, &["merge", "--ff-only", "-q", &head], &[]).with_context(|| { + format!( + "moving {branch} (checked out) to the PR head {}: switch to another branch \ + and run `dg pr checkout` again to reset it", + short(&head) + ) + })?; + } + CheckoutStep::CreateAndSwitch | CheckoutStep::CreateOnly => { + git::git(&cwd, &["branch", "-f", &branch, &head], &[]) + .with_context(|| format!("creating branch {branch}"))?; + } + } + if step == CheckoutStep::CreateAndSwitch { + git::git(&cwd, &["switch", "-q", &branch], &[]).with_context(|| { + format!("switching to {branch} (it is created: git switch {branch})") + })?; + } + let switched = step != CheckoutStep::CreateOnly; ctx.emit( json!({ "pr": number, @@ -2318,18 +2345,50 @@ async fn checkout(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { "branch": branch, "sourceRepoId": source, "fetched": fetched, - "branchCreated": true, + "branchCreated": step != CheckoutStep::FastForward, + "switched": switched, }), - || { - println!( - "✓ branch {branch} at {} (git switch {branch})", - short(&head) - ); + || match step { + CheckoutStep::CreateAndSwitch => { + println!("✓ switched to branch {branch} at {}", short(&head)); + } + CheckoutStep::FastForward => { + println!("✓ branch {branch} (checked out) at {}", short(&head)); + } + CheckoutStep::CreateOnly => { + println!( + "✓ branch {branch} at {} (git switch {branch})", + short(&head) + ); + println!(" not switched: the working tree has uncommitted changes"); + } }, ); Ok(()) } +/// What `dg pr checkout` does with branch `pr/`, as `gh pr checkout` does, never losing +/// uncommitted work. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CheckoutStep { + /// Point the branch at the head and switch to it (the working tree is clean). + CreateAndSwitch, + /// Point the branch at the head, stay put: there are uncommitted changes. + CreateOnly, + /// The branch is checked out: fast-forward it (git refuses what would lose work). + FastForward, +} + +fn checkout_step(current: Option<&str>, branch: &str, clean: bool) -> CheckoutStep { + if current == Some(branch) { + CheckoutStep::FastForward + } else if clean { + CheckoutStep::CreateAndSwitch + } else { + CheckoutStep::CreateOnly + } +} + async fn diff(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { let Located { source, @@ -2477,6 +2536,32 @@ mod tests { assert_eq!(state_label(&with(true, false, false)), "merged"); } + /// QW-083: `dg pr checkout` switches to `pr/` as `gh pr checkout` does, but only from + /// a clean working tree; already on it, it fast-forwards instead of failing. + #[test] + fn checkout_switches_only_from_a_clean_tree() { + assert_eq!( + checkout_step(Some("main"), "pr/7", true), + CheckoutStep::CreateAndSwitch + ); + assert_eq!( + checkout_step(None, "pr/7", true), + CheckoutStep::CreateAndSwitch + ); + assert_eq!( + checkout_step(Some("main"), "pr/7", false), + CheckoutStep::CreateOnly + ); + assert_eq!( + checkout_step(Some("pr/7"), "pr/7", false), + CheckoutStep::FastForward + ); + assert_eq!( + checkout_step(Some("pr/71"), "pr/7", true), + CheckoutStep::CreateAndSwitch + ); + } + /// JSON's `"state"` field stays a stable three-value enum (`open`/`closed`/`merged`) even /// for a draft, since `"draft"` is already its own boolean field: an open draft must keep /// matching `dg pr list --state open --json | jq 'select(.state=="open")'`, unlike the diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index 6b360bafe..1cbf3b5ba 100644 --- a/docs/guides/collaborating.md +++ b/docs/guides/collaborating.md @@ -237,7 +237,7 @@ dg pr view /project 7 --comments # + threads under their file and l dg pr diff /project 7 # fetches head and base, then git diff base...head dg pr commits /project 7 # the commits the PR adds dg pr checks /project 7 # check runs reported on the head -dg pr checkout /project 7 # creates local branch pr/7 at the PR head +dg pr checkout /project 7 # branch pr/7 at the PR head, switched to if the tree is clean dg pr review /project 7 --approve --body "LGTM" dg pr review /project 7 --request-changes --body "Needs a test" \ --file src/a.rs --line 12 --body "off by one?" \ From c0d74833f1c500f2b7f03e7ae7568c0df60e468a Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 11:26:22 -0500 Subject: [PATCH 3/5] feat(dg): align --json fields and show DPNS names in collab list and issue view QW-081: repo view --json gains description (as repo list has it; null when the repo document cannot be read). Issue JSON gains state (open/closed) beside open; outputs with only documentId (issue view, collab accept/add/list, ci runner add, ci report) also get id. No field is renamed or removed. QW-083: dg collab list and dg issue view print each identity's DPNS name after its id, read concurrently in one batch (PlatformClient::dpns_first_names), human output only; a failed read shows the bare id. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/ci.rs | 3 +- crates/dg/src/collab.rs | 17 ++++++- crates/dg/src/fmt.rs | 18 +++++++ crates/dg/src/issue.rs | 55 ++++++++++++++++++---- crates/dg/src/repo.rs | 19 ++++++-- crates/forge-core/src/platform/identity.rs | 19 ++++++++ crates/forge-core/src/resolve.rs | 11 +++++ 7 files changed, 125 insertions(+), 17 deletions(-) diff --git a/crates/dg/src/ci.rs b/crates/dg/src/ci.rs index 199c9d6f9..ab0fb6fba 100644 --- a/crates/dg/src/ci.rs +++ b/crates/dg/src/ci.rs @@ -474,7 +474,7 @@ async fn runner_add(ctx: &Ctx, repo: &str, runner: &str) -> Result<()> { .await?; let spent = s.spent_since(before).await; ctx.emit( - json!({ "status": "enrolled", "runner": runner, "documentId": m.document_id, "cost": cost_json(spent, dash_usd_price()) }), + json!({ "status": "enrolled", "runner": runner, "documentId": m.document_id, "id": m.document_id, "cost": cost_json(spent, dash_usd_price()) }), || println!("✓ {runner} is a runner of {} ({})", s.repo.display(), cost_line(spent, dash_usd_price())), ); Ok(()) @@ -724,6 +724,7 @@ fn emit_report( json!({ "status": done.action, "documentId": done.document_id, + "id": done.document_id, "name": r.name, "checkStatus": r.status, "conclusion": r.conclusion, diff --git a/crates/dg/src/collab.rs b/crates/dg/src/collab.rs index 84bfee37d..b5d205739 100644 --- a/crates/dg/src/collab.rs +++ b/crates/dg/src/collab.rs @@ -130,6 +130,7 @@ async fn accept(ctx: &Ctx, repo: &str, withdraw: bool) -> Result<()> { "repo": handle.display(), "identityId": me, "documentId": document_id, + "id": document_id, }), || { println!( @@ -232,6 +233,7 @@ async fn add(ctx: &Ctx, repo: &str, member: &str, role: RoleArg, wait: Option Result<()> { "identityId": m.identity_id, "role": role_name(m.role), "documentId": m.document_id, + "id": m.document_id, "since": m.created_at, }) }) .collect(); + // DPNS names for the human list only, read together; a failed read shows the bare id. + let names = if ctx.json { + std::collections::BTreeMap::default() + } else { + client + .dpns_first_names(members.iter().map(|m| m.identity_id.as_str())) + .await + }; ctx.emit( json!({ "count": rows.len(), "members": rows, "ownerId": handle.owner_id() }), || { println!("{} member(s) of {}:", members.len(), handle.display()); for m in &members { - println!(" {} {}", m.identity_id, role_name(m.role)); + println!( + " {} {}", + crate::fmt::with_name(&m.identity_id, &names), + role_name(m.role) + ); } }, ); diff --git a/crates/dg/src/fmt.rs b/crates/dg/src/fmt.rs index 7a1556f1f..8d444f5be 100644 --- a/crates/dg/src/fmt.rs +++ b/crates/dg/src/fmt.rs @@ -37,6 +37,16 @@ pub fn safe(text: &str) -> std::borrow::Cow<'_, str> { } } +/// An identity id for display, with its DPNS name after it when `names` has one +/// (`Fi8b… (alice.dash)`), as [`forge_core::platform::PlatformClient::dpns_first_names`] +/// reads them. +pub fn with_name(id: &str, names: &std::collections::BTreeMap) -> String { + match names.get(id) { + Some(name) => format!("{id} ({})", safe(name)), + None => id.to_string(), + } +} + /// A commit id shortened for display (12 hex digits). pub fn short(oid: &str) -> &str { // By character: the value may be untrusted document text, not hex. @@ -193,6 +203,14 @@ mod tests { assert_eq!(cost_json(0, 30.0)["usd"].as_f64(), Some(0.0)); } + /// QW-083: an id with a DPNS name shows it; one without (or whose read failed) is bare. + #[test] + fn an_identity_shows_its_dpns_name_when_it_has_one() { + let names = [("A1".to_string(), "alice.dash\u{1b}[2J".to_string())].into(); + assert_eq!(with_name("A1", &names), "A1 (alice.dash[2J)"); + assert_eq!(with_name("B2", &names), "B2"); + } + /// The timeline's words for each transition kind (the web's), and how a state change was /// written. #[test] diff --git a/crates/dg/src/issue.rs b/crates/dg/src/issue.rs index a5f877218..cd5d926b7 100644 --- a/crates/dg/src/issue.rs +++ b/crates/dg/src/issue.rs @@ -15,7 +15,7 @@ use forge_core::rules::{Event, EventKind, IssueState}; use crate::common::{number_arg, Reader, Session}; use crate::context::Ctx; use crate::fmt::{ - cost_json, cost_line, dash_usd_price, safe, transition_phrase, transition_route_text, + cost_json, cost_line, dash_usd_price, safe, transition_phrase, transition_route_text, with_name, }; use crate::{IssueCommand, IssueListArgs}; @@ -332,6 +332,7 @@ async fn list(ctx: &Ctx, args: &IssueListArgs) -> Result<()> { "title": title, "author": author, "open": st.open, + "state": state_word(st.open), "labels": st.labels, "assignees": st.assignees, "pinned": pinned, @@ -353,7 +354,7 @@ async fn list(ctx: &Ctx, args: &IssueListArgs) -> Result<()> { println!("no issues"); } for (n, title, _, st, pinned) in &rows { - let mark = if st.open { "open" } else { "closed" }; + let mark = state_word(st.open); let mark = if *pinned { format!("{mark}, pinned") } else { @@ -409,6 +410,18 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { let state = view.state; let i = view.issue; let (id, title, body, author) = (i.document_id, i.title, i.body, i.author); + // DPNS names for the human view only, read together; a failed read shows the bare id. + let names = if ctx.json { + std::collections::BTreeMap::default() + } else { + let actors = comments.iter().map(|c| c.author.as_str()); + let actors = actors.chain(events.iter().map(|e| e.actor.as_str())); + let actors = actors.chain(transitions.iter().map(|t| t.actor.as_str())); + s.client + .dpns_first_names(std::iter::once(author.as_str()).chain(actors)) + .await + }; + let who = |id: &str| with_name(id, &names); ctx.emit( json!({ @@ -417,6 +430,7 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { "body": body, "author": author, "documentId": id, + "id": id, "state": { "open": state.open, "labels": state.labels, "assignees": state.assignees }, "milestone": meta.milestone, "pinned": meta.pinned, @@ -441,9 +455,9 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { "plaintextEventValues": plaintext_values, }), || { - let mark = if state.open { "open" } else { "closed" }; + let mark = state_word(state.open); println!("#{number} [{mark}] {}", safe(&title)); - println!("author: {author}"); + println!("author: {}", who(&author)); if !state.labels.is_empty() { println!("labels: {}", safe(&labels_of(&state))); } @@ -453,11 +467,12 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { for item in &timeline { match item { Item::Comment(c) => { - println!("\n— {} ({}):\n{}", c.author, c.document_id, safe(&c.body)); + let author = who(&c.author); + println!("\n— {author} ({}):\n{}", c.document_id, safe(&c.body)); } - Item::Event(e) => println!("\n· {} {}", e.actor, safe(&event_phrase(e))), + Item::Event(e) => println!("\n· {} {}", who(&e.actor), safe(&event_phrase(e))), Item::Transition(t) => { - println!("\n· {} {}", t.actor, transition_phrase(t.kind)); + println!("\n· {} {}", who(&t.actor), transition_phrase(t.kind)); } } } @@ -738,6 +753,16 @@ async fn refuse_if_locked(s: &Session, number: u64, target_id: &str) -> Result<( .into()) } +/// The `"state"` of an issue in JSON, `"open"` or `"closed"`, as `dg pr`'s: emitted beside +/// the older `"open": bool`, which stays for the consumers that read it (QW-081). +fn state_word(open: bool) -> &'static str { + if open { + "open" + } else { + "closed" + } +} + /// `(past tense, prompt verb)` of a close or a reopen ("reopend" was L-35). fn open_words(close: bool) -> (&'static str, &'static str) { if close { @@ -758,9 +783,9 @@ async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()> // way `set_state` reads it. let open = status_of_code(collab.state_sum(&s.repo, &target.id).await?).open; if open != close { - let state = if open { "open" } else { "closed" }; + let state = state_word(open); ctx.emit( - json!({ "status": "unchanged", "issue": number, "open": open, "written": false }), + json!({ "status": "unchanged", "issue": number, "open": open, "state": state, "written": false }), || println!("issue #{number} is already {state}; nothing written"), ); return Ok(()); @@ -784,6 +809,7 @@ async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()> "transitionId": change.transition_id, "kind": change.kind, "open": open_now, + "state": open_now.map(state_word), }), || { println!( @@ -991,7 +1017,16 @@ async fn assign(ctx: &Ctx, repo: &str, number: u64, who: &[String], add: bool) - #[cfg(test)] mod tests { - use super::{changes, event_phrase, label_args, open_words, timeline, title_matches, Item}; + use super::{ + changes, event_phrase, label_args, open_words, state_word, timeline, title_matches, Item, + }; + + /// QW-081: an issue's JSON `"state"` uses the words `dg pr`'s does. + #[test] + fn an_issue_state_is_the_word_a_pr_state_uses() { + assert_eq!(state_word(true), "open"); + assert_eq!(state_word(false), "closed"); + } /// QW-035: a label (or assignee) already on the issue is not written again, one already /// off is not removed again, and a name given twice is written once. An unreadable state diff --git a/crates/dg/src/repo.rs b/crates/dg/src/repo.rs index 35ed4feb5..757ef6572 100644 --- a/crates/dg/src/repo.rs +++ b/crates/dg/src/repo.rs @@ -17,7 +17,7 @@ use serde_json::json; use forge_core::create::{default_journal_dir, CreateRepoOpts}; use forge_core::members::MemberReader; use forge_core::repo::RepoService; -use forge_core::resolve::{list_owned, repo_slug}; +use forge_core::resolve::{list_owned, repo_description, repo_slug}; use forge_core::user_error::{codes, UserError}; use crate::common::{resolve, Reader, RepoRef, Session}; @@ -52,7 +52,7 @@ pub async fn run(ctx: &Ctx, cmd: &RepoCommand) -> Result<()> { RepoCommand::Watch { repo } => watch(ctx, repo, true).await, RepoCommand::Unwatch { repo } => watch(ctx, repo, false).await, RepoCommand::Topic { repo, add, remove } => topic(ctx, repo, add, remove).await, - RepoCommand::View { repo } => view(ctx, repo).await, + RepoCommand::View { repo } => Box::pin(view(ctx, repo)).await, RepoCommand::List { owner } => list(ctx, owner.as_deref()).await, RepoCommand::Backend(RepoBackendCommand::Set { repo, mode }) => { backend_set(ctx, repo, mode.mode(), mode.label()).await @@ -482,11 +482,16 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { if handle.visibility == Visibility::Private { svc.keyring(handle).await?.require_key(handle)?; } - // `archived` is `null` when the config cannot be read, not a guessed `false` (QW-081). - let (default_branch, config) = - tokio::join!(svc.read_default_branch(handle), svc.current_config(handle)); + // `archived` is `null` when the config cannot be read, not a guessed `false` (QW-081); + // likewise `description` (`""` when the repo has none, as `repo list` has it). + let (default_branch, config, description) = tokio::join!( + svc.read_default_branch(handle), + svc.current_config(handle), + repo_description(client, handle) + ); let default_branch = default_branch.unwrap_or(None); let archived = config.ok().map(|c| c.archived); + let description = description.ok(); let visibility = match handle.visibility { Visibility::Private => "private", Visibility::Public => "public", @@ -511,6 +516,7 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { "repoId": handle.id(), "ownerId": handle.owner_id(), "name": handle.name(), + "description": description, "visibility": visibility, "archived": archived, "defaultBranch": default_branch, @@ -523,6 +529,9 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { || { println!("{}", handle.display()); println!(" id: {}", handle.id()); + if let Some(d) = description.as_deref().filter(|d| !d.is_empty()) { + println!(" description: {}", crate::fmt::safe(d)); + } println!( " visibility: {visibility}{}", if archived == Some(true) { diff --git a/crates/forge-core/src/platform/identity.rs b/crates/forge-core/src/platform/identity.rs index 8c4df7f9d..9763cf025 100644 --- a/crates/forge-core/src/platform/identity.rs +++ b/crates/forge-core/src/platform/identity.rs @@ -936,6 +936,25 @@ impl PlatformClient { .map_err(|e| sdk_err("reading DPNS names", e)) } + /// The first DPNS name ([`Self::dpns_names_of`]) of each distinct id in `ids` that has + /// one, read concurrently (a few at a time). For display only: an id whose read fails is + /// left out, so a caller shows it bare. + pub async fn dpns_first_names<'a>( + &self, + ids: impl IntoIterator, + ) -> BTreeMap { + use futures::StreamExt as _; + let ids: std::collections::BTreeSet<&str> = ids.into_iter().collect(); + futures::stream::iter(ids) + .map(|id| async move { (id, self.dpns_names_of(id).await) }) + .buffer_unordered(8) + .filter_map(|(id, names)| async move { + Some((id.to_string(), names.ok()?.into_iter().next()?)) + }) + .collect() + .await + } + /// The identity DPNS name `name` (`alice` or `alice.dash`, compared homograph-safe as /// DPNS does) resolves to, or `None` when no such name is registered. A proof-verified /// read of the DPNS `domain` document (`normalizedParentDomainName == "dash"`, diff --git a/crates/forge-core/src/resolve.rs b/crates/forge-core/src/resolve.rs index 1eea97b7d..d1ad2a477 100644 --- a/crates/forge-core/src/resolve.rs +++ b/crates/forge-core/src/resolve.rs @@ -190,6 +190,17 @@ pub async fn fork_parent(client: &PlatformClient, repo: &RepoRef) -> Result Result { + let core = client.fetch_contract(&repo.forge.core).await?; + Ok(client + .fetch_document(&core, DOC_REPO, &repo.repo_id) + .await? + .and_then(|d| d.field_str("description")) + .unwrap_or_default()) +} + /// Every repository `owner` has, by name. pub async fn list_owned(client: &PlatformClient, owner: &str) -> Result> { let owner_bytes = platform::decode_identifier(owner)?; From da3bb1919ad51e6d0ba5525cc04c398ab4dd5ab2 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 11:32:47 -0500 Subject: [PATCH 4/5] fix(dg): never drop commits or a detached HEAD in dg pr checkout A local pr/ holding commits the PR head does not is left alone (E206 naming the rename or delete), as gh pr checkout refuses a non-fast-forward; branch -f used to move it silently. A clean but detached HEAD that no branch, tag or remote ref holds is not switched away from either. The git work moves to place_pr_branch. docs/errors.md E206 covers the new case. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/pr/mod.rs | 137 ++++++++++++++++++---------- crates/forge-core/src/user_error.rs | 3 +- docs/errors.md | 4 +- 3 files changed, 94 insertions(+), 50 deletions(-) diff --git a/crates/dg/src/pr/mod.rs b/crates/dg/src/pr/mod.rs index 77731dfe0..6a8c3d46b 100644 --- a/crates/dg/src/pr/mod.rs +++ b/crates/dg/src/pr/mod.rs @@ -2309,35 +2309,8 @@ async fn checkout(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { )); } let branch = format!("pr/{number}"); - // Tracked changes only: git refuses a switch that would overwrite an untracked file. - let clean = git::git( - &cwd, - &["status", "--porcelain", "--untracked-files=no"], - &[], - ) - .is_ok_and(|out| out.is_empty()); - let step = checkout_step(git::current_branch(&cwd).as_deref(), &branch, clean); - match step { - CheckoutStep::FastForward => { - git::git(&cwd, &["merge", "--ff-only", "-q", &head], &[]).with_context(|| { - format!( - "moving {branch} (checked out) to the PR head {}: switch to another branch \ - and run `dg pr checkout` again to reset it", - short(&head) - ) - })?; - } - CheckoutStep::CreateAndSwitch | CheckoutStep::CreateOnly => { - git::git(&cwd, &["branch", "-f", &branch, &head], &[]) - .with_context(|| format!("creating branch {branch}"))?; - } - } - if step == CheckoutStep::CreateAndSwitch { - git::git(&cwd, &["switch", "-q", &branch], &[]).with_context(|| { - format!("switching to {branch} (it is created: git switch {branch})") - })?; - } - let switched = step != CheckoutStep::CreateOnly; + let step = place_pr_branch(&cwd, &branch, &head)?; + let switched = !matches!(step, CheckoutStep::CreateOnly(_)); ctx.emit( json!({ "pr": number, @@ -2355,37 +2328,104 @@ async fn checkout(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { CheckoutStep::FastForward => { println!("✓ branch {branch} (checked out) at {}", short(&head)); } - CheckoutStep::CreateOnly => { + CheckoutStep::CreateOnly(why) => { println!( "✓ branch {branch} at {} (git switch {branch})", short(&head) ); - println!(" not switched: the working tree has uncommitted changes"); + println!(" not switched: {why}"); } }, ); Ok(()) } +/// Point `branch` (`pr/`) at `head` in the repository at `cwd` and switch to it when that +/// loses nothing ([`checkout_step`]). +fn place_pr_branch(cwd: &Path, branch: &str, head: &str) -> Result { + // A `pr/` holding commits the PR head does not is left alone (as `gh pr checkout` + // refuses a non-fast-forward): moving it would leave them only in the reflog. + let local = format!("refs/heads/{branch}"); + if git::git_ok(cwd, &["rev-parse", "--verify", "-q", &local]) + && !git::is_ancestor(cwd, &local, head) + { + return Err(UserError::new( + codes::GIT_REPO, + format!( + "branch {branch} has commits the PR head {} does not", + short(head) + ), + ) + .cause("moving it to the PR head would drop them; nothing was changed") + .fix(format!( + "keep them under another name (`git branch -m {branch} {branch}-old`) or drop them \ + (`git branch -D {branch}`, from another branch), then run it again" + )) + .into()); + } + // Tracked changes only: git refuses a switch that would overwrite an untracked file. + let clean = git::git(cwd, &["status", "--porcelain", "--untracked-files=no"], &[]) + .is_ok_and(|out| out.is_empty()); + let current = git::current_branch(cwd); + // A detached HEAD no ref holds would be left only in the reflog by a switch. + let a_ref_holds_head = || { + git::git( + cwd, + &[ + "for-each-ref", + "--count=1", + "--contains", + "HEAD", + "refs/heads", + "refs/tags", + "refs/remotes", + ], + &[], + ) + .is_ok_and(|out| !out.is_empty()) + }; + let stay = if !clean { + Some("the working tree has uncommitted changes") + } else if current.is_none() && !a_ref_holds_head() { + Some("HEAD is detached at a commit no branch or tag holds") + } else { + None + }; + let step = checkout_step(current.as_deref(), branch, stay); + if step == CheckoutStep::FastForward { + // Never a real merge: the check above made the branch an ancestor of the head. + git::git(cwd, &["merge", "--ff-only", "-q", head], &[]) + .with_context(|| format!("moving {branch} (checked out) to the PR head"))?; + } else { + git::git(cwd, &["branch", "-f", branch, head], &[]) + .with_context(|| format!("creating branch {branch}"))?; + } + if step == CheckoutStep::CreateAndSwitch { + git::git(cwd, &["switch", "-q", branch], &[]).with_context(|| { + format!("switching to {branch} (it is created: git switch {branch})") + })?; + } + Ok(step) +} + /// What `dg pr checkout` does with branch `pr/`, as `gh pr checkout` does, never losing -/// uncommitted work. +/// work. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CheckoutStep { - /// Point the branch at the head and switch to it (the working tree is clean). + /// Point the branch at the head and switch to it. CreateAndSwitch, - /// Point the branch at the head, stay put: there are uncommitted changes. - CreateOnly, + /// Point the branch at the head, stay put, for this reason (uncommitted changes, …). + CreateOnly(&'static str), /// The branch is checked out: fast-forward it (git refuses what would lose work). FastForward, } -fn checkout_step(current: Option<&str>, branch: &str, clean: bool) -> CheckoutStep { - if current == Some(branch) { - CheckoutStep::FastForward - } else if clean { - CheckoutStep::CreateAndSwitch - } else { - CheckoutStep::CreateOnly +/// `stay`: why switching away from where the user is could lose work, if it could. +fn checkout_step(current: Option<&str>, branch: &str, stay: Option<&'static str>) -> CheckoutStep { + match stay { + _ if current == Some(branch) => CheckoutStep::FastForward, + Some(why) => CheckoutStep::CreateOnly(why), + None => CheckoutStep::CreateAndSwitch, } } @@ -2540,24 +2580,25 @@ mod tests { /// a clean working tree; already on it, it fast-forwards instead of failing. #[test] fn checkout_switches_only_from_a_clean_tree() { + let dirty = Some("the working tree has uncommitted changes"); assert_eq!( - checkout_step(Some("main"), "pr/7", true), + checkout_step(Some("main"), "pr/7", None), CheckoutStep::CreateAndSwitch ); assert_eq!( - checkout_step(None, "pr/7", true), + checkout_step(None, "pr/7", None), CheckoutStep::CreateAndSwitch ); assert_eq!( - checkout_step(Some("main"), "pr/7", false), - CheckoutStep::CreateOnly + checkout_step(Some("main"), "pr/7", dirty), + CheckoutStep::CreateOnly("the working tree has uncommitted changes") ); assert_eq!( - checkout_step(Some("pr/7"), "pr/7", false), + checkout_step(Some("pr/7"), "pr/7", dirty), CheckoutStep::FastForward ); assert_eq!( - checkout_step(Some("pr/71"), "pr/7", true), + checkout_step(Some("pr/71"), "pr/7", None), CheckoutStep::CreateAndSwitch ); } diff --git a/crates/forge-core/src/user_error.rs b/crates/forge-core/src/user_error.rs index e2971d3b9..7342e9aaa 100644 --- a/crates/forge-core/src/user_error.rs +++ b/crates/forge-core/src/user_error.rs @@ -182,7 +182,8 @@ pub mod codes { /// A git operation dash:// does not support (shallow clone). pub const UNSUPPORTED: &str = "E205"; /// `dg init` / `dg repo create --push` cannot use the local git repository: not inside - /// one, or the remote name is taken by another URL. + /// one, or the remote name is taken by another URL; or `dg pr checkout` would drop local + /// commits on `pr/`. pub const GIT_REPO: &str = "E206"; /// An operation a private repository does not support (a release, a fork, a webhook): /// refused before anything is written. diff --git a/docs/errors.md b/docs/errors.md index 8339c5c6b..a2f5af7d7 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -115,7 +115,9 @@ Fix: use a partial clone for a lightweight checkout: `git clone --filter=blob:no **Git repository not usable.** `dg init` or `dg repo create --push` needs the local git repository, and could not use it: the current directory is not inside a git work tree, or the remote it would add (`origin` by default) already points somewhere else. Nothing was written to Platform when this is reported before the create; after a create, the repository exists and only the local setup is missing. -Fix: run `git init` first (or `cd` into the repository), or pass `--remote ` to add the Forge remote under another name and leave the existing one alone. +`dg pr checkout` reports it too when the local branch `pr/` has commits the PR head does not (the PR was force-pushed, or you committed on the branch). Moving the branch would drop them, so nothing is changed. + +Fix: run `git init` first (or `cd` into the repository), or pass `--remote ` to add the Forge remote under another name and leave the existing one alone. For `dg pr checkout`, rename the branch to keep its commits (`git branch -m pr/ pr/-old`) or delete it (`git branch -D pr/`), then run it again. ## E207 From e1996fcf2fe6ef92f329f140c49287741aeb5c3a Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 12:21:43 -0500 Subject: [PATCH 5/5] fix(dg): never overwrite an ignored file in dg pr checkout, and bound DPNS display lookups git replaces an ignored file silently when a switch or fast-forward brings a tracked file to its path, so pr checkout now stays put when the PR head tracks a path that is an ignored file (or directory) here, and fast-forwards with --no-overwrite-ignore. place_pr_branch gains temp-repository tests for every case it must not lose work in: a clean switch, a fast-forward, uncommitted changes, an ignored file, a diverged pr/, and an unheld detached HEAD. dpns_first_names looks up at most 50 ids and stops waiting after 5 s, keeping the names it has. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/pr/mod.rs | 189 ++++++++++++++++++++- crates/forge-core/src/platform/identity.rs | 13 +- 2 files changed, 196 insertions(+), 6 deletions(-) diff --git a/crates/dg/src/pr/mod.rs b/crates/dg/src/pr/mod.rs index 6a8c3d46b..f910b0d93 100644 --- a/crates/dg/src/pr/mod.rs +++ b/crates/dg/src/pr/mod.rs @@ -2388,14 +2388,23 @@ fn place_pr_branch(cwd: &Path, branch: &str, head: &str) -> Result Some("the working tree has uncommitted changes") } else if current.is_none() && !a_ref_holds_head() { Some("HEAD is detached at a commit no branch or tag holds") + } else if ignored_overwritten_by(cwd, head) { + // git replaces an ignored file (a local `.env`, …) silently when a switch brings a + // tracked file to its path. + Some("the PR head tracks a path that is an ignored file here, which a switch would overwrite") } else { None }; let step = checkout_step(current.as_deref(), branch, stay); if step == CheckoutStep::FastForward { - // Never a real merge: the check above made the branch an ancestor of the head. - git::git(cwd, &["merge", "--ff-only", "-q", head], &[]) - .with_context(|| format!("moving {branch} (checked out) to the PR head"))?; + // Never a real merge: the check above made the branch an ancestor of the head. An + // ignored file in the way stops it instead of being overwritten. + git::git( + cwd, + &["merge", "--ff-only", "--no-overwrite-ignore", "-q", head], + &[], + ) + .with_context(|| format!("moving {branch} (checked out) to the PR head"))?; } else { git::git(cwd, &["branch", "-f", branch, head], &[]) .with_context(|| format!("creating branch {branch}"))?; @@ -2408,6 +2417,52 @@ fn place_pr_branch(cwd: &Path, branch: &str, head: &str) -> Result Ok(step) } +/// Whether checking out `head` would overwrite an ignored, untracked file of the working tree +/// at `cwd` (a path, or a directory holding one, that `head` tracks). `true` when either +/// listing fails: the caller then stays put. +fn ignored_overwritten_by(cwd: &Path, head: &str) -> bool { + let listing = |args: &[&str]| -> Option> { + let out = git::git(cwd, args, &[]).ok()?; + Some( + out.split('\0') + .filter(|p| !p.is_empty()) + .map(str::to_owned) + .collect(), + ) + }; + let (Some(ignored), Some(tracked)) = ( + listing(&[ + "ls-files", + "-z", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + ]), + listing(&["ls-tree", "-r", "-z", "--name-only", head]), + ) else { + return true; + }; + overlaps(&ignored, &tracked) +} + +/// Whether a path in `tracked` is, or lies under, an entry of `ignored` (a directory entry +/// ends in `/`), or an ignored file sits where `tracked` has a directory. +fn overlaps(ignored: &[String], tracked: &[String]) -> bool { + // Sorted, so the paths under `dir/` are one range: a build tree's thousands of ignored + // files cost a lookup each, not a scan of the tree. + let tracked: std::collections::BTreeSet<&str> = tracked.iter().map(String::as_str).collect(); + ignored.iter().any(|i| { + let dir = i.trim_end_matches('/'); + let under = format!("{dir}/"); + tracked.contains(dir) + || tracked + .range(under.as_str()..) + .next() + .is_some_and(|t| t.starts_with(&under)) + }) +} + /// What `dg pr checkout` does with branch `pr/`, as `gh pr checkout` does, never losing /// work. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -2576,6 +2631,134 @@ mod tests { assert_eq!(state_label(&with(true, false, false)), "merged"); } + /// Run git in `dir` for a test fixture (no signing, fixed identity), returning stdout. + fn fixture_git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(["-c", "user.name=t", "-c", "user.email=t@example.org"]) + .args([ + "-c", + "commit.gpgsign=false", + "-c", + "init.defaultBranch=main", + ]) + .args(args) + .output() + .expect("git"); + assert!(out.status.success(), "git {args:?}: {out:?}"); + String::from_utf8(out.stdout).unwrap().trim().to_owned() + } + + /// A repository on `main` (one commit) with a PR head one commit ahead of it that adds + /// `pr.txt`; returns the repository and the head oid. + fn checkout_fixture() -> (tempfile::TempDir, String) { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + fixture_git(d, &["init", "-q"]); + std::fs::write(d.join("a.txt"), "a\n").unwrap(); + fixture_git(d, &["add", "a.txt"]); + fixture_git(d, &["commit", "-q", "-m", "base"]); + fixture_git(d, &["switch", "-q", "-c", "work"]); + std::fs::write(d.join("pr.txt"), "from the PR\n").unwrap(); + fixture_git(d, &["add", "pr.txt"]); + fixture_git(d, &["commit", "-q", "-m", "head"]); + let head = fixture_git(d, &["rev-parse", "HEAD"]); + fixture_git(d, &["switch", "-q", "main"]); + fixture_git(d, &["branch", "-q", "-D", "work"]); + (dir, head) + } + + /// The real git work of `dg pr checkout`, against temp repositories: it switches from a + /// clean tree, and never loses uncommitted changes, ignored files, extra commits on + /// `pr/` or an unheld detached HEAD. + #[test] + fn place_pr_branch_never_loses_work() { + let at = |d: &Path, r: &str| fixture_git(d, &["rev-parse", r]); + // Clean: created and switched to. + let (dir, head) = checkout_fixture(); + let d = dir.path(); + assert_eq!( + place_pr_branch(d, "pr/7", &head).unwrap(), + CheckoutStep::CreateAndSwitch + ); + assert_eq!(git::current_branch(d).as_deref(), Some("pr/7")); + assert_eq!(at(d, "pr/7"), head); + + // Already on pr/7, behind the head: fast-forwarded. + fixture_git(d, &["reset", "-q", "--hard", "HEAD~1"]); + assert_eq!( + place_pr_branch(d, "pr/7", &head).unwrap(), + CheckoutStep::FastForward + ); + assert_eq!(at(d, "HEAD"), head); + + // Uncommitted tracked change: the branch is placed, the tree and branch stay. + let (dir, head) = checkout_fixture(); + let d = dir.path(); + std::fs::write(d.join("a.txt"), "edited\n").unwrap(); + assert!(matches!( + place_pr_branch(d, "pr/7", &head).unwrap(), + CheckoutStep::CreateOnly(_) + )); + assert_eq!(git::current_branch(d).as_deref(), Some("main")); + assert_eq!( + std::fs::read_to_string(d.join("a.txt")).unwrap(), + "edited\n" + ); + assert_eq!(at(d, "pr/7"), head); + + // An ignored file at a path the head tracks: not switched, the file is kept. + let (dir, head) = checkout_fixture(); + let d = dir.path(); + std::fs::write(d.join(".git/info/exclude"), "pr.txt\n").unwrap(); + std::fs::write(d.join("pr.txt"), "my local secret\n").unwrap(); + assert!(matches!( + place_pr_branch(d, "pr/7", &head).unwrap(), + CheckoutStep::CreateOnly(_) + )); + assert_eq!(git::current_branch(d).as_deref(), Some("main")); + assert_eq!( + std::fs::read_to_string(d.join("pr.txt")).unwrap(), + "my local secret\n" + ); + + // pr/7 holds a commit the head does not: refused, nothing moves. + let (dir, head) = checkout_fixture(); + let d = dir.path(); + fixture_git(d, &["switch", "-q", "-c", "pr/7"]); + std::fs::write(d.join("mine.txt"), "mine\n").unwrap(); + fixture_git(d, &["add", "mine.txt"]); + fixture_git(d, &["commit", "-q", "-m", "mine"]); + let mine = at(d, "pr/7"); + fixture_git(d, &["switch", "-q", "main"]); + assert!(place_pr_branch(d, "pr/7", &head).is_err()); + assert_eq!(at(d, "pr/7"), mine); + + // A detached HEAD at a commit no ref holds: not switched away from. + let (dir, head) = checkout_fixture(); + let d = dir.path(); + fixture_git(d, &["switch", "-q", "--detach"]); + std::fs::write(d.join("loose.txt"), "loose\n").unwrap(); + fixture_git(d, &["add", "loose.txt"]); + fixture_git(d, &["commit", "-q", "-m", "loose"]); + let loose = at(d, "HEAD"); + assert!(matches!( + place_pr_branch(d, "pr/7", &head).unwrap(), + CheckoutStep::CreateOnly(_) + )); + assert_eq!(at(d, "HEAD"), loose); + } + + #[test] + fn an_ignored_path_overlaps_a_tracked_file_or_directory() { + let s = |v: &[&str]| v.iter().map(ToString::to_string).collect::>(); + let tracked = s(&["src/main.rs", "config/app.toml", "README.md"]); + assert!(overlaps(&s(&["README.md"]), &tracked)); + assert!(overlaps(&s(&["config/"]), &tracked)); + assert!(overlaps(&s(&["src"]), &tracked)); // an ignored file where the head has a dir + assert!(!overlaps(&s(&["target/", "src.bak", "READ"]), &tracked)); + } + /// QW-083: `dg pr checkout` switches to `pr/` as `gh pr checkout` does, but only from /// a clean working tree; already on it, it fast-forwards instead of failing. #[test] diff --git a/crates/forge-core/src/platform/identity.rs b/crates/forge-core/src/platform/identity.rs index 9763cf025..548e47596 100644 --- a/crates/forge-core/src/platform/identity.rs +++ b/crates/forge-core/src/platform/identity.rs @@ -937,17 +937,19 @@ impl PlatformClient { } /// The first DPNS name ([`Self::dpns_names_of`]) of each distinct id in `ids` that has - /// one, read concurrently (a few at a time). For display only: an id whose read fails is - /// left out, so a caller shows it bare. + /// one, read concurrently (a few at a time). For display only: an id whose read fails, or + /// that is past the first [`Self::DPNS_DISPLAY_MAX`] ids, or whose read has not finished + /// within [`Self::DPNS_DISPLAY_DEADLINE`], is left out, so a caller shows it bare. pub async fn dpns_first_names<'a>( &self, ids: impl IntoIterator, ) -> BTreeMap { use futures::StreamExt as _; let ids: std::collections::BTreeSet<&str> = ids.into_iter().collect(); - futures::stream::iter(ids) + futures::stream::iter(ids.into_iter().take(Self::DPNS_DISPLAY_MAX)) .map(|id| async move { (id, self.dpns_names_of(id).await) }) .buffer_unordered(8) + .take_until(tokio::time::sleep(Self::DPNS_DISPLAY_DEADLINE)) .filter_map(|(id, names)| async move { Some((id.to_string(), names.ok()?.into_iter().next()?)) }) @@ -955,6 +957,11 @@ impl PlatformClient { .await } + /// At most this many distinct ids get a DPNS lookup in [`Self::dpns_first_names`]. + pub const DPNS_DISPLAY_MAX: usize = 50; + /// [`Self::dpns_first_names`] stops waiting after this long and keeps the names it has. + pub const DPNS_DISPLAY_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5); + /// The identity DPNS name `name` (`alice` or `alice.dash`, compared homograph-safe as /// DPNS does) resolves to, or `None` when no such name is registered. A proof-verified /// read of the DPNS `domain` document (`normalizedParentDomainName == "dash"`,