Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop iOS Home Screen app getting stuck on download previews

[._.]/ Adam Eivy668a27b16d09
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d8883112fe..9f659ce83c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -174,6 +174,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `dndKeyboardCoordinates.js` | `createFreeDroppableKeyboardCoordinates({ isSkipped? })` + `keyboardAwareCollisionDetection` — build a `KeyboardSensor` `coordinateGetter` for a `DndContext` whose drop targets are free `useDroppable` zones (no `SortableContext`): arrow keys JUMP to the adjacent zone in visual order instead of nudging 25px. Use it in `LibraryPane` / `GoalsListView`-shaped surfaces; a sortable list uses `@dnd-kit/sortable`'s `sortableKeyboardCoordinates` instead. Pair the getter with `keyboardAwareCollisionDetection` (keeps `rectIntersection` for pointer drags, `closestCenter` for keyboard ones) so adding keyboard support does not change where a mouse drop lands. |
| `dndTransform.js` | `dndTransformToCss(transform)` — render a dnd-kit `useSortable` transform (`{ x, y, scaleX, scaleY }` or `null`) as a CSS `transform` string. Owned replacement for `@dnd-kit/utilities`' `CSS.Transform.toString()`; use it in every `useSortable` style object instead of re-adding that dependency. |
| `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. |
+| `standaloneDownload.js` | `installStandaloneDownloadHandler()` — in an iOS Home Screen PWA, routes same-origin `<a download>` clicks through the native share sheet instead of navigating to a dead-end Quick Look page; `isStandalonePwa()`. |
| `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS. Re-exported from `server/lib/extensionErrors.js`, which the ingest route filters on. |
| `firstRunMissions.js` | Dashboard first-run missions (#5640). `FIRST_RUN_MISSIONS` is the four-slice catalog (Creative studio → `/start-story`, Personal knowledge → `/brain/inbox`, Run my machines → `/apps`, Delegate work → `/cos/tasks`) plus the matching Settings → Features ids each mission writes. `shouldShowFirstRunCard` / `parseFirstRunQueryParam` / `featuresToEnable` are the show/hide and write-set helpers — `/` only, session dismiss vs durable `hideFirstRunCard`, `?firstRun=` force on/off. Pure / React-free; the card lives in `components/onboarding/`. |
| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index ff5b49194e..1a8d4b91c0 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -225,6 +225,7 @@ export * from './spriteFacets.js';
export * from './spriteRecordGroups.js';
export * from './spriteTrimmer.js';
export * from './spriteWalkUnlock.js';
+export * from './standaloneDownload.js';
export * from './streakGlyph.js';
export * from './syncCounts.js';
export * from './tabNotation.js';
diff --git a/client/src/lib/standaloneDownload.js b/client/src/lib/standaloneDownload.js
new file mode 100644
index 0000000000..20350074be
--- /dev/null
+++ b/client/src/lib/standaloneDownload.js
@@ -0,0 +1,59 @@
+// iOS Home Screen (standalone) PWAs have no browser chrome: a tap on
+// `<a download>` navigates the whole app to Quick Look's file preview, which has
+// no back affordance, so the user must swipe-kill and relaunch. In that mode we
+// intercept same-origin `a[download]` clicks, fetch the bytes, and hand them to
+// the native share sheet (Save Image / Save Video / Files) — the app never
+// navigates. Everywhere else the default download behavior is untouched.
+
+export function isStandalonePwa() {
+ if (typeof window === 'undefined') return false;
+ return window.navigator.standalone === true
+ || Boolean(window.matchMedia?.('(display-mode: standalone)').matches);
+}
+
+const MIME_BY_EXT = {
+ mp4: 'video/mp4', mov: 'video/quicktime', webm: 'video/webm',
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4',
+};
+
+function filenameFor(anchor, url) {
+ const named = anchor.getAttribute('download');
+ if (named) return named;
+ const last = decodeURIComponent(url.pathname.split('/').pop() || '');
+ return last || 'download';
+}
+
+export async function shareDownload(anchor) {
+ const url = new URL(anchor.href, window.location.href);
+ const filename = filenameFor(anchor, url);
+ const res = await fetch(url.href, { credentials: 'same-origin' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const blob = await res.blob();
+ const ext = filename.split('.').pop()?.toLowerCase();
+ const type = blob.type && blob.type !== 'application/octet-stream' ? blob.type : (MIME_BY_EXT[ext] || blob.type);
+ const file = new File([blob], filename, { type });
+ if (!navigator.canShare?.({ files: [file] })) throw new Error('share unsupported');
+ await navigator.share({ files: [file] });
+}
+
+// Returns an uninstall function. Capture phase so it runs before the browser's
+// default download navigation.
+export function installStandaloneDownloadHandler() {
+ if (!isStandalonePwa() || typeof navigator.share !== 'function') return () => {};
+ const onClick = (event) => {
+ if (event.defaultPrevented || event.button > 0) return;
+ const anchor = event.target?.closest?.('a[download][href]');
+ if (!anchor) return;
+ const url = new URL(anchor.href, window.location.href);
+ if (url.origin !== window.location.origin) return;
+ event.preventDefault();
+ shareDownload(anchor).catch((err) => {
+ // User dismissing the share sheet is not an error.
+ if (err?.name === 'AbortError') return;
+ console.error(`❌ Download share failed: ${err.message}`);
+ });
+ };
+ document.addEventListener('click', onClick, true);
+ return () => document.removeEventListener('click', onClick, true);
+}
diff --git a/client/src/lib/standaloneDownload.test.js b/client/src/lib/standaloneDownload.test.js
new file mode 100644
index 0000000000..e24fad56e2
--- /dev/null
+++ b/client/src/lib/standaloneDownload.test.js
@@ -0,0 +1,33 @@
+// @vitest-environment happy-dom
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { installStandaloneDownloadHandler } from './standaloneDownload.js';
+
+describe('installStandaloneDownloadHandler', () => {
+ afterEach(() => { vi.unstubAllGlobals(); document.body.innerHTML = ''; });
+
+ it('shares a same-origin a[download] instead of navigating when standalone', async () => {
+ const share = vi.fn().mockResolvedValue();
+ Object.defineProperty(window.navigator, 'standalone', { value: true, configurable: true });
+ Object.defineProperty(navigator, 'share', { value: share, configurable: true });
+ Object.defineProperty(navigator, 'canShare', { value: () => true, configurable: true });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, blob: async () => new Blob(['x'], { type: 'video/mp4' }) }));
+ const off = installStandaloneDownloadHandler();
+ document.body.innerHTML = '<a id="a" href="/data/videos/clip.mp4" download>d</a>';
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true });
+ document.getElementById('a').dispatchEvent(ev);
+ expect(ev.defaultPrevented).toBe(true);
+ await vi.waitFor(() => expect(share).toHaveBeenCalled());
+ expect(share.mock.calls[0][0].files[0].name).toBe('clip.mp4');
+ off();
+ });
+
+ it('leaves clicks alone outside standalone mode', () => {
+ Object.defineProperty(window.navigator, 'standalone', { value: false, configurable: true });
+ const off = installStandaloneDownloadHandler();
+ document.body.innerHTML = '<a id="a" href="/x.mp4" download>d</a>';
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true });
+ document.getElementById('a').dispatchEvent(ev);
+ expect(ev.defaultPrevented).toBe(false);
+ off();
+ });
+});
diff --git a/client/src/main.jsx b/client/src/main.jsx
index d5470a1960..e492f28183 100644
--- a/client/src/main.jsx
+++ b/client/src/main.jsx
@@ -10,12 +10,14 @@ import { ThemeProvider } from './components/ThemeContext';
import { isStaleChunkError, reloadOnceForStaleChunk } from './utils/staleChunkReload';
import { reportClientError } from './lib/clientErrorReporter';
import { registerServiceWorker } from './lib/registerServiceWorker';
+import { installStandaloneDownloadHandler } from './lib/standaloneDownload';
import App from './App';
import './index.css';
// Offline app-shell + low-bandwidth asset caching (production, secure-context
// only — no-op in dev and over plain-HTTP Tailnet). See lib/registerServiceWorker.
registerServiceWorker();
+installStandaloneDownloadHandler();
// Start checking for a newer build as soon as a chunk preload fails. Vite also
// emits this for module evaluation errors, so the recovery helper reloads only