Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): keep the previous build's chunks loadable after an upgrade (#2874)

Call White06bb784458bf
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index d34fc6c76..ce769b20a 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1,6 +1,7 @@
import asyncio
import gzip
import json
+import shutil
import threading
from types import SimpleNamespace
@@ -2729,6 +2730,41 @@ def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):
assert spa_response.headers["Cache-Control"] == "no-store, private"
+def test_static_ui_serves_previous_build_chunks_after_upgrade(monkeypatch, tmp_path):
+ # An upgrade replaces ui/dist wholesale. A page loaded before it keeps
+ # requesting its own build's hashed chunks; the previous build must stay
+ # loadable, and a build two upgrades back must be pruned.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ ui_dist = tmp_path / "dist"
+ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)
+ client = app.test_client()
+
+ def install_build(build: str) -> None:
+ shutil.rmtree(ui_dist, ignore_errors=True)
+ assets_dir = ui_dist / "assets"
+ assets_dir.mkdir(parents=True)
+ (ui_dist / "index.html").write_text(f'<script src="/assets/index-{build}.js"></script>', encoding="utf-8")
+ (assets_dir / f"index-{build}.js").write_text(f"import('./Page-{build}.js')", encoding="utf-8")
+ (assets_dir / f"Page-{build}.js").write_text(f"// page {build}", encoding="utf-8")
+ (assets_dir / "shared-000.js").write_text("// shared", encoding="utf-8")
+ assert client.get("/workbench/session-1").status_code == 200
+
+ install_build("111")
+ install_build("222")
+
+ previous_chunk = client.get("/assets/Page-111.js")
+ assert previous_chunk.status_code == 200
+ assert previous_chunk.text == "// page 111"
+ assert previous_chunk.headers["Cache-Control"] == "public, max-age=31536000, immutable"
+ assert "javascript" in previous_chunk.headers["Content-Type"]
+
+ install_build("333")
+
+ assert client.get("/assets/Page-111.js").status_code == 404
+ assert client.get("/assets/Page-222.js").text == "// page 222"
+ assert client.get("/assets/shared-000.js").status_code == 200
+
+
def test_static_ui_asset_omits_csrf_cookie(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
ui_dist = tmp_path / "dist"
diff --git a/ui/src/components/ui/error-fallback.test.tsx b/ui/src/components/ui/error-fallback.test.tsx
new file mode 100644
index 000000000..c30a68d61
--- /dev/null
+++ b/ui/src/components/ui/error-fallback.test.tsx
@@ -0,0 +1,47 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import { ErrorFallback } from './error-fallback';
+
+beforeEach(async () => {
+ await i18n.changeLanguage('en');
+});
+
+afterEach(cleanup);
+
+function renderFallback(error: unknown, reset = vi.fn()) {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ErrorFallback error={error} reset={reset} variant="page" />
+ </I18nextProvider>,
+ );
+ return reset;
+}
+
+describe('ErrorFallback', () => {
+ it.each([
+ 'Failed to fetch dynamically imported module: https://app.example/assets/SettingsModelsPage-D_wFDg8R.js',
+ 'Importing a module script failed.',
+ 'error loading dynamically imported module: https://app.example/assets/TerminalView-qpFWlPaW.js',
+ ])('offers only a reload, with feedback, when a lazy module failed to load: %s', (message) => {
+ renderFallback(new TypeError(message));
+
+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Reload page' }));
+
+ const reloading = screen.getByRole('button', { name: 'Reloading…' });
+ expect(reloading).toHaveProperty('disabled', true);
+ expect(reloading.getAttribute('aria-busy')).toBe('true');
+ });
+
+ it('keeps retry for an ordinary render error', () => {
+ const reset = renderFallback(new Error('Cannot read properties of undefined'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+
+ expect(reset).toHaveBeenCalledOnce();
+ expect(screen.getByRole('button', { name: 'Reload page' })).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/ui/error-fallback.tsx b/ui/src/components/ui/error-fallback.tsx
index 4f0aae506..dd3fc32bd 100644
--- a/ui/src/components/ui/error-fallback.tsx
+++ b/ui/src/components/ui/error-fallback.tsx
@@ -1,33 +1,70 @@
+import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { AlertTriangle, RotateCcw } from 'lucide-react';
+import { AlertTriangle, Loader2, RotateCcw, RotateCw } from 'lucide-react';
import clsx from 'clsx';
import { Button } from './button';
+// A lazy module that failed to load, worded differently by Chromium, Firefox, and Safari, plus
+// Vite's own message when a lazy chunk's CSS fails to preload. Retrying in place cannot recover
+// it: React.lazy keeps the rejected import, and browsers keep a failed module fetch until the page
+// reloads. The usual cause is a page left open across an Avibe update.
+const CHUNK_LOAD_ERROR =
+ /Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|Unable to preload CSS/i;
+
+function isChunkLoadError(error: unknown): boolean {
+ return error instanceof Error && CHUNK_LOAD_ERROR.test(error.message);
+}
+
// Kept dependency-light on purpose: this renders precisely when something else just threw, so it must
// not itself rely on app data that might be the cause. i18n `t` returns the key if missing (no throw).
export const ErrorFallback: React.FC<{ error: unknown; reset: () => void; variant: 'page' | 'inline' }> = ({ error, reset, variant }) => {
const { t } = useTranslation();
+ // A reload keeps showing this page until the next one arrives, which can take a while over a
+ // remote connection, so the button shows that it is working.
+ const [reloading, setReloading] = React.useState(false);
+ const chunkLoadFailed = isChunkLoadError(error);
const detail = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
+ const reload = () => {
+ setReloading(true);
+ window.location.reload();
+ };
return (
<div className={clsx('grid h-full w-full place-items-center bg-surface p-6 text-center', variant === 'page' && 'min-h-[60vh]')}>
<div className="flex max-w-sm flex-col items-center gap-3">
<span className="grid size-12 shrink-0 place-items-center rounded-2xl border border-gold/40 bg-gold/[0.08]">
<AlertTriangle className="size-6 text-gold-ink" />
</span>
- <div className="text-[15px] font-semibold text-foreground">{t('errorBoundary.title')}</div>
- <div className="text-[12.5px] text-muted">{t('errorBoundary.body')}</div>
+ <div className="text-[15px] font-semibold text-foreground">
+ {t(chunkLoadFailed ? 'errorBoundary.chunkLoadTitle' : 'errorBoundary.title')}
+ </div>
+ <div className="text-[12.5px] text-muted">{t(chunkLoadFailed ? 'errorBoundary.chunkLoadBody' : 'errorBoundary.body')}</div>
{detail && (
<div className="max-w-full truncate rounded bg-surface-3 px-2 py-1 font-mono text-[11px] text-muted" title={detail}>
{detail}
</div>
)}
<div className="mt-1 flex items-center gap-2">
- <Button type="button" size="sm" variant="brand" className="gap-1.5" onClick={reset}>
- <RotateCcw className="size-3.5" /> {t('errorBoundary.retry')}
- </Button>
- <Button type="button" size="sm" variant="outline" onClick={() => window.location.reload()}>
- {t('errorBoundary.reload')}
+ {!chunkLoadFailed && (
+ <Button type="button" size="sm" variant="brand" className="gap-1.5" onClick={reset} disabled={reloading}>
+ <RotateCcw className="size-3.5" /> {t('errorBoundary.retry')}
+ </Button>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant={chunkLoadFailed ? 'brand' : 'outline'}
+ className="gap-1.5"
+ onClick={reload}
+ disabled={reloading}
+ aria-busy={reloading}
+ >
+ {reloading ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ chunkLoadFailed && <RotateCw className="size-3.5" />
+ )}
+ {t(reloading ? 'errorBoundary.reloading' : 'errorBoundary.reload')}
</Button>
</div>
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 01cf9db64..b8de47681 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -156,7 +156,10 @@
"title": "Something went wrong",
"body": "This part of the app hit an unexpected error. The rest still works — retry, or reload the page.",
"retry": "Retry",
- "reload": "Reload page"
+ "reload": "Reload page",
+ "reloading": "Reloading…",
+ "chunkLoadTitle": "Reload to continue",
+ "chunkLoadBody": "This part couldn't load, most likely because Avibe was updated after this page opened. Reload the page to continue."
},
"remoteLogin": {
"title": "Sign in to continue",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ae16ff6ce..62f440af8 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -156,7 +156,10 @@
"title": "出了点问题",
"body": "这部分遇到了意外错误。其他功能仍可正常使用——可以重试,或刷新页面。",
"retry": "重试",
- "reload": "刷新页面"
+ "reload": "刷新页面",
+ "reloading": "正在刷新…",
+ "chunkLoadTitle": "刷新后即可继续",
+ "chunkLoadBody": "这部分没能加载,多半是这个页面打开后 Avibe 已经更新。刷新页面即可继续使用。"
},
"remoteLogin": {
"title": "登录后继续",
diff --git a/vibe/ui_asset_archive.py b/vibe/ui_asset_archive.py
new file mode 100644
index 000000000..e0311ab6a
--- /dev/null
+++ b/vibe/ui_asset_archive.py
@@ -0,0 +1,150 @@
+"""Keep the previous Web UI build's hashed assets reachable after an upgrade.
+
+Vite gives every JS/CSS chunk a content-hashed name, and an upgrade replaces
+the packaged ``ui/dist`` wholesale. A page loaded before the upgrade still
+holds the old build's chunk graph, so opening one of its lazy modules would
+404 (``Failed to fetch dynamically imported module``), and the browser keeps
+that failure until the page reloads.
+
+Each build whose ``index.html`` the UI server serves is recorded here, and
+``serve_static`` answers asset requests the current build cannot from this
+archive. Only the ``KEEP_BUILDS`` most recently served builds are kept, so the
+archive holds the current build plus the one before it, with unchanged chunks
+stored once. Everything here is a cache: losing it only means an unrefreshed
+page has to reload.
+
+Layout under ``<runtime>/ui-assets/``:
+
+- ``files/<name>``: one copy of each hashed asset (a hard link when possible)
+- ``builds/<id>.json``: the asset names of one build and when it was last
+ recorded
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import re
+import shutil
+import threading
+import time
+from pathlib import Path
+
+from config import paths
+
+logger = logging.getLogger(__name__)
+
+KEEP_BUILDS = 2
+
+_ASSET_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
+_record_lock = threading.Lock()
+_recorded_index_key: tuple[str, str] | None = None
+
+
+def _archive_dir() -> Path:
+ return paths.get_runtime_dir() / "ui-assets"
+
+
+def find_archived_asset(name: str) -> Path | None:
+ """Return the archived file for a flat ``/assets/<name>`` request, if any."""
+ if not _ASSET_NAME.fullmatch(name):
+ return None
+ candidate = _archive_dir() / "files" / name
+ return candidate if candidate.is_file() else None
+
+
+def record_served_build(ui_dist: Path) -> None:
+ """Record the build behind ``ui_dist/index.html`` before a page uses it.
+
+ Cheap when the build is unchanged since the last call in this process.
+ Never raises, and a failure is not retried until the build changes: it
+ only costs unrefreshed pages of this build their fallback.
+ """
+ global _recorded_index_key
+ try:
+ index_html = (ui_dist / "index.html").read_bytes()
+ except OSError:
+ return
+ # The entry page names its build's hashed entry chunks. File metadata is
+ # not a reliable build identity: reproducible wheels pin timestamps.
+ key = (str(ui_dist), hashlib.sha256(index_html).hexdigest())
+ if key == _recorded_index_key:
+ return
+ # A concurrent request is already recording this build; serving the page
+ # does not need to wait for it.
+ if not _record_lock.acquire(blocking=False):
+ return
+ try:
+ if key == _recorded_index_key:
+ return
+ _archive_build(ui_dist / "assets", _archive_dir())
+ except Exception:
+ logger.warning("Failed to archive Web UI assets for unrefreshed pages", exc_info=True)
+ finally:
+ _recorded_index_key = key
+ _record_lock.release()
+
+
+def _archive_build(assets_dir: Path, archive: Path) -> None:
+ if not assets_dir.is_dir():
+ return
+ names = sorted(
+ entry.name for entry in os.scandir(assets_dir) if entry.is_file() and _ASSET_NAME.fullmatch(entry.name)
+ )
+ if not names:
+ return
+ files_dir = archive / "files"
+ builds_dir = archive / "builds"
+ files_dir.mkdir(parents=True, exist_ok=True)
+ builds_dir.mkdir(parents=True, exist_ok=True)
+
+ for name in names:
+ target = files_dir / name
+ if target.exists():
+ # Names are content hashes, so an existing file is this file.
+ continue
+ partial = files_dir / f".{name}.{os.getpid()}.partial"
+ partial.unlink(missing_ok=True)
+ try:
+ os.link(assets_dir / name, partial)
+ except OSError:
+ shutil.copyfile(assets_dir / name, partial)
+ os.replace(partial, target)
+
+ build_id = hashlib.sha256("\n".join(names).encode("utf-8")).hexdigest()[:16]
+ manifest = builds_dir / f"{build_id}.json"
+ partial_manifest = builds_dir / f".{build_id}.{os.getpid()}.partial"
+ # File timestamps can be coarser than successive recordings, so the
+ # recording order lives in the manifest itself.
+ partial_manifest.write_text(json.dumps({"recorded_at": time.time_ns(), "assets": names}), encoding="utf-8")
+ os.replace(partial_manifest, manifest)
+ _prune(files_dir, builds_dir, current=manifest, current_assets=names)
+
+
+def _prune(files_dir: Path, builds_dir: Path, *, current: Path, current_assets: list[str]) -> None:
+ others: list[tuple[int, list[str], Path]] = []
+ for entry in builds_dir.iterdir():
+ if entry == current:
+ continue
+ try:
+ if entry.name.startswith(".") or entry.suffix != ".json":
+ raise ValueError("not a manifest")
+ manifest = json.loads(entry.read_text(encoding="utf-8"))
+ recorded_at, assets = int(manifest["recorded_at"]), manifest["assets"]
+ if not isinstance(assets, list):
+ raise TypeError("assets is not a list")
+ others.append((recorded_at, assets, entry))
+ except (OSError, ValueError, KeyError, TypeError):
+ # Leftover partials and unreadable manifests protect nothing.
+ entry.unlink(missing_ok=True)
+ others.sort(key=lambda item: item[0], reverse=True)
+ referenced = set(current_assets)
+ for _, assets, _ in others[: KEEP_BUILDS - 1]:
+ referenced.update(name for name in assets if isinstance(name, str))
+ for _, _, entry in others[KEEP_BUILDS - 1 :]:
+ entry.unlink(missing_ok=True)
+ for entry in files_dir.iterdir():
+ if entry.name not in referenced:
+ entry.unlink(missing_ok=True)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 9322f6dae..ab7f7c30d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -83,6 +83,7 @@ from vibe.i18n import get_supported_languages, t
from vibe.logging_config import application_log_paths
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
+from vibe import ui_asset_archive
from storage.delivery_states import ADMITTED_DELIVERY_STATES
if TYPE_CHECKING:
@@ -17184,12 +17185,19 @@ def serve_static(path):
if ui_dist.resolve() not in resolved_path.parents and resolved_path != ui_dist.resolve():
return jsonify({"error": "not_found"}), 404
+ if not (resolved_path.exists() and resolved_path.is_file()) and path.startswith("assets/"):
+ # A page loaded before an upgrade still requests its own build's chunks.
+ archived_path = ui_asset_archive.find_archived_asset(path.removeprefix("assets/"))
+ if archived_path is not None:
+ resolved_path = archived_path
+
if resolved_path.exists() and resolved_path.is_file():
mime_type, _ = mimetypes.guess_type(str(resolved_path))
if path.startswith("assets/"):
cache_control = "public, max-age=31536000, immutable"
elif resolved_path.name == "index.html":
cache_control = "no-store, private"
+ ui_asset_archive.record_served_build(ui_dist)
else:
cache_control = "public, max-age=3600"
return _ui_static_file_response(
@@ -17202,6 +17210,7 @@ def serve_static(path):
if "." not in path:
index_path = ui_dist / "index.html"
if index_path.exists():
+ ui_asset_archive.record_served_build(ui_dist)
return _ui_static_file_response(
index_path,
content_type="text/html",