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(media): preserve original attachment download filenames (#1884)

Call Whitefae5f421c68c
diff --git a/core/workbench_media.py b/core/workbench_media.py
index 540240d4c..b7e63ed3e 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -375,7 +375,7 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: s
return text
def _replace(match) -> str:
- bang, label, url = match.group(1), match.group(2), match.group(3)
+ bang, url = match.group(1), match.group(3)
source_url = text[match.start(3) : match.end(3)]
parsed = _parse_file_uri(url)
if parsed.scheme.casefold() != "file":
@@ -396,7 +396,7 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: s
session_id=session_id,
kind="image" if bang == "!" else "file",
local_path=safe_path,
- file_name=label or os.path.basename(safe_path),
+ file_name=os.path.basename(safe_path),
)
except Exception:
logger.exception("workbench_media: failed to register media for %s", safe_path)
diff --git a/storage/media_service.py b/storage/media_service.py
index bb79bbd54..cb6890233 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -186,7 +186,14 @@ def get_by_token(conn: Connection, token: str) -> Optional[dict[str, Any]]:
if not token:
return None
row = conn.execute(select(media_objects).where(media_objects.c.token == token)).mappings().first()
- return dict(row) if row else None
+ if not row:
+ return None
+ result = dict(row)
+ # Older agent replies stored the Markdown label as file_name. Resolve the
+ # actual name on read so existing links work without rewriting saved state.
+ if result["source"] == "agent_reply":
+ result["file_name"] = Path(result["local_path"]).name
+ return result
def referenced_session_ids(conn: Connection, token: str) -> list[str]:
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index fb632168b..98730206e 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -11,8 +11,10 @@ from __future__ import annotations
import struct
import zlib
from datetime import datetime, timezone
+from email.message import Message
from unittest.mock import patch
+import pytest
from sqlalchemy import select
from core.workbench_media import MAX_WORKBENCH_ATTACHMENT_BYTES, rewrite_agent_media
@@ -140,6 +142,82 @@ def test_rewrite_in_place_image_file_and_external(tmp_path):
assert all(r["source"] == "agent_reply" for r in rows)
[email protected]("legacy", [False, True], ids=["new", "existing"])
[email protected]("filename", ["report.pdf", "报告 (最终).docx", "data.v2.tar.gz", "README"])
+def test_agent_download_and_metadata_preserve_real_filename(tmp_path, monkeypatch, filename, legacy):
+ from tests.ui_server_test_helpers import _save_config
+ from vibe import ui_server
+
+ _save_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: engine)
+ document = tmp_path / filename
+ document.write_bytes(b"document contents")
+ label = "下载报告 v2.1.pdf"
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ rewritten = rewrite_agent_media(
+ conn, scope_id=scope_id, session_id="sess_x", text=f"[{label}](<{document.as_uri()}>)"
+ )
+ row = dict(conn.execute(select(media_objects)).mappings().one())
+ token = row["token"]
+ assert rewritten == f"[{label}](</api/media/{token}>)"
+ if legacy:
+ conn.execute(media_objects.update().where(media_objects.c.token == token).values(file_name=label))
+ else:
+ assert row["file_name"] == filename
+
+ client = ui_server.app.test_client()
+ meta = client.get(f"/api/media/{token}/meta")
+ assert meta.status_code == 200
+ assert meta.get_json()["name"] == filename
+ assert meta.get_json()["ext"] == row["file_ext"]
+ for query in ("", "?download=1"):
+ response = client.get(f"/api/media/{token}{query}")
+ assert response.status_code == 200
+ assert response.content == document.read_bytes()
+ disposition = Message()
+ disposition["Content-Disposition"] = response.headers["Content-Disposition"]
+ assert disposition.get_filename() == filename
+ assert response.headers["Content-Type"].split(";", 1)[0] == row["content_type"]
+ if query:
+ assert disposition.get_content_disposition() == "attachment"
+ with engine.connect() as conn:
+ stored_name = conn.execute(select(media_objects.c.file_name).where(media_objects.c.token == token)).scalar_one()
+ assert stored_name == (label if legacy else filename)
+ engine.dispose()
+
+
+def test_uploaded_download_keeps_original_name_instead_of_storage_basename(tmp_path, monkeypatch):
+ from tests.ui_server_test_helpers import _save_config
+ from vibe import ui_server
+
+ _save_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: engine)
+ document = tmp_path / "random-upload-id_report.docx"
+ document.write_bytes(b"uploaded document")
+ filename = "原始报告.docx"
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="file", source="user_upload",
+ local_path=str(document.resolve()), file_name=filename,
+ )
+ client = ui_server.app.test_client()
+ assert client.get(f"/api/media/{token}/meta").get_json()["name"] == filename
+ response = client.get(f"/api/media/{token}?download=1")
+ assert response.status_code == 200
+ disposition = Message()
+ disposition["Content-Disposition"] = response.headers["Content-Disposition"]
+ assert disposition.get_filename() == filename
+ engine.dispose()
+
+
def test_rewrite_angle_wrapped_file_links(tmp_path):
db = tmp_path / "vibe.sqlite"
run_migrations(db)
diff --git a/ui/src/lib/downloadMedia.test.ts b/ui/src/lib/downloadMedia.test.ts
new file mode 100644
index 000000000..e6b6df4f2
--- /dev/null
+++ b/ui/src/lib/downloadMedia.test.ts
@@ -0,0 +1,74 @@
+import type { MouseEvent } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { apiFetch } from './apiFetch';
+import { handleMediaDownloadClick } from './downloadMedia';
+import { isIosDevice, isStandalonePwa } from './platform';
+
+vi.mock('./apiFetch', () => ({ apiFetch: vi.fn() }));
+vi.mock('./platform', () => ({ isIosDevice: vi.fn(), isStandalonePwa: vi.fn() }));
+
+const share = vi.fn();
+const canShare = vi.fn();
+const url = '/api/media/test-file';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(isIosDevice).mockReturnValue(true);
+ vi.mocked(isStandalonePwa).mockReturnValue(true);
+ share.mockResolvedValue(undefined);
+ canShare.mockReturnValue(true);
+ vi.stubGlobal('navigator', { share, canShare });
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+function click(filename?: string, href = url) {
+ const event = { preventDefault: vi.fn() };
+ handleMediaDownloadClick(event as unknown as MouseEvent, href, filename);
+ return event;
+}
+
+describe('media download filenames', () => {
+ it.each([
+ ['report.pdf', 'application/pdf', 'Download report'],
+ ['报告 (最终).docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'report.pdf'],
+ ['data.v2.tar.gz', 'application/gzip', 'Download v2.1'],
+ ["100%; user's report.pdf", 'application/pdf', undefined],
+ ['README', 'text/plain', 'Notes'],
+ ])('shares the server filename unchanged: %s', async (filename, mime, label) => {
+ vi.mocked(apiFetch).mockResolvedValue(new Response('file contents', {
+ headers: {
+ 'Content-Type': mime,
+ 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
+ },
+ }));
+
+ expect(click(label).preventDefault).toHaveBeenCalledOnce();
+
+ await vi.waitFor(() => expect(share).toHaveBeenCalledOnce());
+ const file = share.mock.calls[0][0].files[0] as File;
+ expect(file.name).toBe(filename);
+ expect(file.type).toBe(mime);
+ expect(canShare).toHaveBeenCalledWith({ files: [file] });
+ });
+
+ it.each([null, "attachment; filename*=UTF-8''bad%ZZ"])(
+ 'retains the filename fallback for an unavailable server name: %s', async (disposition) => {
+ const headers = new Headers({ 'Content-Type': 'application/pdf' });
+ if (disposition) headers.set('Content-Disposition', disposition);
+ vi.mocked(apiFetch).mockResolvedValue(new Response('file contents', { headers }));
+ click('report');
+ await vi.waitFor(() => expect(share).toHaveBeenCalledOnce());
+ expect(share.mock.calls[0][0].files[0].name).toBe('report.pdf');
+ },
+ );
+
+ it('leaves browser downloads and external links to native navigation', () => {
+ vi.mocked(isStandalonePwa).mockReturnValue(false);
+ expect(click().preventDefault).not.toHaveBeenCalled();
+ vi.mocked(isStandalonePwa).mockReturnValue(true);
+ expect(click(undefined, 'https://example.test/report.pdf').preventDefault).not.toHaveBeenCalled();
+ expect(apiFetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/lib/downloadMedia.ts b/ui/src/lib/downloadMedia.ts
index 495cf6ed2..dbe55ce53 100644
--- a/ui/src/lib/downloadMedia.ts
+++ b/ui/src/lib/downloadMedia.ts
@@ -52,6 +52,18 @@ function inferFilename(mime: string, fallback?: string): string {
return `media.${ext || 'bin'}`;
}
+function serverFilename(response: Response): string | undefined {
+ // The media proxy emits an RFC 5987 UTF-8 filename for both preview and download.
+ const encoded = response.headers.get('Content-Disposition')?.match(/(?:^|;)\s*filename\*=UTF-8''([^;]*)/i)?.[1];
+ if (!encoded) return undefined;
+ try {
+ return decodeURIComponent(encoded);
+ } catch {
+ // An invalid header must not prevent saving with the caller's fallback name.
+ return undefined;
+ }
+}
+
// Reload the current page so the server re-runs its auth gate and 302s to the
// cloud login (mirrors apiFetch's 401 recovery / RemoteLoginRedirect).
function recoverFromExpiredSession(): void {
@@ -80,7 +92,7 @@ async function saveViaShareSheet(url: string, filename?: string): Promise<void>
}
if (!res.ok) return;
const blob = await res.blob();
- const file = new File([blob], inferFilename(blob.type, filename), {
+ const file = new File([blob], serverFilename(res) || inferFilename(blob.type, filename), {
type: blob.type || 'application/octet-stream',
});
// Probe the REAL file (type + size matter on iOS), not a dummy: canShare can