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): route media downloads through the share sheet on iOS PWA (#428)

Call White7fd3d9aa6566
diff --git a/ui/src/components/InstallHint.tsx b/ui/src/components/InstallHint.tsx
index 61e8b5d69..0fd06065e 100644
--- a/ui/src/components/InstallHint.tsx
+++ b/ui/src/components/InstallHint.tsx
@@ -4,6 +4,7 @@ import { Plus, Share, Sparkles, X } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { Button } from './ui/button';
+import { isIosDevice, isStandalonePwa } from '@/lib/platform';
const STORAGE_KEY = 'vibe-remote-a2hs';
@@ -19,18 +20,12 @@ const IN_APP_UA =
function shouldShowHint(): boolean {
if (typeof window === 'undefined' || !window.matchMedia) return false;
if (!window.matchMedia('(max-width: 767px)').matches) return false;
+ if (!isIosDevice()) return false;
const ua = navigator.userAgent || '';
- const isIOS =
- /iP(hone|ad|od)/.test(ua) ||
- (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
- if (!isIOS) return false;
const isRealSafari =
/Safari/.test(ua) && /Version\//.test(ua) && !NON_SAFARI_UA.test(ua) && !IN_APP_UA.test(ua);
if (!isRealSafari) return false;
- const standalone =
- (navigator as unknown as { standalone?: boolean }).standalone === true ||
- window.matchMedia('(display-mode: standalone)').matches;
- return !standalone;
+ return !isStandalonePwa();
}
// Top-right nudge to install the app to the iOS Home Screen (standalone PWA),
diff --git a/ui/src/components/ui/chat-image.tsx b/ui/src/components/ui/chat-image.tsx
index 5e6493137..384e7bd1a 100644
--- a/ui/src/components/ui/chat-image.tsx
+++ b/ui/src/components/ui/chat-image.tsx
@@ -4,6 +4,7 @@ import { Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useImageViewer } from '@/components/ui/image-viewer';
+import { handleMediaDownloadClick } from '@/lib/downloadMedia';
import { cn } from '@/lib/utils';
// When a markdown image is wrapped in a link (``[![](media)](href)``),
@@ -62,7 +63,10 @@ export const ChatImage: React.FC<{ src: string; alt?: string; className?: string
<a
href={`${src}?download=1`}
download
- onClick={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleMediaDownloadClick(e, src);
+ }}
aria-label={t('chat.media.download')}
style={{ color: '#fff', textDecoration: 'none' }}
>
diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsx
index b116eae45..6c5a62a7c 100644
--- a/ui/src/components/ui/file-card.tsx
+++ b/ui/src/components/ui/file-card.tsx
@@ -6,6 +6,7 @@ import type { LucideIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/apiFetch';
import { isProxyMediaUrl } from '@/lib/mediaProxy';
+import { handleMediaDownloadClick } from '@/lib/downloadMedia';
import { cn } from '@/lib/utils';
// Download card for an agent-reply file that was rewritten to the same-origin
@@ -93,7 +94,11 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =
</a>
</Button>
<Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}>
- <a href={`${href}?download=1`} download>
+ <a
+ href={`${href}?download=1`}
+ download
+ onClick={(e) => handleMediaDownloadClick(e, href, meta?.name || label)}
+ >
<Download className="size-4" />
</a>
</Button>
diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsx
index 662d93732..a4ec9e6ce 100644
--- a/ui/src/components/ui/image-viewer.tsx
+++ b/ui/src/components/ui/image-viewer.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { ChevronLeft, ChevronRight, Download, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
+import { handleMediaDownloadClick } from '@/lib/downloadMedia';
// A session-scoped image lightbox. ChatPage computes the ordered list of media-
// proxy image URLs in the transcript and wraps the page in a provider; any chat
@@ -97,7 +98,10 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R
<a
href={`${src}?download=1`}
download
- onClick={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleMediaDownloadClick(e, src);
+ }}
aria-label={t('chat.media.download')}
>
<Download className="size-4" />
diff --git a/ui/src/lib/downloadMedia.ts b/ui/src/lib/downloadMedia.ts
new file mode 100644
index 000000000..5934fb162
--- /dev/null
+++ b/ui/src/lib/downloadMedia.ts
@@ -0,0 +1,107 @@
+import type { MouseEvent } from 'react';
+
+import { apiFetch } from '@/lib/apiFetch';
+import { isProxyMediaUrl } from '@/lib/mediaProxy';
+import { isIosDevice, isStandalonePwa } from '@/lib/platform';
+
+// Saving an agent-reply attachment (image / file) on an iOS Home-Screen PWA.
+//
+// The download buttons render a plain ``<a href="/api/media/...?download=1"
+// download>``. That works everywhere with browser chrome — desktop, Android,
+// in-browser iOS Safari — where the anchor downloads, or, if iOS previews
+// instead, there's a back button. But in an INSTALLED iOS PWA there is no
+// chrome and iOS ignores the ``download`` attribute, so the tap becomes a
+// same-origin top-level navigation to the file preview with no way back: the
+// app is trapped.
+//
+// In a standalone PWA the only save path that does NOT trap is the native share
+// sheet (Web Share API level 2) — a dismissible overlay offering "Save to
+// Files" / "Save Image" that returns to the app. A ``window.open`` / ``_blank``
+// "fallback" is not safe: WebKit loads a same-origin in-scope URL in place in
+// the standalone window, i.e. the very trap we're escaping. So when sharing
+// can't run we do nothing (a rare no-op the user can just tap again — the
+// refetch is cache-warm and instant) rather than navigate into the trap.
+
+const MIME_EXT: Record<string, string> = {
+ 'image/png': 'png',
+ 'image/jpeg': 'jpg',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/svg+xml': 'svg',
+ 'image/avif': 'avif',
+ 'image/heic': 'heic',
+ 'application/pdf': 'pdf',
+};
+
+// A name for the shared File. Prefer the caller's known filename; otherwise
+// synthesize ``media.<ext>`` from the blob's MIME so the share sheet still has a
+// sensible name + extension to save under.
+function inferFilename(mime: string, fallback?: string): string {
+ const base = (mime || '').split(';')[0].trim().toLowerCase();
+ const ext = MIME_EXT[base] || base.split('/')[1] || '';
+ const named = (fallback || '').trim();
+ if (named) return /\.[a-z0-9]{1,8}$/i.test(named) || !ext ? named : `${named}.${ext}`;
+ return `media.${ext || 'bin'}`;
+}
+
+// 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 {
+ if (typeof window !== 'undefined') window.location.assign(window.location.href);
+}
+
+async function saveViaShareSheet(url: string, filename?: string): Promise<void> {
+ if (typeof navigator === 'undefined' || typeof navigator.share !== 'function') return;
+ try {
+ // ``redirect: 'manual'`` so we can SEE an auth redirect instead of chasing
+ // it: an expired remote-access session 302s GETs to the cloud login (only
+ // non-GET gets the JSON 401 apiFetch handles), which would otherwise be a
+ // cross-origin CORS throw swallowed below. Accept any type — binary media,
+ // not JSON.
+ const res = await apiFetch(url, {
+ credentials: 'same-origin',
+ headers: { Accept: '*/*' },
+ redirect: 'manual',
+ });
+ // Session expired (302 → opaqueredirect, or a defensive 401): send the user
+ // through the full login flow the old top-level navigation would have,
+ // instead of a silent no-op.
+ if (res.type === 'opaqueredirect' || res.status === 401) {
+ recoverFromExpiredSession();
+ return;
+ }
+ if (!res.ok) return;
+ const blob = await res.blob();
+ const file = new File([blob], inferFilename(blob.type, filename), {
+ type: blob.type || 'application/octet-stream',
+ });
+ // Probe the REAL file (type + size matter on iOS), not a dummy: canShare can
+ // accept a tiny text file yet reject the actual media.
+ if (typeof navigator.canShare === 'function' && !navigator.canShare({ files: [file] })) return;
+ await navigator.share({ files: [file] });
+ } catch {
+ // Either the user dismissed the sheet (AbortError — a success) or the share
+ // couldn't run: e.g. a large / slow fetch outlived the click's transient
+ // activation, so share() rejected with NotAllowedError. Either way, never
+ // navigate as a "fallback" — that re-traps the PWA. A second tap re-shares
+ // from warm cache and succeeds.
+ }
+}
+
+// Click handler for the media download anchors. Two gates before we intercept:
+// 1. Only our same-origin ``/api/media`` proxy URLs — a non-proxy attachment
+// (ChatPage renders third-party hrefs as a click-through FileCard too) must
+// keep native navigation; we must not auto-fetch a remote host, and a
+// cross-origin fetch would just CORS-fail into a dead button anyway.
+// 2. Only the installed iOS PWA traps on the native anchor download; every
+// other context falls through to the browser's own ``<a download>``.
+// Propagation is the call site's concern (stopping a parent lightbox/zoom
+// handler on every platform), so this only owns the iOS-specific
+// ``preventDefault`` that stops the trapping navigation. ``url`` is the bare
+// proxy URL — no ``?download=1`` needed, since we name the File ourselves.
+export function handleMediaDownloadClick(e: MouseEvent, url: string, filename?: string): void {
+ if (!isProxyMediaUrl(url)) return;
+ if (!(isIosDevice() && isStandalonePwa())) return;
+ e.preventDefault();
+ void saveViaShareSheet(url, filename);
+}
diff --git a/ui/src/lib/platform.ts b/ui/src/lib/platform.ts
new file mode 100644
index 000000000..c4547ed95
--- /dev/null
+++ b/ui/src/lib/platform.ts
@@ -0,0 +1,29 @@
+// Shared device / display-context detection. An iOS Home-Screen PWA has no
+// browser chrome (no address bar, no back button), so a same-origin top-level
+// navigation — e.g. a plain ``<a download>`` to our media proxy — has no way
+// back and traps the app on the file preview. Callers that would otherwise
+// navigate use these checks to pick a non-trapping path instead. Kept in one
+// place so the detection can't drift between the InstallHint nudge and the
+// media-download helper.
+
+// iPhone / iPad / iPod, plus iPadOS 13+ which reports as desktop "MacIntel"
+// while still exposing multi-touch.
+export function isIosDevice(): boolean {
+ if (typeof navigator === 'undefined') return false;
+ const ua = navigator.userAgent || '';
+ return (
+ /iP(hone|ad|od)/.test(ua) ||
+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
+ );
+}
+
+// Launched from the Home Screen / installed as a PWA: no browser chrome.
+// ``navigator.standalone`` is Apple's proprietary signal; the display-mode
+// media query is the cross-browser one.
+export function isStandalonePwa(): boolean {
+ if (typeof window === 'undefined') return false;
+ return (
+ (navigator as unknown as { standalone?: boolean }).standalone === true ||
+ (!!window.matchMedia && window.matchMedia('(display-mode: standalone)').matches)
+ );
+}