A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(chat): attach files to messages
Alan Buscaglia8a79b48b40e9
diff --git a/docs/design.md b/docs/design.mdindex b0d7d02..e2a53f9 100644--- a/docs/design.md+++ b/docs/design.md@@ -189,6 +189,16 @@ The user can talk to the assistant: a mic button in the composer, and spoken rep- Mic button (S30.4): tap to start and tap to send. While recording, the composer shows the elapsed time, a level meter, the live partial text (desktop recognizer), and ✕. Esc also cancels, and it is handled before the panel's own Esc. Recordings stop on their own at 60 s. The transcript is sent as the user's message and stays in the chat. When voice cannot work, the button is disabled and its tooltip says why (permission, insecure page, no recorder); on the web without a key it is hidden.- Spoken replies (S30.3): only the reply to a spoken message is read aloud, once the assistant is idle and the reply did not end in an error or Stop. Markdown, code, and links are stripped first. With `voice.speak` the daemon synthesizes it and the UI plays the mp3. Otherwise `speechSynthesis` reads it with a voice in the reply's language (a Spanish/English guess, then the browser language). A speaker toggle in the header mutes it, and the choice is kept in `localStorage` (`gentle-dot-voice-muted`). Starting to talk, or Stop (shown while speaking), cuts the speech.+### Attachments (S31)++The user can send files to the assistant (never the other way, L91).++- Upload (`packages/daemon/src/uploads.ts`): `POST /upload`, one file per request, the raw bytes as the body, the name URI-encoded in `X-File-Name`, and `X-Upload-Id` to add a file to the folder of the message's first file. The access key goes only in `Authorization: Bearer`; a key in the address is ignored. A foreign `Origin` is refused as on the WebSocket, and allowed origins (the desktop app's `tauri://localhost`) get a CORS preflight answer. The answer is `{uploadId, name, size, mime, path}`, with `path` relative to the workspace.+- Storage and limits (S31.3): `<workspace>/uploads/<uploadId>/<name>`, folders 0700 and files 0600, written with `wx`. Names keep only the last path segment, without control or invisible characters, leading dots, or reserved names (`file` when nothing is left), and duplicates become `name (2).ext`. The daemon enforces 25 MB per file and 10 files / 50 MB per message (`ATTACHMENT_LIMITS`) while the bytes arrive: a declared `Content-Length` over the limit is refused before reading, and a refused or broken upload removes its partial file. Nothing is opened or run. The type comes from the first bytes (PNG, JPEG, GIF, WebP, PDF), never from the name. An upload never sent is removed after an hour.+- Sending: `send` takes `attachments: {uploadId, name}[]` (1-10; the text may then be empty). Each upload is sent once; an unknown or used one answers `error attachment_not_found`, and nothing reaches the engine. The bridge appends an `<attachments>` block to the prompt, with one JSON line per file (name, size, type, absolute path). Images up to 3.75 MB (about 5 MB in base64) go to the engine as `images` only when the current model accepts them (`supervisor.modelImages`); otherwise the line says the model cannot see images.+- Display: the block is stored with the message in the session file, so `user_message`, `history`, the queue, and titles show the user's own text, and `attachments: {name, size, mime}[]` become chips. A plain `send` is unchanged.+- UI: a paper-clip button, drag and drop onto the chat, and pasted images add chips (name, size, ✕). The app checks the limits first and explains a refusal on the chip. Files upload on send with `XMLHttpRequest`, for progress, and an upload error stays on its chip with the message kept. In the desktop panel, HTML5 drops need the window's native drag-and-drop handler off (`disable_drag_drop_handler()` on the panel's `WebviewWindowBuilder`).+## 5. White-label layer- **Identity**: `--append-system-prompt` with `identity.md`: the assistant is "Gentle Dot", a personal assistant; it must not mention Gentle Shell, Pi, el Gentleman, ODD, or Engram by name, and describes them as "my workflow" and "my memory" when needed. It keeps every behavior.diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 599589e..1b403dc 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -31,6 +31,7 @@ import {} from "./profiles.ts";import { DEFAULT_ROTATION, type RotationLimits, SessionRotator } from "./rotation.ts";import type { AgentRecord, AgentSupervisor, SupervisorEvent } from "./supervisor.ts";+import { composePrompt, type StoredFile, splitAttachments, type UploadStore } from "./uploads.ts";import type { VoiceService } from "./voice.ts";import { isBlockedInput, presentText, shouldShowToast } from "./white-label.ts";@@ -46,6 +47,8 @@ export interface BridgeOptions {connectors?: ConnectorManager;/** Speech to text and text to speech with an OpenAI API key (S30.2). */voice?: VoiceService;+ /** Files the user uploaded for their messages (S31). */+ uploads?: UploadStore;/** How long switching conversations waits for a running answer to stop. Default 10 s. */stopTimeoutMs?: number;/** Optional parts of the app; by default one continuous chat. */@@ -209,32 +212,23 @@ export class DotBridge {return;}if (message.requestId && this.alreadySeen(message.requestId)) return;- if (/^\s*\/login\s*$/i.test(message.text)) {- await this.sendProviders(client, true);- return;- }- if (/^\s*\/profiles\s*$/i.test(message.text)) {- await this.sendProfiles(client, true);- return;- }- if (/^\s*\/connectors\s*$/i.test(message.text)) {- this.deliver(client, {- type: "connectors",- connectors: this.requireConnectors().list(),- open: true,- });- return;- }+ const files = message.attachments ? this.attachedFiles(client, message.attachments) : [];+ if (!files) return;+ // Slash commands are typed alone; a message with files always goes to the assistant.+ if (files.length === 0 && (await this.openScreen(client, message.text))) return;await this.switching;this.interrupted = false;const busy = this.supervisor.busy;+ const prompt =+ files.length > 0+ ? composePrompt(message.text, files, { images: this.supervisor.modelImages })+ : { message: message.text };this.sending += 1;try {await this.supervisor.request(- busy- ? { type: "prompt", message: message.text, streamingBehavior: "steer" }- : { type: "prompt", message: message.text },+ busy ? { type: "prompt", ...prompt, streamingBehavior: "steer" } : { type: "prompt", ...prompt },);+ if (message.attachments) this.options.uploads?.consume(message.attachments);} finally {this.sending -= 1;// The run may have settled before the answer to this prompt was handled.@@ -428,6 +422,38 @@ export class DotBridge {}}+ /** `/login`, `/profiles`, and `/connectors` open their screen instead of reaching the assistant. */+ private async openScreen(client: BridgeClient, text: string): Promise<boolean> {+ if (/^\s*\/login\s*$/i.test(text)) {+ await this.sendProviders(client, true);+ return true;+ }+ if (/^\s*\/profiles\s*$/i.test(text)) {+ await this.sendProfiles(client, true);+ return true;+ }+ if (/^\s*\/connectors\s*$/i.test(text)) {+ this.deliver(client, { type: "connectors", connectors: this.requireConnectors().list(), open: true });+ return true;+ }+ return false;+ }++ /** The uploaded files a message sends; undefined (and an error for the window) when one is not available. */+ private attachedFiles(+ client: BridgeClient,+ refs: NonNullable<Extract<ClientMessage, { type: "send" }>["attachments"]>,+ ): StoredFile[] | undefined {+ const found = this.options.uploads?.resolve(refs) ?? {+ ok: false as const,+ code: "attachment_not_found",+ message: "Files cannot be sent here.",+ };+ if (found.ok) return found.files;+ this.deliver(client, { type: "error", code: found.code, message: found.message });+ return undefined;+ }+/** With the conversations list off there is one chat; starting or opening another is refused. */private conversationsOn(client: BridgeClient): boolean {if (this.features.conversations) return true;@@ -831,7 +857,8 @@ export class DotBridge {private onQueueUpdate(event: AgentRecord): void {const queue = parseQueue(event);if (!queue) return;- this.queue = { steering: queue.steering.map(presentText), followUp: queue.followUp.map(presentText) };+ const shown = (text: string) => presentText(queuedText(text));+ this.queue = { steering: queue.steering.map(shown), followUp: queue.followUp.map(shown) };this.broadcast({ type: "queue", ...this.queue });}@@ -848,7 +875,13 @@ export class DotBridge {private onMessageStart(event: AgentRecord): void {const message = event.message as { role?: string } | undefined;if (message?.role === "user") {- this.broadcast({ type: "user_message", messageId: `u${++this.nextMessage}`, text: textOf(message) });+ const { text, attachments } = splitAttachments(textOf(message));+ this.broadcast({+ type: "user_message",+ messageId: `u${++this.nextMessage}`,+ text,+ ...(attachments.length > 0 ? { attachments } : {}),+ });}if (message?.role === "assistant") this.assistantId = `m${++this.nextMessage}`;}@@ -985,3 +1018,11 @@ export class DotBridge {this.options.log?.(line);}}++/** A queued message as the user wrote it; files show by name. */+function queuedText(message: string): string {+ const { text, attachments } = splitAttachments(message);+ if (attachments.length === 0) return text;+ const names = `📎 ${attachments.map((a) => a.name).join(", ")}`;+ return text ? `${text}\n${names}` : names;+}diff --git a/packages/daemon/src/conversations.ts b/packages/daemon/src/conversations.tsindex 6d5167c..160a471 100644--- a/packages/daemon/src/conversations.ts+++ b/packages/daemon/src/conversations.ts@@ -11,6 +11,7 @@ import {import { join, relative, resolve, sep } from "node:path";import type { Activity, ConversationSummary, HistoryMessage } from "@gentle-dot/protocol";import { describeTool, textOf } from "./presentation.ts";+import { splitAttachments } from "./uploads.ts";import { presentText } from "./white-label.ts";const TITLE_SCAN_BYTES = 256 * 1024;@@ -74,7 +75,10 @@ function titleOf(path: string): string {}if (record.type === "session_info") name = typeof record.name === "string" ? record.name : undefined;const message = (record.message ?? record) as { role?: unknown };- if (firstUser === undefined && message.role === "user") firstUser = textOf(message);+ if (firstUser === undefined && message.role === "user") {+ const { text, attachments } = splitAttachments(textOf(message));+ firstUser = text || attachments.map((a) => a.name).join(", ");+ }}const title = (name ?? firstUser ?? "").replace(/\s+/g, " ").trim();if (!title) return "New conversation";@@ -173,7 +177,14 @@ export function historyFromMessages(messages: unknown[]): HistoryMessage[] {for (const raw of messages) {const m = raw as AgentMessage;if (m.role === "user") {- history.push({ id: `h${++index}`, role: "user", text: textOf(m), activities: [] });+ const { text, attachments } = splitAttachments(textOf(m));+ history.push({+ id: `h${++index}`,+ role: "user",+ text,+ activities: [],+ ...(attachments.length > 0 ? { attachments } : {}),+ });continue;}if (m.role !== "assistant") continue;diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 2ae1bdd..83dad28 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -3,7 +3,13 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSyncimport { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { extname, join, resolve, sep } from "node:path";-import { type ClientMessage, CloseCode, PROTOCOL_VERSION, parseClientMessage } from "@gentle-dot/protocol";+import {+ type AttachmentLimits,+ type ClientMessage,+ CloseCode,+ PROTOCOL_VERSION,+ parseClientMessage,+} from "@gentle-dot/protocol";import { type WebSocket, WebSocketServer } from "ws";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";@@ -19,6 +25,7 @@ import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemoryimport { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";import { AgentSupervisor } from "./supervisor.ts";+import { UploadStore } from "./uploads.ts";import { VoiceService } from "./voice.ts";import { identityArgs } from "./white-label.ts";@@ -57,6 +64,8 @@ export interface DaemonOptions {rotation?: RotationLimits;/** Messages per history page; default `GENTLE_DOT_HISTORY_PAGE` or 100. */historyPage?: number;+ /** Upload limits; default 25 MB per file, 10 files and 50 MB per message (S31.3). */+ uploadLimits?: AttachmentLimits;log?: (line: string) => void;}@@ -185,6 +194,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(options.voiceFetch ? { fetch: options.voiceFetch } : {}),log,});+ const uploads = new UploadStore({+ workspace: options.workspace,+ ...(options.uploadLimits ? { limits: options.uploadLimits } : {}),+ });const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);const bridge = new DotBridge(supervisor, {dataDir: options.dataDir,@@ -193,6 +206,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {profiles,connectors,voice,+ uploads,features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },rotation: options.rotation ?? rotationLimits(process.env),...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),@@ -202,7 +216,13 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {connectorStore.enforce(false);connectorStore.watch();- const server = createServer((req, res) => handleHttp(req, res, options.uiDir, bridge));+ const server = createServer((req, res) => {+ if (new URL(req.url ?? "/", "http://localhost").pathname === "/upload") {+ void handleUpload(req, res, token, allowedOrigins(port, options), uploads);+ return;+ }+ handleHttp(req, res, options.uiDir, bridge);+ });const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });let port = options.port;@@ -304,6 +324,74 @@ function sameToken(given: string, expected: string): boolean {return a.length === b.length && timingSafeEqual(a, b);}+/**+ * `POST /upload` (S31.2): one file per request, the raw bytes as the body, its name in+ * `X-File-Name` (URI-encoded), and `X-Upload-Id` to add it to the message folder of an earlier+ * file. The same access key and Origin rules as the WebSocket: the key only in+ * `Authorization: Bearer`, never in the address.+ */+async function handleUpload(+ req: IncomingMessage,+ res: ServerResponse,+ token: string,+ origins: Set<string>,+ uploads: UploadStore,+): Promise<void> {+ res.setHeader("X-Content-Type-Options", "nosniff");+ res.setHeader("Cache-Control", "no-store");+ const refuse = (status: number, code: string, message: string) => {+ // The rest of the body is discarded, never stored.+ res.setHeader("Connection", "close");+ reply(res, status, { code, message });+ req.resume();+ };+ const origin = req.headers.origin;+ if (origin !== undefined && !origins.has(origin))+ return refuse(403, "forbidden", "This page may not upload.");+ if (origin !== undefined) {+ res.setHeader("Access-Control-Allow-Origin", origin);+ res.setHeader("Vary", "Origin");+ }+ if (req.method === "OPTIONS") {+ res.writeHead(204, {+ "Access-Control-Allow-Methods": "POST",+ "Access-Control-Allow-Headers": "Authorization, Content-Type, X-File-Name, X-Upload-Id",+ "Access-Control-Max-Age": "600",+ });+ res.end();+ return;+ }+ if (req.method !== "POST") return refuse(405, "method_not_allowed", "Upload files with POST.");+ const bearer = /^Bearer (\S+)$/.exec(req.headers.authorization ?? "")?.[1];+ if (!bearer || !sameToken(bearer, token))+ return refuse(401, "unauthorized", "The access key is not valid.");+ let name: string;+ try {+ name = decodeURIComponent(String(req.headers["x-file-name"] ?? ""));+ } catch {+ name = "";+ }+ if (name.trim() === "") return refuse(400, "bad_request", "The file has no name.");+ const uploadId = req.headers["x-upload-id"];+ if (uploadId !== undefined && (typeof uploadId !== "string" || !/^[A-Za-z0-9_-]{8,64}$/.test(uploadId))) {+ return refuse(400, "bad_request", "That upload is not valid.");+ }+ const declared = Number(req.headers["content-length"]);+ const outcome = await uploads.receive(req, {+ name,+ ...(uploadId ? { uploadId } : {}),+ ...(Number.isFinite(declared) && req.headers["content-length"] !== undefined ? { length: declared } : {}),+ });+ if (!outcome.ok) return refuse(outcome.status, outcome.code, outcome.message);+ reply(res, 200, outcome.file);+}++function reply(res: ServerResponse, status: number, body: object): void {+ if (res.headersSent || res.destroyed) return;+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify(body));+}+function handleHttp(req: IncomingMessage, res: ServerResponse, uiDir: string, bridge: DotBridge): void {res.setHeader("X-Content-Type-Options", "nosniff");res.setHeader("Referrer-Policy", "no-referrer");diff --git a/packages/daemon/src/uploads.ts b/packages/daemon/src/uploads.tsnew file mode 100644index 0000000..b69b84d--- /dev/null+++ b/packages/daemon/src/uploads.ts@@ -0,0 +1,394 @@+import { randomBytes } from "node:crypto";+import { createWriteStream, existsSync, readFileSync, rmdirSync, rmSync, unlinkSync } from "node:fs";+import { extname, join } from "node:path";+import type { Readable } from "node:stream";+import {+ ATTACHMENT_LIMITS,+ type AttachmentInfo,+ type AttachmentLimits,+ type AttachmentRef,+ type UploadedFile,+} from "@gentle-dot/protocol";+import { ensurePrivateDir } from "./isolation.ts";++/** A stored file, with its absolute path. */+export interface StoredFile extends AttachmentInfo {+ path: string;+}++export interface UploadRefusal {+ ok: false;+ /** The HTTP status for the refusal. */+ status: number;+ code: string;+ /** Plain words for the user. */+ message: string;+}++export type UploadOutcome = { ok: true; file: UploadedFile } | UploadRefusal;++export type ResolveOutcome = { ok: true; files: StoredFile[] } | { ok: false; code: string; message: string };++/** One message's folder: its stored files, and the bytes taken by them and by uploads still running. */+interface Batch {+ dir: string;+ files: Map<string, StoredFile>;+ writing: Set<string>;+ bytes: number;+ createdAt: number;+}++export interface UploadStoreOptions {+ /** The assistant's workspace; files go to `<workspace>/uploads/<uploadId>/<name>`. */+ workspace: string;+ limits?: AttachmentLimits;+ /** How long an upload that was never sent is kept. Default one hour. */+ ttlMs?: number;+ now?: () => number;+}++const UNSENT_TTL_MS = 60 * 60 * 1000;+/** The longest image passed to the model: about 5 MB once base64-encoded, the strictest provider limit. */+export const MAX_IMAGE_BYTES = 3_750_000;+const MAX_NAME_LENGTH = 120;+const MAX_EXTENSION = 16;+const SNIFF_BYTES = 16;+/** Control characters, invisible and direction-changing marks. */+// biome-ignore lint/suspicious/noControlCharactersInRegex: removing control characters is the point+const HIDDEN_CHARS = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g;+const RESERVED = /^(con|prn|aux|nul|com\d|lpt\d)$/i;+const IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);++const tooLarge = (limits: AttachmentLimits): UploadRefusal => ({+ ok: false,+ status: 413,+ code: "file_too_large",+ message: `This file is too large: up to ${megabytes(limits.fileBytes)} per file.`,+});+const messageTooLarge = (limits: AttachmentLimits): UploadRefusal => ({+ ok: false,+ status: 413,+ code: "message_too_large",+ message: `These files are too large together: up to ${megabytes(limits.messageBytes)} per message.`,+});+const NOT_FOUND = {+ code: "attachment_not_found",+ message: "A file you attached is no longer available. Attach it again.",+};++function megabytes(bytes: number): string {+ return bytes >= 1024 * 1024 ? `${Math.round(bytes / (1024 * 1024))} MB` : `${bytes} bytes`;+}++/**+ * A safe file name: the last path segment only, without control or invisible characters,+ * a leading dot (hidden files), or a reserved name; "file" when nothing is left.+ */+export function sanitizeName(raw: string): string {+ let name = (raw.split(/[\\/]/).pop() ?? "").normalize("NFC").replace(HIDDEN_CHARS, "");+ name = name+ .replace(/[<>:"|?*]/g, "_")+ .replace(/^[.\s]+/, "")+ .replace(/[.\s]+$/, "");+ let extension = extname(name);+ if (extension.length > MAX_EXTENSION) extension = "";+ let stem = name.slice(0, name.length - extension.length);+ if (stem === "" || RESERVED.test(stem)) stem = "file";+ return `${stem.slice(0, MAX_NAME_LENGTH - extension.length).trimEnd()}${extension}`;+}++/** The type of an image or PDF from its first bytes; anything else is `application/octet-stream`. */+export function sniffMime(head: Buffer): string {+ const starts = (bytes: number[] | string, at = 0) => {+ const expected = typeof bytes === "string" ? Buffer.from(bytes, "latin1") : Buffer.from(bytes);+ return head.length >= at + expected.length && head.subarray(at, at + expected.length).equals(expected);+ };+ if (starts([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";+ if (starts([0xff, 0xd8, 0xff])) return "image/jpeg";+ if (starts("GIF87a") || starts("GIF89a")) return "image/gif";+ if (starts("RIFF") && starts("WEBP", 8)) return "image/webp";+ if (starts("%PDF-")) return "application/pdf";+ return "application/octet-stream";+}++/**+ * Files the user uploads for a message (S31). Each message gets a private folder under+ * `<workspace>/uploads/`; nothing is opened or run. The limits are checked while the bytes+ * arrive, and a refused or broken upload leaves nothing behind. Uploads wait here until a+ * message sends them, once; one never sent is removed after an hour.+ */+export class UploadStore {+ private readonly root: string;+ private readonly limits: AttachmentLimits;+ private readonly ttlMs: number;+ private readonly now: () => number;+ private readonly batches = new Map<string, Batch>();++ constructor(options: UploadStoreOptions) {+ this.root = join(options.workspace, "uploads");+ this.limits = options.limits ?? ATTACHMENT_LIMITS;+ this.ttlMs = options.ttlMs ?? UNSENT_TTL_MS;+ this.now = options.now ?? Date.now;+ }++ /**+ * Streams one file to disk. Without `uploadId` it starts a new message folder; with it, the+ * file joins that folder. `length` is the size the client declared, refused early when too large.+ */+ async receive(+ body: Readable,+ request: { name: string; uploadId?: string; length?: number },+ ): Promise<UploadOutcome> {+ this.prune();+ const limits = this.limits;+ if (request.length !== undefined && request.length > limits.fileBytes) return tooLarge(limits);+ const uploadId = request.uploadId ?? `u_${randomBytes(16).toString("base64url")}`;+ const known = this.batches.get(uploadId);+ if (request.uploadId !== undefined && !known) {+ return {+ ok: false,+ status: 404,+ code: "upload_not_found",+ message: "That upload is no longer available. Attach the files again.",+ };+ }+ const batch: Batch = known ?? {+ dir: join(this.root, uploadId),+ files: new Map(),+ writing: new Set(),+ bytes: 0,+ createdAt: this.now(),+ };+ if (batch.files.size + batch.writing.size >= limits.files) {+ return {+ ok: false,+ status: 413,+ code: "too_many_files",+ message: `Too many files: up to ${limits.files} per message.`,+ };+ }+ if (request.length !== undefined && batch.bytes + request.length > limits.messageBytes) {+ return messageTooLarge(limits);+ }+ const name = this.freeName(batch, sanitizeName(request.name));+ batch.writing.add(name);+ this.batches.set(uploadId, batch);+ ensurePrivateDir(this.root);+ ensurePrivateDir(batch.dir);+ const path = join(batch.dir, name);+ const written = await this.write(body, path, batch);+ batch.writing.delete(name);+ if (!written.ok) {+ batch.bytes -= written.size;+ removeQuietly(path);+ this.dropIfEmpty(uploadId, batch);+ return written.refusal;+ }+ const file: StoredFile = { name, size: written.size, mime: sniffMime(written.head), path };+ batch.files.set(name, file);+ return {+ ok: true,+ file: { uploadId, name, size: file.size, mime: file.mime, path: `uploads/${uploadId}/${name}` },+ };+ }++ /** The stored files a message refers to, checked against the per-message limits; nothing is used up. */+ resolve(refs: AttachmentRef[]): ResolveOutcome {+ const files: StoredFile[] = [];+ const seen = new Set<string>();+ for (const { uploadId, name } of refs) {+ const file = this.batches.get(uploadId)?.files.get(name);+ const key = `${uploadId}/${name}`;+ if (!file || seen.has(key)) return { ok: false, ...NOT_FOUND };+ seen.add(key);+ files.push(file);+ }+ const bytes = files.reduce((sum, file) => sum + file.size, 0);+ if (files.length > this.limits.files || bytes > this.limits.messageBytes) {+ const { code, message } = messageTooLarge(this.limits);+ return { ok: false, code, message };+ }+ return { ok: true, files };+ }++ /** The files were sent: they stay on disk for the assistant, but no other message can send them. */+ consume(refs: AttachmentRef[]): void {+ for (const { uploadId, name } of refs) {+ const batch = this.batches.get(uploadId);+ if (!batch) continue;+ batch.files.delete(name);+ if (batch.files.size === 0 && batch.writing.size === 0) this.batches.delete(uploadId);+ }+ }++ private write(+ body: Readable,+ path: string,+ batch: Batch,+ ): Promise<{ ok: true; size: number; head: Buffer } | { ok: false; size: number; refusal: UploadRefusal }> {+ const limits = this.limits;+ return new Promise((resolve) => {+ const out = createWriteStream(path, { flags: "wx", mode: 0o600 });+ let size = 0;+ let head = Buffer.alloc(0);+ let ended = false;+ let settled = false;+ const detach = () => {+ body.off("data", onData);+ body.off("end", onEnd);+ body.off("error", onBroken);+ body.off("close", onClose);+ };+ const fail = (refusal: UploadRefusal) => {+ if (settled) return;+ settled = true;+ detach();+ body.pause();+ out.once("close", () => resolve({ ok: false, size, refusal }));+ out.destroy();+ };+ const onData = (data: Buffer | string) => {+ const chunk = typeof data === "string" ? Buffer.from(data) : data;+ size += chunk.length;+ batch.bytes += chunk.length;+ if (size > limits.fileBytes) return fail(tooLarge(limits));+ if (batch.bytes > limits.messageBytes) return fail(messageTooLarge(limits));+ if (head.length < SNIFF_BYTES) head = Buffer.concat([head, chunk.subarray(0, SNIFF_BYTES)]);+ if (!out.write(chunk)) {+ body.pause();+ out.once("drain", () => body.resume());+ }+ };+ const onEnd = () => {+ ended = true;+ detach();+ out.end();+ };+ const onBroken = () =>+ fail({+ ok: false,+ status: 400,+ code: "upload_failed",+ message: "The upload did not finish. Try again.",+ });+ const onClose = () => {+ if (!ended) onBroken();+ };+ out.on("error", onBroken);+ out.on("close", () => {+ if (settled) return;+ settled = true;+ resolve({ ok: true, size, head: head.subarray(0, SNIFF_BYTES) });+ });+ body.on("data", onData);+ body.on("end", onEnd);+ body.on("error", onBroken);+ body.on("close", onClose);+ body.resume();+ });+ }++ /** The name, or "name (2).ext", "name (3).ext"… when the folder already has it. */+ private freeName(batch: Batch, name: string): string {+ const taken = (candidate: string) =>+ batch.files.has(candidate) || batch.writing.has(candidate) || existsSync(join(batch.dir, candidate));+ if (!taken(name)) return name;+ const extension = extname(name);+ const stem = name.slice(0, name.length - extension.length);+ for (let n = 2; ; n++) {+ const candidate = `${stem} (${n})${extension}`;+ if (!taken(candidate)) return candidate;+ }+ }++ private dropIfEmpty(uploadId: string, batch: Batch): void {+ if (batch.files.size > 0 || batch.writing.size > 0) return;+ this.batches.delete(uploadId);+ try {+ rmdirSync(batch.dir);+ } catch {+ // Not empty or already gone.+ }+ }++ /** Removes message folders that were never sent. */+ private prune(): void {+ const cutoff = this.now() - this.ttlMs;+ for (const [uploadId, batch] of this.batches) {+ if (batch.createdAt > cutoff || batch.writing.size > 0) continue;+ this.batches.delete(uploadId);+ rmSync(batch.dir, { recursive: true, force: true });+ }+ }+}++function removeQuietly(path: string): void {+ try {+ unlinkSync(path);+ } catch {+ // Never created, or already removed.+ }+}++const INTRO =+ "The user attached these files, saved in your workspace. Read them with your tools when needed.";+const BLOCK_START = "<attachments>";+const BLOCK_END = "</attachments>";++/**+ * The prompt for a message with files: the user's text, then a block with each file's name, size,+ * type, and absolute path. Images go to the model as images only when it accepts them.+ */+export function composePrompt(+ text: string,+ files: StoredFile[],+ options: { images: boolean | undefined; read?: (path: string) => Buffer },+): { message: string; images?: { type: "image"; mimeType: string; data: string }[] } {+ const read = options.read ?? ((path: string) => readFileSync(path));+ const images: { type: "image"; mimeType: string; data: string }[] = [];+ const lines = files.map((file) => {+ const entry: Record<string, unknown> = {+ name: file.name,+ size: file.size,+ type: file.mime,+ path: file.path,+ };+ if (IMAGE_TYPES.has(file.mime)) {+ if (file.size > MAX_IMAGE_BYTES) entry.image = "too large to show you; read it from the path if needed";+ else if (options.images === true) {+ images.push({ type: "image", mimeType: file.mime, data: read(file.path).toString("base64") });+ entry.image = "attached to this message";+ } else entry.image = "saved, but the current model cannot see images";+ }+ return JSON.stringify(entry);+ });+ const block = [BLOCK_START, INTRO, ...lines, BLOCK_END].join("\n");+ const message = text === "" ? block : `${text}\n\n${block}`;+ return images.length > 0 ? { message, images } : { message };+}++/** Splits a user message into the text the user typed and the chips of the files the daemon appended. */+export function splitAttachments(message: string): { text: string; attachments: AttachmentInfo[] } {+ const none = { text: message, attachments: [] };+ if (!message.endsWith(`\n${BLOCK_END}`)) return none;+ const start = message.lastIndexOf(`${BLOCK_START}\n${INTRO}\n`);+ if (start < 0 || (start > 0 && message.slice(start - 2, start) !== "\n\n")) return none;+ const lines = message+ .slice(start, -BLOCK_END.length - 1)+ .split("\n")+ .slice(2);+ const attachments: AttachmentInfo[] = [];+ for (const line of lines) {+ let entry: Record<string, unknown>;+ try {+ entry = JSON.parse(line) as Record<string, unknown>;+ } catch {+ return none;+ }+ const { name, size, type } = entry;+ if (typeof name !== "string" || typeof size !== "number" || typeof type !== "string") return none;+ attachments.push({ name, size, mime: type });+ }+ if (attachments.length === 0) return none;+ return { text: message.slice(0, Math.max(0, start - 2)), attachments };+}diff --git a/packages/daemon/test/attachments-gateway.test.ts b/packages/daemon/test/attachments-gateway.test.tsnew file mode 100644index 0000000..af33028--- /dev/null+++ b/packages/daemon/test/attachments-gateway.test.ts@@ -0,0 +1,172 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { request } from "node:http";+import { join } from "node:path";+import type { ServerMessage, UploadedFile } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 1, 2, 3]);++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++type Prompt = { type: "prompt"; message: string; images?: unknown[]; streamingBehavior?: string };++async function setup() {+ const dataDir = tempDir();+ const uiDir = join(dataDir, "ui");+ mkdirSync(uiDir);+ writeFileSync(join(uiDir, "index.html"), "<!doctype html>");+ const workspace = join(dataDir, "workspace");+ const promptsFile = join(dataDir, "prompts.jsonl");+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace,+ uiDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentEnv: { ...process.env, FAKE_AGENT_PROMPTS_FILE: promptsFile },+ backoffMs: [50],+ });+ daemons.push(d);+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (message: object) => ws.send(JSON.stringify(message));+ const find = <T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ ) =>+ waitFor(() =>+ messages.find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+ const prompts = (): Prompt[] =>+ existsSync(promptsFile)+ ? readFileSync(promptsFile, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as Prompt)+ : [];+ const upload = (name: string, body: Buffer | string, uploadId?: string) =>+ new Promise<UploadedFile>((resolve, reject) => {+ const req = request(+ {+ host: "127.0.0.1",+ port: d.port,+ path: "/upload",+ method: "POST",+ headers: {+ Authorization: `Bearer ${d.token}`,+ "X-File-Name": encodeURIComponent(name),+ ...(uploadId ? { "X-Upload-Id": uploadId } : {}),+ },+ },+ (res) => {+ let text = "";+ res.on("data", (chunk) => {+ text += chunk;+ });+ res.on("end", () =>+ res.statusCode === 200 ? resolve(JSON.parse(text) as UploadedFile) : reject(new Error(text)),+ );+ },+ );+ req.on("error", reject);+ req.end(body);+ });+ return { d, workspace, messages, send, find, prompts, upload };+}++describe("sending files to the assistant", () => {+ it("leaves a plain message unchanged (regression)", async () => {+ const { send, find, prompts } = await setup();+ send({ type: "send", text: "hello", requestId: "r1" });+ const shown = await find("user_message");+ expect(shown).toEqual({+ type: "user_message",+ messageId: shown.messageId,+ text: "hello",+ seq: shown.seq,+ });+ await find("message_done");+ expect(prompts()).toEqual([{ type: "prompt", message: "hello" }]);+ });++ it("tells the assistant each file's path, shows chips instead, and passes images to a model that sees them", async () => {+ const { send, find, prompts, upload, workspace } = await setup();+ const doc = await upload("report.txt", "quarterly numbers");+ const shot = await upload("shot.png", PNG, doc.uploadId);+ send({+ type: "send",+ text: "what do you see?",+ requestId: "r1",+ attachments: [+ { uploadId: doc.uploadId, name: doc.name },+ { uploadId: shot.uploadId, name: shot.name },+ ],+ });+ const shown = await find("user_message");+ expect(shown.text).toBe("what do you see?");+ expect(shown.attachments).toEqual([+ { name: "report.txt", size: 17, mime: "application/octet-stream" },+ { name: "shot.png", size: PNG.length, mime: "image/png" },+ ]);+ await find("message_done");+ const [prompt] = prompts();+ expect(prompt?.message.startsWith("what do you see?\n\n<attachments>\n")).toBe(true);+ expect(prompt?.message).toContain(JSON.stringify(join(workspace, doc.path)));+ expect(prompt?.message).toContain(JSON.stringify(join(workspace, shot.path)));+ expect(prompt?.images).toEqual([{ type: "image", mimeType: "image/png", data: PNG.toString("base64") }]);++ // History keeps the chips and hides the block.+ send({ type: "get_history" });+ const history = await find("history", (h) => h.messages.length >= 2);+ const user = history.messages.find((m) => m.role === "user");+ expect(user?.text).toBe("what do you see?");+ expect(user?.attachments?.map((a) => a.name)).toEqual(["report.txt", "shot.png"]);+ });++ it("keeps images out of the prompt when the model cannot see them, and says so", async () => {+ const { d, send, find, prompts, upload } = await setup();+ await d.supervisor.request({ type: "set_model", provider: "fake", modelId: "fake-fast" });+ const shot = await upload("shot.png", PNG);+ send({ type: "send", text: "", attachments: [{ uploadId: shot.uploadId, name: shot.name }] });+ const shown = await find("user_message");+ expect(shown.text).toBe("");+ await find("message_done");+ const [prompt] = prompts();+ expect(prompt?.images).toBeUndefined();+ expect(prompt?.message).toMatch(/cannot see images/);+ });++ it("refuses unknown and already sent uploads without prompting", async () => {+ const { send, find, prompts, upload, messages } = await setup();+ const refusals = () => messages.filter((m) => m.type === "error" && m.code === "attachment_not_found");+ send({+ type: "send",+ text: "here",+ attachments: [{ uploadId: "u_00000000000000000000", name: "a.txt" }],+ });+ expect((await find("error")).code).toBe("attachment_not_found");+ const doc = await upload("a.txt", "hi");+ const ref = { uploadId: doc.uploadId, name: doc.name };+ send({ type: "send", text: "first", attachments: [ref] });+ await find("message_done");+ send({ type: "send", text: "again", attachments: [ref] });+ await waitFor(() => refusals().length === 2);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(prompts().map((p) => p.message.split("\n")[0])).toEqual(["first"]);+ });+});diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex ddadb7c..2debb6b 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -36,6 +36,7 @@// FAKE_AGENT_IGNORE_ABORT answer abort but keep running (a session switch still ends the run)// FAKE_AGENT_START_DELAY_MS answer the first get_state only after this delay// FAKE_AGENT_DROP_CUSTOM load session files without their custom messages (a format drift)+// FAKE_AGENT_PROMPTS_FILE append every prompt command (message, images, streamingBehavior) as JSONL// get_available_models lists MODELS; set_model and set_thinking_level change what// get_state reports, so tests can read the last values back. A model's `input` says whether it// accepts images, like the engine's models.@@ -44,7 +45,12 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } frimport { join } from "node:path";type Rec = Record<string, unknown>;-type Message = { role: "user" | "assistant" | "custom"; content: string; customType?: string };+type Message = {+ role: "user" | "assistant" | "custom";+ content: string;+ customType?: string;+ images?: Rec[];+};const MODELS: Rec[] = [{@@ -175,7 +181,13 @@ function appendEntry(entry: Rec): void {function remember(message: Message): void {messages.push(message);- const content = message.role === "assistant" ? [{ type: "text", text: message.content }] : message.content;+ // Like Pi, a user message with images keeps them as content blocks after the text.+ const content =+ message.role === "assistant"+ ? [{ type: "text", text: message.content }]+ : message.images+ ? [{ type: "text", text: message.content }, ...message.images]+ : message.content;appendEntry({ type: "message", message: { role: message.role, content } });}@@ -212,10 +224,11 @@ function enqueue(text: string, behavior: unknown): void {emitQueue();}-function userMessage(text: string): void {- remember({ role: "user", content: text });- out({ type: "message_start", message: { role: "user", content: text } });- out({ type: "message_end", message: { role: "user", content: text } });+function userMessage(text: string, images?: Rec[]): void {+ remember(images ? { role: "user", content: text, images } : { role: "user", content: text });+ const content = images ? [{ type: "text", text }, ...images] : text;+ out({ type: "message_start", message: { role: "user", content } });+ out({ type: "message_end", message: { role: "user", content } });}function endRun(): void {@@ -243,22 +256,22 @@ function endedAnswer(stopReason: "aborted" | "error", errorMessage: string): voiout({ type: "message_end", message });}-async function run(text: string) {+async function run(text: string, images?: Rec[]) {busy = true;let ended: () => void = () => {};runEnded = new Promise((resolve) => {ended = resolve;});try {- await runPrompt(text);+ await runPrompt(text, images);} finally {ended();}}-async function runPrompt(text: string) {+async function runPrompt(text: string, images?: Rec[]) {out({ type: "agent_start" });- userMessage(text);+ userMessage(text, images);if (text === "crash") {// Give the pipe time to flush; macOS pipes are asynchronous.setTimeout(() => process.exit(1), 50);@@ -404,6 +417,10 @@ function handle(rec: Rec) {case "get_commands":return respond(id, "get_commands", { commands: [{ name: "gentle:status" }, { name: "history" }] });case "prompt": {+ if (process.env.FAKE_AGENT_PROMPTS_FILE) {+ const { id: _id, ...command } = rec;+ appendFileSync(process.env.FAKE_AGENT_PROMPTS_FILE, `${JSON.stringify(command)}\n`);+ }if (busy && !rec.streamingBehavior) return respond(id, "prompt", undefined, "Agent is streaming");if (busy) {enqueue(String(rec.message), rec.streamingBehavior);@@ -413,7 +430,8 @@ function handle(rec: Rec) {const burst = String(rec.message).startsWith("burst");if (burst) batch = [];respond(id, "prompt", { disposition: "started" });- void run(burst ? String(rec.message).replace(/^burst:/, "") : String(rec.message));+ const images = Array.isArray(rec.images) && rec.images.length > 0 ? (rec.images as Rec[]) : undefined;+ void run(burst ? String(rec.message).replace(/^burst:/, "") : String(rec.message), images);if (batch) {process.stdout.write(batch.join(""));batch = undefined;diff --git a/packages/daemon/test/uploads.test.ts b/packages/daemon/test/uploads.test.tsnew file mode 100644index 0000000..72aa824--- /dev/null+++ b/packages/daemon/test/uploads.test.ts@@ -0,0 +1,389 @@+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { request } from "node:http";+import { join } from "node:path";+import { Readable } from "node:stream";+import type { UploadedFile } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import { type DaemonOptions, type DotDaemon, startDaemon } from "../src/daemon.ts";+import { composePrompt, sanitizeName, sniffMime, splitAttachments, UploadStore } from "../src/uploads.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 1, 2, 3]);+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46]);+const GIF = Buffer.from("GIF89a\x01\x00\x01\x00", "latin1");+const WEBP = Buffer.concat([Buffer.from("RIFF"), Buffer.from([1, 0, 0, 0]), Buffer.from("WEBPVP8 ")]);++describe("file names", () => {+ it("keeps only a safe base name", () => {+ expect(sanitizeName("report.pdf")).toBe("report.pdf");+ expect(sanitizeName("../x")).toBe("x");+ expect(sanitizeName("../../etc/passwd")).toBe("passwd");+ expect(sanitizeName("C:\\Users\\me\\notes.txt")).toBe("notes.txt");+ expect(sanitizeName(".env")).toBe("env");+ expect(sanitizeName("...hidden")).toBe("hidden");+ expect(sanitizeName("bad\u0000na\nme\u202e.txt")).toBe("badname.txt");+ expect(sanitizeName("..")).toBe("file");+ expect(sanitizeName("")).toBe("file");+ expect(sanitizeName(" ")).toBe("file");+ expect(sanitizeName("CON")).toBe("file");+ expect(sanitizeName("nul.txt")).toBe("file.txt");+ const long = sanitizeName(`${"a".repeat(300)}.png`);+ expect(long.length).toBeLessThanOrEqual(120);+ expect(long.endsWith(".png")).toBe(true);+ });+});++describe("image types", () => {+ it("tells PNG, JPEG, GIF, and WebP by their first bytes, never by the name", () => {+ expect(sniffMime(PNG)).toBe("image/png");+ expect(sniffMime(JPEG)).toBe("image/jpeg");+ expect(sniffMime(GIF)).toBe("image/gif");+ expect(sniffMime(WEBP)).toBe("image/webp");+ expect(sniffMime(Buffer.from("%PDF-1.7"))).toBe("application/pdf");+ expect(sniffMime(Buffer.from("plain text"))).toBe("application/octet-stream");+ expect(sniffMime(Buffer.alloc(0))).toBe("application/octet-stream");+ });+});++function store(limits = { fileBytes: 100, messageBytes: 150, files: 3 }) {+ const workspace = tempDir();+ return { workspace, uploads: new UploadStore({ workspace, limits }) };+}++const listUploads = (workspace: string) => {+ const root = join(workspace, "uploads");+ if (!existsSync(root)) return [];+ return readdirSync(root, { recursive: true }).map(String).sort();+};++describe("upload store", () => {+ it("stores a file privately under uploads/<id>/<name> and reports its metadata", async () => {+ const { workspace, uploads } = store();+ const outcome = await uploads.receive(Readable.from([PNG]), { name: "../shot.png" });+ if (!outcome.ok) throw new Error(outcome.message);+ const { uploadId, name, size, mime, path } = outcome.file;+ expect({ name, size, mime }).toEqual({ name: "shot.png", size: PNG.length, mime: "image/png" });+ expect(uploadId).toMatch(/^[A-Za-z0-9_-]{16,64}$/);+ expect(path).toBe(`uploads/${uploadId}/shot.png`);+ const file = join(workspace, path);+ expect(readFileSync(file)).toEqual(PNG);+ expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(statSync(join(workspace, "uploads", uploadId)).mode & 0o777).toBe(0o700);+ expect(statSync(join(workspace, "uploads")).mode & 0o777).toBe(0o700);+ });++ it("adds files to the same message folder, renaming duplicates", async () => {+ const { uploads } = store();+ const first = await uploads.receive(Readable.from(["a"]), { name: "notes.txt" });+ if (!first.ok) throw new Error(first.message);+ const uploadId = first.file.uploadId;+ const second = await uploads.receive(Readable.from(["b"]), { name: "notes.txt", uploadId });+ const third = await uploads.receive(Readable.from(["c"]), { name: "../notes.txt", uploadId });+ expect(second.ok && second.file.name).toBe("notes (2).txt");+ expect(third.ok && third.file.name).toBe("notes (3).txt");+ expect(second.ok && second.file.uploadId).toBe(uploadId);+ });++ it("refuses a file over the per-file limit while it streams, and leaves nothing behind", async () => {+ const { workspace, uploads } = store();+ const outcome = await uploads.receive(Readable.from([Buffer.alloc(60), Buffer.alloc(60)]), {+ name: "big.bin",+ });+ expect(outcome).toMatchObject({ ok: false, status: 413, code: "file_too_large" });+ expect(outcome.ok ? "" : outcome.message).toMatch(/too large/i);+ expect(listUploads(workspace)).toEqual([]);+ });++ it("refuses a declared size over the limit before reading anything", async () => {+ const { workspace, uploads } = store();+ const outcome = await uploads.receive(Readable.from([]), { name: "big.bin", length: 101 });+ expect(outcome).toMatchObject({ ok: false, status: 413, code: "file_too_large" });+ expect(listUploads(workspace)).toEqual([]);+ });++ it("enforces the per-message size and file count, keeping the files already stored", async () => {+ const { workspace, uploads } = store();+ const first = await uploads.receive(Readable.from([Buffer.alloc(100)]), { name: "a.bin" });+ if (!first.ok) throw new Error(first.message);+ const uploadId = first.file.uploadId;+ const over = await uploads.receive(Readable.from([Buffer.alloc(30), Buffer.alloc(30)]), {+ name: "b.bin",+ uploadId,+ });+ expect(over).toMatchObject({ ok: false, status: 413, code: "message_too_large" });+ expect(listUploads(workspace)).toEqual([uploadId, `${uploadId}/a.bin`]);+ await uploads.receive(Readable.from(["x"]), { name: "c.bin", uploadId });+ await uploads.receive(Readable.from(["x"]), { name: "d.bin", uploadId });+ const fourth = await uploads.receive(Readable.from(["x"]), { name: "e.bin", uploadId });+ expect(fourth).toMatchObject({ ok: false, status: 413, code: "too_many_files" });+ });++ it("removes a partial file when the upload breaks off", async () => {+ const { workspace, uploads } = store();+ const body = new Readable({ read() {} });+ const pending = uploads.receive(body, { name: "cut.bin" });+ body.push(Buffer.alloc(10));+ await new Promise((resolve) => setTimeout(resolve, 20));+ body.destroy(new Error("connection reset"));+ expect(await pending).toMatchObject({ ok: false, code: "upload_failed" });+ expect(listUploads(workspace)).toEqual([]);+ });++ it("refuses an unknown message folder", async () => {+ const { uploads } = store();+ const outcome = await uploads.receive(Readable.from(["x"]), {+ name: "a.txt",+ uploadId: "u_00000000000000000000",+ });+ expect(outcome).toMatchObject({ ok: false, status: 404, code: "upload_not_found" });+ });++ it("hands out stored files once: unknown names and used uploads are refused", async () => {+ const { workspace, uploads } = store();+ const sent = await uploads.receive(Readable.from(["hello"]), { name: "a.txt" });+ if (!sent.ok) throw new Error(sent.message);+ const ref = { uploadId: sent.file.uploadId, name: "a.txt" };+ expect(uploads.resolve([{ ...ref, name: "zzz.txt" }])).toMatchObject({ ok: false });+ expect(uploads.resolve([{ uploadId: "u_00000000000000000000", name: "a.txt" }])).toMatchObject({+ ok: false,+ });+ const found = uploads.resolve([ref]);+ expect(found).toMatchObject({+ ok: true,+ files: [+ {+ name: "a.txt",+ size: 5,+ mime: "application/octet-stream",+ path: join(workspace, "uploads", ref.uploadId, "a.txt"),+ },+ ],+ });+ uploads.consume([ref]);+ expect(uploads.resolve([ref])).toMatchObject({ ok: false, code: "attachment_not_found" });+ // The file itself stays for the assistant to read.+ expect(existsSync(join(workspace, "uploads", ref.uploadId, "a.txt"))).toBe(true);+ });+});++describe("the prompt for a message with files", () => {+ const doc = { name: "report.pdf", size: 1234, mime: "application/pdf", path: "/w/uploads/u1/report.pdf" };+ const image = { name: "shot.png", size: PNG.length, mime: "image/png", path: "/w/uploads/u1/shot.png" };+ const read = () => PNG;++ it("appends a block with each file's name and absolute path", () => {+ const { message, images } = composePrompt("summarize this", [doc], { images: true, read });+ expect(message.startsWith("summarize this\n\n<attachments>\n")).toBe(true);+ expect(message).toContain('"path":"/w/uploads/u1/report.pdf"');+ expect(message).toContain('"name":"report.pdf"');+ expect(images).toBeUndefined();+ });++ it("passes images to a model that accepts them, and notes it when the model does not", () => {+ const seeing = composePrompt("", [image], { images: true, read });+ expect(seeing.images).toEqual([{ type: "image", mimeType: "image/png", data: PNG.toString("base64") }]);+ expect(seeing.message.startsWith("<attachments>\n")).toBe(true);+ const blind = composePrompt("what is it", [image], { images: false, read });+ expect(blind.images).toBeUndefined();+ expect(blind.message).toMatch(/cannot see images/);+ const unknown = composePrompt("what is it", [image], { images: undefined, read });+ expect(unknown.images).toBeUndefined();+ });++ it("does not pass an image that is too large to show", () => {+ const huge = { ...image, size: 20 * 1024 * 1024 };+ const { images, message } = composePrompt("x", [huge], { images: true, read });+ expect(images).toBeUndefined();+ expect(message).toMatch(/too large/);+ });++ it("reads back the user's own text and the attachment chips", () => {+ const { message } = composePrompt("summarize this", [doc, image], { images: true, read });+ expect(splitAttachments(message)).toEqual({+ text: "summarize this",+ attachments: [+ { name: "report.pdf", size: 1234, mime: "application/pdf" },+ { name: "shot.png", size: PNG.length, mime: "image/png" },+ ],+ });+ expect(splitAttachments(composePrompt("", [doc], { images: true, read }).message).text).toBe("");+ expect(splitAttachments("no files here")).toEqual({ text: "no files here", attachments: [] });+ const typed = "look: <attachments>\nnot a block\n</attachments>";+ expect(splitAttachments(typed)).toEqual({ text: typed, attachments: [] });+ });+});++// ---------------------------------------------------------------- over HTTP++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++async function daemon(extra: Partial<DaemonOptions> = {}) {+ const dataDir = tempDir();+ const uiDir = join(dataDir, "ui");+ mkdirSync(uiDir);+ writeFileSync(join(uiDir, "index.html"), "<!doctype html><title>Gentle Dot</title>");+ const workspace = join(dataDir, "workspace");+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace,+ uiDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ backoffMs: [50],+ ...extra,+ });+ daemons.push(d);+ return { d, workspace };+}++type Reply = { status: number; headers: Record<string, string | string[] | undefined>; body: string };++function post(+ d: DotDaemon,+ options: { path?: string; method?: string; headers?: Record<string, string>; body?: Buffer | string },+): Promise<Reply> {+ return new Promise((resolve, reject) => {+ const req = request(+ {+ host: "127.0.0.1",+ port: d.port,+ path: options.path ?? "/upload",+ method: options.method ?? "POST",+ headers: options.headers ?? {},+ },+ (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (chunk) => {+ body += chunk;+ });+ res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }));+ },+ );+ req.on("error", reject);+ req.end(options.body);+ });+}++const auth = (d: DotDaemon, name = "notes.txt", extra: Record<string, string> = {}) => ({+ Authorization: `Bearer ${d.token}`,+ "X-File-Name": encodeURIComponent(name),+ "Content-Type": "application/octet-stream",+ ...extra,+});++describe("POST /upload", () => {+ it("requires the access key in the Authorization header, never in the address", async () => {+ const { d, workspace } = await daemon();+ const missing = await post(d, { headers: { "X-File-Name": "a.txt" }, body: "x" });+ expect(missing.status).toBe(401);+ const wrong = await post(d, { headers: { ...auth(d), Authorization: "Bearer wrong" }, body: "x" });+ expect(wrong.status).toBe(401);+ const query = await post(d, {+ path: `/upload?token=${d.token}`,+ headers: { "X-File-Name": "a.txt" },+ body: "x",+ });+ expect(query.status).toBe(401);+ expect(listUploads(workspace)).toEqual([]);+ });++ it("rejects a foreign Origin, like the WebSocket", async () => {+ const { d, workspace } = await daemon();+ const reply = await post(d, { headers: { ...auth(d), Origin: "https://evil.example" }, body: "x" });+ expect(reply.status).toBe(403);+ const preflight = await post(d, {+ method: "OPTIONS",+ headers: { Origin: "https://evil.example", "Access-Control-Request-Method": "POST" },+ });+ expect(preflight.status).toBe(403);+ expect(listUploads(workspace)).toEqual([]);+ });++ it("answers the desktop app's preflight and stores its file", async () => {+ const { d, workspace } = await daemon();+ const preflight = await post(d, {+ method: "OPTIONS",+ headers: {+ Origin: "tauri://localhost",+ "Access-Control-Request-Method": "POST",+ "Access-Control-Request-Headers": "authorization,x-file-name,x-upload-id,content-type",+ },+ });+ expect(preflight.status).toBe(204);+ expect(preflight.headers["access-control-allow-origin"]).toBe("tauri://localhost");+ expect(String(preflight.headers["access-control-allow-headers"]).toLowerCase()).toContain("x-upload-id");+ const reply = await post(d, {+ headers: auth(d, "../../shot.png", { Origin: "tauri://localhost" }),+ body: PNG,+ });+ expect(reply.status).toBe(200);+ expect(reply.headers["access-control-allow-origin"]).toBe("tauri://localhost");+ const file = JSON.parse(reply.body) as UploadedFile;+ expect(file).toMatchObject({ name: "shot.png", size: PNG.length, mime: "image/png" });+ expect(file.path).toBe(`uploads/${file.uploadId}/shot.png`);+ expect(statSync(join(workspace, file.path)).mode & 0o777).toBe(0o600);+ expect(statSync(join(workspace, "uploads", file.uploadId)).mode & 0o777).toBe(0o700);+ });++ it("enforces the size limits on the server and cleans up", async () => {+ const { d, workspace } = await daemon({+ uploadLimits: { fileBytes: 1000, messageBytes: 1500, files: 10 },+ });+ const declared = await post(d, {+ headers: auth(d, "big.bin", { "Content-Length": "5000" }),+ body: Buffer.alloc(5000),+ });+ expect(declared.status).toBe(413);+ expect(JSON.parse(declared.body)).toMatchObject({ code: "file_too_large" });+ const streamed = await post(d, {+ headers: { ...auth(d, "big.bin"), "Transfer-Encoding": "chunked" },+ body: Buffer.alloc(5000),+ });+ expect(streamed.status).toBe(413);+ await waitFor(() => listUploads(workspace).length === 0);+ });++ it("refuses an unknown upload id and a request without a file name", async () => {+ const { d } = await daemon();+ const unknown = await post(d, {+ headers: auth(d, "a.txt", { "X-Upload-Id": "u_00000000000000000000" }),+ body: "x",+ });+ expect(unknown.status).toBe(404);+ const nameless = await post(d, { headers: { Authorization: `Bearer ${d.token}` }, body: "x" });+ expect(nameless.status).toBe(400);+ });++ it("removes the partial file when the client hangs up mid-upload", async () => {+ const { d, workspace } = await daemon();+ await new Promise<void>((resolve) => {+ const req = request({+ host: "127.0.0.1",+ port: d.port,+ path: "/upload",+ method: "POST",+ headers: { ...auth(d, "cut.bin"), "Content-Length": "100000" },+ });+ req.on("error", () => resolve());+ req.write(Buffer.alloc(1000));+ setTimeout(() => {+ req.destroy();+ resolve();+ }, 100);+ });+ await waitFor(() => listUploads(workspace).length === 0 || undefined);+ expect(listUploads(workspace)).toEqual([]);+ });++ it("still serves the interface and refuses other methods elsewhere", async () => {+ const { d } = await daemon();+ expect((await post(d, { path: "/", method: "GET" })).status).toBe(200);+ expect((await post(d, { path: "/other", method: "POST", body: "x" })).status).toBe(405);+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex a944980..f5a684c 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -29,11 +29,43 @@ export interface Ask {timeoutMs?: number;}+/** A file the user sent with a message, as its chip shows it (S31). */+export interface AttachmentInfo {+ name: string;+ size: number;+ mime: string;+}++/** A file uploaded with `POST /upload`, waiting to be sent with a message. */+export interface AttachmentRef {+ /** The message folder the daemon gave the first file; later files of the message reuse it. */+ uploadId: string;+ /** The name the daemon stored the file under. */+ name: string;+}++/** The daemon's answer to `POST /upload`. */+export interface UploadedFile extends AttachmentRef, AttachmentInfo {+ /** Where the file is, relative to the assistant's workspace: `uploads/<uploadId>/<name>`. */+ path: string;+}++/** Limits the daemon enforces on uploads (S31.3); the app checks them first to explain a refusal. */+export const ATTACHMENT_LIMITS = {+ fileBytes: 25 * 1024 * 1024,+ messageBytes: 50 * 1024 * 1024,+ files: 10,+} as const;++export type AttachmentLimits = { fileBytes: number; messageBytes: number; files: number };+export interface HistoryMessage {id: string;role: "user" | "assistant";text: string;activities: Activity[];+ /** Files the user sent with the message. */+ attachments?: AttachmentInfo[];/** From an earlier session of the same chat, before the daemon last rotated it. */earlier?: true;}@@ -257,7 +289,8 @@ export function parseProfileRoles(value: unknown): ProfileRoles | undefined {export type ClientMessage =| { type: "hello"; token: string; protocol: number }- | { type: "send"; text: string; requestId?: string }+ /** `text` may be empty when files are attached. */+ | { type: "send"; text: string; requestId?: string; attachments?: AttachmentRef[] }| { type: "steer"; text: string }| { type: "abort" }| { type: "ui_response"; requestId: string; value?: string; confirmed?: boolean; cancelled?: boolean }@@ -310,7 +343,7 @@ export type ServerPayload =voice?: VoiceCapability;}| { type: "agent_state"; state: AgentState }- | { type: "user_message"; messageId: string; text: string }+ | { type: "user_message"; messageId: string; text: string; attachments?: AttachmentInfo[] }| { type: "message_delta"; messageId: string; delta: string }| {type: "message_done";@@ -404,6 +437,23 @@ export function parseQueue(value: unknown): MessageQueue | undefined {return { steering: texts(steering), followUp: texts(followUp) };}+const UPLOAD_ID = /^[A-Za-z0-9_-]{8,64}$/;+const MAX_NAME = 255;++/** 1-10 uploaded files: an upload id and a stored name, never a path. */+function parseAttachments(value: unknown): AttachmentRef[] | undefined {+ if (!Array.isArray(value) || value.length === 0 || value.length > ATTACHMENT_LIMITS.files) return undefined;+ const refs: AttachmentRef[] = [];+ for (const item of value) {+ if (typeof item !== "object" || item === null) return undefined;+ const { uploadId, name } = item as Record<string, unknown>;+ if (!isString(uploadId) || !UPLOAD_ID.test(uploadId)) return undefined;+ if (!isString(name) || name === "" || name.length > MAX_NAME || /[/\\\0]/.test(name)) return undefined;+ refs.push({ uploadId, name });+ }+ return refs;+}+/** Validates one raw client frame; returns undefined when it is not a known, well-formed message. */export function parseClientMessage(raw: string): ClientMessage | undefined {let value: unknown;@@ -419,12 +469,17 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {return isString(m.token) && typeof m.protocol === "number"? { type: "hello", token: m.token, protocol: m.protocol }: undefined;- case "send":- if (!isString(m.text) || m.text.trim() === "" || m.text.length > MAX_TEXT) return undefined;+ case "send": {+ const attachments = m.attachments === undefined ? undefined : parseAttachments(m.attachments);+ if (m.attachments !== undefined && !attachments) return undefined;+ if (!isString(m.text) || m.text.length > MAX_TEXT) return undefined;+ if (m.text.trim() === "" && !attachments) return undefined;if (!isOptional(m.requestId, isString)) return undefined;- return m.requestId === undefined- ? { type: "send", text: m.text }- : { type: "send", text: m.text, requestId: m.requestId as string };+ const send: Extract<ClientMessage, { type: "send" }> = { type: "send", text: m.text };+ if (m.requestId !== undefined) send.requestId = m.requestId as string;+ if (attachments) send.attachments = attachments;+ return send;+ }case "steer":return isString(m.text) && m.text.trim() !== "" && m.text.length <= MAX_TEXT? { type: "steer", text: m.text }diff --git a/packages/protocol/test/attachments.test.ts b/packages/protocol/test/attachments.test.tsnew file mode 100644index 0000000..4d9cc35--- /dev/null+++ b/packages/protocol/test/attachments.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import { ATTACHMENT_LIMITS, parseClientMessage } from "../src/index.ts";++const parse = (value: object) => parseClientMessage(JSON.stringify(value));+const UPLOAD = "u_0123456789abcdef";++describe("send with attachments (S31)", () => {+ it("leaves a plain send unchanged", () => {+ expect(parse({ type: "send", text: "hello" })).toEqual({ type: "send", text: "hello" });+ expect(parse({ type: "send", text: "hello", requestId: "r1" })).toEqual({+ type: "send",+ text: "hello",+ requestId: "r1",+ });+ expect(parse({ type: "send", text: " " })).toBeUndefined();+ });++ it("accepts files uploaded for the message, with or without text", () => {+ const attachments = [+ { uploadId: UPLOAD, name: "report.pdf" },+ { uploadId: UPLOAD, name: "photo (2).png", extra: true },+ ];+ expect(parse({ type: "send", text: "look", requestId: "r1", attachments })).toEqual({+ type: "send",+ text: "look",+ requestId: "r1",+ attachments: [+ { uploadId: UPLOAD, name: "report.pdf" },+ { uploadId: UPLOAD, name: "photo (2).png" },+ ],+ });+ expect(parse({ type: "send", text: "", attachments: [{ uploadId: UPLOAD, name: "a.txt" }] })).toEqual({+ type: "send",+ text: "",+ attachments: [{ uploadId: UPLOAD, name: "a.txt" }],+ });+ });++ it("refuses malformed attachments and more files than a message may carry", () => {+ const one = { uploadId: UPLOAD, name: "a.txt" };+ expect(parse({ type: "send", text: "x", attachments: [] })).toBeUndefined();+ expect(parse({ type: "send", text: "", attachments: [] })).toBeUndefined();+ expect(parse({ type: "send", text: "x", attachments: one })).toBeUndefined();+ expect(+ parse({ type: "send", text: "x", attachments: [{ uploadId: "../etc", name: "a" }] }),+ ).toBeUndefined();+ expect(parse({ type: "send", text: "x", attachments: [{ uploadId: UPLOAD, name: "" }] })).toBeUndefined();+ expect(+ parse({ type: "send", text: "x", attachments: [{ uploadId: UPLOAD, name: "a/b.txt" }] }),+ ).toBeUndefined();+ expect(+ parse({ type: "send", text: "x", attachments: [{ uploadId: UPLOAD, name: "x".repeat(256) }] }),+ ).toBeUndefined();+ const many = Array.from({ length: ATTACHMENT_LIMITS.files + 1 }, (_, i) => ({+ uploadId: UPLOAD,+ name: `f${i}.txt`,+ }));+ expect(parse({ type: "send", text: "x", attachments: many })).toBeUndefined();+ expect(parse({ type: "send", text: "x", attachments: many.slice(1) })?.type).toBe("send");+ });++ it("states the limits: 25 MB per file, 10 files and 50 MB per message", () => {+ expect(ATTACHMENT_LIMITS).toEqual({+ fileBytes: 25 * 1024 * 1024,+ messageBytes: 50 * 1024 * 1024,+ files: 10,+ });+ });+});diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsxindex 038e950..691288e 100644--- a/packages/ui/src/App.tsx+++ b/packages/ui/src/App.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { type ConnectionInfo, tokenFromLocation } from "./client.ts";import { ChatSurface } from "./components/ChatSurface.tsx";import type { ComputerControls } from "./components/Computer.tsx";@@ -14,6 +14,7 @@ import {startDragging,togglePanel,} from "./desktop.ts";+import { createUploader } from "./uploads.ts";import { useComputerRegistration, useComputerState } from "./useComputer.ts";import { useDot } from "./useDot.ts";import { usePanelWindow } from "./usePanelWindow.ts";@@ -62,6 +63,8 @@ function Assistant({ surface }: { surface: Surface }) {const [missingToken, setMissingToken] = useState(false);const [focusKey, setFocusKey] = useState(0);const { state, send, dismiss, dispatch } = useDot(info);+ // Files go to the daemon over HTTP, with the same access key as the WebSocket (S31.2).+ const upload = useMemo(() => (info ? createUploader(info) : undefined), [info]);const conversations = useRef(state.features.conversations);conversations.current = state.features.conversations;// Computer control lives in the desktop app only (S24.7); the panel registers the helper.@@ -170,6 +173,7 @@ function Assistant({ surface }: { surface: Surface }) {{...(surface === "panel" ? { onHide: hidePanel } : {})}{...(computer ? { computer } : {})}{...(desktop && surface === "panel" ? { panelWindow: panel.controls } : {})}+ {...(upload ? { upload } : {})}/>);}diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex 55ba286..f054097 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -1,7 +1,9 @@import type { ClientMessage } from "@gentle-dot/protocol";-import { useState } from "react";+import { type DragEvent, useState } from "react";import { openUrl as openExternal } from "../desktop.ts";import { activeTitle, type DotAction, type DotState, isBusy, needsAccount } from "../store.ts";+import type { Uploader } from "../uploads.ts";+import { useAttachments } from "../useAttachments.ts";import type { PanelWindowControls } from "../usePanelWindow.ts";import { useVoice, type VoiceControls } from "../useVoice.ts";import { AccountsPanel } from "./AccountsPanel.tsx";@@ -42,6 +44,8 @@ interface ChatSurfaceProps {computer?: ComputerControls;/** Hiding the rose and full screen (S26), in the desktop panel only; the web page already fills the browser. */panelWindow?: PanelWindowControls;+ /** Sends files to the daemon (S31); without it the composer has no attachments. */+ upload?: Uploader;}const CONTINUE_TEXT = "Continue where you left off.";@@ -70,6 +74,7 @@ export function ChatSurface({openUrl = openExternal,computer,panelWindow,+ upload,}: ChatSurfaceProps) {const openAccounts = () => {send({ type: "auth_list" });@@ -85,6 +90,28 @@ export function ChatSurface({};const [showConversations, setShowConversations] = useState(false);const voice = useVoice(state, send);+ const attachments = useAttachments(upload);+ /** Files are being dragged over the chat. */+ const [dropping, setDropping] = useState(false);+ const carriesFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes("Files");+ const dropHandlers = attachments+ ? {+ onDragOver: (event: DragEvent<HTMLDivElement>) => {+ if (!carriesFiles(event)) return;+ event.preventDefault();+ setDropping(true);+ },+ onDragLeave: (event: DragEvent<HTMLDivElement>) => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDropping(false);+ },+ onDrop: (event: DragEvent<HTMLDivElement>) => {+ if (!carriesFiles(event)) return;+ event.preventDefault();+ setDropping(false);+ attachments.add(Array.from(event.dataTransfer.files));+ },+ }+ : {};/** A switch that waits for the user to confirm stopping the running answer. */const [pendingSwitch, setPendingSwitch] = useState<SwitchMessage | undefined>(undefined);const switchTo = (message: SwitchMessage) => {@@ -109,8 +136,9 @@ export function ChatSurface({return (<div- className={`chat chat-${variant}${panelWindow?.fullscreen ? " chat-fullscreen" : ""}`}+ className={`chat chat-${variant}${panelWindow?.fullscreen ? " chat-fullscreen" : ""}${dropping ? " chat-dropping" : ""}`}data-state={state.agentState}+ {...dropHandlers}><header className="chat-header" data-tauri-drag-region={variant === "panel" ? "" : undefined}><span className={`state-dot state-${state.agentState}`} aria-hidden="true" />@@ -327,6 +355,7 @@ export function ChatSurface({focusKey={focusKey}onStartTyping={closeOptions}voice={voice}+ {...(attachments ? { attachments } : {})}/></div>);diff --git a/packages/ui/src/components/Composer.tsx b/packages/ui/src/components/Composer.tsxindex 2bce319..2b52ec1 100644--- a/packages/ui/src/components/Composer.tsx+++ b/packages/ui/src/components/Composer.tsx@@ -1,6 +1,8 @@-import { type KeyboardEvent, useEffect, useRef, useState } from "react";+import { type ClipboardEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";+import { formatSize } from "../uploads.ts";+import type { AttachmentControls, PendingFile } from "../useAttachments.ts";import type { VoiceControls } from "../useVoice.ts";-import { MicIcon, SendIcon } from "./icons.tsx";+import { MicIcon, PaperclipIcon, SendIcon } from "./icons.tsx";import { newRequestId, type Send } from "./types.ts";interface ComposerProps {@@ -13,9 +15,19 @@ interface ComposerProps {onStartTyping?: () => void;/** Talking to the assistant (S30.4); without it there is no mic. */voice?: VoiceControls;+ /** Files for the message (S31.1); without it there is no attach button. */+ attachments?: AttachmentControls;}-export function Composer({ busy, disabled, send, focusKey, onStartTyping, voice }: ComposerProps) {+export function Composer({+ busy,+ disabled,+ send,+ focusKey,+ onStartTyping,+ voice,+ attachments,+}: ComposerProps) {const [text, setText] = useState("");const box = useRef<HTMLTextAreaElement>(null);const recording = voice?.phase === "recording";@@ -25,18 +37,35 @@ export function Composer({ busy, disabled, send, focusKey, onStartTyping, voiceif (focusKey !== undefined) box.current?.focus();}, [focusKey]);- function submit() {+ const files = attachments?.files ?? [];+ const uploading = attachments?.uploading === true;+ const blocked = files.some((f) => f.refused);++ async function submit() {const value = text.trim();- if (!value || disabled) return;- send({ type: "send", text: value, requestId: newRequestId() });+ if ((!value && files.length === 0) || disabled || uploading || blocked) return;+ // Files upload on send; a failed one keeps the message so sending again retries it.+ const refs = files.length > 0 ? await attachments?.upload() : undefined;+ if (files.length > 0 && !refs) return;+ send({ type: "send", text: value, requestId: newRequestId(), ...(refs ? { attachments: refs } : {}) });+ attachments?.clear();voice?.typed();setText("");}+ /** A pasted image becomes an attachment; pasted text stays text. */+ function onPaste(event: ClipboardEvent<HTMLTextAreaElement>) {+ if (!attachments) return;+ const images = Array.from(event.clipboardData?.files ?? []).filter((f) => f.type.startsWith("image/"));+ if (images.length === 0) return;+ event.preventDefault();+ attachments.add(images);+ }+function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {event.preventDefault();- submit();+ void submit();}}@@ -47,13 +76,42 @@ export function Composer({ busy, disabled, send, focusKey, onStartTyping, voice{voiceStatus}</p>) : null}+ {attachments && files.length > 0 ? (+ <ul className="attachment-chips" aria-label="Files to send">+ {files.map((file) => (+ <FileChip+ key={file.id}+ file={file}+ locked={uploading}+ remove={() => attachments.remove(file.id)}+ />+ ))}+ </ul>+ ) : null}<formclassName="composer"onSubmit={(event) => {event.preventDefault();- submit();+ void submit();}}>+ {attachments && !recording ? (+ <label className="composer-attach" title="Attach files">+ <PaperclipIcon />+ <input+ type="file"+ multiple+ aria-label="Attach files"+ className="visually-hidden"+ disabled={disabled || uploading}+ onChange={(event) => {+ attachments.add(Array.from(event.target.files ?? []));+ // The same file can be picked again after removing it.+ event.target.value = "";+ }}+ />+ </label>+ ) : null}{recording ? (<div className="voice-recording"><span className="voice-time" role="timer" aria-label="Recording time">@@ -90,6 +148,7 @@ export function Composer({ busy, disabled, send, focusKey, onStartTyping, voicesetText(event.target.value);}}onKeyDown={onKeyDown}+ onPaste={onPaste}/>)}{busy || voice?.speaking ? (@@ -120,7 +179,7 @@ export function Composer({ busy, disabled, send, focusKey, onStartTyping, voice<buttontype="submit"className="composer-send"- disabled={disabled || text.trim() === ""}+ disabled={disabled || uploading || blocked || (text.trim() === "" && files.length === 0)}aria-label="Send"title="Send">@@ -132,6 +191,37 @@ export function Composer({ busy, disabled, send, focusKey, onStartTyping, voice);}+/** One attached file: name, size, upload progress, and why it cannot be sent. */+function FileChip({ file, locked, remove }: { file: PendingFile; locked: boolean; remove: () => void }) {+ const name = file.file.name;+ const problem = file.refused ?? file.error;+ return (+ <li className={`attachment-chip${problem ? " attachment-chip-error" : ""}`}>+ <span className="chip-name" title={name}>+ {name}+ </span>+ <span className="chip-size">{formatSize(file.file.size)}</span>+ {file.progress !== undefined ? (+ <progress className="chip-progress" aria-label={`Uploading ${name}`} max={1} value={file.progress} />+ ) : null}+ {problem ? (+ <span className="chip-error" role="alert">+ {problem}+ </span>+ ) : null}+ <button+ type="button"+ className="chip-remove"+ aria-label={`Remove ${name}`}+ disabled={locked}+ onClick={remove}+ >+ ×+ </button>+ </li>+ );+}+function formatElapsed(seconds: number): string {return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;}diff --git a/packages/ui/src/components/MessageList.tsx b/packages/ui/src/components/MessageList.tsxindex c14a1f7..93172d3 100644--- a/packages/ui/src/components/MessageList.tsx+++ b/packages/ui/src/components/MessageList.tsx@@ -3,6 +3,7 @@ import { Fragment, useEffect, useRef, useState } from "react";import Markdown from "react-markdown";import remarkGfm from "remark-gfm";import type { ChatMessage } from "../store.ts";+import { formatSize } from "../uploads.ts";const VERBS: Record<ActivityKind, [string, string, string]> = {read: ["Read", "file", "files"],@@ -93,6 +94,19 @@ export function MessageList({ messages, queued = [], hasEarlier = false, onShowE{message.text && message.role === "user" ? (<div className="message-body message-plain">{message.text}</div>) : null}+ {message.attachments && message.attachments.length > 0 ? (+ <ul className="message-attachments" aria-label="Attached files">+ {message.attachments.map((file, i) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: two files may share a name across folders+ <li key={i} className="attachment-chip">+ <span className="chip-name" title={file.name}>+ {file.name}+ </span>+ <span className="chip-size">{formatSize(file.size)}</span>+ </li>+ ))}+ </ul>+ ) : null}{message.text && message.role === "assistant" ? (<div className="message-body"><Markdown remarkPlugins={[remarkGfm]}>{message.text}</Markdown>diff --git a/packages/ui/src/components/icons.tsx b/packages/ui/src/components/icons.tsxindex c3a6903..513e553 100644--- a/packages/ui/src/components/icons.tsx+++ b/packages/ui/src/components/icons.tsx@@ -101,6 +101,15 @@ export function MicIcon() {);}+/** A paper clip: attach files (S31.1). */+export function PaperclipIcon() {+ return (+ <Icon>+ <path d="m21 11.5-8.5 8.5a5.5 5.5 0 0 1-7.8-7.8l9-9a3.7 3.7 0 0 1 5.2 5.2l-9 9a1.8 1.8 0 0 1-2.6-2.6l8.3-8.3" />+ </Icon>+ );+}+/** A speaker: spoken replies are on. */export function SpeakerIcon() {return (diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex d13d89e..f8b6ef3 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -2,6 +2,7 @@ import type {Activity,AgentState,Ask,+ AttachmentInfo,AuthEvent,AuthPrompt,AuthProvider,@@ -79,6 +80,8 @@ export interface ChatMessage {note?: { kind: "stopped" | "error"; text: string };/** From an earlier session of the chat; a divider follows the last one. */earlier?: boolean;+ /** Files the user sent with the message. */+ attachments?: AttachmentInfo[];}export interface Notice {@@ -208,7 +211,14 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {interrupted: false,messages: [...state.messages,- { id: message.messageId, role: "user", text: message.text, streaming: false, activities: [] },+ {+ id: message.messageId,+ role: "user",+ text: message.text,+ streaming: false,+ activities: [],+ ...(message.attachments ? { attachments: message.attachments } : {}),+ },],};case "message_delta":diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssindex ceee92d..334d1e7 100644--- a/packages/ui/src/styles.css+++ b/packages/ui/src/styles.css@@ -1543,3 +1543,120 @@ html[data-surface="glow"] body {clip-path: inset(0 0 0 0);}}++/* ---------- Attachments (S31) ---------- */++.visually-hidden {+ position: absolute;+ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++.composer-attach {+ position: relative;+ display: grid;+ place-items: center;+ flex: none;+ width: 32px;+ height: 32px;+ margin-left: -8px;+ border-radius: 50%;+ color: var(--muted);+ cursor: pointer;+}++.composer-attach:hover,+.composer-attach:focus-within {+ color: var(--text);+ background: var(--surface-2);+}++.attachment-chips,+.message-attachments {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin: 0;+ padding: 0;+ list-style: none;+}++.attachment-chips {+ margin: 0 12px 8px;+}++.message-attachments {+ justify-content: flex-end;+ max-width: 85%;+ margin-top: 6px;+}++.attachment-chip {+ display: inline-flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 6px;+ max-width: 100%;+ padding: 4px 6px 4px 10px;+ border: 1px solid var(--line);+ border-radius: var(--radius-pill);+ background: var(--surface-2);+ font-size: 12px;+ line-height: 18px;+}++.message-attachments .attachment-chip {+ padding-right: 10px;+ border-color: var(--accent-line);+}++.attachment-chip-error {+ border-color: var(--red);+ border-radius: var(--radius-md);+}++.chip-name {+ max-width: 180px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.chip-size {+ color: var(--muted);+ font-variant-numeric: tabular-nums;+}++.chip-progress {+ width: 56px;+ height: 4px;+ accent-color: var(--accent);+}++.chip-error {+ flex-basis: 100%;+ color: var(--red);+}++.chip-remove {+ padding: 0 6px;+ border: none;+ background: none;+ color: var(--muted);+ line-height: 18px;+}++.chip-remove:hover:not(:disabled) {+ color: var(--text);+}++.chat-dropping {+ outline: 2px dashed var(--accent-line);+ outline-offset: -6px;+}diff --git a/packages/ui/src/uploads.ts b/packages/ui/src/uploads.tsnew file mode 100644index 0000000..e7c5691--- /dev/null+++ b/packages/ui/src/uploads.ts@@ -0,0 +1,54 @@+import type { UploadedFile } from "@gentle-dot/protocol";+import type { ConnectionInfo } from "./client.ts";++/** Uploads one file to the daemon; `uploadId` adds it to the message folder of an earlier file. */+export type Uploader = (+ file: File,+ options: { uploadId?: string; onProgress?: (fraction: number) => void },+) => Promise<UploadedFile>;++/** The daemon's HTTP address, from the WebSocket one: `ws://host:port/ws` → `http://host:port`. */+export function uploadBase(wsUrl: string): string {+ const url = new URL(wsUrl);+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";+ return url.origin;+}++/**+ * `POST /upload` with the raw file (S31.2). XMLHttpRequest, unlike fetch, reports upload+ * progress. The access key goes in the Authorization header, never in the address.+ */+export function createUploader(info: ConnectionInfo, Xhr: typeof XMLHttpRequest = XMLHttpRequest): Uploader {+ const endpoint = `${uploadBase(info.url)}/upload`;+ return (file, options) =>+ new Promise((resolve, reject) => {+ const xhr = new Xhr();+ xhr.open("POST", endpoint);+ xhr.setRequestHeader("Authorization", `Bearer ${info.token}`);+ xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));+ if (options.uploadId) xhr.setRequestHeader("X-Upload-Id", options.uploadId);+ xhr.upload.onprogress = (event) => {+ if (event.lengthComputable && event.total > 0) options.onProgress?.(event.loaded / event.total);+ };+ xhr.onload = () => {+ let body: { message?: unknown } | undefined;+ try {+ body = JSON.parse(xhr.responseText) as { message?: unknown };+ } catch {+ body = undefined;+ }+ if (xhr.status === 200 && body) resolve(body as unknown as UploadedFile);+ else reject(new Error(typeof body?.message === "string" ? body.message : "The upload did not work."));+ };+ xhr.onerror = () => reject(new Error("The upload did not work. Check the connection and try again."));+ xhr.send(file);+ });+}++/** "512 B", "2 KB", "1.5 MB". */+export function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;+ const mb = bytes / (1024 * 1024);+ return `${mb >= 10 ? Math.round(mb) : Math.round(mb * 10) / 10} MB`;+}diff --git a/packages/ui/src/useAttachments.ts b/packages/ui/src/useAttachments.tsnew file mode 100644index 0000000..f84f2db--- /dev/null+++ b/packages/ui/src/useAttachments.ts@@ -0,0 +1,119 @@+import { ATTACHMENT_LIMITS, type AttachmentRef, type UploadedFile } from "@gentle-dot/protocol";+import { useCallback, useMemo, useRef, useState } from "react";+import { formatSize, type Uploader } from "./uploads.ts";++/** A file the user attached to the message they are writing. */+export interface PendingFile {+ id: string;+ file: File;+ /** Uploading: 0 to 1. */+ progress?: number;+ uploaded?: UploadedFile;+ /** It cannot be sent (over a limit); the user removes it. */+ refused?: string;+ /** The last upload failed; sending again retries it. */+ error?: string;+}++export interface AttachmentControls {+ files: PendingFile[];+ uploading: boolean;+ add(files: File[]): void;+ remove(id: string): void;+ /** Uploads what is not uploaded yet, one message folder for all; undefined when one failed. */+ upload(): Promise<AttachmentRef[] | undefined>;+ clear(): void;+}++let nextId = 0;++/** The files of the message being written (S31.1); undefined without an uploader. */+export function useAttachments(uploader?: Uploader): AttachmentControls | undefined {+ const [files, setFiles] = useState<PendingFile[]>([]);+ const [uploading, setUploading] = useState(false);+ const current = useRef(files);+ current.current = files;++ const update = useCallback((id: string, change: (file: PendingFile) => PendingFile) => {+ setFiles((list) => {+ const next = list.map((f) => (f.id === id ? change(f) : f));+ current.current = next;+ return next;+ });+ }, []);++ const add = useCallback((added: File[]) => {+ setFiles((list) => {+ const next = [...list];+ for (const file of added) {+ const kept = next.filter((f) => !f.refused);+ const bytes = kept.reduce((sum, f) => sum + f.file.size, 0);+ const item: PendingFile = { id: `a${++nextId}`, file };+ if (kept.length >= ATTACHMENT_LIMITS.files) {+ item.refused = `Too many files: up to ${ATTACHMENT_LIMITS.files} files per message.`;+ } else if (file.size > ATTACHMENT_LIMITS.fileBytes) {+ item.refused = `Too large: up to ${formatSize(ATTACHMENT_LIMITS.fileBytes)} per file.`;+ } else if (bytes + file.size > ATTACHMENT_LIMITS.messageBytes) {+ item.refused = `Too large together: up to ${formatSize(ATTACHMENT_LIMITS.messageBytes)} per message.`;+ }+ next.push(item);+ }+ current.current = next;+ return next;+ });+ }, []);++ const remove = useCallback((id: string) => {+ setFiles((list) => {+ const next = list.filter((f) => f.id !== id);+ current.current = next;+ return next;+ });+ }, []);++ const clear = useCallback(() => {+ current.current = [];+ setFiles([]);+ }, []);++ const upload = useCallback(async (): Promise<AttachmentRef[] | undefined> => {+ if (!uploader) return undefined;+ const list = current.current;+ if (list.some((f) => f.refused)) return undefined;+ setUploading(true);+ let uploadId = list.find((f) => f.uploaded)?.uploaded?.uploadId;+ const refs: AttachmentRef[] = [];+ let failed = false;+ try {+ for (const item of list) {+ let done = item.uploaded;+ if (!done) {+ update(item.id, ({ error: _error, ...f }) => ({ ...f, progress: 0 }));+ try {+ done = await uploader(item.file, {+ ...(uploadId ? { uploadId } : {}),+ onProgress: (progress) => update(item.id, (f) => ({ ...f, progress })),+ });+ const uploaded = done;+ update(item.id, ({ progress: _progress, ...f }) => ({ ...f, uploaded }));+ } catch (error) {+ failed = true;+ const message = (error as Error).message || "The upload did not work.";+ update(item.id, ({ progress: _progress, ...f }) => ({ ...f, error: message }));+ continue;+ }+ }+ uploadId ??= done.uploadId;+ refs.push({ uploadId: done.uploadId, name: done.name });+ }+ } finally {+ setUploading(false);+ }+ return failed ? undefined : refs;+ }, [uploader, update]);++ return useMemo(+ () => (uploader ? { files, uploading, add, remove, upload, clear } : undefined),+ [uploader, files, uploading, add, remove, upload, clear],+ );+}diff --git a/packages/ui/test/attachments.test.tsx b/packages/ui/test/attachments.test.tsxnew file mode 100644index 0000000..5f609d4--- /dev/null+++ b/packages/ui/test/attachments.test.tsx@@ -0,0 +1,264 @@+import type { ClientMessage, ServerMessage, ServerPayload, UploadedFile } from "@gentle-dot/protocol";+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { Composer } from "../src/components/Composer.tsx";+import { MessageList } from "../src/components/MessageList.tsx";+import { type DotState, initialState, reduce } from "../src/store.ts";+import { createUploader, formatSize, type Uploader, uploadBase } from "../src/uploads.ts";+import { useAttachments } from "../src/useAttachments.ts";++const open: DotState = { ...initialState, connection: "open", agentState: "idle" };++function file(name: string, size = 10, type = "text/plain"): File {+ return new File([new Uint8Array(size)], name, { type });+}++function uploaded(f: File, uploadId = "u_0123456789abcdef"): UploadedFile {+ return {+ uploadId,+ name: f.name,+ size: f.size,+ mime: f.type || "application/octet-stream",+ path: `uploads/${uploadId}/${f.name}`,+ };+}++/** An uploader that answers right away, recording each call. */+function instantUploader() {+ return vi.fn<Uploader>(async (f, options) => {+ options.onProgress?.(1);+ return uploaded(f, options.uploadId ?? "u_0123456789abcdef");+ });+}++function ComposerWith({ upload, send }: { upload: Uploader; send: (m: ClientMessage) => void }) {+ const attachments = useAttachments(upload);+ return <Composer busy={false} disabled={false} send={send} attachments={attachments} />;+}++const attachInput = () => screen.getByLabelText("Attach files") as HTMLInputElement;+const chips = () => within(screen.getByRole("list", { name: "Files to send" })).queryAllByRole("listitem");++describe("attaching files in the composer", () => {+ it("adds chosen files as chips with name and size, and removes one", async () => {+ render(<ComposerWith upload={instantUploader()} send={vi.fn()} />);+ await userEvent.upload(attachInput(), [file("notes.txt", 2048), file("photo.png", 10, "image/png")]);+ expect(chips().map((c) => c.textContent)).toEqual([+ expect.stringContaining("notes.txt"),+ expect.stringContaining("photo.png"),+ ]);+ expect(chips()[0]?.textContent).toContain("2 KB");+ await userEvent.click(screen.getByRole("button", { name: "Remove notes.txt" }));+ expect(chips()).toHaveLength(1);+ });++ it("uploads on send with one message folder, then sends the text with the attachments", async () => {+ const upload = instantUploader();+ upload.mockImplementationOnce(async (f, options) => {+ options.onProgress?.(1);+ return uploaded(f, "u_first0000000000000");+ });+ const send = vi.fn<(m: ClientMessage) => void>();+ render(<ComposerWith upload={upload} send={send} />);+ await userEvent.upload(attachInput(), [file("a.txt"), file("b.txt")]);+ await userEvent.type(screen.getByRole("textbox", { name: "Message" }), "read these{Enter}");+ await waitFor(() => expect(send).toHaveBeenCalledTimes(1));+ expect(upload.mock.calls.map(([f, o]) => [f.name, o.uploadId])).toEqual([+ ["a.txt", undefined],+ ["b.txt", "u_first0000000000000"],+ ]);+ expect(send.mock.calls[0]?.[0]).toMatchObject({+ type: "send",+ text: "read these",+ attachments: [+ { uploadId: "u_first0000000000000", name: "a.txt" },+ { uploadId: "u_first0000000000000", name: "b.txt" },+ ],+ });+ expect(screen.queryByRole("list", { name: "Files to send" })).toBeNull();+ expect(screen.getByRole("textbox", { name: "Message" })).toHaveValue("");+ });++ it("sends files without text", async () => {+ const send = vi.fn<(m: ClientMessage) => void>();+ render(<ComposerWith upload={instantUploader()} send={send} />);+ await userEvent.upload(attachInput(), [file("a.txt")]);+ await userEvent.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(send).toHaveBeenCalledTimes(1));+ expect(send.mock.calls[0]?.[0]).toMatchObject({ type: "send", text: "" });+ });++ it("shows progress while uploading", async () => {+ let finish: (value: UploadedFile) => void = () => {};+ const upload = vi.fn<Uploader>(+ (f, options) =>+ new Promise((resolve) => {+ options.onProgress?.(0.5);+ finish = () => resolve(uploaded(f));+ }),+ );+ const send = vi.fn();+ render(<ComposerWith upload={upload} send={send} />);+ await userEvent.upload(attachInput(), [file("a.txt")]);+ await userEvent.click(screen.getByRole("button", { name: "Send" }));+ const bar = await screen.findByRole("progressbar", { name: "Uploading a.txt" });+ expect(bar).toHaveAttribute("value", "0.5");+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await act(async () => finish(uploaded(file("a.txt"))));+ await waitFor(() => expect(send).toHaveBeenCalledTimes(1));+ });++ it("shows an upload error on the file and keeps the message", async () => {+ const upload = vi.fn<Uploader>(async () => {+ throw new Error("This file is too large: up to 25 MB per file.");+ });+ const send = vi.fn();+ render(<ComposerWith upload={upload} send={send} />);+ await userEvent.upload(attachInput(), [file("a.txt")]);+ await userEvent.type(screen.getByRole("textbox", { name: "Message" }), "hi{Enter}");+ const chip = chips()[0] as HTMLElement;+ expect(await within(chip).findByRole("alert")).toHaveTextContent("too large");+ expect(send).not.toHaveBeenCalled();+ expect(screen.getByRole("textbox", { name: "Message" })).toHaveValue("hi");+ });++ it("refuses files over the limits before uploading, with a reason on the chip", async () => {+ const upload = instantUploader();+ const first = render(<ComposerWith upload={upload} send={vi.fn()} />);+ await userEvent.upload(attachInput(), [file("huge.bin", 26 * 1024 * 1024)]);+ expect(within(chips()[0] as HTMLElement).getByRole("alert")).toHaveTextContent(/25 MB/);+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ first.unmount();++ render(<ComposerWith upload={upload} send={vi.fn()} />);+ await userEvent.upload(+ attachInput(),+ Array.from({ length: 11 }, (_, i) => file(`f${i}.txt`)),+ );+ const refused = chips().filter((c) => within(c).queryByRole("alert"));+ expect(refused).toHaveLength(1);+ expect(refused[0]).toHaveTextContent("f10.txt");+ expect(refused[0]).toHaveTextContent(/10 files/);+ expect(upload).not.toHaveBeenCalled();+ });++ it("adds a pasted image and leaves pasted text alone", async () => {+ render(<ComposerWith upload={instantUploader()} send={vi.fn()} />);+ const box = screen.getByRole("textbox", { name: "Message" });+ fireEvent.paste(box, {+ clipboardData: { files: [file("image.png", 10, "image/png")], types: ["Files"] },+ });+ expect(chips().map((c) => c.textContent)).toEqual([expect.stringContaining("image.png")]);+ fireEvent.paste(box, { clipboardData: { files: [], types: ["text/plain"] } });+ expect(chips()).toHaveLength(1);+ });++ it("has no attach button without an uploader, and a plain send is unchanged", async () => {+ const send = vi.fn();+ render(<Composer busy={false} disabled={false} send={send} />);+ expect(screen.queryByLabelText("Attach files")).toBeNull();+ await userEvent.type(screen.getByRole("textbox", { name: "Message" }), "hello{Enter}");+ expect(send).toHaveBeenCalledWith({ type: "send", text: "hello", requestId: expect.any(String) });+ });+});++describe("dropping files on the chat", () => {+ it("adds dropped files to the message", async () => {+ const { container } = render(+ <ChatSurface variant="web" state={open} send={vi.fn()} dismiss={vi.fn()} upload={instantUploader()} />,+ );+ const chat = container.querySelector(".chat") as HTMLElement;+ const dropped = file("dropped.pdf", 100, "application/pdf");+ fireEvent.dragOver(chat, { dataTransfer: { types: ["Files"], files: [] } });+ expect(chat.className).toContain("chat-dropping");+ fireEvent.drop(chat, { dataTransfer: { types: ["Files"], files: [dropped] } });+ expect(chat.className).not.toContain("chat-dropping");+ expect(chips().map((c) => c.textContent)).toEqual([expect.stringContaining("dropped.pdf")]);+ });+});++let seq = 0;+const apply = (state: DotState, payload: ServerPayload) =>+ reduce(state, { type: "server", message: { ...payload, seq: ++seq } as ServerMessage });++describe("sent messages with files", () => {+ it("keeps the attachments of a user message and shows them as chips", () => {+ const s = apply(open, {+ type: "user_message",+ messageId: "u1",+ text: "look",+ attachments: [{ name: "report.pdf", size: 2048, mime: "application/pdf" }],+ });+ expect(s.messages[0]?.attachments).toEqual([{ name: "report.pdf", size: 2048, mime: "application/pdf" }]);+ render(<MessageList messages={s.messages} />);+ const list = screen.getByRole("list", { name: "Attached files" });+ expect(within(list).getByRole("listitem")).toHaveTextContent("report.pdf");+ expect(within(list).getByRole("listitem")).toHaveTextContent("2 KB");+ });+});++describe("the uploader", () => {+ it("posts the raw file to the daemon's /upload with the key in a header", async () => {+ const sent: { url: string; headers: Record<string, string>; body: unknown }[] = [];+ class FakeXhr {+ status = 0;+ responseText = "";+ upload = {+ onprogress: null as+ | ((e: { loaded: number; total: number; lengthComputable: boolean }) => void)+ | null,+ };+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ private url = "";+ private headers: Record<string, string> = {};+ open(_method: string, url: string) {+ this.url = url;+ }+ setRequestHeader(name: string, value: string) {+ this.headers[name] = value;+ }+ send(body: unknown) {+ sent.push({ url: this.url, headers: this.headers, body });+ this.upload.onprogress?.({ loaded: 5, total: 10, lengthComputable: true });+ this.status = this.headers["X-File-Name"] === "bad.txt" ? 413 : 200;+ this.responseText = JSON.stringify(+ this.status === 200+ ? uploaded(file("a b.txt"), "u_server000000000000")+ : { code: "file_too_large", message: "This file is too large." },+ );+ this.onload?.();+ }+ }+ const upload = createUploader(+ { url: "ws://127.0.0.1:4317/ws", token: "secret-key" },+ FakeXhr as unknown as typeof XMLHttpRequest,+ );+ const progress: number[] = [];+ const result = await upload(file("a b.txt"), {+ uploadId: "u_prev0000000000000000",+ onProgress: (p) => progress.push(p),+ });+ expect(result.uploadId).toBe("u_server000000000000");+ expect(sent[0]?.url).toBe("http://127.0.0.1:4317/upload");+ expect(sent[0]?.headers).toMatchObject({+ Authorization: "Bearer secret-key",+ "X-File-Name": "a%20b.txt",+ "X-Upload-Id": "u_prev0000000000000000",+ });+ expect(sent[0]?.url).not.toContain("secret-key");+ expect(progress).toContain(0.5);+ await expect(upload(file("bad.txt"), {})).rejects.toThrow("This file is too large.");+ });++ it("derives the HTTP address from the WebSocket one, and formats sizes", () => {+ expect(uploadBase("ws://127.0.0.1:4317/ws")).toBe("http://127.0.0.1:4317");+ expect(uploadBase("wss://dot.example.com/ws")).toBe("https://dot.example.com");+ expect(formatSize(512)).toBe("512 B");+ expect(formatSize(2048)).toBe("2 KB");+ expect(formatSize(5 * 1024 * 1024)).toBe("5 MB");+ expect(formatSize(1.5 * 1024 * 1024)).toBe("1.5 MB");+ });+});