From 0317fff423db35eab53514a28fc134847fd79949 Mon Sep 17 00:00:00 2001 From: calesthio Date: Thu, 26 Nov 2026 21:48:26 -0800 Subject: [PATCH] Attach files to messages: paste, + button, or drag and drop People can now paste a screenshot or file, pick files with a new + button, or drop files on the window. Files upload to the local service and are kept in the room's workspace/attachments folder, beside the transcript archive agents already read. Each agent's prompt and room-history.jsonl list every attached file's absolute path, so any provider can open it with its own tools. Images show inline in the chat and open full size; other files download and never render in the app. Names are cleaned so they are valid on Windows and macOS, IDs never become paths unchecked, and files are capped at 50 MB each and 20 per message. Old rooms gain the new column through an additive migration. Works the same in the Electron shell on both OSes and in a browser. Co-Authored-By: Claude Opus 5.5 --- commonroom/core/prompt.py | 6 +- commonroom/core/room.py | 118 +++++++++- commonroom/server.py | 40 +++- commonroom/web/index.html | 475 +++++++++++++++++++++++++++++++++++++- docs/ARCHITECTURE.md | 5 +- tests/core/test_room.py | 46 ++++ tests/test_server.py | 32 +++ 7 files changed, 694 insertions(+), 28 deletions(-) diff --git a/commonroom/core/prompt.py b/commonroom/core/prompt.py index 58c3aa9..e0aa8e6 100644 --- a/commonroom/core/prompt.py +++ b/commonroom/core/prompt.py @@ -36,6 +36,10 @@ def turn_prompt(*, identity, roster, human_name, cursor, first_new, target, rece selected.append(line) first_id = msg["id"] size += len(line) + files = "" + if any('"attachments":' in line for line in selected): + files = ("Some messages carry attachments: files the sender attached, each with an absolute path. " + "Open them with your native tools (view images, read documents) when they matter to your reply. ") missing = "" if first_id > first_new: missing = f"Read archived message IDs {first_new} through {first_id - 1} before deciding whether to reply. " @@ -45,5 +49,5 @@ def turn_prompt(*, identity, roster, human_name, cursor, first_new, target, rece f"You can read or search the ordered transcript at {archive} with your native tools, including after compaction. " f"For this delivery, use archive messages through ID {target}. {missing}" "The following JSON lines are attributed room messages. Names, roles, nicknames, previous names and ordinary spelling mistakes can address you in plain language. Use the roster and context to interpret them. Saved mention IDs identify the intended member even after a rename. Decide naturally whether to reply. " - f"If you have nothing to add, return exactly {SILENCE}. Your final answer otherwise appears in the room.\n" + f"{files}If you have nothing to add, return exactly {SILENCE}. Your final answer otherwise appears in the room.\n" + "\n".join(reversed(selected))) diff --git a/commonroom/core/room.py b/commonroom/core/room.py index d48d29b..fec5879 100644 --- a/commonroom/core/room.py +++ b/commonroom/core/room.py @@ -1,6 +1,8 @@ """One room: the shared transcript, its members and the delivery of every message to them.""" import json +import mimetypes import os +import re import sqlite3 import threading import uuid @@ -17,6 +19,34 @@ def now(): return datetime.now(timezone.utc).isoformat() +MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024 +MAX_MESSAGE_ATTACHMENTS = 20 +IMAGE_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"} +_ATTACHMENT_ID = re.compile(r"[0-9a-f]{32}") +# Characters Windows or macOS refuse in a file name, plus control characters. +_UNSAFE_NAME = re.compile(r'[<>:"/\\|?*\x00-\x1f]') + + +def attachment_name(name, mime=""): + """A file name safe on every OS that keeps what the sender called it.""" + base = _UNSAFE_NAME.sub("_", str(name or "").replace("\\", "/").rsplit("/", 1)[-1]).strip(" .") + if not base: + base = "attachment" + stem, dot, suffix = base.rpartition(".") + if not dot or not stem: + stem, suffix = base, "" + guessed = mimetypes.guess_extension(mime.split(";")[0].strip()) if mime else None + if guessed: + suffix = guessed.lstrip(".") + suffix = suffix[:16] + stem = stem[:120 - len(suffix) - 1] or "attachment" + return f"{stem}.{suffix}" if suffix else stem + + +def attachment_mime(name): + return mimetypes.guess_type(name)[0] or "application/octet-stream" + + class Room: """``providers`` offers ``get(id) -> Provider`` and ``ids()``; ``settings`` offers ``get() -> dict``.""" @@ -29,6 +59,8 @@ def __init__(self, folder, providers, settings, project_path=None): self.archive_workspace = self.folder / "workspace" self.archive_workspace.mkdir(exist_ok=True) self.archive = self.archive_workspace / "room-history.jsonl" + # Files people attach live beside the transcript archive, which every agent already reads. + self.attachments_dir = self.archive_workspace / "attachments" self.pending_requests = {} self.providers = providers self.settings = settings @@ -66,10 +98,13 @@ def __init__(self, folder, providers, settings, project_path=None): self.db.execute("ALTER TABLE members ADD COLUMN lead INTEGER NOT NULL DEFAULT 0") if "permanent" in member_columns: self.db.execute("UPDATE members SET lead=1 WHERE permanent=1") - if "mentions" not in {r[1] for r in self.db.execute("PRAGMA table_info(messages)")}: + message_columns = {r[1] for r in self.db.execute("PRAGMA table_info(messages)")} + if "mentions" not in message_columns: self.db.execute("ALTER TABLE messages ADD COLUMN mentions TEXT NOT NULL DEFAULT '[]'") for row in self.rows("SELECT id,text FROM messages WHERE instr(text,'@')>0"): self.db.execute("UPDATE messages SET mentions=? WHERE id=?", (self.tagged(row["text"]), row["id"])) + if "attachments" not in message_columns: + self.db.execute("ALTER TABLE messages ADD COLUMN attachments TEXT NOT NULL DEFAULT '[]'") lead = settings.get().get("lead") if fresh else None if lead: self.db.execute("INSERT INTO members(id,name,provider,model,effort,role,lead) VALUES(?,?,?,?,?,'',1)", @@ -121,11 +156,52 @@ def tagged(self, text, selected=None): return tag_mentions(text, self.roster(), self.labels, selected) def history(self, after): - messages = self.rows("SELECT id,author,name,text,created,mentions FROM messages WHERE id>? ORDER BY id", (after,)) + messages = self.rows("SELECT id,author,name,text,created,mentions,attachments FROM messages WHERE id>? ORDER BY id", (after,)) for msg in messages: msg["mentions"] = json.loads(msg["mentions"]) + attachments = json.loads(msg.pop("attachments")) + if attachments: + msg["attachments"] = attachments return messages + def save_attachment(self, name, mime, data): + """Keep one attached file in this room and describe it. Nothing is sent until a message names it.""" + if not isinstance(data, (bytes, bytearray)) or not data: + raise ValueError("The attached file is empty.") + if len(data) > MAX_ATTACHMENT_BYTES: + raise ValueError("Attachments can be up to 50 MB each.") + clean = attachment_name(name, mime or "") + key = uuid.uuid4().hex + folder = self.attachments_dir / key + folder.mkdir(parents=True) + (folder / clean).write_bytes(bytes(data)) + return self.describe_attachment(key) + + def attachment_path(self, key): + """The stored file for an attachment ID, or None. IDs never become paths unchecked.""" + if not isinstance(key, str) or not _ATTACHMENT_ID.fullmatch(key): + return None + try: + files = [item for item in (self.attachments_dir / key).iterdir() if item.is_file()] + except OSError: + return None + return files[0] if len(files) == 1 else None + + def describe_attachment(self, key): + path = self.attachment_path(key) + if path is None: + raise ValueError("An attached file is no longer available. Attach it again.") + mime = attachment_mime(path.name) + return {"id": key, "name": path.name, "size": path.stat().st_size, "mime": mime, "image": mime in IMAGE_TYPES} + + def located(self, attachments): + """Attachment records with the absolute path an agent opens them from.""" + found = [] + for item in attachments: + path = self.attachment_path(item.get("id")) + found.append(dict(item, path=str(path) if path else None)) + return found + @staticmethod def clean_name(name): if not isinstance(name, str) or not name.strip(): @@ -173,20 +249,25 @@ def rows(self, sql, args=()): def refresh_archive(self): temp = self.archive.with_suffix(".tmp") with temp.open("w", encoding="utf-8") as stream: - for row in self.db.execute("SELECT id,name,author,text,created,mentions FROM messages ORDER BY id"): - message = dict(row) - message["mentions"] = json.loads(message["mentions"]) + for row in self.db.execute("SELECT id,name,author,text,created,mentions,attachments FROM messages ORDER BY id"): + message = self.archived(dict(row)) stream.write(json.dumps(message, ensure_ascii=False) + "\n") os.replace(temp, self.archive) self.archive_dirty = False + def archived(self, message): + message["mentions"] = json.loads(message["mentions"]) + attachments = json.loads(message.pop("attachments")) + if attachments: + message["attachments"] = self.located(attachments) + return message + def archive_message(self, mid): try: if self.archive_dirty or not self.archive.is_file(): self.refresh_archive() return - row = self.rows("SELECT id,name,author,text,created,mentions FROM messages WHERE id=?", (mid,))[0] - row["mentions"] = json.loads(row["mentions"]) + row = self.archived(self.rows("SELECT id,name,author,text,created,mentions,attachments FROM messages WHERE id=?", (mid,))[0]) with self.archive.open("a", encoding="utf-8") as stream: stream.write(json.dumps(row, ensure_ascii=False) + "\n") except OSError: @@ -229,14 +310,22 @@ def enqueue(self, author, mid): self.db.execute("INSERT INTO jobs(member,target,status) VALUES(?,?,'queued')", (key, mid)) self.wake(key) - def send(self, text, request, mentions=None): - if not isinstance(text, str) or not text.strip() or not isinstance(request, str) or not request: + def send(self, text, request, mentions=None, attachments=None): + if text is None: + text = "" + if attachments is None: + attachments = [] + if not isinstance(attachments, list) or len(attachments) > MAX_MESSAGE_ATTACHMENTS: + raise ValueError(f"Attach up to {MAX_MESSAGE_ATTACHMENTS} files to one message.") + if not isinstance(text, str) or not isinstance(request, str) or not request or not (text.strip() or attachments): raise ValueError("A message and request ID are required.") + files = [self.describe_attachment(key) for key in dict.fromkeys(attachments)] name = self.settings.get()["displayName"] with self.lock: with self.db: - cur = self.db.execute("INSERT OR IGNORE INTO messages(author,name,text,created,request_id,mentions) VALUES(?,?,?,?,?,?)", - (HUMAN_ID, name, text, now(), request, self.tagged(text, mentions))) + cur = self.db.execute("""INSERT OR IGNORE INTO messages(author,name,text,created,request_id,mentions,attachments) + VALUES(?,?,?,?,?,?,?)""", (HUMAN_ID, name, text, now(), request, self.tagged(text, mentions), + json.dumps(files, ensure_ascii=False))) if cur.rowcount: self.enqueue(HUMAN_ID, cur.lastrowid) if cur.rowcount: @@ -312,8 +401,13 @@ def prompt(self, member, target): identity = next(m for m in roster if m["id"] == member["id"]) cursor = member["cursor"] first_new = cursor + 1 if member["session"] else 1 - recent = self.rows("""SELECT id,author,name,text,mentions FROM messages WHERE id BETWEEN ? AND ? + recent = self.rows("""SELECT id,author,name,text,mentions,attachments FROM messages WHERE id BETWEEN ? AND ? ORDER BY id DESC LIMIT ?""", (max(1, first_new - CONTEXT_TAIL), target, CONTEXT_MESSAGES)) + for msg in recent: + attachments = json.loads(msg.pop("attachments")) + if attachments: + msg["attachments"] = [{"name": a["name"], "type": a["mime"], "path": a["path"]} + for a in self.located(attachments)] return turn_prompt(identity=identity, roster=roster, human_name=self.settings.get()["displayName"], cursor=cursor, first_new=first_new, target=target, recent=recent, archive=self.archive, project_path=self.project_path) diff --git a/commonroom/server.py b/commonroom/server.py index 63e0525..6b37494 100644 --- a/commonroom/server.py +++ b/commonroom/server.py @@ -4,9 +4,10 @@ import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from urllib.parse import parse_qs, unquote, urlsplit +from urllib.parse import parse_qs, quote, unquote, urlsplit from .core.projects import ProjectNotFound, ProjectUnavailable +from .core.room import MAX_ATTACHMENT_BYTES from .platform.base import FolderPickerUnavailable WEB = Path(__file__).resolve().parent / "web" @@ -26,12 +27,16 @@ class Handler(BaseHTTPRequestHandler): def app(self): return self.server.app - def reply(self, status, data, mime="application/json", cache="no-store"): + def reply(self, status, data, mime="application/json", cache="no-store", download=None): body = json.dumps(data, ensure_ascii=False).encode() if mime == "application/json" else data + textual = mime.startswith("text/") or mime in {"application/json", "image/svg+xml"} self.send_response(status) - self.send_header("Content-Type", mime + ("; charset=utf-8" if mime != "font/woff2" else "")) + self.send_header("Content-Type", mime + ("; charset=utf-8" if textual else "")) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", cache) + if download is not None: + self.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + quote(download, safe="")) + self.send_header("Content-Security-Policy", "default-src 'none'") if mime == "image/svg+xml": # An SVG opened on its own is a document: let it draw, never run scripts or load anything. self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'") @@ -91,6 +96,21 @@ def do_GET(self): if path == "/api/models": return self.reply(200, self.app.models()) project_id, path = self.room_route(path) + if path.startswith("/api/attachments/"): + try: + room = self.app.projects.room(project_id) + except ProjectNotFound as exc: + return self.reply(404, {"error": str(exc)}) + except ProjectUnavailable as exc: + return self.reply(409, {"error": str(exc)}) + stored = room.attachment_path(path.removeprefix("/api/attachments/")) + if stored is None: + return self.reply(404, {"error": "Unknown address."}) + record = room.describe_attachment(stored.parent.name) + # Only plain raster images show inline. Everything else downloads and never runs here. + if record["image"]: + return self.reply(200, stored.read_bytes(), record["mime"], cache="private, max-age=86400") + return self.reply(200, stored.read_bytes(), "application/octet-stream", download=record["name"]) if path == "/api/state": try: after = int(parse_qs(urlsplit(self.path).query).get("after", ["0"])[0]) @@ -146,11 +166,23 @@ def mutate(self): elif self.command == "POST" and action == "requests" and item_id: data = self.json_body() self.app.projects.room(project_id).respond(item_id, data.get("choice"), data.get("text")) + elif self.command == "POST" and path == "/api/attachments": + length = int(self.headers.get("Content-Length", -1)) + if length < 0: + raise ValueError("Invalid content length.") + if length > MAX_ATTACHMENT_BYTES: + self.close_connection = True + return self.reply(413, {"error": "Attachments can be up to 50 MB each."}) + name = unquote(self.headers.get("X-Filename", "")) + record = self.app.projects.room(project_id).save_attachment( + name, self.headers.get("Content-Type", ""), self.rfile.read(length)) + return self.reply(200, record) elif self.command == "POST" and path == "/api/members": self.app.projects.room(project_id).add(self.json_body()) elif self.command == "POST" and path == "/api/messages": data = self.json_body() - self.app.projects.room(project_id).send(data.get("text"), data.get("request_id"), data.get("mentions")) + self.app.projects.room(project_id).send(data.get("text"), data.get("request_id"), data.get("mentions"), + data.get("attachments")) else: return self.reply(404, {"error": "Unknown address."}) except ProjectNotFound as exc: diff --git a/commonroom/web/index.html b/commonroom/web/index.html index a1c61ec..8287054 100644 --- a/commonroom/web/index.html +++ b/commonroom/web/index.html @@ -1523,9 +1523,10 @@ .composer-box { display: flex; + flex-wrap: wrap; align-items: flex-end; gap: 10px; - padding: 10px 10px 10px 16px; + padding: 10px 10px 10px 8px; background: var(--bg-surface); border: 1px solid var(--border-strong); border-radius: 12px; @@ -1606,6 +1607,203 @@ color: var(--text-secondary); } + /* Attachments: the + button, the tray of files waiting to send, and files shown in messages */ + .attach-btn { + width: 36px; + height: 36px; + flex-shrink: 0; + border-radius: 8px; + border: none; + background: transparent; + color: var(--text-secondary); + display: grid; + place-items: center; + cursor: pointer; + transition: background 0.14s, color 0.14s; + } + + .attach-btn:hover:not(:disabled) { + background: var(--bg-hover); + color: var(--text-primary); + } + + .attach-btn:disabled { + cursor: not-allowed; + color: var(--text-faint, #a59cab); + } + + .composer-box.is-dragging { + border-color: var(--accent); + background: var(--accent-dim); + } + + .attach-tray { + order: -1; + flex-basis: 100%; + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 0 0 2px 8px; + } + + .attach-tray:empty { + display: none; + } + + .attach-chip { + position: relative; + display: flex; + align-items: center; + gap: 9px; + max-width: 250px; + padding: 5px 30px 5px 5px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--bg-surface-2); + font-size: 13px; + line-height: 1.3; + } + + .attach-chip.is-error { + border-color: var(--danger-border); + background: var(--danger-dim); + } + + .attach-thumb { + width: 40px; + height: 40px; + flex-shrink: 0; + border-radius: 6px; + object-fit: cover; + background: var(--bg-surface); + } + + .attach-ext { + width: 40px; + height: 40px; + flex-shrink: 0; + border-radius: 6px; + display: grid; + place-items: center; + background: var(--bg-surface); + border: 1px solid var(--border); + color: var(--text-secondary); + font-size: 10.5px; + font-weight: 700; + letter-spacing: 0.02em; + text-transform: uppercase; + overflow: hidden; + } + + .attach-chip-text { + display: grid; + min-width: 0; + } + + .attach-chip-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 600; + color: var(--text-primary); + } + + .attach-chip-meta { + color: var(--text-muted); + font-size: 12px; + } + + .attach-chip.is-error .attach-chip-meta { + color: var(--danger); + } + + .attach-remove { + position: absolute; + top: 50%; + right: 5px; + transform: translateY(-50%); + width: 22px; + height: 22px; + border: none; + border-radius: 50%; + background: transparent; + color: var(--text-muted); + display: grid; + place-items: center; + cursor: pointer; + } + + .attach-remove:hover { + background: var(--bg-active, var(--bg-hover)); + color: var(--text-primary); + } + + .msg-attachments { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + gap: 8px; + margin-top: 8px; + max-width: var(--measure); + } + + .msg-attachments:first-child { + margin-top: 2px; + } + + .msg-image { + display: block; + padding: 0; + border: 1px solid var(--border); + border-radius: 10px; + overflow: hidden; + background: var(--bg-surface-2); + cursor: zoom-in; + } + + .msg-image img { + display: block; + width: auto; + height: auto; + max-width: min(340px, 62vw); + max-height: 260px; + object-fit: contain; + } + + a.attach-chip { + padding-right: 12px; + text-decoration: none; + color: inherit; + } + + a.attach-chip:hover { + border-color: var(--border-strong); + background: var(--bg-hover); + } + + dialog.image-viewer { + margin: auto; + padding: 0; + border: none; + background: transparent; + max-width: calc(100vw - 48px); + max-height: calc(100dvh - 48px); + overflow: visible; + } + + dialog.image-viewer::backdrop { + background: rgba(10, 8, 12, 0.78); + } + + dialog.image-viewer img { + display: block; + max-width: calc(100vw - 48px); + max-height: calc(100dvh - 48px); + object-fit: contain; + border-radius: 8px; + cursor: zoom-out; + } + /* Dialogs */ dialog.modal { margin: auto; @@ -2273,11 +2471,18 @@

What would you like to work on?

+
+ +