Skip to content

fix(gitea): use user-facing base URL for links published in comments - #2617

Merged
IsmaelMartinez merged 3 commits into
The-PR-Agent:mainfrom
niallsemple:fix/gitea-user-facing-links
Aug 19, 2026
Merged

IsmaelMartinez merged 3 commits into
The-PR-Agent:mainfrom
niallsemple:fix/gitea-user-facing-links

Conversation

@niallsemple

Copy link
Copy Markdown
Contributor

Fixes #2612

Problem

GiteaProvider derives both its API endpoint and every user-facing link from the single gitea.url setting. On self-hosted Gitea/Forgejo deployments where the API is reached via an internal address (Docker service name, cluster DNS) but users browse a different external address, every link PR-Agent publishes points at the internal address and is unclickable:

  • get_line_link() built code links from the API base URL
  • get_pr_url() returned the raw (possibly API-form) webhook URL

Fix

Mirrors the separation GithubProvider already has (base_url vs base_url_html), following the approach suggested in the issue:

  • New base_url_html attribute, resolved by _resolve_base_url_html():
    1. the new optional gitea.web_url setting (also documented in configuration.toml and the Gitea installation guide, env var GITEA__WEB_URL)
    2. otherwise derived from pr.html_url, which Gitea/Forgejo builds from its own external ROOT_URL (zero-config for correctly configured instances)
    3. otherwise falls back to gitea.url, so existing single-URL deployments are unaffected
  • get_line_link() now builds links from base_url_html; base_url stays in use for the API host, get_git_repo_url() and clone URL preparation (those should stay internal)
  • get_pr_url() returns pr.html_url when available, falling back to the raw PR URL otherwise

Tests

Added 7 unit tests to tests/unittest/test_gitea_provider.py covering: web_url precedence, derivation from pr.html_url (the reverse-proxy scenario from the issue), fallback to base_url for the issue flow and for missing/foreign html_url, all three get_line_link() variants, and both get_pr_url() paths.

PYTHONPATH=. pytest tests/unittest/test_gitea_provider.py -q   # 32 passed
PYTHONPATH=. pytest tests/unittest -q                          # 1734 passed, 1 skipped, 1 xfailed

Ruff (repo config) reports only pre-existing findings in untouched regions of the file; all lines this PR touches are clean.

GiteaProvider derived both its API endpoint and every user-facing link
from the single gitea.url setting, so on self-hosted Gitea/Forgejo
deployments where the API is reached via an internal address, every
link PR-Agent published pointed at the internal address.

Mirror GithubProvider's separation of the two concerns:

- add base_url_html, resolved from the new optional gitea.web_url
  setting, then derived from pr.html_url (built by Gitea/Forgejo from
  its external ROOT_URL), falling back to gitea.url so existing
  single-URL deployments are unaffected
- get_line_link() now builds links from base_url_html; base_url stays
  in use for the API host and clone URLs
- get_pr_url() returns pr.html_url when available instead of the raw
  (possibly API-form) webhook URL

Fixes The-PR-Agent#2612
@github-actions github-actions Bot added the bug label Aug 9, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix GiteaProvider to publish user-facing links in comments

🐞 Bug fix 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Separate API base URL from user-facing URL for links published in PR comments.
• Prefer gitea.web_url or derive from pr.html_url, with safe fallback to gitea.url.
• Add regression tests and document the new configuration/env var.
Diagram

graph TD
  A(["GiteaProvider init"]) --> B[("Settings\nGITEA.WEB_URL") ] --> C{"WEB_URL set?"}
  C -- "yes" --> F["base_url_html (web_url)"] --> G["Publish links\n(get_line_link/get_pr_url)"]
  C -- "no" --> D["PR metadata\npr.html_url"] --> E{"Matches PR path?"}
  E -- "yes" --> F
  E -- "no" --> H["base_url_html (base_url fallback)"] --> G
  subgraph Legend
    direction LR
    _cfg[("Config")] ~~~ _proc["Process"] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Require explicit `gitea.web_url` for user-facing links
  • ➕ Simplest logic; avoids heuristics based on pr.html_url shape
  • ➕ Eliminates ambiguity when instances return unexpected html_url formats
  • ➖ Worse out-of-the-box experience; breaks “zero-config” reverse-proxy setups
  • ➖ More support burden for users upgrading existing installations
2. Always use `pr.html_url` as the source of truth for PR links and derive all others from it
  • ➕ Maximizes correctness for proxied/external URL scenarios when html_url is accurate
  • ➕ Reduces dependency on config consistency
  • ➖ Doesn’t work for issue-only flows (no PR object)
  • ➖ Derivation can fail if html_url is missing/foreign; still needs fallbacks

Recommendation: Keep the PR’s current resolution order (explicit web_url override → derive from pr.html_url when it matches expected PR path → fallback to base_url). It preserves backward compatibility while fixing proxied/self-hosted setups, and the added tests cover the key edge cases.

Files changed (4) +120 / -3

Bug fix (1) +31 / -3
gitea_provider.pyResolve and use user-facing base URL for Gitea comment links +31/-3

Resolve and use user-facing base URL for Gitea comment links

• Introduces 'base_url_html' and '_resolve_base_url_html()' to separate API access ('base_url') from user-facing links. Updates 'get_line_link()' to build URLs from 'base_url_html' and updates 'get_pr_url()' to prefer 'pr.html_url' when available.

pr_agent/git_providers/gitea_provider.py

Tests (1) +84 / -0
test_gitea_provider.pyAdd regression tests for user-facing link generation (#2612) +84/-0

Add regression tests for user-facing link generation (#2612)

• Adds a dedicated test class covering precedence of 'web_url', derivation from 'pr.html_url', and fallbacks to 'base_url'. Verifies all 'get_line_link()' variants and both 'get_pr_url()' paths.

tests/unittest/test_gitea_provider.py

Documentation (1) +1 / -0
gitea.mdDocument optional 'GITEA__WEB_URL' for user-facing links +1/-0

Document optional 'GITEA__WEB_URL' for user-facing links

• Adds the 'GITEA__WEB_URL' environment variable to the Gitea installation instructions. Clarifies that it is optional and intended for cases where the API URL differs from the external URL users browse.

docs/docs/installation/gitea.md

Other (1) +4 / -0
configuration.tomlAdd 'gitea.web_url' configuration option (commented) +4/-0

Add 'gitea.web_url' configuration option (commented)

• Documents a new optional 'gitea.web_url' setting to control the base URL used for links published in comments. Notes the reverse-proxy/internal-API use case and default behavior (fallback to 'url').

pr_agent/settings/configuration.toml

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. html_url fallback bypassed ✓ Resolved 🐞 Bug ≡ Correctness
Description
_resolve_base_url_html() returns self.base_url whenever GITEA.URL has any non-empty value, so the
pr.html_url derivation branch won’t run under the default settings loading path where [gitea].url is
always set. This makes the new “derive from pr.html_url” behavior (and its unit tests/docs)
misleading unless GITEA.URL is intentionally absent/empty.
Code

pr_agent/git_providers/gitea_provider.py[R131-133]

+        if get_settings().get("GITEA.URL", None):
+            return self.base_url
+        pr_html_url = getattr(self.pr, "html_url", "") if self.pr else ""
Evidence
Because global settings always include a non-empty default GITEA.URL, the `if
get_settings().get("GITEA.URL", None)` branch will typically be taken, so the subsequent
pr.html_url derivation code is skipped; the unit test derives only by mocking GITEA.URL as
absent.

pr_agent/git_providers/gitea_provider.py[39-41]
pr_agent/git_providers/gitea_provider.py[128-137]
pr_agent/config_loader.py[17-24]
pr_agent/settings/configuration.toml[309-315]
tests/unittest/test_gitea_provider.py[656-664]
tests/unittest/test_gitea_provider.py[683-690]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`GiteaProvider._resolve_base_url_html()` short-circuits on `GITEA.URL` being set, which prevents the `pr.html_url`-based derivation from being used under normal settings loading (where `[gitea].url` is defined by default).
## Issue Context
- `get_settings()` always loads `settings/configuration.toml`, which defines `[gitea].url` with a non-empty default.
- The new unit tests for derivation explicitly mock `get_settings()` so that `GITEA.URL` is unset, which doesn’t reflect production settings loading.
## Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[113-137]
- pr_agent/config_loader.py[17-44]
- pr_agent/settings/configuration.toml[309-318]
## Suggested change
Adjust `_resolve_base_url_html()` so the `pr.html_url` derivation can be used when present (per the PR description/tests), e.g.:
1) `GITEA.WEB_URL` if set
2) derive from `self.pr.html_url` when it matches the expected PR suffix
3) fallback to `self.base_url`
If the intended behavior is instead “configured `GITEA.URL` always wins”, then update docs/tests to remove the claim/test for `pr.html_url` derivation under default settings, and/or add an explicit setting to opt into derivation.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went through this against #2612. The shape is right and it does solve the reported problem. A few inline notes, mostly about web_url not reaching every published link. Nothing needing a redesign.

return web_url
pr_html_url = getattr(self.pr, "html_url", "") if self.pr else ""
pr_url_suffix = f"/{self.owner}/{self.repo}/pulls/{self.pr_number}"
if pr_html_url and pr_html_url.endswith(pr_url_suffix):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ranks the derived value above GITEA.URL. On an instance where the operator set GITEA__URL correctly but the server's own ROOT_URL is still the default, pr.html_url is built from ROOT_URL and does end with this suffix, so the match succeeds and get_line_link() moves from the working configured URL to an unbrowsable one.

Narrow in practice, since such a deployment already had broken links elsewhere and GITEA__WEB_URL fixes it. Might be worth a docs line saying instances with a stale ROOT_URL now need to set it, or preferring base_url when it was explicitly configured.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in ee68be9. _resolve_base_url_html() now prefers an explicitly configured GITEA.URL over the pr.html_url derivation, so an instance whose server ROOT_URL is still a stale default keeps its working configured links. Resolution order is now: GITEA.WEB_URL → configured GITEA.URL → derived from pr.html_url → base_url. gitea.md also got a short paragraph spelling out the order and when to set GITEA__WEB_URL explicitly.

# pr.html_url is the user-facing page; self.pr_url may carry the API-form
# URL (e.g. when the run was triggered by a webhook payload).
if self.pr and getattr(self.pr, "html_url", ""):
return self.pr.html_url

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

base_url_html is not consulted here, so GITEA.WEB_URL does not reach links built from get_pr_url(). Someone who sets it precisely because ROOT_URL is wrong still gets a ROOT_URL derived link in the /describe "PR Description updated to latest commit" comment (pr_description.py:205) and in the changelog link (pr_update_changelog.py:122, on by default).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ee68be9: get_pr_url() now builds the page URL from base_url_html ({base_url_html}/{owner}/{repo}/pulls/{n}), so a configured GITEA.WEB_URL reaches the /describe update comment, the changelog link, and the incremental-review commit link in pr_reviewer.py.

I checked every call site before switching: pr_description.py:205, pr_update_changelog.py:122 and pr_reviewer.py:280 are all user-facing output, and repo_context.py uses the value only as a cache key. No API or clone path goes through get_pr_url() — the API host and _prepare_clone_url_with_token/get_git_repo_url still use base_url directly.


def get_pr_url(self) -> str:
# pr.html_url is the user-facing page; self.pr_url may carry the API-form
# URL (e.g. when the run was triggered by a webhook payload).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitea sets url and html_url to the same value on the PR payload, so self.pr_url should not carry the API form here. The API-shaped default in the new fixture would not survive _parse_pr_url either, since it strips /api/v1 then checks path_parts[2] == 'pulls', which sees the repo name and raises. The change looks harmless, but the stated rationale may not be the real one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right on both counts. I verified against the gitea.com API that url and html_url on the PR payload are set identically to the user-facing page, and an API-shaped URL indeed wouldn't survive _parse_pr_url (after stripping /api/v1 the pulls segment check sees the repo name and raises). In ee68be9 the fixture default now uses the realistic user-facing form, and the get_pr_url() comment states the actual rationale.

# Optional user-facing base URL used to build links published in comments, for
# self-hosted instances where the API is reached via an internal address but
# users browse a different external URL. Defaults to `url`.
# web_url = ""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One caveat on offering this as a per repo key: apply_repo_settings constructs and caches the provider before merging the repo's .pr_agent.toml, and /describe, /review and /improve reuse that cached instance, so web_url set in a repo's .pr_agent.toml will not apply for those commands while tools that build a fresh provider do pick it up.

Inherited rather than introduced, since base_url has the same staleness. The env var form in gitea.md is unaffected.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — inherited behavior, since base_url has the same staleness, so no code change here. I documented it instead: the comment on web_url in configuration.toml now notes that a per-repo .pr_agent.toml override does not apply to /describe, /review and /improve because the provider is constructed and cached before repo settings are merged, and recommends setting it globally or via GITEA__WEB_URL.

def _provider(pr_html_url="", pr_url="http://forgejo:3000/api/v1/repos/owner/repo/pulls/4"):
from pr_agent.git_providers.gitea_provider import GiteaProvider

provider = GiteaProvider.__new__(GiteaProvider)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since every test builds the provider with __new__, line 111 (self.base_url_html = self._resolve_base_url_html()) has no coverage and removing it would leave the suite green. Having test_get_line_link_uses_user_facing_base_url set provider.base_url_html = provider._resolve_base_url_html() instead of hardcoding it would cover the wiring by proxy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ee68be9: test_get_line_link_uses_user_facing_base_url now sets provider.base_url_html = provider._resolve_base_url_html() under patched settings instead of hardcoding it, and the two new get_pr_url tests do the same — so the line-111 wiring is covered by proxy and the suite goes red if the assignment is dropped.

…url via base_url_html, fix fixture, cover resolver

- _resolve_base_url_html now prefers an explicitly configured GITEA.URL
  over the pr.html_url derivation, so instances whose server ROOT_URL is
  a stale default keep their working configured links
- get_pr_url() builds the user-facing page URL from base_url_html, so
  GITEA.WEB_URL reaches the /describe update comment, the changelog
  link and the incremental-review commit link; verified no API/clone
  call sites use get_pr_url (those paths use base_url directly)
- drop the API-form pr_url rationale: Gitea sets url and html_url
  identically on the PR payload, and _parse_pr_url rejects the API form
  anyway; fixture now uses the realistic user-facing form
- tests resolve base_url_html through _resolve_base_url_html() instead
  of hardcoding it, covering the __init__ wiring by proxy
- document the GITEA__WEB_URL resolution order, the ROOT_URL caveat and
  the per-repo .pr_agent.toml limitation for cached providers
@niallsemple

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, @IsmaelMartinez — all five notes are addressed in ee68be9:

  • Precedence: _resolve_base_url_html() now prefers an explicitly configured GITEA.URL over the pr.html_url derivation (order: GITEA.WEB_URL → configured GITEA.URL → derived from pr.html_url → base_url), so a stale server ROOT_URL no longer overrides a working configured URL.
  • get_pr_url(): now builds the page URL from base_url_html, so GITEA.WEB_URL reaches the /describe update comment, the changelog link and the incremental-review commit link. All call sites verified user-facing; API and clone paths still use base_url directly.
  • Fixture/rationale: corrected — confirmed against the gitea.com API that url and html_url are identical on the PR payload, and _parse_pr_url rejects the API form anyway.
  • Per-repo caveat: documented on the web_url entry in configuration.toml and in gitea.md (inherited behavior, no code change).
  • Coverage: tests now set base_url_html via _resolve_base_url_html(), covering the __init__ wiring by proxy.

tests/unittest/test_gitea_provider.py: 34 passed.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit ee68be9

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for turning all of that around so quickly. Re-checked the new resolution order and spotted one thing worth another pass, noted inline.

web_url = (get_settings().get("GITEA.WEB_URL", "") or "").rstrip("/")
if web_url:
return web_url
if get_settings().get("GITEA.URL", None):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not distinguish an operator-set value from the shipped default. configuration.toml:310 defines url = "https://gitea.com", so get_settings().get("GITEA.URL", None) is truthy on every deployment, this branch always returns, and the pr.html_url derivation below is unreachable in production.

The new tests pass because _settings() omits GITEA.URL unless a test supplies it, which no real run does.

The effect is that this issue's own scenario regresses: an operator whose GITEA__URL is the internal API address gets that address back in links unless they also set GITEA__WEB_URL, which is what the derivation was there to avoid. Preferring the configured value only when it differs from the shipped default would keep both behaviours.

Can you fix this one? I hope it helps.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in 2fb2227. You're right on both counts: configuration.toml always ships url = "https://gitea.com", so the truthiness check made the derivation unreachable, and the _settings() helper omitting GITEA.URL is exactly why the suite stayed green against a condition no real run has.

Done as you suggested: the configured value now only wins when it differs from the shipped default. The resolver rstrips and compares GITEA.URL against a new DEFAULT_GITEA_URL module constant, which __init__ also uses as its fallback so the two can't drift. Precedence: GITEA.WEB_URL → non-default GITEA.URL → derived from pr.html_url → base_url. The operator with an internal GITEA__URL and no GITEA__WEB_URL gets the html_url derivation again; an explicitly configured URL still beats a stale server ROOT_URL.

Two regression tests added, this time supplying GITEA.URL the way a real run does: the exact shipped default, and a trailing-slash variant — neither shadows the derivation anymore. The configuration.toml comment and gitea.md now state the new precedence. tests/unittest/test_gitea_provider.py: 36 passed.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 2fb2227

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a clean fix for self-hosted Gitea where the API base and the browsable base differ. Merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GiteaProvider uses the API base URL for user-facing links, breaking self-hosted Gitea/Forgejo behind a reverse proxy

2 participants