Support instances that serve SSH from another hostname
CI / Tests (push) Successful in 36s
CI / Generated images (push) Successful in 1m1s

Discovery matched a git remote's host against the instance URL's host, so
a server answering SSH on a different name than its web UI resolved to
nothing — and said so only in a debug log.

Resolution now runs in three stages. A remote host is matched directly,
then against configured aliases, and failing both the instances are asked
for the repository: Gitea publishes its SSH hostname in a repository's
ssh_url, so the right instance identifies itself. What that turns up is
saved as a host alias, so later repositories on the same host resolve
with no lookup at all, and the mapping is visible and editable rather
than hidden. Each unknown host is probed at most once per session.

When nothing resolves the sidebar now names the unmatched host and offers
Add Host Alias, instead of showing an empty section.

Aliases can also be written by hand as "remote-host = instance URL",
accepting =, -> and =>, ignoring ports, and skipping # comments. List
preferences now merge workspace entries onto global ones rather than
letting an empty global array mask them.

Adds Tests/host-aliases.test.js covering both directions: unmatched hosts
reported and nothing persisted, a hand-written alias, detection from
ssh_url, and a later repository resolving from the stored alias without a
probe. 131 checks across three suites.

Also adds CLAUDE.md, and .gitea/workflows/ci.yml running the suites,
script syntax checks, manifest validation, and a generated-image check.
Tools/make-icons.py gains --check, which compares decompressed pixels so
a differing zlib version cannot fail it spuriously.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MQuusXgZC2dzwpJJ1qhtti
This commit is contained in:
2026-08-28 20:10:05 -03:00
co-authored by Claude Opus 5
parent 694609a3cc
commit 87851de921
22 changed files with 870 additions and 41 deletions
+34
View File
@@ -139,6 +139,40 @@ function register(store, refresh) {
await refresh({ rediscover: true });
});
// Reachable from the warning row a repository shows when its remote host
// matches nothing, which is where users actually hit this.
nova.commands.register("gitea.addHostAlias", async (argument) => {
const node = selection.selectedNode(argument);
const suggested = node && node.data ? node.data.host : null;
const host =
suggested ||
(await ui.input("Which git remote host should be mapped?", {
placeholder: "ssh.example.com",
prompt:
"The hostname your git remotes use, when it differs from the " +
"instance's web address.",
}));
if (!host) return;
const urls = config.instances();
if (!urls.length) {
ui.warn("Configure a Gitea instance before adding an alias for one.");
return;
}
const baseUrl =
urls.length === 1
? urls[0]
: await ui.choose(urls, { placeholder: `Map ${host} onto which instance?` });
if (!baseUrl) return;
config.addHostAlias(host, baseUrl);
store.router.invalidate();
ui.info(`Remotes on ${host} now resolve to ${baseUrl}.`);
await refresh({ rediscover: true });
});
nova.commands.register("gitea.openPreferences", () => {
nova.openConfig();
});
+30 -7
View File
@@ -33,10 +33,11 @@ function makeRepo({ baseUrl, owner, name, dir = null, remoteName = null, remoteU
async function discoverFromWorkspace(router) {
const root = nova.workspace.path;
if (!root) return [];
if (!root) return { repos: [], unmatched: [] };
const dirs = await git.discoverRepositories(root);
const found = new Map();
const unmatched = new Map();
for (const dir of dirs) {
const list = await git.remotes(dir);
@@ -50,13 +51,22 @@ async function discoverFromWorkspace(router) {
return 0;
});
let matched = false;
const skipped = [];
for (const remote of ordered) {
const parsed = remotes.parse(remote.url);
if (!parsed) continue;
const baseUrl = router.baseUrlForHost(parsed.host);
// A configured or already-learned host resolves immediately;
// otherwise ask the instances whether one of them serves it.
const baseUrl =
router.baseUrlForHost(parsed.host) ||
(await router.detectHostAlias(parsed.host, parsed.owner, parsed.name));
if (!baseUrl) {
log.debug(`no configured instance for host ${parsed.host} (${remote.url})`);
skipped.push({ host: parsed.host, remoteUrl: remote.url, dir: dir });
continue;
}
@@ -74,11 +84,20 @@ async function discoverFromWorkspace(router) {
repo.headSha = await git.headSha(dir);
found.set(repo.key, repo);
}
matched = true;
break;
}
// Only report hosts for a checkout that resolved to nothing at all; a
// repository with a matching origin plus an unrelated fork is fine.
if (!matched) {
for (const entry of skipped) {
if (!unmatched.has(entry.host)) unmatched.set(entry.host, entry);
}
}
}
return [...found.values()];
return { repos: [...found.values()], unmatched: [...unmatched.values()] };
}
async function discoverFromApi(router) {
@@ -108,15 +127,16 @@ async function discoverFromApi(router) {
}
/**
* Discovers repositories for the configured mode. Workspace mode additionally
* Discovers repositories for the configured mode, returning them alongside any
* remote hosts that matched no configured instance. Workspace mode additionally
* merges in local checkouts so allAccessible never loses the local directory
* needed for checkout and log-saving.
*/
async function discover(router) {
const mode = config.discoveryMode();
const workspaceRepos = await discoverFromWorkspace(router);
const { repos: workspaceRepos, unmatched } = await discoverFromWorkspace(router);
if (mode !== "allAccessible") return workspaceRepos;
if (mode !== "allAccessible") return { repos: workspaceRepos, unmatched: unmatched };
const byKey = new Map();
for (const repo of await discoverFromApi(router)) byKey.set(repo.key, repo);
@@ -133,7 +153,10 @@ async function discover(router) {
}
}
return [...byKey.values()].sort((a, b) => a.fullName.localeCompare(b.fullName));
return {
repos: [...byKey.values()].sort((a, b) => a.fullName.localeCompare(b.fullName)),
unmatched: unmatched,
};
}
exports.discover = discover;
+16 -5
View File
@@ -57,11 +57,22 @@ function parse(url) {
return null;
}
/** The host of an instance base URL, for matching against a remote's host. */
function hostOf(baseUrl) {
const match = String(baseUrl || "").match(/^[a-z][a-z0-9+.-]*:\/\/([^/]+)/i);
if (!match) return null;
return stripCredentials(match[1]).replace(/:\d+$/, "").toLowerCase();
/**
* The bare host of an instance base URL, a remote URL, or a plain hostname,
* without scheme, credentials, port, or path. Used to compare a remote against
* a configured instance and to normalise both sides of a host alias.
*/
function hostOf(value) {
const text = String(value || "").trim();
if (!text) return null;
const scheme = text.match(/^[a-z][a-z0-9+.-]*:\/\/([^/]+)/i);
// Without a scheme this is already a bare host, possibly carrying
// credentials, a port, or an SCP-style path after a colon.
const authority = scheme ? scheme[1] : text.replace(/[/:].*$/, "");
const host = stripCredentials(authority).replace(/:\d+$/, "").toLowerCase();
return host || null;
}
exports.parse = parse;
+93 -4
View File
@@ -1,17 +1,24 @@
//
// Instance routing. Repositories are matched to a configured Gitea instance by
// their git remote's host; anything unmatched falls back to the default one.
// their git remote's host, directly or through a configured host alias for
// servers that answer SSH on a different hostname than the web UI.
//
const config = require("../util/config.js");
const credentials = require("./credentials.js");
const log = require("../util/log.js");
const remotes = require("./remotes.js");
const { GiteaClient } = require("./client.js");
const { GiteaApi } = require("./api.js");
// "ssh.example.com = https://git.example.com", also accepting -> and =>.
const ALIAS_SEPARATOR = /\s*(?:=>|->|=)\s*/;
class InstanceRouter {
constructor() {
this.apis = new Map();
this._aliases = null;
this._probedHosts = new Set();
}
/** Base URLs of every configured instance, default first. */
@@ -36,12 +43,49 @@ class InstanceRouter {
return urls.length ? this.apiFor(urls[0]) : null;
}
/** The instance whose host matches `host`, or null when none does. */
/**
* Alternate remote hosts mapped onto instance hosts, parsed from the
* "remote-host = instance" preference entries. Blank lines, comments, and
* malformed entries are ignored rather than breaking discovery.
*/
get aliases() {
if (this._aliases) return this._aliases;
const map = new Map();
for (const entry of config.hostAliasEntries()) {
const text = String(entry || "").trim();
if (!text || text.startsWith("#")) continue;
const parts = text.split(ALIAS_SEPARATOR);
if (parts.length !== 2) continue;
const from = remotes.hostOf(parts[0]);
const to = remotes.hostOf(parts[1]);
if (from && to && from !== to) map.set(from, to);
}
this._aliases = map;
return map;
}
/**
* The instance whose host matches `host`, directly or through an alias, or
* null when none does.
*/
baseUrlForHost(host) {
if (!host) return null;
const target = host.toLowerCase();
const target = String(host).toLowerCase();
return (
this._instanceForHost(target) ||
this._instanceForHost(this.aliases.get(target)) ||
null
);
}
_instanceForHost(host) {
if (!host) return null;
for (const baseUrl of this.baseUrls) {
if (remotes.hostOf(baseUrl) === target) return baseUrl;
if (remotes.hostOf(baseUrl) === host) return baseUrl;
}
return null;
}
@@ -54,8 +98,53 @@ class InstanceRouter {
/** Drops cached clients and tokens so the next call re-reads preferences. */
invalidate() {
this.apis.clear();
this._aliases = null;
this._probedHosts.clear();
credentials.invalidate();
}
/**
* Works out which instance serves `host` by asking each one for the
* repository and comparing the clone URLs it reports. Gitea publishes its
* SSH hostname in a repository's ssh_url, so a server that answers SSH on a
* different name than its web UI identifies itself here.
*
* Probes each host at most once per session and remembers what it learns.
*/
async detectHostAlias(host, owner, name) {
if (!host || !owner || !name) return null;
if (this._probedHosts.has(host)) return null;
this._probedHosts.add(host);
for (const baseUrl of this.baseUrls) {
if (!credentials.hasToken(baseUrl)) continue;
let repository;
try {
repository = await this.apiFor(baseUrl).repository({ owner: owner, name: name });
} catch (error) {
log.debug(`${baseUrl} does not serve ${owner}/${name}:`, String(error.message || error));
continue;
}
const advertised = [repository.ssh_url, repository.clone_url, repository.html_url]
.map((url) => remotes.hostOf(url))
.filter(Boolean);
if (!advertised.includes(host)) continue;
this.rememberAlias(host, baseUrl);
log.info(`detected that git remotes on ${host} belong to ${baseUrl}`);
return baseUrl;
}
return null;
}
/** Records an alias for this session and persists it for the next one. */
rememberAlias(host, baseUrl) {
this.aliases.set(remotes.hostOf(host), remotes.hostOf(baseUrl));
config.addHostAlias(host, baseUrl);
}
}
exports.InstanceRouter = InstanceRouter;
+6 -1
View File
@@ -26,7 +26,12 @@ const RELOAD_DEBOUNCE_MS = 150;
// Preferences that change which repositories exist, rather than only how they
// are displayed, force a full rediscovery.
const REDISCOVERY_KEYS = ["gitea.baseUrl", "gitea.instances", "gitea.discovery.mode"];
const REDISCOVERY_KEYS = [
"gitea.baseUrl",
"gitea.instances",
"gitea.hostAliases",
"gitea.discovery.mode",
];
const DISPLAY_KEYS = [
"gitea.maxRunsPerRepo",
"gitea.maxJobsPerRun",
+4 -1
View File
@@ -35,6 +35,7 @@ class Store {
this.router = new InstanceRouter();
this.repos = [];
this.unmatchedHosts = [];
this.instanceStatus = new Map();
this.runs = new Map(); // repoKey -> { runs, legacy, error }
this.jobs = new Map(); // repoKey:runId -> jobs
@@ -143,7 +144,9 @@ class Store {
try {
if (rediscover || !this._discovered) {
this.router.invalidate();
this.repos = await discovery.discover(this.router);
const discovered = await discovery.discover(this.router);
this.repos = discovered.repos;
this.unmatchedHosts = discovered.unmatched;
this._discovered = true;
this._pruneCaches();
} else {
+44 -6
View File
@@ -45,6 +45,14 @@ function bool(key) {
return value === null ? DEFAULTS[key] === true : value === true;
}
/** List preferences merge the workspace's entries on top of the global ones. */
function arrayPref(key) {
const globalEntries = nova.config.get(key, "array") || [];
const workspaceEntries =
(nova.workspace && nova.workspace.config && nova.workspace.config.get(key, "array")) || [];
return [...globalEntries, ...workspaceEntries];
}
/** Trailing slashes make every later URL join ambiguous, so strip them once here. */
function normalizeBaseUrl(url) {
if (!url) return null;
@@ -67,12 +75,7 @@ function instances() {
};
add(get("gitea.baseUrl", "string"));
const extra =
nova.config.get("gitea.instances", "array") ||
(nova.workspace && nova.workspace.config.get("gitea.instances", "array")) ||
[];
for (const url of extra) add(url);
for (const url of arrayPref("gitea.instances")) add(url);
return list;
}
@@ -107,11 +110,46 @@ function setBranchFilter(mode, branch) {
}
}
/**
* Raw "remote-host = instance" entries. Some servers answer SSH on a different
* hostname than the web UI, which would otherwise leave those remotes matching
* no instance at all.
*/
function hostAliasEntries() {
return arrayPref("gitea.hostAliases");
}
/**
* Appends an alias, replacing any existing entry for the same remote host.
* Returns false and writes nothing when the preference already says this, so
* auto-detection cannot bounce the change observers.
*/
function addHostAlias(host, baseUrl) {
const key = String(host).trim().toLowerCase();
const entry = `${key} = ${baseUrl}`;
const current = nova.config.get("gitea.hostAliases", "array") || [];
const kept = current.filter((existing) => {
const left = String(existing).split(/\s*(?:=>|->|=)\s*/)[0];
return String(left).trim().toLowerCase() !== key;
});
const next = [...kept, entry];
if (next.length === current.length && next.every((value, i) => value === current[i])) {
return false;
}
nova.config.set("gitea.hostAliases", next);
return true;
}
exports.get = get;
exports.num = num;
exports.bool = bool;
exports.instances = instances;
exports.setInstances = setInstances;
exports.hostAliasEntries = hostAliasEntries;
exports.addHostAlias = addHostAlias;
exports.normalizeBaseUrl = normalizeBaseUrl;
exports.branchFilter = branchFilter;
exports.setBranchFilter = setBranchFilter;
+1
View File
@@ -21,6 +21,7 @@ class BranchProvider extends NodeProvider {
return [message("No token stored. Run “Gitea → Set Token…” to sign in.")];
}
if (!store.repos.length) {
if (store.unmatchedHosts.length) return builders.unmatchedHostNodes(store);
return [
message(
store.loading
+25
View File
@@ -270,6 +270,30 @@ function pullRequestNode(store, repo, pull, { showRepo = false } = {}) {
});
}
/**
* Rows for remote hosts that matched no configured instance. This is what an
* instance serving SSH from a different hostname than the web UI looks like,
* so the row offers the fix directly.
*/
function unmatchedHostNodes(store) {
return store.unmatchedHosts.map((entry) =>
node("unmatchedHost", `\u26A0 No Gitea instance for ${entry.host}`, {
identifier: `unmatched-${entry.host}`,
description: "add a host alias",
tooltip: [
entry.remoteUrl,
"",
"This remote's host matches no configured Gitea instance.",
"If your server answers SSH on a different hostname than its web",
"UI, map one onto the other with an SSH host alias.",
].join("\n"),
contextValue: "unmatchedHost",
command: "gitea.addHostAlias",
data: { host: entry.host, remoteUrl: entry.remoteUrl },
}),
);
}
function firstLine(text) {
const line = String(text || "").split("\n").find((entry) => entry.trim());
if (!line) return "(empty comment)";
@@ -282,5 +306,6 @@ exports.artifactNode = artifactNode;
exports.pullRequestNode = pullRequestNode;
exports.reviewCommentNode = reviewCommentNode;
exports.changedFileNode = changedFileNode;
exports.unmatchedHostNodes = unmatchedHostNodes;
exports.formatBytes = formatBytes;
exports.firstLine = firstLine;
+1
View File
@@ -17,6 +17,7 @@ class PullRequestsProvider extends NodeProvider {
return [message("No token stored. Run “Gitea → Set Token…” to sign in.")];
}
if (!store.repos.length) {
if (store.unmatchedHosts.length) return builders.unmatchedHostNodes(store);
return [message(store.loading ? "Loading…" : "No Gitea repositories found.")];
}
+16
View File
@@ -53,6 +53,22 @@ class SettingsProvider extends NodeProvider {
const children = [];
if (status && status.error) children.push(errorNode(status.error));
const instanceHost = baseUrl.replace(/^https?:\/\//, "").replace(/:\d+$/, "");
const aliases = [...this.store.router.aliases.entries()]
.filter(([, target]) => target === instanceHost)
.map(([alias]) => alias);
for (const alias of aliases) {
children.push(
node("hostAlias", `${alias}`, {
identifier: `settings-alias-${baseUrl}-${alias}`,
description: "host alias",
tooltip: `Git remotes on ${alias} resolve to ${baseUrl}.`,
contextValue: "hostAlias",
data: { baseUrl: baseUrl, alias: alias },
}),
);
}
if (!hasToken) {
children.push(
node("action", "Set Token…", {
+1
View File
@@ -17,6 +17,7 @@ class WorkflowsProvider extends NodeProvider {
return [message("No token stored. Run “Gitea → Set Token…” to sign in.")];
}
if (!store.repos.length) {
if (store.unmatchedHosts.length) return builders.unmatchedHostNodes(store);
return [message(store.loading ? "Loading…" : "No Gitea repositories found.")];
}