M6 1900: any-file attachments + audio memos (broaden beyond images)
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 5s
CI & Build / Python tests (push) Successful in 7s
CI & Build / Build & push image (push) Successful in 32s

A note can now carry any file, not just images — PDFs, documents, audio
memos, etc. "Dump anything" capture.

Backend:
- note_attachments.filename (migration 0019) records the original name for
  download + display.
- Upload drops the image-only mime gate: accepts any type, derives the
  storage extension from the filename, and enforces a DB-backed per-file
  cap — new setting max_attachment_mb (default 25, rule 25). App body
  ceiling raised 12→64 MB (also lifts the import-zip / sync-push limits);
  the per-file cap is the effective attachment limit.
- Serve sets Content-Disposition: images inline, everything else downloads
  with its original (header-sanitized) filename.
- Import (native + Keep Takeout) now brings in ANY attachment, not just
  images — completing the Keep audio-memo gap; preserves filename + sha256.
- Attachment metadata (delta feed + REST) carries filename.

Frontend:
- Editor renders attachments by kind: images inline (thumbnail), audio via
  an inline <audio> player, any other file as a download chip (paperclip +
  filename + size). File picker accepts any type; "Attach a file".
- Card previews the first image; non-image files show as compact chips.

Tests (DB-free): _safe_filename, _attachment_ext, _header_filename.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FRgehjoz7Yv8LkUfADxACm
This commit is contained in:
2026-07-22 23:37:43 -04:00
co-authored by Claude Opus 4.8
parent 7dd74d2946
commit b5f545f655
10 changed files with 203 additions and 43 deletions
@@ -0,0 +1,25 @@
"""note_attachments.filename (any-file attachments — M6 1900)
Revision ID: 0019
Revises: 0018
Create Date: 2026-07-23
Attachments broaden beyond images to any file; the original filename is recorded
for the download name + display of non-image files. Nullable (old image rows have
none — they render inline by mime anyway).
"""
from alembic import op
import sqlalchemy as sa
revision = "0019"
down_revision = "0018"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("note_attachments", sa.Column("filename", sa.Text(), nullable=True))
def downgrade() -> None:
op.drop_column("note_attachments", "filename")
+1
View File
@@ -26,6 +26,7 @@ const paths: Record<string, string> = {
download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>',
device: '<rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/>',
paperclip: '<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>',
copy: '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
};
</script>
+17 -3
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from "vue";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useNotesStore } from "../stores/notes";
import {
LABEL_CHIP_CLASSES,
@@ -24,6 +24,10 @@ const emit = defineEmits<{
}>();
const notes = useNotesStore();
// The card previews the first image inline; non-image files show as compact chips.
const firstImage = computed(() => props.note.attachments.find((a) => a.mime.startsWith("image/")));
const otherAttachments = computed(() => props.note.attachments.filter((a) => !a.mime.startsWith("image/")));
const root = ref<HTMLElement | null>(null);
// --- Drag-to-reorder. Native HTML5 DnD, gated behind an explicit grip handle so
@@ -139,14 +143,24 @@ onBeforeUnmount(() => document.removeEventListener("mousedown", onDocMousedown))
</button>
<img
v-if="note.attachments.length"
:src="note.attachments[0].url"
v-if="firstImage"
:src="firstImage.url"
alt=""
loading="lazy"
decoding="async"
class="mb-2 max-h-48 w-full cursor-pointer rounded-lg object-cover"
@click="emit('open', note)"
/>
<div v-if="otherAttachments.length" class="mb-2 flex flex-wrap gap-1">
<span
v-for="att in otherAttachments"
:key="att.id"
class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/5 px-1.5 py-0.5 text-xs text-neutral-500 dark:bg-white/10 dark:text-neutral-400"
>
<Icon name="paperclip" />
<span class="max-w-[140px] truncate">{{ att.filename || "file" }}</span>
</span>
</div>
<!-- Checklist notes can't nest interactive controls in a <button>, so use a
focusable div; text notes keep a semantic button. -->
+66 -24
View File
@@ -423,9 +423,20 @@ async function toggleKind() {
}
// ---- attachments ----
function pickImage() {
function pickFile() {
fileInput.value?.click();
}
function attKind(mime: string): "image" | "audio" | "file" {
if (mime.startsWith("image/")) return "image";
if (mime.startsWith("audio/")) return "audio";
return "file";
}
function fmtSize(bytes?: number): string {
if (!bytes) return "";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
async function uploadFile(file: File) {
const id = await ensureDraft();
if (!id) return;
@@ -433,7 +444,7 @@ async function uploadFile(file: File) {
try {
await notes.uploadAttachment(id, file);
} catch (e) {
uploadError.value = (e as { error?: string }).error ?? "Could not upload image.";
uploadError.value = (e as { error?: string }).error ?? "Could not upload file.";
}
}
async function onFileChange(e: Event) {
@@ -541,18 +552,55 @@ defineExpose({ open });
@paste="onPaste"
>
<div class="flex flex-col gap-2 p-4">
<div v-if="liveNote.attachments.length" class="flex flex-wrap gap-2">
<div v-for="att in liveNote.attachments" :key="att.id" class="group/att relative">
<img :src="att.url" alt="" loading="lazy" decoding="async" class="h-24 w-24 rounded-lg object-cover" />
<button
type="button"
class="absolute right-1 top-1 rounded-full bg-black/50 px-1.5 text-white opacity-0 transition group-hover/att:opacity-100"
aria-label="Remove image"
@click="notes.deleteAttachment(liveNote.id, att.id)"
<div v-if="liveNote.attachments.length" class="flex flex-wrap items-center gap-2">
<template v-for="att in liveNote.attachments" :key="att.id">
<!-- Image inline thumbnail -->
<div v-if="attKind(att.mime) === 'image'" class="group/att relative">
<img :src="att.url" alt="" loading="lazy" decoding="async" class="h-24 w-24 rounded-lg object-cover" />
<button
type="button"
class="absolute right-1 top-1 rounded-full bg-black/50 px-1.5 text-white opacity-0 transition group-hover/att:opacity-100"
aria-label="Remove attachment"
@click="notes.deleteAttachment(liveNote.id, att.id)"
>
×
</button>
</div>
<!-- Audio inline player -->
<div
v-else-if="attKind(att.mime) === 'audio'"
class="flex items-center gap-2 rounded-lg border border-neutral-200 px-2 py-1 dark:border-neutral-700"
>
×
</button>
</div>
<audio controls :src="att.url" class="h-8 max-w-[220px]"></audio>
<button
type="button"
class="text-neutral-400 hover:text-red-500"
aria-label="Remove attachment"
@click="notes.deleteAttachment(liveNote.id, att.id)"
>
×
</button>
</div>
<!-- Any other file download chip -->
<a
v-else
:href="att.url"
download
class="flex items-center gap-2 rounded-lg border border-neutral-200 px-3 py-2 text-xs hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800"
>
<Icon name="paperclip" />
<span class="max-w-[160px] truncate">{{ att.filename || "file" }}</span>
<span v-if="att.size" class="text-neutral-400">{{ fmtSize(att.size) }}</span>
<button
type="button"
class="ml-1 text-neutral-400 hover:text-red-500"
aria-label="Remove attachment"
@click.prevent.stop="notes.deleteAttachment(liveNote.id, att.id)"
>
×
</button>
</a>
</template>
</div>
<p v-if="uploadError" class="text-xs text-red-600 dark:text-red-400">{{ uploadError }}</p>
@@ -710,19 +758,13 @@ defineExpose({ open });
v-if="richEnabled && !liveNote.trashed"
type="button"
class="icon-btn"
title="Add image"
aria-label="Add image"
@click="pickImage"
title="Attach a file"
aria-label="Attach a file"
@click="pickFile"
>
<Icon name="image" />
<Icon name="paperclip" />
</button>
<input
ref="fileInput"
type="file"
accept="image/png,image/jpeg,image/gif,image/webp"
class="hidden"
@change="onFileChange"
/>
<input ref="fileInput" type="file" class="hidden" @change="onFileChange" />
<button
v-if="!liveNote.trashed"
type="button"
+1
View File
@@ -26,6 +26,7 @@ export interface ChecklistItem {
export interface Attachment {
id: string;
url: string;
filename?: string | null;
mime: string;
size?: number;
sha256?: string | null;
+4 -1
View File
@@ -35,7 +35,10 @@ def create_app() -> Quart:
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=30)
app.config["MAX_CONTENT_LENGTH"] = 12 * 1024 * 1024 # image-upload body cap
# Hard request-body ceiling (any-file attachments, import zips, sync push). The
# per-file attachment limit is the DB-backed `max_attachment_mb` setting, enforced
# in the upload handler; this must stay >= the largest value that allows.
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024
app.register_blueprint(auth_bp)
app.register_blueprint(notes_bp)
+4 -2
View File
@@ -11,8 +11,8 @@ from . import Base
class NoteAttachment(Base):
"""An image uploaded onto a note. Bytes live under Config.media_root(); this
row records the relative path + metadata."""
"""A file uploaded onto a note (any type — images render inline, others download).
Bytes live under Config.media_root(); this row records the relative path + metadata."""
__tablename__ = "note_attachments"
@@ -21,6 +21,8 @@ class NoteAttachment(Base):
UUID(as_uuid=True), ForeignKey("notes.id", ondelete="CASCADE"), nullable=False
)
path: Mapped[str] = mapped_column(Text(), nullable=False) # relative to media_root
# Original upload filename, for the download name + display (non-image files).
filename: Mapped[str | None] = mapped_column(Text(), nullable=True)
mime: Mapped[str] = mapped_column(Text(), nullable=False)
size: Mapped[int] = mapped_column(BigInteger(), nullable=False)
# Content hash (sha256 hex) for client-side dedupe + integrity over sync. Nullable
+52 -13
View File
@@ -17,6 +17,7 @@ from .acl import visible_to_user
from .auth import login_required
from .config import Config
from .db import session_scope
from .settings import get_setting
from .models.label import Label, NoteLabel
from .models.note import NOTE_COLORS, Note
from .models.note_attachment import NoteAttachment
@@ -163,6 +164,7 @@ async def _attachments_for_notes(db, note_ids: list) -> dict:
{
"id": str(att.id),
"url": _attachment_url(att.note_id, att.id),
"filename": att.filename,
"mime": att.mime,
"size": att.size,
"sha256": att.sha256,
@@ -637,24 +639,34 @@ def _read_import_specs(zf: zipfile.ZipFile) -> tuple[list[dict], str]:
def _import_attachment(db, note: Note, zf: zipfile.ZipFile, att: dict) -> bool:
"""Copy one image attachment out of the zip into media storage and record it.
Non-image types (e.g. Keep audio memos) are skipped until any-file attachments
land. Returns True if written."""
mime = (att.get("mime") or "").split(";")[0].strip().lower()
ext = ALLOWED_IMAGE_MIMES.get(mime)
"""Copy one attachment (any type — incl. Keep audio memos) out of the zip into
media storage and record it, preserving its filename + hash. Returns True if written."""
zpath = att.get("file")
if ext is None or not zpath:
if not zpath:
return False
try:
raw = zf.read(zpath)
except KeyError:
return False
filename = _safe_filename(posixpath.basename(zpath))
mime = (att.get("mime") or "application/octet-stream").split(";")[0].strip().lower()
ext = _attachment_ext(filename, mime)
att_id = uuid.uuid4()
rel = os.path.join(str(note.id), f"{att_id}{ext}")
dest = Config.media_root() / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(raw)
db.add(NoteAttachment(id=att_id, note_id=note.id, path=rel, mime=mime, size=len(raw)))
db.add(
NoteAttachment(
id=att_id,
note_id=note.id,
path=rel,
filename=filename,
mime=mime,
size=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
)
)
return True
@@ -1179,6 +1191,25 @@ async def reorder_items(note_id: str):
return jsonify(await _serialize_note(db, note))
def _safe_filename(name: str | None) -> str:
"""The upload's original name reduced to a safe basename (display + download)."""
base = os.path.basename((name or "").strip().replace("\\", "/"))
return base[:255] or "file"
def _attachment_ext(filename: str, mime: str) -> str:
"""Storage extension: the original file's extension, else a known image ext."""
ext = os.path.splitext(filename)[1].lower()
if ext and len(ext) <= 12:
return ext
return ALLOWED_IMAGE_MIMES.get(mime, "")
def _header_filename(name: str) -> str:
"""Sanitize a filename for a Content-Disposition header (drop quotes/newlines)."""
return re.sub(r'[\r\n"]', "", name or "")[:255] or "file"
@bp.post("/<note_id>/attachments")
@login_required
async def upload_attachment(note_id: str):
@@ -1190,10 +1221,10 @@ async def upload_attachment(note_id: str):
upload = files.get("file")
if upload is None:
return jsonify({"error": "no file provided"}), 400
mime = (upload.content_type or "").split(";")[0].strip().lower()
ext = ALLOWED_IMAGE_MIMES.get(mime)
if ext is None:
return jsonify({"error": "unsupported image type (png, jpeg, gif, webp only)"}), 415
# Any file type is allowed — images render inline, everything else downloads.
mime = (upload.content_type or "application/octet-stream").split(";")[0].strip().lower()
filename = _safe_filename(upload.filename)
ext = _attachment_ext(filename, mime)
# A native client may supply the attachment's id so an offline-attached file
# keeps its identity across sync. Re-uploading an id it already has is a no-op.
form = await request.form
@@ -1209,16 +1240,20 @@ async def upload_attachment(note_id: str):
)
if existing is not None:
return jsonify(await _serialize_note(db, note)) # already have this blob
raw = upload.stream.read()
max_mb = int(await get_setting(db, "max_attachment_mb"))
if len(raw) > max_mb * 1024 * 1024:
return jsonify({"error": f"file is too large (max {max_mb} MB)"}), 413
rel = os.path.join(str(note.id), f"{att_id}{ext}")
dest = Config.media_root() / rel
dest.parent.mkdir(parents=True, exist_ok=True)
await upload.save(str(dest))
raw = dest.read_bytes()
dest.write_bytes(raw)
db.add(
NoteAttachment(
id=att_id,
note_id=note.id,
path=rel,
filename=filename,
mime=mime,
size=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
@@ -1247,12 +1282,16 @@ async def get_attachment(note_id: str, att_id: str):
if att is None:
return jsonify({"error": "not found"}), 404
mime = att.mime
filename = att.filename or os.path.basename(att.path)
file_path = Config.media_root() / att.path
if not file_path.is_file():
return jsonify({"error": "not found"}), 404
response = await send_file(str(file_path), mimetype=mime)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Cache-Control"] = "private, max-age=86400"
# Images display inline; every other type downloads with its original name.
disposition = "inline" if mime.startswith("image/") else "attachment"
response.headers["Content-Disposition"] = f'{disposition}; filename="{_header_filename(filename)}"'
return response
+8
View File
@@ -43,6 +43,14 @@ REGISTRY: list[SettingDef] = [
"How long a signed-in session stays valid before another login is required.",
"Access",
),
SettingDef(
"max_attachment_mb",
"int",
25,
"Max attachment size (MB)",
"Largest single file that can be attached to a note. Capped by the server body limit.",
"Attachments",
),
]
_BY_KEY: dict[str, SettingDef] = {d.key: d for d in REGISTRY}
+25
View File
@@ -3,10 +3,13 @@ import pytest
from thoughtsync.app import create_app
from thoughtsync.models.note import NOTE_COLORS, Note
from thoughtsync.notes import (
_attachment_ext,
_escape_like,
_header_filename,
_keep_spec,
_native_spec,
_parse_iso_dt,
_safe_filename,
_slugify,
_usec_to_dt,
derive_display_title,
@@ -234,6 +237,28 @@ async def test_import_requires_auth(app):
assert resp.status_code == 401
def test_safe_filename():
assert _safe_filename("report.pdf") == "report.pdf"
assert _safe_filename("/etc/passwd") == "passwd" # path components stripped
assert _safe_filename("a\\b\\c.doc") == "c.doc" # windows separators too
assert _safe_filename("") == "file" # fallback
assert _safe_filename(None) == "file"
def test_attachment_ext():
assert _attachment_ext("report.pdf", "application/pdf") == ".pdf"
assert _attachment_ext("memo.m4a", "audio/mp4") == ".m4a"
# no extension in the name → fall back to a known image mime, else empty
assert _attachment_ext("noext", "image/png") == ".png"
assert _attachment_ext("noext", "application/octet-stream") == ""
def test_header_filename():
# Quotes/newlines are stripped so the Content-Disposition header can't be broken.
assert _header_filename('a"b\r\n.pdf') == "ab.pdf"
assert _header_filename("") == "file"
def test_usec_to_dt():
# Google Keep timestamps are microseconds since the epoch (UTC).
d = _usec_to_dt(1600000000000000)