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 file pickers that never open over tailscale (WebKit/PWA ignores a synthetic input.click)

[._.]/ Adam Eivybb4c557278ee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index af627a69a6..80fc096a4a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,8 @@
## Internal
- **[issue-3001] Approving and compiling a walk direction now agree on what "valid packaged frames" means** — the check that a direction's per-frame images are all present was written twice: the cheap gate that runs when you *approve* a direction only checked the files existed (and, for an imported character, could silently drop a frame whose path it couldn't re-anchor — understating the count in its own error), while the stricter gate that runs when you *compile* the atlas also verified each frame's checksum and gait-phase order. So a direction could pass approval and then fail compile for a frame reason the approve step was meant to catch. Both now call one shared `verifyPackagedFrames` helper: approve runs its existence-only prefix (resolving imported frame paths the same drift-tolerant way the clip and strip checks beside it already do, and counting an un-re-anchorable path as a failure instead of dropping it), and compile runs the same resolution plus the checksum/order checks — reading each frame's bytes exactly once. The approve gate is now a strict prefix of the compile gate, so the two can no longer disagree.
+- **Shared `ui/FilePickerButton` + two hygiene guards for file pickers** — 28 call sites across the client hand-rolled the same hidden-`<input type="file">` idiom; they now share `client/src/components/ui/FilePickerButton.jsx` (sr-only-but-focusable input + native `<label for>` activation, extra props spread onto the label so a drop zone can pass `onDrop`/`onDragOver` and a forwarded ref, and an async-aware value clear that waits for the handler to settle before emptying `input.files`). Because the failure only reproduces in WebKit-as-installed-PWA — invisible to lint, CI, and local testing — `a11yConventions.test.js` gains two cases mirroring the existing `crypto.randomUUID` lint precedent: no `type="file"` input may carry `hidden`/`aria-hidden`/`tabIndex={-1}`, and no `.current.click()` may appear in a tracked `.jsx`.
+- **`server/lib/uploadLimits.js` is the single source of truth for upload size caps** — `express.json`'s limit lived as a bare `'55mb'` literal in `server/index.js` while four routes each re-derived their own byte cap against it, two of them landing on unreachable values (100MB, 50MB). The limit and the base64-derived file cap now live in one module (mirroring the `lib/ports.js` pattern), consumed by `index.js` and every upload route; `uploadLimits.test.js` asserts the derivation actually fits, that no route re-hardcodes a cap, and that the client mirror in `utils/fileUpload.js` agrees.
- **The Agents page no longer lists macOS's native text-caret helper as a "Cursor" agent** — the running-agents scan matches process names by substring, so `cursor` also matched `CursorUIViewService` — a macOS TextInputUI framework helper (the blinking text caret), not the Cursor AI editor — and it showed up as a running agent. The scan now excludes system framework / XPC-service helpers (paths under `/System/Library/`, `*.framework/`, `*.xpc/`) alongside the existing `.app` bundle exclusion, so only real agent CLIs appear.
- **[issue-2958] Polyfill jsdom `scrollIntoView` in the client test setup** — jsdom doesn't implement `Element.prototype.scrollIntoView`, so a `requestAnimationFrame` callback that calls it (e.g. `Tribe.jsx`, `CmdKSearch.jsx`, and other components) could fire after its test unmounted and turn into an unhandled error that failed the *entire* client suite despite every assertion passing — an intermittent CI flake that forced no-op re-runs on unrelated PRs. `client/src/test/setup.js` now installs a guarded no-op `scrollIntoView` stub alongside the storage polyfill, killing the whole class of flake in one place. Production is unaffected (the stub only fills the jsdom gap).
- **[issue-2951] Image-to-3D target registry (foundation)** — added a pluggable `server/services/imageTo3d/targets.js` registry (mirroring `imageGen/modes.js`) that models image→3D models as selectable targets with hardware-gated availability resolution, TRELLIS.2 registered as the first target, and a read-only `GET /api/image-to-3d/targets` endpoint. Backend groundwork for the forthcoming 3D page under Create (#2952 install/runner, #2953 page/viewer, #2954 CUDA lane); no user-visible surface yet.
@@ -102,6 +104,8 @@
## Fixed
+- **"Choose a file" buttons now open the file picker from a remote browser** — the Screenshot and Attach buttons on the task form, Browse Files on the Uploads page, and ~20 other upload buttons across PortOS did nothing when you clicked them from another machine over the tailnet. Each one was a plain button whose click handler reached over and *programmatically* clicked a hidden `<input type="file">` — a synthetic click that several browsers refuse to honor, most notably Safari/WebKit when PortOS is running as an installed (standalone) app rather than a normal tab, which is exactly how it tends to get opened on a second machine or a tablet. Every one of those triggers is now a real `<label>` bound to its file input, so the browser opens the picker itself with no scripting involved. Three related annoyances went with it: every file picker in the app is now reachable by keyboard and screen reader (they were hidden from both, including six that already opened fine); re-picking the *same* file after a failed upload now works everywhere; and the Attach picker no longer greys out every file on iOS/iPadOS, where an extension-only filter isn't understood.
+- **Uploads now state the real size limit instead of failing past ~41MB** — the Uploads page advertised a 100MB maximum and task attachments 50MB, but files are sent base64-encoded inside a JSON body, and the server's 55MB body cap means anything past roughly 41MB was rejected by the body parser before the size check ever ran — so a 60MB file produced an opaque failure rather than a limit message. Every upload path (general uploads, task attachments, SongBook attachments, screenshots) now derives its cap from the body limit itself, so the advertised number is always one the server can actually accept.
- **Installing or removing an Ollama model now refreshes provider model pickers instantly** — the Ollama provider (and any Claude/Codex/Gemini CLI running against a local Ollama daemon) picks up the change immediately instead of waiting for a manual "Refresh Models" click on the AI Providers page. The scheduled-task model picker also stays in sync automatically, no app restart required.
- **Hugging Face models with a custom quant scheme no longer produce an uninstallable Ollama id** — `quantFromFilename` matched a standard quant anywhere at the end of a GGUF filename, so a repo-specific scheme suffix bled into a bogus tag (`BTL-3-Compact-AVQ2.gguf` → `Q2`) and the resulting `hf.co/<repo>:Q2` pull failed with Ollama's `400 The specified tag is not a valid quantization scheme`. The quant now has to be its own trailing token (start-of-name or after a `-`/`_`/`.`); when nothing parses, the install id falls back to the bare repo, which Ollama resolves through its `latest` manifest.
- **CoS task cards no longer render a wall of prompt text** — a task's `context`, `blockedReason`/`blocker`, and challenge `reason` are now clamped to two lines with a Show more/Show less toggle, matching the description. Orchestrator tasks (e.g. the Creative Director production plan) store their entire prompt in `metadata.context`, so one pending task previously rendered as thousands of pixels of unclamped text the user had to scroll past to reach the rest of the queue; auto-blocked tasks had the same problem with LLM/stderr-derived block reasons, and a challenge reason is free text a worker agent writes to argue its case. The clamp+toggle (measured overflow, so the toggle only appears when the text actually spills) is extracted from `TaskItem` into a shared `client/src/components/ui/CollapsibleText.jsx`. Editing a task's context also moves from a single-line `<input>` to a bounded scrolling `<textarea>`, which was unusable for a multi-thousand-character prompt.
diff --git a/PLAN.md b/PLAN.md
index d7a8a81f2b..076438a169 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -88,9 +88,8 @@ by `/do:replan --issues`:
`routes/attachments.js` + `routes/brainSongbook.js`). Left out of the SongBook
pass because uploads.js has a different response shape and uses the full
`EXTENSION_MIME_MAP` rather than an allowlist.
- Also fix while there: `routes/attachments.js`'s 50MB cap is unreachable —
- base64 ×4/3 inflation exceeds the 55mb express.json body limit above ~41MB
- (same latent mismatch fixed in `routes/brainSongbook.js`, which now caps at 40MB).
+ (The unreachable-cap half of this item is done: every route now derives its
+ byte cap from `server/lib/uploadLimits.js`.)
- [ ] SongBook practice/spaced-rep integration (SM-2 style, cf.
`meatspacePostMemory`) — the `stage` field on `songs` records is manual in v1
(`server/lib/brainValidation.js` `songStageEnum`).
diff --git a/client/src/a11yConventions.test.js b/client/src/a11yConventions.test.js
index 1e60ce6d1c..d9270b1b90 100644
--- a/client/src/a11yConventions.test.js
+++ b/client/src/a11yConventions.test.js
@@ -14,6 +14,12 @@
* with no on/off state. `components/ToggleSwitch.jsx` is the shared
* widget; hand-rolled tracks must at least carry `role="switch"` +
* `aria-checked`.
+ * 3. A `<input type="file">` hidden with `hidden`/`aria-hidden`/`tabIndex={-1}`
+ * and driven by a programmatic `ref.current.click()`. That is unreachable
+ * by keyboard and screen reader, and the synthetic click doesn't open the
+ * picker at all in WebKit-as-installed-PWA — the shape PortOS is opened in
+ * from a second machine over the tailnet. `components/ui/FilePickerButton.jsx`
+ * is the shared widget (sr-only input + native `<label for>` activation).
*
* Scoped to git-tracked `.jsx` under `client/src` so an untracked scratch file
* can't fail the suite.
@@ -102,6 +108,49 @@ describe('a11y conventions', () => {
expect(offenders, `Toggle-switch button without role="switch" + aria-checked — prefer components/ToggleSwitch.jsx:\n${offenders.join('\n')}`).toEqual([]);
});
+ it('keeps every file input focusable and label-activated', () => {
+ // Two failures ride on the same markup, and neither reproduces for the
+ // author: `display:none` (Tailwind `hidden`) drops the input from the tab
+ // order AND the a11y tree, and a `<button onClick={ref.current.click()}>`
+ // paired with it is a synthetic click several engines refuse to honor —
+ // notably WebKit with PortOS installed as a standalone PWA, which is how it
+ // gets opened from a second machine over the tailnet. The picker simply
+ // never appears. components/ui/FilePickerButton.jsx is the shared fix
+ // (sr-only input + a real <label for>); this test is what stops the old
+ // idiom from creeping back in one component at a time.
+ const offenders = [];
+ for (const file of trackedJsxFiles()) {
+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');
+ const re = /<input\b/g;
+ let m;
+ while ((m = re.exec(src))) {
+ const tag = openingTagAt(src, m.index, '<input'.length);
+ if (!tag || !/type="file"/.test(tag)) continue;
+ const hidden = /className="[^"]*\bhidden\b[^"]*"/.test(tag);
+ const ariaHidden = /aria-hidden/.test(tag);
+ const untabbable = /tabIndex=\{-1\}/.test(tag);
+ if (!hidden && !ariaHidden && !untabbable) continue;
+ offenders.push(`${file}:${lineOf(src, m.index)}`);
+ }
+ }
+ expect(offenders, `File input hidden from keyboard/AT — use components/ui/FilePickerButton.jsx (sr-only input + native <label for> activation), never className="hidden" / aria-hidden / tabIndex={-1}:\n${offenders.join('\n')}`).toEqual([]);
+ });
+
+ it('never opens a file picker with a programmatic ref click', () => {
+ // The other half of the same bug: even a correctly-focusable input is
+ // unopenable in those engines if a button reaches over and clicks it.
+ const offenders = [];
+ for (const file of trackedJsxFiles()) {
+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');
+ const re = /\.current\??\.click\(\)/g;
+ let m;
+ while ((m = re.exec(src))) {
+ offenders.push(`${file}:${lineOf(src, m.index)}`);
+ }
+ }
+ expect(offenders, `Programmatic .click() on a ref — if it targets a file input the picker never opens in WebKit/PWA. Use components/ui/FilePickerButton.jsx:\n${offenders.join('\n')}`).toEqual([]);
+ });
+
it('gives every role="switch" an aria-checked state', () => {
const offenders = [];
for (const file of trackedJsxFiles()) {
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index 0fd2a93046..aac504ed74 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from 'react';
+import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {Upload,
ArrowLeft,
@@ -15,7 +15,7 @@ import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import BrailleSpinner from '../../BrailleSpinner';
import { formatBytes, formatDateShort } from '../../../utils/formatters';
-import { clickableProps } from '../../../lib/a11yKeyboard.js';
+import FilePickerButton from '../../ui/FilePickerButton';
// Sources we plan to support. Only `available` ones are clickable.
const SOURCES = [
@@ -135,7 +135,6 @@ function ChatGPTWizard({ onExit, navigate }) {
const [skipEmpty, setSkipEmpty] = useState(true);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
- const fileInputRef = useRef(null);
const step = STEPS[stepIdx];
const goNext = () => setStepIdx((i) => Math.min(i + 1, STEPS.length - 1));
@@ -247,9 +246,7 @@ function ChatGPTWizard({ onExit, navigate }) {
<StepUpload
uploading={uploading}
fileMeta={fileMeta}
- onPick={() => fileInputRef.current?.click()}
onFile={handleFile}
- fileInputRef={fileInputRef}
onBack={goBack}
/>
)}
@@ -382,7 +379,7 @@ function StepInstructions({ onNext }) {
);
}
-function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack }) {
+function StepUpload({ uploading, fileMeta, onFile, onBack }) {
const handleDrop = (e) => {
e.preventDefault();
const file = e.dataTransfer.files?.[0];
@@ -396,12 +393,13 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
The file stays on this device — nothing is uploaded to OpenAI or any third party.
</p>
- <div
- onClick={onPick}
- {...clickableProps(onPick)}
+ <FilePickerButton
+ accept=".zip,application/zip,.json,application/json"
+ onChange={(e) => onFile(e.target.files?.[0])}
onDragOver={(e) => e.preventDefault()}
onDrop={handleDrop}
- className="border-2 border-dashed border-port-border rounded-lg p-8 text-center cursor-pointer hover:border-port-accent hover:bg-port-card/40 transition-colors"
+ ariaLabel="Choose a ChatGPT export file to import"
+ className="block border-2 border-dashed border-port-border rounded-lg p-8 text-center hover:border-port-accent hover:bg-port-card/40 transition-colors"
>
<FileJson size={32} className="text-gray-500 mx-auto mb-3" aria-hidden="true" />
{fileMeta ? (
@@ -420,14 +418,7 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
<BrailleSpinner /> Parsing…
</div>
)}
- <input
- ref={fileInputRef}
- type="file"
- accept=".zip,application/zip,.json,application/json"
- className="hidden"
- onChange={(e) => onFile(e.target.files?.[0])}
- />
- </div>
+ </FilePickerButton>
<div className="flex items-center justify-between pt-2">
<button
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 9d8427731c..ca1e2a710d 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -3,7 +3,8 @@ import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip
import toast from '../ui/Toast';
import AppContextPicker from '../AppContextPicker';
import * as api from '../../services/api';
-import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';
+import { processScreenshotUploads, processAttachmentUploads, ATTACHMENT_ACCEPT } from '../../utils/fileUpload';
+import FilePickerButton from '../ui/FilePickerButton';
import { formatBytes } from '../../utils/formatters';
import { filterSelectableModels, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, effortLevelsForProvider } from '../../utils/providers';
import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from './constants';
@@ -37,8 +38,6 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [showTemplateSave, setShowTemplateSave] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const submittingRef = useRef(false);
- const fileInputRef = useRef(null);
- const attachmentInputRef = useRef(null);
// Fetch templates
useEffect(() => {
@@ -201,7 +200,6 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
onError: (msg) => toast.error(msg)
});
- e.target.value = '';
};
const removeScreenshot = (id) => {
@@ -214,7 +212,6 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
onSuccess: (fileInfo) => setAttachments(prev => [...prev, fileInfo]),
onError: (msg) => toast.error(msg)
});
- e.target.value = '';
};
const removeAttachment = (id) => {
@@ -595,42 +592,26 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
)}
{/* Screenshot and Attachment Upload */}
<div className="flex items-center gap-3 flex-wrap">
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ multiple
+ onChange={handleFileSelect}
+ ariaLabel="Attach screenshots"
className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm transition-colors min-h-[44px]"
>
<Image size={16} aria-hidden="true" />
Screenshot
- </button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
+ </FilePickerButton>
+ <FilePickerButton
+ accept={ATTACHMENT_ACCEPT}
multiple
- onChange={handleFileSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
- <button
- type="button"
- onClick={() => attachmentInputRef.current?.click()}
+ onChange={handleAttachmentSelect}
+ ariaLabel="Attach files"
className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm transition-colors min-h-[44px]"
>
<Paperclip size={16} aria-hidden="true" />
Attach
- </button>
- <input
- ref={attachmentInputRef}
- type="file"
- accept=".txt,.md,.json,.csv,.xml,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp,.svg,.pdf,.js,.ts,.jsx,.tsx,.py,.sh,.sql,.html,.css,.zip,.tar,.gz"
- multiple
- onChange={handleAttachmentSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
+ </FilePickerButton>
{screenshots.length > 0 && (
<span className="text-xs text-gray-500">{screenshots.length} screenshot{screenshots.length > 1 ? 's' : ''}</span>
)}
diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsx
index eef1aa1130..50b4e3aa23 100644
--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx
+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx
@@ -3,6 +3,7 @@ import { X, CheckCircle, AlertCircle, RotateCcw, Image, Loader2 } from 'lucide-r
import { processScreenshotUploads } from '../../../utils/fileUpload';
import toast from '../../ui/Toast';
import Modal from '../../ui/Modal';
+import FilePickerButton from '../../ui/FilePickerButton';
import { FormField } from '../../ui/FormField';
import { filterSelectableModels } from '../../../utils/providers';
@@ -41,14 +42,12 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
});
const [screenshots, setScreenshots] = useState([]);
const [isSubmitting, setIsSubmitting] = useState(false);
- const fileInputRef = useRef(null);
const handleFileSelect = async (e) => {
await processScreenshotUploads(e.target.files, {
onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
onError: (msg) => toast.error(msg)
});
- e.target.value = '';
};
const removeScreenshot = (id) => {
@@ -148,24 +147,16 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
{/* Screenshot Upload */}
<div>
<div className="flex items-center gap-3 flex-wrap">
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ multiple
+ onChange={handleFileSelect}
+ ariaLabel="Add screenshots"
className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm transition-colors"
>
<Image size={16} aria-hidden="true" />
Add Screenshot
- </button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- multiple
- onChange={handleFileSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
+ </FilePickerButton>
{screenshots.length > 0 && (
<span className="text-xs text-gray-500">{screenshots.length} screenshot{screenshots.length > 1 ? 's' : ''}</span>
)}
diff --git a/client/src/components/digital-twin/tabs/AppearanceTab.jsx b/client/src/components/digital-twin/tabs/AppearanceTab.jsx
index 9c708e74f0..4eb43151de 100644
--- a/client/src/components/digital-twin/tabs/AppearanceTab.jsx
+++ b/client/src/components/digital-twin/tabs/AppearanceTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useRef } from 'react';
+import { useState } from 'react';
import {
Camera,
RefreshCw,
@@ -12,6 +12,7 @@ import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
+import FilePickerButton from '../../ui/FilePickerButton';
// Cap the uploaded image so the base64 data URL stays well under the server's
// JSON body limit and vision providers don't choke on huge payloads.
@@ -36,7 +37,6 @@ export default function AppearanceTab({ onRefresh }) {
setSelectedProviderId, setSelectedModel, loading: providersLoading
} = useProviderModels();
- const fileInputRef = useRef(null);
const [imageDataUrl, setImageDataUrl] = useState('');
const [analyzing, setAnalyzing] = useState(false);
const [result, setResult] = useState(null);
@@ -70,7 +70,6 @@ export default function AppearanceTab({ onRefresh }) {
setResult(null);
setDocDraft('');
setSaved(false);
- if (fileInputRef.current) fileInputRef.current.value = '';
};
const handleAnalyze = async () => {
@@ -156,27 +155,21 @@ export default function AppearanceTab({ onRefresh }) {
)}
<div>
- <label htmlFor="appearance-image" className="block text-sm font-medium text-gray-300 mb-1">
+ {/* A <span>, not a <label>: the file input only exists in the
+ no-photo branch below, so a second `htmlFor` would dangle once a
+ photo is chosen. */}
+ <span className="block text-sm font-medium text-gray-300 mb-1">
Photo
- </label>
- <input
- id="appearance-image"
- ref={fileInputRef}
- type="file"
- accept={ACCEPT_ATTR}
- onChange={(e) => handleFile(e.target.files?.[0])}
- disabled={analyzing}
- className="hidden"
- />
+ </span>
{!imageDataUrl ? (
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept={ACCEPT_ATTR}
+ onChange={(e) => handleFile(e.target.files?.[0])}
disabled={analyzing}
- className="flex items-center gap-2 px-4 py-3 min-h-[48px] w-full justify-center border border-dashed border-port-border rounded-lg text-gray-400 hover:border-port-accent hover:text-white transition-colors disabled:opacity-50"
+ className="flex items-center gap-2 px-4 py-3 min-h-[48px] w-full justify-center border border-dashed border-port-border rounded-lg text-gray-400 hover:border-port-accent hover:text-white transition-colors"
>
<Upload size={18} /> Choose a photo (max 10MB)
- </button>
+ </FilePickerButton>
) : (
<div className="relative inline-block">
<img
diff --git a/client/src/components/digital-twin/tabs/ImportTab.jsx b/client/src/components/digital-twin/tabs/ImportTab.jsx
index 0c0f39fa13..8bf2822389 100644
--- a/client/src/components/digital-twin/tabs/ImportTab.jsx
+++ b/client/src/components/digital-twin/tabs/ImportTab.jsx
@@ -16,6 +16,7 @@ import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import { FormField } from '../../ui/FormField';
import { formatBytes } from '../../../utils/formatters';
+import FilePickerButton from '../../ui/FilePickerButton';
const SOURCE_ICONS = {
goodreads: BookOpen,
@@ -210,24 +211,23 @@ export default function ImportTab() {
{/* File Upload */}
<div className="mb-6">
- <label className="block text-sm font-medium text-gray-400 mb-2">
+ <span className="block text-sm font-medium text-gray-400 mb-2">
Upload {selectedSource.format} File
- </label>
+ </span>
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
- <label className="flex-1 flex items-center justify-center px-4 py-8 border-2 border-dashed border-port-border rounded-lg cursor-pointer hover:border-port-accent transition-colors">
- <input
- type="file"
- accept={selectedSource.format === 'CSV' ? '.csv' : selectedSource.format === 'JSON' ? '.json' : '.ics,.ical'}
- onChange={handleFileUpload}
- className="hidden"
- />
+ <FilePickerButton
+ accept={selectedSource.format === 'CSV' ? '.csv,text/csv' : selectedSource.format === 'JSON' ? '.json,application/json' : '.ics,.ical,text/calendar'}
+ onChange={handleFileUpload}
+ ariaLabel={`Upload ${selectedSource.format} file`}
+ className="flex-1 flex items-center justify-center px-4 py-8 border-2 border-dashed border-port-border rounded-lg hover:border-port-accent transition-colors"
+ >
<div className="text-center">
<Upload className="w-8 h-8 text-gray-500 mx-auto mb-2" />
<span className="text-sm text-gray-400">
{fileContent ? 'File loaded - click to change' : `Click to upload ${selectedSource.format} file`}
</span>
</div>
- </label>
+ </FilePickerButton>
</div>
{fileContent && (
<div className="mt-2 flex items-center gap-2 text-sm text-port-success">
diff --git a/client/src/components/imageGen/InitImagePicker.jsx b/client/src/components/imageGen/InitImagePicker.jsx
index 93fd90fcbf..6cff809577 100644
--- a/client/src/components/imageGen/InitImagePicker.jsx
+++ b/client/src/components/imageGen/InitImagePicker.jsx
@@ -10,6 +10,8 @@
// image (shown as a required warning), regular i2i is optional.
import { Image as ImageIcon, Images, X } from 'lucide-react';
+import FilePickerButton from '../ui/FilePickerButton';
+import { IMAGE_ACCEPT } from '../../utils/fileUpload';
export default function InitImagePicker({
initImage,
@@ -83,11 +85,15 @@ export default function InitImagePicker({
</div>
) : (
<div className="flex flex-col sm:flex-row gap-2">
- <label className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent cursor-pointer transition-colors">
+ <FilePickerButton
+ accept={IMAGE_ACCEPT}
+ onChange={onPick}
+ disabled={disabled}
+ className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent transition-colors"
+ >
<ImageIcon className="w-4 h-4" />
Upload (PNG/JPG/WebP)
- <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={onPick} disabled={disabled} />
- </label>
+ </FilePickerButton>
{onBrowse && (
<button
type="button"
diff --git a/client/src/components/imageGen/ReferenceImagePicker.jsx b/client/src/components/imageGen/ReferenceImagePicker.jsx
index 51b8b3944c..9805d27dec 100644
--- a/client/src/components/imageGen/ReferenceImagePicker.jsx
+++ b/client/src/components/imageGen/ReferenceImagePicker.jsx
@@ -15,6 +15,8 @@
// caller can run EXIF orientation normalization before storing the File.
import { Image as ImageIcon, Images, X } from 'lucide-react';
+import FilePickerButton from '../ui/FilePickerButton';
+import { IMAGE_ACCEPT } from '../../utils/fileUpload';
export default function ReferenceImagePicker({
referenceImages = [],
@@ -69,21 +71,17 @@ export default function ReferenceImagePicker({
</>
) : (
<div className="flex flex-col gap-1">
- <label
- htmlFor={slotId}
- className="flex flex-col items-center justify-center gap-1 h-[64px] border border-dashed border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent cursor-pointer transition-colors"
+ <FilePickerButton
+ id={slotId}
+ accept={IMAGE_ACCEPT}
+ onChange={(e) => onPick(i, e)}
+ disabled={disabled}
+ ariaLabel={`Upload reference image ${i + 1}`}
+ className="flex flex-col items-center justify-center gap-1 h-[64px] border border-dashed border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent transition-colors"
>
<ImageIcon className="w-4 h-4" />
Upload
- <input
- id={slotId}
- type="file"
- accept="image/png,image/jpeg,image/webp"
- className="hidden"
- onChange={(e) => onPick(i, e)}
- disabled={disabled}
- />
- </label>
+ </FilePickerButton>
{onBrowse && (
<button
type="button"
diff --git a/client/src/components/meatspace/tabs/GenomeTab.jsx b/client/src/components/meatspace/tabs/GenomeTab.jsx
index 4d40b6651f..7e83431633 100644
--- a/client/src/components/meatspace/tabs/GenomeTab.jsx
+++ b/client/src/components/meatspace/tabs/GenomeTab.jsx
@@ -59,7 +59,7 @@ import { ATTACHMENT_MAX_FILE_SIZE } from '../../../utils/fileUpload';
import GenomeCategoryCard from '../GenomeCategoryCard';
import EpigeneticTracker from '../EpigeneticTracker';
import ProvenanceChip from '../../ui/ProvenanceChip';
-import { clickableProps } from '../../../lib/a11yKeyboard';
+import FilePickerButton from '../../ui/FilePickerButton';
const CATEGORY_META = {
longevity: { emoji: '\u2728', label: 'Longevity', color: 'purple' },
@@ -136,7 +136,6 @@ export default function GenomeTab() {
const [clinvarExpanded, setClinvarExpanded] = useState({});
const [clinvarFilter, setClinvarFilter] = useState('all');
const [clinvarStarFilter, setClinvarStarFilter] = useState(0);
- const fileInputRef = useRef(null);
const dropRef = useRef(null);
const notesTimerRef = useRef({});
const jumpRef = useRef(null);
@@ -362,16 +361,17 @@ export default function GenomeTab() {
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 items-start">
- {/* Drop zone */}
- <div
+ {/* Drop zone — click opens the picker via FilePickerButton's native
+ label activation; the drag handlers ride along on the label. */}
+ <FilePickerButton
ref={dropRef}
+ accept=".txt,.tsv,.csv,.zip,text/plain,text/csv,text/tab-separated-values,application/zip"
+ onChange={(e) => handleFileUpload(e.target.files?.[0])}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
- className="border-2 border-dashed border-port-border rounded-lg p-12 text-center transition-colors hover:border-gray-500 cursor-pointer focus:outline-none focus:border-port-accent"
- onClick={() => fileInputRef.current?.click()}
- {...clickableProps(() => fileInputRef.current?.click())}
- aria-label="Upload your 23andMe raw data file — drag and drop or activate to browse"
+ ariaLabel="Upload your 23andMe raw data file"
+ className="block border-2 border-dashed border-port-border rounded-lg p-12 text-center transition-colors hover:border-gray-500"
>
{uploading ? (
<div className="space-y-3">
@@ -386,16 +386,7 @@ export default function GenomeTab() {
<p className="text-xs text-gray-600">Accepts .zip or .txt files from 23andMe (typically 15-25MB)</p>
</div>
)}
- <input
- ref={fileInputRef}
- type="file"
- accept=".txt,.tsv,.csv,.zip"
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- onChange={(e) => handleFileUpload(e.target.files[0])}
- />
- </div>
+ </FilePickerButton>
<div className="p-3 rounded bg-port-card border border-port-border text-sm text-gray-400">
<p className="flex items-start gap-2">
diff --git a/client/src/components/meatspace/tabs/SettingsTab.jsx b/client/src/components/meatspace/tabs/SettingsTab.jsx
index 8e94551efb..08527a69e4 100644
--- a/client/src/components/meatspace/tabs/SettingsTab.jsx
+++ b/client/src/components/meatspace/tabs/SettingsTab.jsx
@@ -1,9 +1,10 @@
-import { useState, useRef, useEffect } from 'react';
+import { useState, useEffect } from 'react';
import { Upload, Download, FileJson, HeartPulse, CheckCircle, AlertCircle } from 'lucide-react';
import * as api from '../../../services/api';
import socket from '../../../services/socket';
import BrailleSpinner from '../../BrailleSpinner';
import Banner from '../../ui/Banner';
+import FilePickerButton from '../../ui/FilePickerButton';
export default function SettingsTab({ onRefresh }) {
// JSON import state
@@ -11,7 +12,6 @@ export default function SettingsTab({ onRefresh }) {
const [jsonResult, setJsonResult] = useState(null);
const [jsonError, setJsonError] = useState(null);
const [jsonFileName, setJsonFileName] = useState(null);
- const jsonFileInputRef = useRef(null);
// XML import state
const [xmlImporting, setXmlImporting] = useState(false);
@@ -19,7 +19,6 @@ export default function SettingsTab({ onRefresh }) {
const [xmlResult, setXmlResult] = useState(null);
const [xmlError, setXmlError] = useState(null);
const [xmlFileName, setXmlFileName] = useState(null);
- const xmlFileInputRef = useRef(null);
// WebSocket listeners for XML import progress
useEffect(() => {
@@ -151,19 +150,12 @@ export default function SettingsTab({ onRefresh }) {
</p>
<div className="flex items-center gap-4">
- <input
- ref={jsonFileInputRef}
- type="file"
- accept=".json"
+ <FilePickerButton
+ accept=".json,application/json"
onChange={handleJsonFileSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
- <button
- onClick={() => jsonFileInputRef.current?.click()}
disabled={jsonImporting}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ ariaLabel="Choose JSON file to import"
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 transition-colors"
>
{jsonImporting ? (
<BrailleSpinner text="Importing" />
@@ -173,7 +165,7 @@ export default function SettingsTab({ onRefresh }) {
Choose JSON File
</>
)}
- </button>
+ </FilePickerButton>
{jsonFileName && !jsonImporting && !jsonResult && (
<span className="text-sm text-gray-400">{jsonFileName}</span>
)}
@@ -230,19 +222,12 @@ export default function SettingsTab({ onRefresh }) {
</p>
<div className="flex items-center gap-4">
- <input
- ref={xmlFileInputRef}
- type="file"
- accept=".xml,.zip"
+ <FilePickerButton
+ accept=".xml,.zip,text/xml,application/xml,application/zip"
onChange={handleXmlFileSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
- <button
- onClick={() => xmlFileInputRef.current?.click()}
disabled={xmlImporting}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ ariaLabel="Choose XML or ZIP file to import"
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 transition-colors"
>
{xmlImporting ? (
<BrailleSpinner text="Importing" />
@@ -252,7 +237,7 @@ export default function SettingsTab({ onRefresh }) {
Choose XML or ZIP File
</>
)}
- </button>
+ </FilePickerButton>
{xmlFileName && !xmlImporting && !xmlResult && (
<span className="text-sm text-gray-400">{xmlFileName}</span>
)}
diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsx
index 5c75abc867..792d565a2f 100644
--- a/client/src/components/music/AlbumsManager.jsx
+++ b/client/src/components/music/AlbumsManager.jsx
@@ -12,6 +12,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X, ArrowUp, ArrowDown } from 'lucide-react';
import toast from '../ui/Toast';
+import FilePickerButton from '../ui/FilePickerButton';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
@@ -80,7 +81,6 @@ export default function AlbumsManager() {
const [uploadingCover, setUploadingCover] = useState(false);
const [startingGen, setStartingGen] = useState(false);
const [genJobId, setGenJobId] = useState(null);
- const fileInputRef = useRef(null);
const genRequestRef = useRef(0);
const gen = useMediaJobProgress(genJobId);
@@ -163,7 +163,6 @@ export default function AlbumsManager() {
const handleCoverFile = async (e) => {
const file = e.target.files?.[0];
- if (e.target) e.target.value = '';
if (!file) return;
if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
if (file.size > COVER_MAX_BYTES) { toast.error(`Image exceeds ${Math.round(COVER_MAX_BYTES / 1024 / 1024)}MB`); return; }
@@ -345,13 +344,12 @@ export default function AlbumsManager() {
<button type="button" onClick={handleGenerateCover} disabled={isGenerating || uploadingCover || !canGenerate} title={canGenerate ? 'Generate a cover' : 'Add a title, genre, or description first'} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />} Generate cover
</button>
- <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploadingCover || isGenerating} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ <FilePickerButton accept="image/*" onChange={handleCoverFile} disabled={uploadingCover || isGenerating} ariaLabel="Upload album cover" className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent">
{uploadingCover ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload
- </button>
+ </FilePickerButton>
<button type="button" onClick={() => setGalleryOpen(true)} disabled={isGenerating} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
<ImageIcon size={14} /> Gallery
</button>
- <input ref={fileInputRef} type="file" accept="image/*" onChange={handleCoverFile} className="hidden" />
</div>
</div>
</div>
diff --git a/client/src/components/music/ArtistsManager.jsx b/client/src/components/music/ArtistsManager.jsx
index 7ace6f420c..b751957b5d 100644
--- a/client/src/components/music/ArtistsManager.jsx
+++ b/client/src/components/music/ArtistsManager.jsx
@@ -11,6 +11,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucide-react';
import toast from '../ui/Toast';
+import FilePickerButton from '../ui/FilePickerButton';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
@@ -73,7 +74,6 @@ export default function ArtistsManager() {
const [uploadingPortrait, setUploadingPortrait] = useState(false);
const [startingGen, setStartingGen] = useState(false);
const [genJobId, setGenJobId] = useState(null);
- const fileInputRef = useRef(null);
// Bumped on every artist switch / new-artist so a stale generate response
// can't write the wrong persona's portrait (mirrors Authors' genRequestRef).
const genRequestRef = useRef(0);
@@ -132,7 +132,6 @@ export default function ArtistsManager() {
const handlePortraitFile = async (e) => {
const file = e.target.files?.[0];
- if (e.target) e.target.value = '';
if (!file) return;
if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
if (file.size > PORTRAIT_MAX_BYTES) {
@@ -404,15 +403,16 @@ export default function ArtistsManager() {
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
Generate
</button>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ onChange={handlePortraitFile}
disabled={uploadingPortrait || isGenerating}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ ariaLabel="Upload artist portrait"
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
>
{uploadingPortrait ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
Upload
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
@@ -421,13 +421,6 @@ export default function ArtistsManager() {
>
<ImageIcon size={14} /> Choose from gallery
</button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- onChange={handlePortraitFile}
- className="hidden"
- />
</div>
<input
value={form.portraitImageUrl}
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index 5e252bd2c6..3b797e4120 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -16,6 +16,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Plus, Loader2, Trash2, Save, Upload, Music2, Library } from 'lucide-react';
import toast from '../ui/Toast';
+import FilePickerButton from '../ui/FilePickerButton';
import { formatTimecode } from '../../utils/formatters';
import ArtistPicker from './ArtistPicker';
import MusicGenPanel from './MusicGenPanel';
@@ -87,7 +88,6 @@ export default function TracksManager() {
// that already carries a score opens on the chiptune panel.
const [genMode, setGenMode] = useState('audio');
const remixNonceRef = useRef(0);
- const fileInputRef = useRef(null);
// Mirrors `selectedId` so async audio handlers can detect a selection change
// that happened while their server round-trip was in flight (the server write
// still targets the original track id; only the open form must not be clobbered
@@ -207,7 +207,6 @@ export default function TracksManager() {
const handleAudioFile = async (e) => {
const file = e.target.files?.[0];
- if (e.target) e.target.value = '';
if (!file || !requireSaved()) return;
if (file.size > AUDIO_MAX_BYTES) { toast.error(`Audio exceeds ${Math.round(AUDIO_MAX_BYTES / 1024 / 1024)}MB`); return; }
const targetId = persisted.id; // server write targets THIS track
@@ -486,14 +485,17 @@ export default function TracksManager() {
Renders{renders.length ? ` (${renders.length})` : ''}
</span>
<div className="flex items-center gap-2 flex-wrap">
- <button
- type="button"
- onClick={() => (requireSaved() ? fileInputRef.current?.click() : null)}
+ {/* `handleAudioFile` re-checks `requireSaved()` itself, so the
+ picker needs no gate of its own. */}
+ <FilePickerButton
+ accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac"
+ onChange={handleAudioFile}
disabled={uploading}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ ariaLabel="Upload track audio"
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
>
{uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={openLibrary}
@@ -501,7 +503,6 @@ export default function TracksManager() {
>
<Library size={14} /> From library
</button>
- <input ref={fileInputRef} type="file" accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac" onChange={handleAudioFile} className="hidden" />
</div>
</div>
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsx
index f8dd216e20..be470df962 100644
--- a/client/src/components/pipeline/stages/AudioStage.jsx
+++ b/client/src/components/pipeline/stages/AudioStage.jsx
@@ -15,6 +15,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Loader2, Sparkles, Wand2, Mic, Music, Upload, Trash2, ListMusic } from 'lucide-react';
import toast from '../../ui/Toast';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
+import FilePickerButton from '../../ui/FilePickerButton';
import VoicePicker from '../../voice/VoicePicker';
import {
extractPipelineAudioLines,
@@ -86,7 +87,6 @@ export default function AudioStage({ issue, onStageUpdate }) {
// reveals [Cancel] [Delete] for that row only. Stored as the filename so
// only one row shows the confirm at a time.
const [pendingLibraryDelete, setPendingLibraryDelete] = useState(null);
- const fileInputRef = useRef(null);
// Local-OSS music generation (Phase 4c.2). The generators list is fetched
// lazily when the user opens the Generate panel; `ready` gates the prompt box
@@ -954,26 +954,18 @@ export default function AudioStage({ issue, onStageUpdate }) {
</div>
</div>
<div className="flex items-center gap-2 flex-wrap">
- <input
- ref={fileInputRef}
- type="file"
+ <FilePickerButton
accept="audio/mpeg,audio/mp3,audio/wav,audio/x-wav,audio/mp4,audio/m4a,audio/ogg,audio/flac,.mp3,.wav,.m4a,.ogg,.flac"
onChange={(e) => {
const file = e.target.files?.[0];
- e.target.value = '';
if (file) void handleMusicUpload(file);
}}
- className="hidden"
- />
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
disabled={musicUploading}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
>
{musicUploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
Upload track
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => (musicPickerOpen ? setMusicPickerOpen(false) : openMusicPicker())}
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
index d2c40c0e89..72e12258bd 100644
--- a/client/src/components/songs/ReferenceAnalysis.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -27,6 +27,7 @@ import {
ArrowLeft, AudioLines, Download, Flag, FlagOff, Layers, Loader2, Mic, Music, Play, Plus, Square, Trash2, Upload, Wand2, X,
} from 'lucide-react';
import toast from '../ui/Toast';
+import FilePickerButton from '../ui/FilePickerButton';
import ScoreSheet from './ScoreSheet.jsx';
import { uploadFile, getUploadUrl } from '../../services/api';
import {
@@ -95,7 +96,6 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
// quality/speed). Read fresh inside startRequest — useSseJobSlot invokes the
// latest closure each kickoff, so a change here applies to the next run.
const [midiModel, setMidiModel] = useState(DEFAULT_MUSCRIPTOR_MODEL);
- const fileRef = useRef(null);
const handleRef = useRef(null);
// "Download audio from URL" (#2120) — best-effort yt-dlp fetch straight onto
@@ -140,7 +140,6 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
const onFile = useCallback(async (e) => {
const file = e.target.files?.[0];
- e.target.value = ''; // allow re-picking the same file
if (!file) return;
if (file.size > MAX_AUDIO_BYTES) {
toast.error(`Audio file too large (max ${Math.round(MAX_AUDIO_BYTES / 1024 / 1024)} MB)`);
@@ -265,15 +264,15 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
return (
<div className="flex flex-col gap-1.5">
<div className="flex flex-wrap items-center gap-2">
- <input ref={fileRef} type="file" accept="audio/*" onChange={onFile} className="hidden" aria-label="Upload reference audio file" />
- <button
- type="button"
- onClick={() => fileRef.current?.click()}
+ <FilePickerButton
+ accept="audio/*"
+ onChange={onFile}
disabled={busy || recording || downloading}
- className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"
+ ariaLabel="Upload audio file"
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"
>
{busy ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload audio
- </button>
+ </FilePickerButton>
{recording ? (
<button type="button" onClick={stopRecord} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90 animate-pulse">
<Square size={14} /> Stop capture
diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsx
index bad10bfef9..64d18779d7 100644
--- a/client/src/components/songs/ReferenceAnalysis.test.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx
@@ -404,7 +404,9 @@ describe('ReferenceAnalysis — stacked-mix extraction (#2121)', () => {
describe('ReferenceAudioAttach', () => {
it('offers upload + mic capture when no audio is attached', () => {
render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={vi.fn()} />);
- expect(screen.getByRole('button', { name: /upload audio/i })).toBeTruthy();
+ // The upload control is a <label> + file input (native picker activation),
+ // so it's found by its accessible label, not by button role.
+ expect(screen.getByLabelText(/upload audio/i)).toBeTruthy();
expect(screen.getByRole('button', { name: /capture from mic/i })).toBeTruthy();
});
@@ -439,7 +441,7 @@ describe('ReferenceAudioAttach', () => {
refImport.state = { active: true, percent: 42, stage: null };
render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={vi.fn()} />);
expect(screen.getByText(/downloading 42%/i)).toBeTruthy();
- expect(screen.getByRole('button', { name: /upload audio/i }).disabled).toBe(true);
+ expect(screen.getByLabelText(/upload audio/i).disabled).toBe(true);
refImport.state = { active: false, percent: 0, stage: null }; // reset for other tests
});
});
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index 2bc33abac8..aad1cdd8cd 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import {
Lock, Sparkles, RefreshCw, Upload, ChevronDown, ChevronRight,
Images, PersonStanding, GitFork, X,
@@ -11,6 +11,8 @@ import GalleryImagePicker from '../imageGen/GalleryImagePicker.jsx';
import SpriteReferencePicker from './SpriteReferencePicker.jsx';
import ForkSpriteModal from './ForkSpriteModal.jsx';
import CorrectionNote, { correctionPromptPayload } from './CorrectionNote.jsx';
+import FilePickerButton from '../ui/FilePickerButton';
+import { IMAGE_ACCEPT } from '../../utils/fileUpload';
// Reference workflow (issues #2896, #2979): three ordered steps — generate a
// turnaround sheet from text + an optional design image and freeze it, derive
@@ -136,7 +138,6 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
const [galleryOpen, setGalleryOpen] = useState(false);
const [spritePickerOpen, setSpritePickerOpen] = useState(false);
const [forkOpen, setForkOpen] = useState(false);
- const fileInputRef = useRef(null);
// Revoke the previous upload's object URL whenever the source changes or the
// component unmounts (cleanup runs with the prior closure).
@@ -145,10 +146,7 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
return () => { if (url) URL.revokeObjectURL(url); };
}, [refSource]);
- const clearSource = () => {
- setRefSource(null);
- if (fileInputRef.current) fileInputRef.current.value = '';
- };
+ const clearSource = () => setRefSource(null);
const pickUpload = (file) => {
if (!file) return;
setRefSource({ type: 'upload', file, previewUrl: URL.createObjectURL(file) });
@@ -314,15 +312,7 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
rows={2}
className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
/>
- {/* Reference image (optional, i2i seed) — pick ONE of three sources.
- Hidden file input driven by the Upload button. */}
- <input
- ref={fileInputRef}
- type="file"
- accept="image/png,image/jpeg,image/webp"
- className="hidden"
- onChange={(e) => pickUpload(e.target.files?.[0] || null)}
- />
+ {/* Reference image (optional, i2i seed) — pick ONE of three sources. */}
{refSource ? (
<div className="flex items-center gap-3 bg-port-bg border border-port-border rounded p-2">
{refSource.type === 'sprite' ? (
@@ -364,13 +354,14 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
) : (
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-gray-500">Reference image (optional):</span>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept={IMAGE_ACCEPT}
+ onChange={(e) => pickUpload(e.target.files?.[0] || null)}
+ ariaLabel="Upload a reference image"
className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"
>
<Upload className="w-3.5 h-3.5" /> Upload
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
diff --git a/client/src/components/timeline/ActivityImportPanel.jsx b/client/src/components/timeline/ActivityImportPanel.jsx
index 398af41daf..a558dbd3c7 100644
--- a/client/src/components/timeline/ActivityImportPanel.jsx
+++ b/client/src/components/timeline/ActivityImportPanel.jsx
@@ -1,6 +1,7 @@
import { useState, useRef, useEffect } from 'react';
import { Upload, Loader2, CheckCircle2 } from 'lucide-react';
import toast from '../ui/Toast';
+import FilePickerButton from '../ui/FilePickerButton';
// Shared bulk-backfill importer panel for the timeline (#2160). Two-step flow:
// pick a file → preview (parse-only, no write) → confirm import. The import is
@@ -108,11 +109,15 @@ export default function ActivityImportPanel({ icon: Icon, title, noun, help, imp
{typeof controls === 'function' ? controls({ disabled: busy }) : controls}
<div className="flex flex-wrap items-center gap-2">
- <label className={`inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 ${busy ? 'cursor-not-allowed opacity-40' : 'cursor-pointer hover:border-port-accent'}`}>
+ <FilePickerButton
+ accept={accept}
+ onChange={pickFile}
+ disabled={busy}
+ className="inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 hover:border-port-accent"
+ >
<Upload size={14} />
<span>{file ? 'Change file' : 'Choose file'}</span>
- <input type="file" accept={accept} onChange={pickFile} disabled={busy} className="hidden" />
- </label>
+ </FilePickerButton>
{file && <span className="truncate text-xs text-gray-400">{file.name}</span>}
</div>
diff --git a/client/src/components/ui/FilePickerButton.jsx b/client/src/components/ui/FilePickerButton.jsx
new file mode 100644
index 0000000000..c34cac3ed3
--- /dev/null
+++ b/client/src/components/ui/FilePickerButton.jsx
@@ -0,0 +1,103 @@
+import { forwardRef, useId } from 'react';
+
+const DISABLED_CLS = 'opacity-50 cursor-not-allowed pointer-events-none';
+const FOCUS_RING = 'peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-port-accent peer-focus-visible:ring-offset-2 peer-focus-visible:ring-offset-port-bg';
+
+/**
+ * A control that opens the OS file picker — styled as a button, or as a whole
+ * drop zone when you pass drag handlers through.
+ *
+ * Why this exists instead of a button that reaches into a ref and clicks a
+ * hidden input: a *programmatic* click on an `<input type="file">` is a synthetic,
+ * untrusted event, and several browsers refuse to open the picker for it —
+ * most notably Safari/WebKit when PortOS is running as an installed
+ * (`display: standalone`) PWA, which is exactly how it tends to get opened from
+ * a remote machine over the tailnet. Activating a `<label for>` is a *native*
+ * label activation instead: the browser opens the picker itself, with no
+ * reliance on user-activation heuristics, in every engine.
+ *
+ * The input is visually hidden but stays focusable and exposed to the
+ * accessibility tree (it is the labelled control) — do NOT hide a file input
+ * with `className="hidden"` (`display: none` drops it from the tab order and
+ * the a11y tree) or with `aria-hidden`/`tabIndex={-1}`. The visible label
+ * carries the focus ring via `peer-focus-visible:`. `a11yConventions.test.js`
+ * enforces this repo-wide.
+ *
+ * The input's value is cleared after every change — deferred until an async
+ * `onChange` settles, since clearing `value` also empties `input.files` — so
+ * re-picking the SAME file fires `change` again (otherwise a failed upload
+ * can't be retried by re-selecting the same file). Call sites must NOT clear
+ * `e.target.value` themselves.
+ *
+ * Extra props are spread onto the visible `<label>`, and the forwarded ref
+ * points at it — that is what lets a drop zone pass `onDrop`/`onDragOver` and
+ * still get native picker activation from a click.
+ *
+ * @param {Object} props
+ * @param {(e: React.ChangeEvent<HTMLInputElement>) => void} props.onChange - change handler; `e.target.files` holds the picked files
+ * @param {React.ReactNode} props.children - label content (icon + text)
+ * @param {string} [props.accept] - `accept` attribute for the input
+ * @param {boolean} [props.multiple] - allow multi-select
+ * @param {boolean} [props.disabled] - disable the control
+ * @param {string} [props.className] - classes for the visible label
+ * @param {string} [props.ariaLabel] - accessible name. Omit it when the visible
+ * text already says enough; supply it to disambiguate a bare "Upload" among
+ * several on one screen. It OVERRIDES the label text, so per WCAG 2.5.3
+ * (Label in Name) it must CONTAIN the visible text — "Upload artist portrait"
+ * for a button reading "Upload" is fine; "Browse files to upload" for one
+ * reading "Browse Files" is not, and strands voice-control users.
+ * @param {string} [props.id] - explicit input id (defaults to a generated one)
+ * @param {string} [props.name] - input name
+ */
+const FilePickerButton = forwardRef(function FilePickerButton({
+ onChange,
+ children,
+ accept,
+ multiple = false,
+ disabled = false,
+ className = '',
+ ariaLabel,
+ id,
+ name,
+ ...labelProps
+}, ref) {
+ const generatedId = useId();
+ const inputId = id || `file-picker-${generatedId}`;
+
+ const handleChange = (e) => {
+ const input = e.target;
+ const reset = () => { input.value = ''; };
+ // Promise.resolve() normalizes sync and async handlers alike: a handler
+ // that awaits before reading `input.files` must finish before the clear.
+ // Settle on BOTH outcomes rather than `.finally()` — nothing else consumes
+ // the handler's promise, so a rethrow here becomes an unhandled rejection.
+ // Call sites own their own error reporting (they all toast in a `.catch`).
+ Promise.resolve(onChange?.(e)).then(reset, reset);
+ };
+
+ return (
+ <>
+ <input
+ id={inputId}
+ name={name}
+ type="file"
+ accept={accept}
+ multiple={multiple}
+ disabled={disabled}
+ onChange={handleChange}
+ aria-label={ariaLabel}
+ className="sr-only peer"
+ />
+ <label
+ {...labelProps}
+ ref={ref}
+ htmlFor={inputId}
+ className={`${className} ${disabled ? DISABLED_CLS : 'cursor-pointer'} ${FOCUS_RING}`}
+ >
+ {children}
+ </label>
+ </>
+ );
+});
+
+export default FilePickerButton;
diff --git a/client/src/components/ui/FilePickerButton.test.jsx b/client/src/components/ui/FilePickerButton.test.jsx
new file mode 100644
index 0000000000..4fb9b22450
--- /dev/null
+++ b/client/src/components/ui/FilePickerButton.test.jsx
@@ -0,0 +1,95 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import FilePickerButton from './FilePickerButton';
+
+const pick = (input, files) => {
+ Object.defineProperty(input, 'files', { value: files, configurable: true });
+ fireEvent.change(input);
+};
+
+const file = (name) => new File(['x'], name, { type: 'image/png' });
+
+describe('FilePickerButton', () => {
+ it('renders a label bound to the file input so the picker opens natively', () => {
+ render(<FilePickerButton onChange={vi.fn()} ariaLabel="Add screenshots">Screenshot</FilePickerButton>);
+ const input = screen.getByLabelText('Add screenshots');
+ expect(input.tagName).toBe('INPUT');
+ expect(input.type).toBe('file');
+ // The visible trigger must be a <label for> pointing at the input — a
+ // programmatic .click() on a hidden input is what breaks in WebKit/PWA.
+ const label = screen.getByText('Screenshot');
+ expect(label.tagName).toBe('LABEL');
+ expect(label.getAttribute('for')).toBe(input.id);
+ });
+
+ it('keeps the input reachable by keyboard and assistive tech', () => {
+ render(<FilePickerButton onChange={vi.fn()} ariaLabel="Add screenshots">Screenshot</FilePickerButton>);
+ const input = screen.getByLabelText('Add screenshots');
+ expect(input.getAttribute('aria-hidden')).toBeNull();
+ expect(input.getAttribute('tabindex')).toBeNull();
+ });
+
+ it('passes accept/multiple through to the input', () => {
+ render(<FilePickerButton onChange={vi.fn()} accept="image/*" multiple ariaLabel="Pick">Pick</FilePickerButton>);
+ const input = screen.getByLabelText('Pick');
+ expect(input.getAttribute('accept')).toBe('image/*');
+ expect(input.multiple).toBe(true);
+ });
+
+ it('clears the input after a sync handler so the same file can be re-picked', () => {
+ const onChange = vi.fn();
+ render(<FilePickerButton onChange={onChange} ariaLabel="Pick">Pick</FilePickerButton>);
+ const input = screen.getByLabelText('Pick');
+ pick(input, [file('a.png')]);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(input.value).toBe('');
+ });
+
+ it('waits for an async handler to settle before clearing the input', async () => {
+ let release;
+ const seen = [];
+ const onChange = vi.fn((e) => new Promise((resolve) => {
+ release = () => { seen.push(e.target.files.length); resolve(); };
+ }));
+ render(<FilePickerButton onChange={onChange} multiple ariaLabel="Pick">Pick</FilePickerButton>);
+ const input = screen.getByLabelText('Pick');
+ pick(input, [file('a.png'), file('b.png')]);
+ // Still readable mid-flight — clearing `value` would empty `files`.
+ release();
+ await Promise.resolve();
+ expect(seen).toEqual([2]);
+ });
+
+ it('clears the input on a rejecting handler without an unhandled rejection', () => {
+ // The wrapper is the only consumer of the handler's promise, so it must
+ // settle both outcomes — letting the rejection escape would surface as an
+ // unhandled rejection in the browser console (and fail the client suite).
+ const unhandled = vi.fn();
+ process.on('unhandledRejection', unhandled);
+ const onChange = vi.fn(() => Promise.reject(new Error('nope')));
+ render(<FilePickerButton onChange={onChange} ariaLabel="Pick">Pick</FilePickerButton>);
+ const input = screen.getByLabelText('Pick');
+ pick(input, [file('a.png')]);
+ return new Promise((resolve) => setTimeout(resolve, 0)).then(() => {
+ process.off('unhandledRejection', unhandled);
+ expect(unhandled).not.toHaveBeenCalled();
+ expect(input.value).toBe('');
+ });
+ });
+
+ it('disables the input and blocks pointer events on the label when disabled', () => {
+ render(<FilePickerButton onChange={vi.fn()} disabled ariaLabel="Pick">Pick</FilePickerButton>);
+ expect(screen.getByLabelText('Pick').disabled).toBe(true);
+ expect(screen.getByText('Pick').className).toContain('pointer-events-none');
+ });
+
+ it('gives each instance a distinct input id so labels do not cross-wire', () => {
+ render(
+ <>
+ <FilePickerButton onChange={vi.fn()} ariaLabel="First">One</FilePickerButton>
+ <FilePickerButton onChange={vi.fn()} ariaLabel="Second">Two</FilePickerButton>
+ </>
+ );
+ expect(screen.getByLabelText('First').id).not.toBe(screen.getByLabelText('Second').id);
+ });
+});
diff --git a/client/src/components/universe/VisionDescribeModal.jsx b/client/src/components/universe/VisionDescribeModal.jsx
index 04f313392f..f19d9344e5 100644
--- a/client/src/components/universe/VisionDescribeModal.jsx
+++ b/client/src/components/universe/VisionDescribeModal.jsx
@@ -17,9 +17,10 @@
* `onApplyFields(patch)`, and lets the parent write them into the entry.
*/
-import { useState, useCallback, useRef } from 'react';
+import { useState, useCallback } from 'react';
import { Loader2, ImagePlus, Images, Sparkles, X } from 'lucide-react';
import Modal from '../ui/Modal';
+import FilePickerButton from '../ui/FilePickerButton';
import toast from '../ui/Toast';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import VisionProviderPicker from './VisionProviderPicker';
@@ -59,7 +60,6 @@ export default function VisionDescribeModal({
const [fieldEdits, setFieldEdits] = useState({});
// Optional "known context" the user can type to disambiguate the subject.
const [context, setContext] = useState('');
- const fileInputRef = useRef(null);
// Current vision provider/model selection, lifted from VisionProviderPicker.
const [vision, setVision] = useState({ providerId: '', model: '', hasProviders: false, noVisionModel: false });
@@ -231,14 +231,6 @@ export default function VisionDescribeModal({
{/* Image picker + thumbnails */}
<div>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- multiple
- className="hidden"
- onChange={(e) => { handleFiles(e.target.files); e.target.value = ''; }}
- />
<div className="flex flex-wrap gap-2">
{images.map((img) => (
<div key={imageKey(img)} className="relative w-20 h-20">
@@ -260,15 +252,17 @@ export default function VisionDescribeModal({
))}
{images.length < MAX_IMAGES ? (
<>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ multiple
+ onChange={(e) => handleFiles(e.target.files)}
disabled={uploading}
- className="w-20 h-20 flex flex-col items-center justify-center gap-1 rounded border border-dashed border-port-border text-gray-500 hover:text-port-accent hover:border-port-accent/50 disabled:opacity-50"
+ ariaLabel="Upload reference images"
+ className="w-20 h-20 flex flex-col items-center justify-center gap-1 rounded border border-dashed border-port-border text-gray-500 hover:text-port-accent hover:border-port-accent/50"
>
{uploading ? <Loader2 size={16} className="animate-spin" /> : <ImagePlus size={16} />}
<span className="text-[10px]">Upload</span>
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
diff --git a/client/src/components/videoGen/AudioPanel.jsx b/client/src/components/videoGen/AudioPanel.jsx
index 39169edf06..376fb132ac 100644
--- a/client/src/components/videoGen/AudioPanel.jsx
+++ b/client/src/components/videoGen/AudioPanel.jsx
@@ -7,6 +7,7 @@
*/
import { Upload, Music } from 'lucide-react';
import { formatBytes } from '../../utils/formatters';
+import FilePickerButton from '../ui/FilePickerButton';
export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleModel, onPick, onClear }) {
return (
@@ -24,16 +25,14 @@ export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleMod
<span className="text-gray-500">{formatBytes(audioFile.size, 2)}</span>
</div>
) : (
- <label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">
+ <FilePickerButton
+ accept="audio/*"
+ onChange={(e) => onPick(e.target.files?.[0] || null)}
+ className="flex items-center gap-2 text-[11px] text-gray-400 hover:text-white"
+ >
<Upload className="w-3.5 h-3.5" />
<span className="truncate">Upload audio (WAV / MP3 / M4A)</span>
- <input
- type="file"
- accept="audio/*"
- onChange={(e) => onPick(e.target.files?.[0] || null)}
- className="hidden"
- />
- </label>
+ </FilePickerButton>
)}
<p className="text-[10px] text-gray-500 leading-snug">
Audio length should match {`${(numFrames / fps).toFixed(1)}s`} (frames ÷ fps). Longer clips are trimmed to fit; shorter clips fail.
diff --git a/client/src/components/videoGen/FramePanel.jsx b/client/src/components/videoGen/FramePanel.jsx
index 00af183285..55f525f6a2 100644
--- a/client/src/components/videoGen/FramePanel.jsx
+++ b/client/src/components/videoGen/FramePanel.jsx
@@ -10,6 +10,7 @@
* gallery change).
*/
import { Upload } from 'lucide-react';
+import FilePickerButton from '../ui/FilePickerButton';
import ImagePreview from './ImagePreview';
export default function FramePanel({
@@ -59,16 +60,14 @@ export default function FramePanel({
<option key={img.filename} value={img.filename}>{img.filename}</option>
))}
</select>
- <label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">
+ <FilePickerButton
+ accept="image/*"
+ onChange={(e) => onUpload(e.target.files?.[0] || null)}
+ className="flex items-center gap-2 text-[11px] text-gray-400 hover:text-white"
+ >
<Upload className="w-3.5 h-3.5" />
<span className="truncate">Upload an image</span>
- <input
- type="file"
- accept="image/*"
- onChange={(e) => onUpload(e.target.files?.[0] || null)}
- className="hidden"
- />
- </label>
+ </FilePickerButton>
</div>
)}
{advisoryNote && (
diff --git a/client/src/hooks/useOpenClawAttachments.js b/client/src/hooks/useOpenClawAttachments.js
index b9ecd13088..4c3eb9914e 100644
--- a/client/src/hooks/useOpenClawAttachments.js
+++ b/client/src/hooks/useOpenClawAttachments.js
@@ -17,6 +17,19 @@ const ALLOWED_ATTACHMENT_MIME_TYPES = new Set([
]);
const ALLOWED_ATTACHMENT_EXTENSIONS = new Set(['.txt', '.md', '.json', '.csv', '.pdf']);
+/**
+ * `accept` for the composer's file picker, derived from the same allowlists
+ * `isAllowedAttachmentType` enforces — so the picker can never offer a file the
+ * hook then rejects (or hide one it would have taken). Extensions AND MIME
+ * types, because iOS/iPadOS pickers only understand the latter and grey out
+ * everything given an extension-only filter.
+ */
+export const OPENCLAW_ATTACHMENT_ACCEPT = [
+ ...ALLOWED_ATTACHMENT_MIME_PREFIXES.map((p) => `${p}*`),
+ ...ALLOWED_ATTACHMENT_MIME_TYPES,
+ ...ALLOWED_ATTACHMENT_EXTENSIONS
+].join(',');
+
function getAttachmentKind(file) {
return file.type.startsWith('image/') ? 'image' : 'file';
}
@@ -59,7 +72,6 @@ export function useOpenClawAttachments({ sending, onError = () => {} } = {}) {
const [attachments, setAttachments] = useState([]);
const [isDragActive, setIsDragActive] = useState(false);
const dragCounterRef = useRef(0);
- const fileInputRef = useRef(null);
const attachmentsRef = useRef(attachments);
useEffect(() => {
@@ -147,7 +159,6 @@ export function useOpenClawAttachments({ sending, onError = () => {} } = {}) {
const handleAttachmentSelect = async (event) => {
const files = Array.from(event.target.files || []);
await appendFiles(files);
- event.target.value = '';
};
const handlePaste = async (event) => {
@@ -199,7 +210,6 @@ export function useOpenClawAttachments({ sending, onError = () => {} } = {}) {
attachments,
setAttachments,
isDragActive,
- fileInputRef,
appendFiles,
removeAttachment,
handleAttachmentSelect,
diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsx
index a040182959..3bc69d0407 100644
--- a/client/src/pages/Authors.jsx
+++ b/client/src/pages/Authors.jsx
@@ -14,6 +14,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { FilePen, Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import useMediaJobProgress from '../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
@@ -79,7 +80,6 @@ export default function Authors() {
// completes. External SD-API renders synchronously and never sets genJobId.
const [startingGen, setStartingGen] = useState(false);
const [genJobId, setGenJobId] = useState(null);
- const fileInputRef = useRef(null);
// Bumped on every author switch / new-author. A generate request captures
// this before its POST and bails if it changed by the time the POST resolves
// — closes the pre-jobId round-trip window where `clearGeneration` alone
@@ -151,7 +151,6 @@ export default function Authors() {
const handleHeadshotFile = async (e) => {
const file = e.target.files?.[0];
- if (e.target) e.target.value = ''; // allow re-picking the same file
if (!file) return;
if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
if (file.size > HEADSHOT_MAX_BYTES) {
@@ -425,15 +424,16 @@ export default function Authors() {
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
Generate
</button>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ onChange={handleHeadshotFile}
disabled={uploadingHeadshot || isGenerating}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ ariaLabel="Upload author headshot"
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
>
{uploadingHeadshot ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
Upload
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
@@ -442,13 +442,6 @@ export default function Authors() {
>
<ImageIcon size={14} /> Choose from gallery
</button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- onChange={handleHeadshotFile}
- className="hidden"
- />
</div>
<input
value={form.headshotImageUrl}
diff --git a/client/src/pages/Authors.test.jsx b/client/src/pages/Authors.test.jsx
index a562a1287c..37e5e17987 100644
--- a/client/src/pages/Authors.test.jsx
+++ b/client/src/pages/Authors.test.jsx
@@ -136,7 +136,9 @@ describe('Authors headshot generation', () => {
// The async job is in flight — a manual headshot change would be clobbered
// on completion, so Upload / gallery / URL are locked until it settles.
- expect(screen.getByRole('button', { name: 'Upload' }).disabled).toBe(true);
+ // Upload is a <label> + file input (native picker activation) — matched by
+ // its accessible label rather than a button role.
+ expect(screen.getByLabelText('Upload author headshot').disabled).toBe(true);
expect(screen.getByRole('button', { name: 'Choose from gallery' }).disabled).toBe(true);
expect(screen.getByPlaceholderText(/https:/i).disabled).toBe(true);
});
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 4d8b209a87..eaf85eec70 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -9,6 +9,7 @@ import { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
import socket from '../services/socket';
import { startMemoRecording } from '../lib/audioRecorder';
import {
@@ -88,7 +89,6 @@ export default function CatalogIngest() {
const [url, setUrl] = useState('');
const [recording, setRecording] = useState(false);
const recorderRef = useRef(null);
- const fileInputRef = useRef(null);
const brainHandledRef = useRef(false);
// Creative inbox note ids handed off from the Brain batch-send. Once the
// commit below succeeds we stamp these consumed so they drop out of the
@@ -267,7 +267,6 @@ export default function CatalogIngest() {
const handleFilePicked = async (e) => {
const file = e.target.files?.[0];
- e.target.value = ''; // allow re-picking the same file
if (!file) return;
const name = (file.name || '').toLowerCase();
if (name.endsWith('.pdf')) {
@@ -515,12 +514,11 @@ export default function CatalogIngest() {
className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border ${sourceMode === 'url' ? 'border-port-accent text-white bg-port-accent/10' : 'border-port-border text-gray-300 hover:text-white'}`}>
<Link2 size={14} aria-hidden="true" /> URL
</button>
- <button type="button" onClick={() => fileInputRef.current?.click()} disabled={submitting}
- className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white disabled:opacity-50">
+ <FilePickerButton accept=".txt,.md,.markdown,text/plain,text/markdown"
+ onChange={handleFilePicked} disabled={submitting} ariaLabel="Ingest a text or markdown file"
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white">
<FileText size={14} aria-hidden="true" /> File
- </button>
- <input ref={fileInputRef} type="file" accept=".txt,.md,.markdown,text/plain,text/markdown"
- onChange={handleFilePicked} className="hidden" aria-hidden="true" tabIndex={-1} />
+ </FilePickerButton>
{!recording ? (
<button type="button" onClick={startRecording} disabled={submitting}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white disabled:opacity-50">
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 09d65dca41..952647d16d 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -9,6 +9,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown, Upload, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
import Modal from '../components/ui/Modal.jsx';
import {
getCatalogIngredientDetails,
@@ -1087,7 +1088,6 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
const [dragOver, setDragOver] = useState(false);
const [busy, setBusy] = useState(false); // upload or transcription in flight
const [recording, setRecording] = useState(false);
- const fileInputRef = useRef(null);
const recorderRef = useRef(null);
const list = Array.isArray(media) ? media : [];
const portrait = list.find((m) => m.kind === 'portrait');
@@ -1116,7 +1116,6 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
const onFilePicked = (e) => {
const file = e.target.files?.[0];
- e.target.value = ''; // allow re-picking the same file
if (file) doUpload(file);
};
@@ -1158,10 +1157,10 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
<Plus size={12} aria-hidden="true" /> Pick from gallery
</button>
- <button type="button" onClick={() => fileInputRef.current?.click()} disabled={busy || recording}
- className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40">
+ <FilePickerButton accept="image/*,audio/*,video/*" onChange={onFilePicked} disabled={busy || recording}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
<Upload size={12} aria-hidden="true" /> Upload file
- </button>
+ </FilePickerButton>
{!recording ? (
<button type="button" onClick={startRecording} disabled={busy}
className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40">
@@ -1173,7 +1172,6 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
<Square size={12} aria-hidden="true" /> Stop &amp; transcribe
</button>
)}
- <input ref={fileInputRef} type="file" accept="image/*,audio/*,video/*" onChange={onFilePicked} className="hidden" />
</div>
</div>
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsx
index 2d42e3b50d..65556482f2 100644
--- a/client/src/pages/ImageClean.jsx
+++ b/client/src/pages/ImageClean.jsx
@@ -1,6 +1,8 @@
import { useState, useRef, useCallback, useEffect } from 'react';
import { Eraser, Upload, Download, ShieldCheck, Sparkles, Brush, Square, Undo2, X, Cpu, Zap, Save } from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
+import { IMAGE_ACCEPT } from '../utils/fileUpload';
import BrailleSpinner from '../components/BrailleSpinner';
import IgnoreZonePainter from '../components/media/IgnoreZonePainter';
import * as api from '../services/api';
@@ -58,7 +60,6 @@ export default function ImageClean() {
const [feather, setFeather] = useState(3);
const [hasMask, setHasMask] = useState(false);
const painterRef = useRef(null);
- const fileInputRef = useRef(null);
const requestIdRef = useRef(0);
const previewUrlRef = useRef(null);
const resultUrlRef = useRef(null);
@@ -313,9 +314,6 @@ export default function ImageClean() {
URL.revokeObjectURL(resultUrlRef.current);
resultUrlRef.current = null;
}
- // Clear the input so picking the same file again still fires onChange
- // (browsers suppress onChange when the value is unchanged).
- if (fileInputRef.current) fileInputRef.current.value = '';
setOriginal(null);
setResult(null);
setBusy(false);
@@ -416,30 +414,18 @@ export default function ImageClean() {
onDragOver={handleDrag}
onDrop={handleDrop}
>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/png,image/jpeg,image/webp"
- onChange={(e) => {
- const file = e.target.files?.[0];
- e.target.value = '';
- handleFile(file);
- }}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
<Upload size={40} className={`mx-auto mb-4 ${dragActive ? 'text-port-accent' : 'text-gray-500'}`} />
<p className="text-white mb-2">
{dragActive ? 'Drop image here' : 'Drag and drop an image here'}
</p>
<p className="text-gray-500 text-sm mb-4">PNG, JPEG, or WebP</p>
- <button
- onClick={() => fileInputRef.current?.click()}
- className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"
+ <FilePickerButton
+ accept={IMAGE_ACCEPT}
+ onChange={(e) => handleFile(e.target.files?.[0])}
+ className="inline-block px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"
>
Browse File
- </button>
+ </FilePickerButton>
</div>
)}
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index fdbaf7af6c..4775887c93 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -7,12 +7,14 @@
* single source of truth; rendering images poll-refresh until they land.
*/
-import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
+import { useState, useEffect, useMemo, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace, Lightbulb, Eraser,
} from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
+import { IMAGE_ACCEPT } from '../utils/fileUpload';
import Modal from '../components/ui/Modal';
import { useSseProgress } from '../hooks/useSseProgress';
import DatasetImageGrid from '../components/loraTraining/DatasetImageGrid';
@@ -290,7 +292,6 @@ export default function LoraDatasetDetail() {
// unsaved caption drafts the rewrite superseded — otherwise a stale draft
// blur-saves the old text back, undoing the strip.
const [captionDraftResetToken, setCaptionDraftResetToken] = useState(0);
- const fileInputRef = useRef(null);
const refresh = useCallback(() => getLoraDataset(datasetId)
.then((d) => { setDataset(d); return d; })
@@ -437,7 +438,6 @@ export default function LoraDatasetDetail() {
toast.success(`Added ${images.length} image${images.length === 1 ? '' : 's'}`);
} finally {
setUploading(false);
- e.target.value = '';
}
};
@@ -564,14 +564,16 @@ export default function LoraDatasetDetail() {
>
<Wand2 className="w-4 h-4" /> Generate
</button>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept={IMAGE_ACCEPT}
+ multiple
+ onChange={onUpload}
disabled={uploading}
- className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"
+ ariaLabel="Upload dataset images"
+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2"
>
{uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />} Upload
- </button>
+ </FilePickerButton>
<button
type="button"
onClick={() => setShowImport(true)}
@@ -579,14 +581,6 @@ export default function LoraDatasetDetail() {
>
<Images className="w-4 h-4" /> From gallery
</button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/png,image/jpeg,image/webp"
- multiple
- className="hidden"
- onChange={onUpload}
- />
<button
type="button"
onClick={() => setShowSlice(true)}
diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsx
index 9cfd5c6302..62aa0e4390 100644
--- a/client/src/pages/OpenClaw.jsx
+++ b/client/src/pages/OpenClaw.jsx
@@ -32,11 +32,12 @@ import {
ClipboardPaste
} from 'lucide-react';
import AppContextPicker from '../components/AppContextPicker';
+import FilePickerButton from '../components/ui/FilePickerButton';
import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';
import * as api from '../services/apiOpenClaw';
import * as coreApi from '../services/api';
import { formatDateTime } from '../utils/formatters';
-import { useOpenClawAttachments } from '../hooks/useOpenClawAttachments';
+import { useOpenClawAttachments, OPENCLAW_ATTACHMENT_ACCEPT } from '../hooks/useOpenClawAttachments';
import { useOpenClawStream } from '../hooks/useOpenClawStream';
function getRuntimeState(status) {
@@ -140,7 +141,6 @@ export default function OpenClaw() {
attachments,
setAttachments,
isDragActive,
- fileInputRef,
removeAttachment,
handleAttachmentSelect,
handlePaste,
@@ -632,15 +632,16 @@ export default function OpenClaw() {
<span>
{status?.configured && selectedSessionId ? 'Stream via PortOS · ⌘↵ / Ctrl↵ to send' : 'Select a configured session to send.'}
</span>
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ multiple
+ accept={OPENCLAW_ATTACHMENT_ACCEPT}
+ onChange={handleAttachmentSelect}
disabled={!status?.configured || !selectedSessionId || sending}
- className="inline-flex items-center gap-2 rounded-lg border border-port-border bg-port-card px-3 py-2 text-xs text-gray-200 hover:border-gray-500 hover:text-white disabled:cursor-not-allowed disabled:opacity-60"
+ className="inline-flex items-center gap-2 rounded-lg border border-port-border bg-port-card px-3 py-2 text-xs text-gray-200 hover:border-gray-500 hover:text-white"
>
<Paperclip size={14} />
Add file/image
- </button>
+ </FilePickerButton>
</div>
<div className="flex items-center gap-2">
{sending && (
@@ -664,14 +665,6 @@ export default function OpenClaw() {
</div>
</div>
- <input
- ref={fileInputRef}
- type="file"
- multiple
- accept="image/*,.txt,.md,.json,.csv,.pdf"
- className="hidden"
- onChange={handleAttachmentSelect}
- />
</form>
</section>
</div>
diff --git a/client/src/pages/RunnerPage.jsx b/client/src/pages/RunnerPage.jsx
index a03ea6cdd1..5bb81f0553 100644
--- a/client/src/pages/RunnerPage.jsx
+++ b/client/src/pages/RunnerPage.jsx
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Clock, Image, X, Info } from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
import * as api from '../services/api';
import socket from '../services/socket';
import { processScreenshotUploads } from '../utils/fileUpload';
@@ -26,7 +27,6 @@ export function RunnerPage() {
const [allowedCommands, setAllowedCommands] = useState([]);
const [screenshots, setScreenshots] = useState([]);
const [continueContext, setContinueContext] = useState(null);
- const fileInputRef = useRef(null);
const outputRef = useRef(null);
const continueWorkspaceRef = useRef(location.state?.continueFrom?.workspacePath ?? null);
@@ -235,7 +235,6 @@ ${prompt.trim()}`;
onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
onError: (msg) => toast.error(msg)
});
- e.target.value = '';
};
const removeScreenshot = (id) => {
@@ -395,23 +394,16 @@ ${prompt.trim()}`;
</div>
{/* Screenshot Upload */}
- <button
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ accept="image/*"
+ multiple
+ onChange={handleFileSelect}
+ ariaLabel="Add screenshots"
className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm"
>
<Image size={16} />
Add Screenshot
- </button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- multiple
- onChange={handleFileSelect}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
+ </FilePickerButton>
</>
)}
</div>
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 711934b112..f030c182d7 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -30,6 +30,7 @@ import {
ExternalLink, Paperclip, Upload, FileX2,
} from 'lucide-react';
import toast from '../components/ui/Toast';
+import FilePickerButton from '../components/ui/FilePickerButton';
import PageHeader from '../components/PageHeader';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';
@@ -50,18 +51,12 @@ import { VOICING_INSTRUMENTS, toVoicingInstrument } from '../lib/chordShapes.js'
import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
import { formatBytes } from '../utils/formatters';
import { isHttpUrl } from '../utils/urlNormalize';
-import { readFileAsBase64 } from '../utils/fileUpload';
+import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload';
import {
getSong, updateSong, deleteSong,
listSongAttachments, uploadSongAttachment, deleteSongAttachment, songAttachmentUrl,
} from '../services/api';
-// Mirrors MAX_ATTACHMENT_SIZE in server/routes/brainSongbook.js — 40MB, the
-// largest raw payload that survives base64 ×4/3 inflation under the server's
-// 55mb express.json limit. Deliberately NOT utils/fileUpload's
-// ATTACHMENT_MAX_FILE_SIZE (50MB) — other surfaces still use that cap.
-const SONGBOOK_MAX_FILE_SIZE = 40 * 1024 * 1024;
-
const TRANSPOSE_MIN = -11;
const TRANSPOSE_MAX = 11;
const FONT_MIN = 0.625;
@@ -260,11 +255,10 @@ export default function SongBookViewer() {
), [confirmDelete, id, navigate]);
// --- Attachments
- const fileInputRef = useRef(null);
const [uploadFiles, uploading] = useAsyncAction(async (files) => {
for (const file of Array.from(files)) {
- if (file.size > SONGBOOK_MAX_FILE_SIZE) {
- toast.error(`"${file.name}" exceeds ${Math.round(SONGBOOK_MAX_FILE_SIZE / 1024 / 1024)}MB limit`);
+ if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) {
+ toast.error(`"${file.name}" exceeds the ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)} limit`);
continue;
}
const data = await readFileAsBase64(file);
@@ -617,23 +611,16 @@ export default function SongBookViewer() {
Attachments
</h2>
<div>
- <input
- ref={fileInputRef}
- type="file"
+ <FilePickerButton
multiple
- className="hidden"
- aria-label="Upload attachment"
- onChange={(e) => { if (e.target.files?.length) uploadFiles(e.target.files); e.target.value = ''; }}
- />
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
+ onChange={(e) => uploadFiles(e.target.files)}
disabled={uploading}
- className="flex items-center gap-1.5 px-3 py-2 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"
+ ariaLabel="Upload attachment"
+ className="flex items-center gap-1.5 px-3 py-2 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"
>
<Upload size={13} />
{uploading ? 'Uploading…' : 'Upload'}
- </button>
+ </FilePickerButton>
</div>
</div>
{attachments === null ? (
diff --git a/client/src/pages/Uploads.jsx b/client/src/pages/Uploads.jsx
index 3a5f4de1a7..ad16282aeb 100644
--- a/client/src/pages/Uploads.jsx
+++ b/client/src/pages/Uploads.jsx
@@ -1,11 +1,13 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { Upload, Trash2, Download, FileText, Image, File, FolderOpen, RefreshCw } from 'lucide-react';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
-import { formatDateTime } from '../utils/formatters';
+import { formatDateTime, formatBytes } from '../utils/formatters';
import toast from '../components/ui/Toast';
import PageSkeleton from '../components/ui/PageSkeleton';
+import FilePickerButton from '../components/ui/FilePickerButton';
import * as api from '../services/api';
+import { JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload';
// File type icons based on MIME type
function getFileIcon(mimeType) {
@@ -29,7 +31,6 @@ export default function Uploads() {
const [dragActive, setDragActive] = useState(false);
const [confirmingDeleteAll, setConfirmingDeleteAll] = useState(false);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
- const fileInputRef = useRef(null);
const fetchUploads = useCallback(async () => {
const data = await api.listUploads({ silent: true }).catch(err => {
@@ -52,9 +53,8 @@ export default function Uploads() {
const fileArray = Array.from(files);
for (const file of fileArray) {
- // Check file size (100MB limit)
- if (file.size > 100 * 1024 * 1024) {
- toast.error(`File "${file.name}" exceeds 100MB limit`);
+ if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) {
+ toast.error(`File "${file.name}" exceeds the ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)} limit`);
continue;
}
@@ -198,31 +198,22 @@ export default function Uploads() {
onDragOver={handleDrag}
onDrop={handleDrop}
>
- <input
- ref={fileInputRef}
- type="file"
- multiple
- onChange={(e) => handleFileUpload(e.target.files)}
- className="sr-only"
- tabIndex={-1}
- aria-hidden="true"
- />
-
<Upload size={40} className={`mx-auto mb-4 ${dragActive ? 'text-port-accent' : 'text-gray-500'}`} />
<p className="text-white mb-2">
{dragActive ? 'Drop files here' : 'Drag and drop files here'}
</p>
<p className="text-gray-500 text-sm mb-4">or</p>
- <button
- onClick={() => fileInputRef.current?.click()}
+ <FilePickerButton
+ multiple
disabled={uploading}
- className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors disabled:opacity-50"
+ onChange={(e) => handleFileUpload(e.target.files)}
+ className="inline-block px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"
>
{uploading ? 'Uploading...' : 'Browse Files'}
- </button>
+ </FilePickerButton>
<p className="text-gray-500 text-xs mt-4">
- Maximum file size: 100MB
+ Maximum file size: {formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}
</p>
</div>
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index b423fe91aa..fef651c77b 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -53,7 +53,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `fileUpload` | Screenshot/attachment upload helpers: base64 read plus `processScreenshotUploads` / `processAttachmentUploads` and their single-file variants. |
+| `fileUpload` | Screenshot/attachment upload helpers: base64 read plus `processScreenshotUploads` / `processAttachmentUploads` and their single-file variants. Also the shared upload constants — `JSON_UPLOAD_MAX_FILE_SIZE` (max file size / wire limit, mirrors `server/lib/uploadLimits.js`), `ATTACHMENT_MAX_FILE_SIZE`, `ALLOWED_ATTACHMENT_EXTENSIONS`, and the `accept` strings `ATTACHMENT_ACCEPT` / `IMAGE_ACCEPT`. |
## CyberCity — character & avatar
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
index bda5aaf2c8..e5930666d9 100644
--- a/client/src/utils/fileUpload.js
+++ b/client/src/utils/fileUpload.js
@@ -4,9 +4,10 @@
*/
import * as api from '../services/api';
+import { formatBytes } from './formatters';
// Allowed attachment extensions (should match server)
-const ALLOWED_ATTACHMENT_EXTENSIONS = [
+export const ALLOWED_ATTACHMENT_EXTENSIONS = [
'.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg',
'.pdf',
@@ -14,6 +15,46 @@ const ALLOWED_ATTACHMENT_EXTENSIONS = [
'.zip', '.tar', '.gz'
];
+/**
+ * `accept` value for attachment pickers.
+ *
+ * Extensions alone are not enough: iOS/iPadOS pickers only understand MIME
+ * types and UTIs, so an extension-only `accept` greys out every file in the
+ * Files app — the picker opens but nothing can be selected. Pairing the
+ * extensions with the corresponding MIME types keeps desktop filtering precise
+ * while leaving mobile pickers usable. `processAttachmentUploads` still
+ * validates by extension, so a broader picker filter can't widen what uploads.
+ */
+export const ATTACHMENT_ACCEPT = [
+ ...ALLOWED_ATTACHMENT_EXTENSIONS,
+ 'text/*',
+ 'image/*',
+ 'application/pdf',
+ 'application/json',
+ 'application/zip',
+ 'application/gzip',
+ 'application/x-tar'
+].join(',');
+
+/**
+ * Largest raw file the server can accept. Every helper here POSTs its payload
+ * base64-encoded inside a JSON body, so the express body limit is the real
+ * ceiling — advertising anything larger just produces an opaque 413.
+ *
+ * Mirror of `MAX_BASE64_UPLOAD_BYTES` in `server/lib/uploadLimits.js`, which
+ * owns the derivation and the rationale (the client can't import server
+ * modules). Change it there first.
+ */
+export const JSON_UPLOAD_MAX_FILE_SIZE = 41 * 1024 * 1024;
+
+/**
+ * `accept` for the raster-image pickers (reference images, init images, LoRA
+ * dataset uploads, sprite seeds, ImageClean). These are all fed to image-gen
+ * backends that decode PNG/JPEG/WebP only — a broader `image/*` would let a
+ * HEIC or SVG through to a confusing server-side failure.
+ */
+export const IMAGE_ACCEPT = 'image/png,image/jpeg,image/webp';
+
// Default max file size: 10MB
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -60,8 +101,7 @@ export async function processScreenshotUploads(files, options = {}) {
// Check file size
if (file.size > maxFileSize) {
- const sizeMB = Math.round(maxFileSize / (1024 * 1024));
- onError?.(`File "${file.name}" exceeds ${sizeMB}MB limit`);
+ onError?.(`File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`);
continue;
}
@@ -128,8 +168,9 @@ export async function uploadScreenshotFile(file, options = {}) {
});
}
-// Max file size for attachments: 50MB
-export const ATTACHMENT_MAX_FILE_SIZE = 50 * 1024 * 1024;
+// Max file size for attachments. Capped by the base64-in-JSON wire limit, not
+// by any attachment-specific rule — see JSON_UPLOAD_MAX_FILE_SIZE.
+export const ATTACHMENT_MAX_FILE_SIZE = JSON_UPLOAD_MAX_FILE_SIZE;
/**
* Check if a file extension is allowed for attachments
@@ -162,7 +203,7 @@ function isImageFile(filename) {
*
* @param {FileList|File[]} files - Files to process
* @param {Object} options - Upload options
- * @param {number} options.maxFileSize - Max file size in bytes (default: 50MB)
+ * @param {number} options.maxFileSize - Max file size in bytes (default: ATTACHMENT_MAX_FILE_SIZE)
* @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)
* @param {Function} options.onError - Callback for errors (receives error message)
* @returns {Promise<void>}
@@ -186,8 +227,7 @@ export async function processAttachmentUploads(files, options = {}) {
// Check file size
if (file.size > maxFileSize) {
- const sizeMB = Math.round(maxFileSize / (1024 * 1024));
- onError?.(`File "${file.name}" exceeds ${sizeMB}MB limit`);
+ onError?.(`File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`);
continue;
}
diff --git a/server/index.js b/server/index.js
index 2a194eb07b..781e207bc6 100644
--- a/server/index.js
+++ b/server/index.js
@@ -141,6 +141,7 @@ import { initSocket } from './services/socket.js';
import { bootstrapServices, runBootSequence, registerShutdownHandlers } from './services/bootstrap.js';
import { errorMiddleware } from './lib/errorHandler.js';
import { setHttpsEnabledAtBoot } from './lib/httpsState.js';
+import { JSON_BODY_LIMIT } from './lib/uploadLimits.js';
import { wrWorksDir } from './services/writersRoom/_shared.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
@@ -217,8 +218,9 @@ app.use(authGate);
// Body limit is set slightly above the 50MB combined base64 cap enforced by sendMessageSchema
// so the Zod validation (not the body parser) is the binding constraint for attachment payloads.
-app.use(express.json({ limit: '55mb' }));
-app.use(express.urlencoded({ limit: '55mb', extended: true }));
+// Every per-file upload cap is derived from this value — see lib/uploadLimits.js.
+app.use(express.json({ limit: JSON_BODY_LIMIT }));
+app.use(express.urlencoded({ limit: JSON_BODY_LIMIT, extended: true }));
// API Routes
app.use('/api/auth', authRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 69e2576737..7e5631b201 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -286,6 +286,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
+| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Consumed by the `claim-work` router in `cosTaskGenerator.js` and `routes/apps.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 13099483e5..e937b5e0f5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -257,6 +257,7 @@ export * from './sidecarProcess.js';
export * from './singleFlight.js';
export * from './streamBackpressure.js';
export * from './sseUtils.js';
+export * from './uploadLimits.js';
export * from './uuid.js';
export * from './versionUtils.js';
export * from './workTracker.js';
diff --git a/server/lib/uploadLimits.js b/server/lib/uploadLimits.js
new file mode 100644
index 0000000000..8076596fa1
--- /dev/null
+++ b/server/lib/uploadLimits.js
@@ -0,0 +1,37 @@
+/**
+ * Single source of truth for how large an uploaded file may be.
+ *
+ * PortOS ships files to the server base64-encoded inside a JSON body, so the
+ * Express body-parser limit — not any per-route rule — is the real ceiling.
+ * Base64 inflates bytes by 4/3, so a route advertising a cap above
+ * `JSON_BODY_LIMIT × 3/4` is advertising something unreachable: the parser
+ * 413s before the route's own size check ever runs, and the user sees an
+ * opaque failure instead of a limit message.
+ *
+ * Keeping the parser limit and the derived file cap in one module is the same
+ * pattern `server/lib/ports.js` uses for the port map — change the limit here
+ * and every route follows. The client mirrors `MAX_BASE64_UPLOAD_BYTES` as
+ * `JSON_UPLOAD_MAX_FILE_SIZE` in `client/src/utils/fileUpload.js` (it can't
+ * import server modules); `uploadLimits.test.js` is what keeps the two honest.
+ */
+
+// Body-parser limit applied in server/index.js to express.json/urlencoded.
+export const JSON_BODY_LIMIT = '55mb';
+
+// Parsed form of JSON_BODY_LIMIT, in bytes.
+export const JSON_BODY_LIMIT_BYTES = 55 * 1024 * 1024;
+
+// Base64 encodes 3 bytes as 4 characters.
+const BASE64_INFLATION = 4 / 3;
+
+/**
+ * Largest raw file that still fits the body limit once base64-encoded, rounded
+ * DOWN to a whole MB so the number we show users is both honest and tidy.
+ * (55MB ÷ 4/3 ≈ 41.25MB → 41MB.)
+ */
+export const MAX_BASE64_UPLOAD_BYTES =
+ Math.floor(JSON_BODY_LIMIT_BYTES / BASE64_INFLATION / (1024 * 1024)) * 1024 * 1024;
+
+// Screenshots are pasted/dragged UI captures, not archives — a much smaller
+// cap than the wire allows is a deliberate product choice, not a wire limit.
+export const MAX_SCREENSHOT_BYTES = 10 * 1024 * 1024;
diff --git a/server/lib/uploadLimits.test.js b/server/lib/uploadLimits.test.js
new file mode 100644
index 0000000000..77a3d2065b
--- /dev/null
+++ b/server/lib/uploadLimits.test.js
@@ -0,0 +1,70 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import {
+ JSON_BODY_LIMIT,
+ JSON_BODY_LIMIT_BYTES,
+ MAX_BASE64_UPLOAD_BYTES,
+ MAX_SCREENSHOT_BYTES,
+} from './uploadLimits.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const read = (p) => readFileSync(join(HERE, p), 'utf8');
+
+describe('uploadLimits', () => {
+ it('keeps JSON_BODY_LIMIT and its byte form in agreement', () => {
+ const mb = Number(JSON_BODY_LIMIT.replace(/mb$/i, ''));
+ expect(Number.isFinite(mb)).toBe(true);
+ expect(JSON_BODY_LIMIT_BYTES).toBe(mb * 1024 * 1024);
+ });
+
+ it('derives a file cap that actually fits the body limit once base64-encoded', () => {
+ // The whole point of the constant: base64 inflates by 4/3, so a raw file at
+ // the cap must still encode to less than the body limit. A cap that fails
+ // this is the opaque-413 bug it exists to prevent.
+ const encoded = Math.ceil(MAX_BASE64_UPLOAD_BYTES / 3) * 4;
+ expect(encoded).toBeLessThan(JSON_BODY_LIMIT_BYTES);
+ // …and it should not be needlessly conservative: one more MB must overflow.
+ const oneMbMore = Math.ceil((MAX_BASE64_UPLOAD_BYTES + 1024 * 1024) / 3) * 4;
+ expect(oneMbMore).toBeGreaterThan(JSON_BODY_LIMIT_BYTES);
+ });
+
+ it('is a whole number of MB so the advertised limit reads cleanly', () => {
+ expect(MAX_BASE64_UPLOAD_BYTES % (1024 * 1024)).toBe(0);
+ });
+
+ it('caps screenshots below the wire limit', () => {
+ expect(MAX_SCREENSHOT_BYTES).toBeLessThan(MAX_BASE64_UPLOAD_BYTES);
+ });
+
+ it('is the only place the express body limit is written', () => {
+ // server/index.js must consume JSON_BODY_LIMIT rather than re-hardcode it —
+ // otherwise raising the limit here silently leaves the parser behind.
+ const indexSrc = read('../index.js');
+ expect(indexSrc).toContain('JSON_BODY_LIMIT');
+ expect(indexSrc).not.toMatch(/express\.(json|urlencoded)\(\{\s*limit:\s*['"]/);
+ });
+
+ it('matches the client mirror, which cannot import this module', () => {
+ // client/src/utils/fileUpload.js hardcodes the same number to size-check
+ // before uploading. If it drifts high, the user picks a file the parser
+ // then rejects with no message — the bug this constant exists to kill.
+ const clientSrc = read('../../client/src/utils/fileUpload.js');
+ const match = clientSrc.match(/JSON_UPLOAD_MAX_FILE_SIZE = (\d+) \* 1024 \* 1024/);
+ expect(match, 'client mirror not found — did JSON_UPLOAD_MAX_FILE_SIZE move?').toBeTruthy();
+ expect(Number(match[1]) * 1024 * 1024).toBe(MAX_BASE64_UPLOAD_BYTES);
+ });
+
+ it('is the only place per-route upload caps are written', () => {
+ // A route that re-derives its own byte cap is how uploads.js and
+ // attachments.js drifted to unreachable 100MB/50MB claims.
+ for (const route of ['uploads.js', 'attachments.js', 'brainSongbook.js', 'screenshots.js']) {
+ const src = read(`../routes/${route}`);
+ expect(src, `${route} should import its cap from lib/uploadLimits.js`)
+ .toContain("from '../lib/uploadLimits.js'");
+ expect(src, `${route} re-derives a raw byte cap instead of importing one`)
+ .not.toMatch(/const MAX_(FILE_SIZE|ATTACHMENT_SIZE)\s*=\s*\d+\s*\*/);
+ }
+ });
+});
diff --git a/server/routes/attachments.js b/server/routes/attachments.js
index 1338fb30be..d27cd9b2a3 100644
--- a/server/routes/attachments.js
+++ b/server/routes/attachments.js
@@ -11,13 +11,15 @@ import {
pathExists, PATHS, sanitizeFilename, getFileExtension, getMimeType,
ATTACHMENT_ALLOWED_EXTENSIONS, isPathInsideDir, saveBase64Upload, serveLocalFile,
} from '../lib/fileUtils.js';
+import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
const ATTACHMENTS_DIR = PATHS.cosAttachments;
const router = Router();
-// Max file size: 50MB (larger than screenshots to accommodate documents)
-const MAX_FILE_SIZE = 50 * 1024 * 1024;
+// Bounded by the JSON body limit, not by any attachment-specific rule — a
+// larger cap here is unreachable (see lib/uploadLimits.js).
+const MAX_FILE_SIZE = MAX_BASE64_UPLOAD_BYTES;
// POST /api/attachments - Upload a file attachment (base64)
router.post('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.js
index 8c8af3f18a..b20dc05b25 100644
--- a/server/routes/brainSongbook.js
+++ b/server/routes/brainSongbook.js
@@ -27,6 +27,7 @@ import {
} from '../lib/brainValidation.js';
import * as brainStorage from '../services/brainStorage.js';
import { importSongFromUrl } from '../services/brainSongbookImport.js';
+import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
import {
pathExists, PATHS, sanitizeFilename, isPathInsideDir,
SONGBOOK_ATTACHMENT_EXTENSIONS, saveBase64Upload, serveLocalFile,
@@ -34,12 +35,9 @@ import {
const router = Router();
-// Max attachment size: 40MB. Uploads arrive base64-encoded in a JSON body
-// (×4/3 inflation), and the express.json limit is 55mb — so anything above
-// ~41MB raw can never reach this route. 40MB keeps the advertised cap
-// reachable. (routes/attachments.js still claims 50MB with the same latent
-// mismatch — tracked in PLAN.md's uploads-consolidation follow-up.)
-const MAX_ATTACHMENT_SIZE = 40 * 1024 * 1024;
+// Bounded by the JSON body limit, not by any songbook-specific rule — see
+// lib/uploadLimits.js.
+const MAX_ATTACHMENT_SIZE = MAX_BASE64_UPLOAD_BYTES;
// Read lazily (not captured at module load) so test PATHS mocks with
// per-suite temp roots resolve correctly.
diff --git a/server/routes/screenshots.js b/server/routes/screenshots.js
index b104923133..8f55cbe01c 100644
--- a/server/routes/screenshots.js
+++ b/server/routes/screenshots.js
@@ -5,13 +5,14 @@ import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { ensureDir, PATHS, sanitizeFilename, isPathInsideDir } from '../lib/fileUtils.js';
+import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';
const SCREENSHOTS_DIR = PATHS.screenshots;
const router = Router();
-// Max file size: 10MB
-const MAX_FILE_SIZE = 10 * 1024 * 1024;
+// Screenshots cap well below the wire limit on purpose — see lib/uploadLimits.js.
+const MAX_FILE_SIZE = MAX_SCREENSHOT_BYTES;
/**
* Validate image magic bytes
diff --git a/server/routes/uploads.js b/server/routes/uploads.js
index 957f7669ec..6ad7be2d35 100644
--- a/server/routes/uploads.js
+++ b/server/routes/uploads.js
@@ -10,13 +10,15 @@ import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { ensureDir, PATHS, RISKY_MIME_TYPES, sanitizeFilename, getFileExtension, getMimeType, isPathInsideDir } from '../lib/fileUtils.js';
+import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
const UPLOADS_DIR = PATHS.uploads;
const router = Router();
-// Max file size: 100MB for general uploads
-const MAX_FILE_SIZE = 100 * 1024 * 1024;
+// Bounded by the JSON body limit, not by any uploads-specific rule — see
+// lib/uploadLimits.js.
+const MAX_FILE_SIZE = MAX_BASE64_UPLOAD_BYTES;
/**
* Format file size for display