Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Show the reason for each download source when all sources fail
Bowen Xue41334c716767
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.pyindex 8dba831..34b94f4 100644--- a/freevideo_engine/bootstrap.py+++ b/freevideo_engine/bootstrap.py@@ -1777,7 +1777,8 @@ class Installer:return network.download_command(self.network, 'github', attempt, self.env, category='python',extra_sources=['user-python'] if custom else [], notice=notice)except network.PackageSourcesError as error:- failure = RuntimeError('Python download failed on every route; see retained logs')+ failure = RuntimeError('Python download failed on every route; see retained logs'+ + network.sources_text(error.attempts))failure.package_attempts = error.attemptsraise failure from errordiff --git a/freevideo_engine/comfy_host.py b/freevideo_engine/comfy_host.pyindex 8431737..10b44d9 100644--- a/freevideo_engine/comfy_host.py+++ b/freevideo_engine/comfy_host.py@@ -185,7 +185,7 @@ def _prepare(root, comfy, machine, run, download, repair=False):[uv, 'pip', 'install', '--python', python, *NODE_PACKAGES], environment, 'Install ComfyUI packages'), env)except network.PackageSourcesError as error:error.log_files = list(package_logs)- error.args = (str(error) + '. Attempt logs: ' + ', '.join(package_logs),)+ error.args = (str(error) + '\nAttempt logs: ' + ', '.join(package_logs),)raisesave(receipt, identity)elif repair or not recorded:@@ -233,7 +233,7 @@ def _prepare(root, comfy, machine, run, download, repair=False):return network.package_command(plan, family, command, env)except network.PackageSourcesError as error:error.log_files = list(package_logs)- error.args = (str(error) + '. Attempt logs: ' + ', '.join(package_logs),)+ error.args = (str(error) + '\nAttempt logs: ' + ', '.join(package_logs),)raiseprepared = Falsediff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex 286c630..39f99c0 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -361,8 +361,94 @@ def _without_ready_curl_diagnostics(text):return ''.join(lines)-def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_repair=False, repairs_comfy=False,- unavailable='none'):+# What each download source returned, as one short line per host and route on+# the failure card. The full lines stay in the copied error and the report.+SOURCE_REASONS = {+ 'timeout': ('Connection timed out', '连接超时'),+ 'dns': ('Host name could not be resolved', '无法解析域名'),+ 'refused': ('Connection refused', '连接被拒绝'),+ 'connect': ('Could not connect', '无法连接'),+ 'reset': ('Connection interrupted', '连接中断'),+ 'unreachable': ('Network unreachable', '网络不可达'),+ 'proxy': ('Proxy connection failed', '代理连接失败'),+ 'tls': ('Secure connection (certificate) check failed', '安全连接(证书)验证失败'),+ 'http': ('Server returned HTTP {status}', '服务器返回 HTTP {status}'),+ 'disk-full': ('Not enough disk space', '磁盘空间不足'),+ 'write': ('Could not write the file', '无法写入文件'),+ 'access-denied': ('Access denied (possibly blocked by security software)', '访问被拒绝(可能被安全软件拦截)'),+ 'no-progress': ('No data received for a long time', '长时间没有收到数据'),+ 'slow': ('Transfer too slow', '速度过低'),+ 'integrity': ('File check did not match', '文件校验不一致'),+ 'size': ('Response size did not match', '返回的文件大小不符'),+ 'no-resume': ('Resume not supported', '不支持续传'),+ 'faster-source': ('Switched to a faster source', '已改用更快的下载源'),+ 'redirect': ('Redirect refused', '重定向被拒绝'),+ 'exit': ('Failed with exit code {code}', '失败,退出代码 {code}'),+ 'other': ('Other error', '其他错误'),+}+SOURCE_ROUTES = {'direct': ('direct', '直连'), 'inherited': ('current connection', '当前连接')}+SOURCE_CUSTOM = ('custom source', '自定义源')+SOURCE_CARD_LINES = 6+_SOURCE_LINE = re.compile(r'^\s*- (?P<source>[^/\s]+)/(?P<route>[^\s:(]+)(?: \((?P<host>[^)\s]*)\))?: '+ r'(?P<cls>[\w-]+)(?P<rest>.*)$')+++def _sources_block(text):+ """(text without the "Sources tried" block, its source lines)."""+ found = re.search(r'\nSources tried(?: for [^\n:]{1,80})?:\n', text)+ if not found:+ return text, []+ head, tail = text[:found.start()], text[found.end():]+ lines = tail.split('\n')+ count = next((i for i, line in enumerate(lines) if not line.startswith(' - ')), len(lines))+ rest = '\n'.join(lines[count:])+ return head + ('\n' + rest if rest.strip() else ''), lines[:count]+++def source_lines(lines, zh=False):+ """One short line per host and route: what failed and how long it took."""+ rows = {}+ for line in lines:+ found = _SOURCE_LINE.match(line)+ if not found:+ continue+ rest = found['rest']+ status = re.search(r'\bHTTP (\d{3})\b|\b(?:error|status)\D{0,4}([1-5]\d\d)\b', rest)+ code = re.search(r'\bexit (-?\d+)\b|\(exit code (-?\d+)\)|\bcurl-(\d+)\b', rest)+ seconds = re.search(r', (\d+(?:\.\d+)?) s(?::|$)', rest)+ name = found['cls'] if found['cls'] in SOURCE_REASONS else 'other'+ if name == 'http' and not status:+ name = 'other'+ if name == 'exit' and not code:+ name = 'other'+ reason = SOURCE_REASONS[name][zh].format(status=status and (status[1] or status[2]),+ code=code and next(filter(None, code.groups()), ''))+ host = found['host'] or (SOURCE_CUSTOM[zh] if found['source'].startswith('user') else found['source'])+ route = SOURCE_ROUTES.get(found['route'], (found['route'],) * 2)[zh]+ if seconds:+ value = float(seconds[1])+ value = ('%.1f' % value) if value < 10 else '%d' % round(value)+ reason += ('(%s 秒)' if zh else ' (%s s)') % value+ rows.pop((host, route), None)+ rows[host, route] = ('%s · %s:%s' if zh else '%s · %s: %s') % (host, route, reason)+ return list(rows.values())[-SOURCE_CARD_LINES:]+++def launcher_failure(value, *, zh=False, **options):+ """Short guidance; a download that failed on every source also lists what each source returned."""+ text, lines = _sources_block(str(value)) if value else ('', [])+ if not lines:+ return _launcher_failure(value, zh=zh, **options)+ # The source lines never change which guidance applies.+ failure = _launcher_failure(text, zh=zh, **options)+ sources = source_lines(lines, zh)+ if sources:+ failure['sources'] = '\n'.join(sources)+ return failure+++def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_repair=False, repairs_comfy=False,+ unavailable='none'):"""Short guidance for known failures; callers retain the full error separately.other_disk: the launcher can offer another disk with enough room (macOS).diff --git a/freevideo_engine/installation_diagnostics.py b/freevideo_engine/installation_diagnostics.pyindex b4ea83f..b8a186c 100644--- a/freevideo_engine/installation_diagnostics.py+++ b/freevideo_engine/installation_diagnostics.py@@ -36,36 +36,52 @@ def collect(root, since):passexcept OSError:pass- # ComfyUI dependency preparation runs in launcher/host-runs rather- # than setup-runs. Keep only structured package failure events; the- # command output remains available in the local manual bundle.+ # What each download source returned, from structured network events:+ # Python and Git downloads in the setup run, and ComfyUI dependency+ # preparation in launcher/host-runs. The command output remains in the+ # local manual bundle.package_attempts = []+ folders = [run]host_root = root / 'launcher' / 'host-runs'if host_root.is_dir():- candidates = sorted((path for path in host_root.iterdir() if path.is_dir()),- key=lambda path: path.name)[-3:]- for host in candidates:- try:- if host.stat().st_mtime < since - 1:- continue- with (host / 'network.jsonl').open('rb') as stream:- lines = stream.read(256 * 1024).splitlines()[-64:]- for line in lines:- try:- item = d.mapping(json.loads(line))- except (ValueError, UnicodeError):- continue- if item.get('action') != 'package-failed':- continue- package_attempts.append({key: item[key] for key in- ('source', 'route', 'error_type', 'returncode', 'summary') if key in item})- except OSError:+ folders += sorted((path for path in host_root.iterdir() if path.is_dir()),+ key=lambda path: path.name)[-3:]+ for folder in folders:+ try:+ if folder != run and folder.stat().st_mtime < since - 1:continue+ package_attempts += source_failures(folder / 'network.jsonl')+ except OSError:+ continuereturn plain_data(dict(state=state, samples=rows, package_attempts=package_attempts[-16:]))except (OSError, ValueError, KeyError, TypeError):return {}+SOURCE_KEYS = ('category', 'source', 'route', 'host', 'error_class', 'message', 'elapsed_seconds',+ 'error_type', 'returncode', 'summary')+++def source_failures(path):+ """The last failed download attempts in a network event log, one row per source and route tried."""+ with io_path(path).open('rb') as stream:+ size = stream.seek(0, 2)+ stream.seek(max(0, size - 256 * 1024))+ lines = stream.read(256 * 1024).splitlines()+ if size > 256 * 1024:+ lines = lines[1:]+ rows = []+ for line in lines:+ try:+ item = d.mapping(json.loads(line))+ except (ValueError, UnicodeError):+ continue+ if item.get('action') in ('package-failed', 'python-failed') or (+ item.get('category') == 'git' and item.get('action') == 'fallback' and 'error_class' in item):+ rows.append({key: item[key] for key in SOURCE_KEYS if key in item})+ return rows[-16:]++def _errors(rows):result = []for row in d.sequence(rows)[:16]:@@ -141,7 +157,7 @@ def enrich(result, value):for row in d.sequence(value.get('package_attempts'))[-16:]:row = d.mapping(row)item = dict(kind='package_source_failure')- for key in ('source', 'route', 'error_type', 'returncode', 'summary'):+ for key in SOURCE_KEYS:if key in row and (key == 'returncode' or isinstance(row[key], (str, int, float, bool))):item[key] = row[key]result['errors'].append(item)diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qmlindex 8f72418..e683e3a 100644--- a/freevideo_engine/launcher/Main.qml+++ b/freevideo_engine/launcher/Main.qml@@ -426,6 +426,8 @@ ApplicationWindow {id: failureBody; x: 18; y: 18; width: parent.width - 36; spacing: 10FText { text: s.failure.title || t("Something went wrong", "出现问题"); color: theme.danger; font.weight: Font.DemiBold; Layout.fillWidth: true }FText { visible: !!(s.failure.detail || s.failure.action); text: s.failure.detail || s.failure.action; color: theme.text; Layout.fillWidth: true }+ // What each download source returned: one short line per source.+ FText { objectName: "failureSources"; visible: !!s.failure.sources; text: s.failure.sources || ""; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }TextEdit {objectName: "failurePath"; visible: !!s.failure.path; text: s.failure.path || ""readOnly: true; selectByMouse: true; wrapMode: Text.WrapAnywhere; textFormat: TextEdit.PlainText@@ -1441,6 +1443,7 @@ ApplicationWindow {ColumnLayout {id: settingsError; x: 14; y: 14; width: parent.width - 28; spacing: 8FText { text: s.failure.title + "\n" + (s.failure.action || s.failure.detail); color: theme.danger; font.pixelSize: theme.micro + 1; Layout.fillWidth: true }+ FText { objectName: "settingsFailureSources"; visible: !!s.failure.sources; text: s.failure.sources || ""; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }TextEdit {objectName: "settingsFailurePath"; visible: !!s.failure.path; text: s.failure.path || ""readOnly: true; selectByMouse: true; wrapMode: Text.WrapAnywhere; textFormat: TextEdit.PlainTextdiff --git a/freevideo_engine/network.py b/freevideo_engine/network.pyindex b25ea67..734a84b 100644--- a/freevideo_engine/network.py+++ b/freevideo_engine/network.py@@ -560,18 +560,35 @@ class PackageSourcesError(RuntimeError):def __init__(self, family, attempts):self.family = familyself.attempts = [dict(row) for row in attempts]- summaries = []- for row in self.attempts:- detail = row.get('summary') or row.get('detail') or row.get('error_type') or 'unknown failure'- summaries.append('%s/%s: %s' % (row.get('source', 'unknown'),- row.get('route', 'unknown'), detail))- message = 'All package sources failed for %s. Check your network or connection mode in Downloads. Attempts: %s' % (family, '; '.join(summaries))- super().__init__(message)+ self.package_attempts = self.attempts+ message = 'All package sources failed for %s. Check your network or connection mode in Downloads.' % family+ super().__init__(message + sources_text(self.attempts))_ANSI_ESCAPE = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')+def _redact(value):+ """Report-safe text: no credentials, URL parameters, tokens or local paths."""+ if isinstance(value, bytes):+ value = value.decode('utf-8', errors='replace')+ value = _ANSI_ESCAPE.sub('', str(value)).replace('\x00', '')+ # User information in any URL (https, socks5, a token alone before @).+ value = re.sub(r'(?i)\b([a-z][a-z0-9+.-]*://)[^\s/@\x27\x22]+@', r'\1<REDACTED>@', value)+ # Query strings routinely carry signed URLs and access tokens.+ value = re.sub(r'(?i)(https?://[^\s?\x27\x22]+)\?[^\s\x27\x22]+', r'\1', value)+ value = re.sub(r'(?i)(Bearer\s+)[A-Za-z0-9._~+/-]+', r'\1<REDACTED>', value)+ value = re.sub(r'(?i)(\b[\w-]{0,64}(?:token|password|secret|api[_-]?key)\s*[=:]\s*)[^\s,;&]+',+ r'\1<REDACTED>', value)+ # Keep a stable path marker without exposing usernames, drives or mounts.+ # A marker already in place stays as it is, so redacting twice changes nothing.+ return re.sub(r'(?<![A-Za-z0-9_:/>])(?:(?P<relative>\.{1,2}/[^\s"\'<>;,)\]}]*)|'+ r'(?:[A-Za-z]:[\\/]|/)([^\s"\'<>;,)\]}]*))',+ lambda match: match.group('relative') if match.group('relative') is not None+ and not re.search(r'[\\/]', match.group('relative').split('/', 1)[1]) else+ '<PATH>/' + re.split(r'[\\/]', match.group(0).rstrip('\\/'))[-1], value)++def _package_failure(error):"""Return a bounded, report-safe package error detail.@@ -580,30 +597,123 @@ def _package_failure(error):tokens and machine-specific absolute paths before it reaches events or ashared diagnostic report."""- value = getattr(error, 'stderr', None) or getattr(error, 'stdout', None) or str(error)- if isinstance(value, bytes):- value = value.decode('utf-8', errors='replace')- value = _ANSI_ESCAPE.sub('', str(value)).replace('\x00', '')- value = re.sub(r'(?i)(https?://)[^\s/@]+:[^\s/@]+@', r'\1<REDACTED>@', value)- value = re.sub(r'(?i)(Bearer\s+)[A-Za-z0-9._~+/-]+', r'\1<REDACTED>', value)- value = re.sub(r'(?i)(\b[\w-]{0,64}(?:token|password|secret|api[_-]?key)\s*[=:]\s*)[^\s,;&]+',- r'\1<REDACTED>', value)- # Keep a stable path marker without exposing usernames, drives or mounts.- value = re.sub(r'(?<![A-Za-z0-9_:/])(?:(?P<relative>\.{1,2}/[^\s"\'<>;,)\]}]*)|'- r'(?:[A-Za-z]:[\\/]|/)([^\s"\'<>;,)\]}]*))',- lambda match: match.group('relative') if match.group('relative') is not None- and not re.search(r'[\\/]', match.group('relative').split('/', 1)[1]) else- '<PATH>/' + re.split(r'[\\/]', match.group(0).rstrip('\\/'))[-1], value)+ value = _redact(getattr(error, 'stderr', None) or getattr(error, 'stdout', None) or str(error))lines = [line.strip() for line in value.splitlines() if line.strip()]detail = '\n'.join(lines[-12:])[-4096:] if lines else 'no package-manager output'summary = next((line for line in lines if line), detail).strip()[:320]return detail, summary-def _package_attempt(error, source, route):+# What each source returned when a download fails on every source: Git sources,+# the Python runtime, packages and files. One short, redacted line per source+# and route keeps a report actionable (network, proxy, certificate, security+# software or disk) without the full command output.+SOURCE_LINES = 8+SOURCES_TRIED = '\nSources tried:'+# Checked in order on each output line; the last line that names a cause wins.+FAILURE_CLASSES = (+ ('disk-full', r'no space left on device|winerror 112\b|disk (?:is )?full|not enough space on the disk|errno 28\b'),+ ('proxy', r'proxy|\b407\b'),+ ('dns', r'could not resolve|name or service not known|nodename nor servname|getaddrinfo|dns error|'+ r'failed to lookup address|name resolution|no such host|winerror 11001\b'),+ ('timeout', r'timed out|timeout|operation too slow'),+ ('refused', r'connection refused|actively refused|winerror 10061\b|econnrefused'),+ ('unreachable', r'network is unreachable|no route to host|host is unreachable|winerror 1005[01]\b|winerror 10065\b'),+ ('reset', r'connection reset|reset by peer|winerror 10054\b|forcibly closed|remote end hung up|early eof|'+ r'unexpected eof|rpc failed|ssl_error_syscall|connection (?:was )?(?:closed|aborted)'),+ ('tls', r'certificate|ssl|tls|schannel|secure channel|handshake|sec_e_|crypt_e_'),+ ('connect', r"failed to connect|couldn't connect|could not connect|unable to connect|connect error|\(connect\)"),+ ('access-denied', r'access is denied|permission denied|operation not permitted|winerror 5\b|winerror 225\b|virus'),+ ('http', r'(?:returned error|status(?: code)?|http status [a-z ]+error)\D{0,4}\(?[1-5]\d\d\b'),+)+_CURL_CLASSES = dict([*((code, 'tls') for code in (35, 51, 53, 54, 58, 59, 60, 64, 66, 77, 80, 82, 83, 90, 91)),+ *((code, 'reset') for code in (16, 18, 52, 55, 56, 92, 95)),+ (5, 'proxy'), (97, 'proxy'), (6, 'dns'), (7, 'connect'), (28, 'timeout'), (22, 'http'),+ (23, 'write'), (47, 'redirect'), (63, 'size')])+# download_here's own reasons for stopping a transfer.+_REASON_CLASSES = {'no-progress': 'no-progress', 'slow-transfer': 'slow', 'faster-source': 'faster-source',+ 'integrity-mismatch': 'integrity', 'response-size-exceeded': 'size',+ 'source-does-not-support-range': 'no-resume', 'redirect-refused': 'redirect'}+++def _host(address):+ """The host alone: never the user information, path or query of a URL."""+ try:+ return (urlsplit(str(address)).hostname or '')[:80]+ except ValueError:+ return ''+++def source_host(family, name, env=None):+ try:+ return _host(source_url(family, name, env))+ except (KeyError, ValueError):+ return ''+++def exit_code(error):+ """A failed command's exit code: its own, or the one a failed setup step names."""+ if not isinstance(error, str) and getattr(error, 'returncode', None) is not None:+ return error.returncode+ found = re.match(r'(?:[\w.]+: )?Failed step: [^\n]*\(exit code (-?\d+)\)', str(error))+ return int(found[1]) if found else None+++def failure_reason(error):+ """(class, one short redacted line) for a failed source attempt."""+ text = error if isinstance(error, str) else (getattr(error, 'stderr', None) or getattr(error, 'stdout', None) or str(error))+ head, _, output = str(text).partition('\n\nFull step output:\n')+ lines = [line.strip() for line in _redact(output or head).splitlines() if line.strip()]+ returncode = exit_code(error)+ # A word that held a credential or a variable's value goes as a whole.+ lines = [re.sub(r'\S*<REDACTED>\S*', '<REDACTED>', line) for line in lines]+ for line in reversed(lines):+ for name, pattern in FAILURE_CLASSES:+ if re.search(pattern, line, re.I):+ return name, line[:160]+ plain_lines = [line for line in lines if not re.match(r'(?:Failed step|Retained step log|Full step output|Stopped):', line)]+ return ('exit' if returncode not in (None, 0) else 'other'), (plain_lines[-1][:160] if plain_lines else '')+++def _source_row(source, route, host, error_class, message, seconds, code='', **extra):+ row = dict(source=source, route=route, host=host, error_class=error_class, message=message,+ elapsed_seconds=round(max(0., seconds), 1))+ if code:+ row['code'] = code+ row.update(extra)+ return row+++def sources_text(rows, item=''):+ """The lines a copied error and a report carry: one per source and route tried.++ item names what was downloaded (a dependency folder's name), never a path.+ """+ lines = []+ for row in list(rows)[-SOURCE_LINES:]:+ head = '%s/%s' % (row.get('source', 'unknown'), row.get('route', 'unknown'))+ if row.get('host'):+ head += ' (%s)' % row['host']+ parts = [row.get('error_class') or 'other']+ if row.get('code'):+ parts.append(str(row['code']))+ elif row.get('returncode') not in (None, 0):+ parts.append('exit %s' % row['returncode'])+ parts.append('%.1f s' % float(row.get('elapsed_seconds') or 0))+ message = str(row.get('message') or '')+ lines.append(' - %s: %s' % (head, ', '.join(parts)) + (': ' + message if message else ''))+ if not lines:+ return ''+ return (SOURCES_TRIED[:-1] + (' for %s:' % item if item else ':')) + '\n' + '\n'.join(lines)+++def _package_attempt(error, source, route, host='', seconds=0.):detail, summary = _package_failure(error)- return dict(source=source, route=route, error_type=type(error).__name__,- returncode=getattr(error, 'returncode', None), detail=detail, summary=summary)+ error_class, message = failure_reason(error)+ returncode = getattr(error, 'returncode', None)+ code = exit_code(error) if returncode is None else None+ return _source_row(source, route, host, error_class, message, seconds, '' if code is None else 'exit %d' % code,+ error_type=type(error).__name__, returncode=returncode, detail=detail, summary=summary)def download_environment(environ, retry_mode='fast'):@@ -691,6 +801,7 @@ def download_command(network, family, run, env=None, *, category=None, extra_souif operation == 'package' or retry_mode == 'patient':event(network, category=category, source=name, route=route,action=operation + '-attempt', **retry_details)+ started = time.monotonic()try:result = run(name, route, retry_mode)source_health(network, family, name, True)@@ -700,11 +811,14 @@ def download_command(network, family, run, env=None, *, category=None, extra_souresult='success', attempts=len(attempts)-round_start+1)return resultexcept (RuntimeError, subprocess.CalledProcessError) as error:- attempt = dict(_package_attempt(error, name, route), retry_mode=retry_mode)+ attempt = dict(_package_attempt(error, name, route, source_host(family, name, env),+ time.monotonic() - started), retry_mode=retry_mode)attempts.append(attempt)event(network, category=category, source=name, route=route, action=operation + '-failed',error_type=attempt['error_type'], returncode=attempt['returncode'],- detail=attempt['detail'], summary=attempt['summary'], **retry_details)+ detail=attempt['detail'], summary=attempt['summary'], host=attempt['host'],+ error_class=attempt['error_class'], message=attempt['message'],+ elapsed_seconds=attempt['elapsed_seconds'], **retry_details)detail = attempt['detail']if (not retryable(detail)or (retry_mode == 'patient' and not slow_download_failure(detail))):@@ -898,12 +1012,21 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enpath = Path(path)updating = category == 'launcher-update'integrity_failed = False- attempts = {}+ attempts, failures, spent = {}, {}, {}- def note_failure(source, route, reason, status=''):+ def note_failure(source, route, reason, status='', address='', message=''):# The last reason each source and route gave, for the final error.attempts.pop((source, route), None) # a repeat moves to the end, so the last 8 are the latest- attempts[source, route] = reason + (' (HTTP %s)' % status if str(status).isdigit() and status != '000' else '')+ http = str(status).isdigit() and status != '000'+ attempts[source, route] = reason + (' (HTTP %s)' % status if http else '')+ code = int(reason[5:]) if re.fullmatch(r'curl-\d+', reason) else None+ error_class = (_REASON_CLASSES.get(reason) or ('http' if http and code == 22 else _CURL_CLASSES.get(code))+ or (failure_reason(message)[0] if message else 'exit'))+ failures.pop((source, route), None)+ failures[source, route] = _source_row(source, route, _host(address), error_class,+ failure_reason(message)[1] if message else '',+ spent.get((source, route), 0.), attempts[source, route],+ returncode=code, http_status=status if http else '')failed_sources = set()transferred, high_water, last_rate = 0, 0, 0.@@ -1145,7 +1268,8 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enstatus = process.stdout.read(65536 if validate_url else 16).decode(errors='replace')process.stdout.close()# --silent --show-error keeps this to a line or two.- curl_message = _package_failure(SimpleNamespace(stderr=process.stderr.read(2048)))[1] if process.returncode else ''+ stderr = process.stderr.read(2048) if process.returncode else b''+ curl_message = _package_failure(SimpleNamespace(stderr=stderr))[1] if stderr.strip() else ''process.stderr.close()if validate_url:status, destination = _redirect_fields(status)@@ -1157,6 +1281,7 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enurl = urljoin(url, destination)continuecurrent_size = partial.stat().st_size if partial.exists() else 0+ spent[name, route] = spent.get((name, route), 0.) + time.monotonic() - startedif slow_seconds is not None:# A later failure at another address of the same source and# route must not erase the rate it was measured at.@@ -1177,7 +1302,7 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enintegrity_failed = Truefailed_sources.add(name)source_health(network, category, name, False)- note_failure(name, route, 'response-size-exceeded')+ note_failure(name, route, 'response-size-exceeded', address=url)event(network, category=category, source=name, file=path.name, action='fallback',method='curl', reason='response-size-exceeded', observed_bytes=oversized,expected_bytes=size, resume_bytes=offset)@@ -1205,12 +1330,12 @@ def download_here(candidates, path, expected, progress=None, *, network=None, encontinuefailed_sources.add(name)source_health(network, category, name, False)- note_failure(name, route, 'integrity-mismatch')+ note_failure(name, route, 'integrity-mismatch', address=url)event(network, category=category, source=name, file=path.name, action='fallback', reason='integrity-mismatch')breakif offset and (process.returncode == 33 or process.returncode == 22 and status == '416') and restart == 0:if model or keep_partial:- note_failure(name, route, 'source-does-not-support-range')+ note_failure(name, route, 'source-does-not-support-range', address=url)event(network, category=category, source=name, file=path.name,action='resume-refused', resume_bytes=offset, reason='source-does-not-support-range')break@@ -1231,7 +1356,7 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enif updating and stalled:failed_sources.add(name)reason = 'no-progress' if stalled else 'slow-transfer' if slow else 'faster-source' if faster else 'curl-' + str(process.returncode)- note_failure(name, route, reason, status)+ note_failure(name, route, reason, status, url, curl_message)alternatives = route_order(network, category, name, env)if alternatives.index(route) + 1 < len(alternatives):event(network, category=category, source=name, route=alternatives[alternatives.index(route)+1],@@ -1248,11 +1373,9 @@ def download_here(candidates, path, expected, progress=None, *, network=None, enretained_bytes=partial.stat().st_size, reason='resume-unavailable')retain_partial(partial, 'restart-approved')message = 'Every download source failed for %s. Check your network or choose another connection mode in Downloads. Partial files retained' % path.name- if attempts:- message += '. Attempts: ' + '; '.join('%s/%s: %s' % (source, route, reason)- for (source, route), reason in list(attempts.items())[-8:])- error = DownloadError(message)+ error = DownloadError(message + sources_text(failures.values()))error.attempts = [dict(source=source, route=route, reason=reason) for (source, route), reason in attempts.items()]+ error.package_attempts = list(failures.values())error.integrity = integrity_failedraise error@@ -1647,7 +1770,9 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)return run(label, command, env=env)result = subprocess_output.run_external(list(map(str, command)), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **hidden_console())if result.returncode:- raise RuntimeError(result.stdout[-2500:])+ failure = RuntimeError(result.stdout[-2500:])+ failure.returncode = result.returncode+ raise failureio_path(target.parent).mkdir(parents=True, exist_ok=True)candidates = urls(dict(network, sources=dict(network.get('sources', {}), github=network.get('sources', {}).get('git', [{'id': 'official'}]))), 'github', url, env)configured_env = env@@ -1657,6 +1782,7 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)remove_tree(stale)except OSError:pass # Held by another program; the download goes on and a later run tries again.+ attempts = []for name, endpoint, route in [(name, endpoint, route) for name, endpoint in candidatesfor route in route_order(network, 'git', name, configured_env)]:env = route_environment(network, 'git', name, configured_env, route)@@ -1664,6 +1790,7 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)event(network, category='git', source=name, route=route, file=target.name, action='attempt', commit=commit)scratch = git_scratch_folder() if git_folder_too_deep(temporary) else Nonework = scratch / 'repo' if scratch else temporary+ started = time.monotonic()try:execute(target.name + '-init-' + name, ['git', 'init', '--quiet', work])# Never depend on a user's global CRLF conversion or long-path@@ -1722,7 +1849,13 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)if not retryable(error):raisesource_health(network, 'git', name, False)- event(network, category='git', source=name, route=route, file=target.name, action='fallback', reason='network-fetch-failed')+ error_class, message = failure_reason(error)+ attempt = _source_row(name, route, _host(endpoint), error_class, message, time.monotonic() - started,+ returncode=exit_code(error))+ attempts.append(attempt)+ event(network, category='git', source=name, route=route, file=target.name, action='fallback',+ reason='network-fetch-failed', host=attempt['host'], error_class=error_class, message=message,+ returncode=attempt['returncode'], elapsed_seconds=attempt['elapsed_seconds'])finally:# Best effort: a file still held by antivirus or git.exe must not replace the# error being handled or stop the fallback to the next source.@@ -1732,4 +1865,7 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)remove_tree(leftover)except OSError:pass- raise RuntimeError('All Git sources failed. Check your network or connection mode in Downloads.')+ failure = RuntimeError('All Git sources failed. Check your network or connection mode in Downloads.'+ + sources_text(attempts, target.name))+ failure.package_attempts = attempts+ raise failurediff --git a/web/error_panel.js b/web/error_panel.jsindex ae23586..5ef882a 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -318,7 +318,8 @@ export function createErrorReport(detail, context = {}) {// known: a report's known_error. Pass null when the report has none, so an// echoed sentence in its redacted text is not taken for the engine's message.export function failureAdvice(value, t, known = knownError(value)) {- const text = String(value).slice(0, 65536);+ // What each download source returned never changes which advice applies.+ const text = String(value).slice(0, 65536).replace(/\nSources tried(?: for [^\n:]{1,80})?:\n(?: - [^\n]*(?:\n|$))*/g, '\n');const row = (kind, title, summary, action) => ({kind, title: t(...title), summary: t(...summary), action: t(...action)});if (known?.kind === 'sampling-table') {// Names and plan matching follow sampling_effort.js; metadata carries no user text.