Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ app/api/
sessions/[id]/export/route.ts GET exported HTML for a session
agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? }
agent/[id]/route.ts GET state | POST any RPC command
attachments/route.ts POST { kind, name, files: [{ path, size }] } → 201 { batchId } (composer path attachments)
attachments/[batchId]/route.ts PUT multipart (path, offset, data) chunks | POST complete → { path, kind, name, size, fileCount }
events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels
notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? }
notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq }
Expand Down Expand Up @@ -100,6 +102,9 @@ lib/
omp/ shared omp foundations (paths, CLI probe, RpcProcess)
provider-accounts.ts distinct omp accounts per provider from `omp usage` reports (Models → provider detail)
agent-client.ts typed fetch helper for /api/agent commands
attachment-store.ts server: composer upload batches under <agent dir>/omp-web/attachments (path validation, caps, pruning)
attachment-upload.ts browser: chunked upload to /api/attachments + folder pick/drop traversal
chat-attachments.ts pure composer attachment rules: inline text budget, caps, prompt composition (Attached paths block)
btw.ts /btw side-question records + pure frame/snapshot merge (order-safe)
draft-store.ts local draft persistence helpers
event-stream.ts tab-side EventSource-shaped streams over the shared worker
Expand Down Expand Up @@ -564,6 +569,21 @@ during the wait.
- `/api/files` is intentionally not a general filesystem browser. Allowed roots come from session cwds, their resolved project roots, `~/omp-cwd-*`, and roots explicitly added with `allowFileRoot()`.
- `/api/cwd/validate`, `/api/default-cwd`, and `/api/worktrees` call `allowFileRoot()` when they make a new location browsable.

### Composer path attachments (`lib/attachment-store.ts`, `/api/attachments`)
- Small text files are inlined, images go as RPC `images`; everything else
(binary, past the inline budget or slots, folders) is uploaded and the prompt
ends with an `Attached paths` list (`composeMessageWithAttachments`). The
model reads those absolute paths with its own tools.
- One batch = one chip: declared first (every relative path validated and the
2,000-file / 200 MB caps checked before any byte), then filled by ordered
≤ 8 MiB multipart chunks, then completed. Chunking is required: while
`proxy.ts` runs, Next buffers at most 10 MB of a request body
(`proxyClientMaxBodySize`) and silently truncates the rest.
- Batches older than 30 days are pruned on batch creation (at most hourly).
Removing a chip leaves its batch for pruning. References live in the draft
store (memory-only, like other attachment payloads) and are folded into the
prompt text, so queue recovery restores them with the text.

### Session list caching — new sessions must appear immediately
- `listAllSessions()` (sidebar, command palette) is cached twice: a 30s TTL
list cache in `lib/session-reader.ts` plus an mtime-keyed directory walk in
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

## [Unreleased]

### Added

- **Attach any file, or a whole folder, for the model to read.** Files that cannot be inlined as text — PDFs, Office documents, archives and other binaries, or text past the inline budget — used to be dropped; they are now uploaded and sent as a path reference, and the new **Add folder** item in the composer's plus menu (or dropping a folder onto the chat) uploads a folder's files at their relative paths (empty subfolders are not recreated). The prompt ends with an `Attached paths` list of absolute paths the model reads with its own tools. Uploads are stored under `~/.omp/agent/omp-web/attachments/`, limited to 2,000 files and 200 MB per file or folder, and removed after 30 days. Small text files and images attach as before.

### Fixes & Improvements

- **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails.
Expand Down
69 changes: 69 additions & 0 deletions app/api/attachments/[batchId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { NextResponse } from "next/server";
import { parseFormDataWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import { ATTACHMENT_CHUNK_BYTES } from "@/lib/chat-attachments";
import {
AttachmentError,
completeAttachmentBatch,
writeAttachmentChunks,
type AttachmentChunk,
} from "@/lib/attachment-store";

export const dynamic = "force-dynamic";

// Multipart boundaries and part headers are not file bytes, but are bounded too.
const MAX_CHUNK_REQUEST_BYTES = ATTACHMENT_CHUNK_BYTES + 1024 * 1024;

type Params = { params: Promise<{ batchId: string }> };

function errorResponse(error: unknown): NextResponse {
if (error instanceof AttachmentError) {
return NextResponse.json({ error: error.message, code: error.code }, { status: error.status });
}
return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 });
}

/** PUT multipart repeated (path, offset, data) parts → 200 { ok: true }. */
export async function PUT(request: Request, { params }: Params) {
try {
const { batchId } = await params;
let formData: FormData;
try {
formData = await parseFormDataWithinLimit(request, MAX_CHUNK_REQUEST_BYTES);
} catch (error) {
if (error instanceof RequestBodyTooLargeError) {
return NextResponse.json({ error: "Attachment chunk is too large", code: "attachment_chunk_too_large" }, { status: 413 });
}
return NextResponse.json({ error: "Invalid multipart body", code: "invalid_attachment" }, { status: 400 });
}
const paths = formData.getAll("path");
const offsets = formData.getAll("offset");
const data = formData.getAll("data");
if (paths.length !== offsets.length || paths.length !== data.length) {
return NextResponse.json({ error: "Each chunk needs a path, an offset and data", code: "invalid_attachment" }, { status: 400 });
}
const chunks: AttachmentChunk[] = [];
for (let index = 0; index < paths.length; index += 1) {
const chunkPath = paths[index];
const offset = offsets[index];
const blob = data[index];
if (typeof chunkPath !== "string" || typeof offset !== "string" || !/^\d+$/.test(offset) || typeof blob === "string") {
return NextResponse.json({ error: "Malformed attachment chunk", code: "invalid_attachment" }, { status: 400 });
}
chunks.push({ path: chunkPath, offset: Number(offset), data: new Uint8Array(await blob.arrayBuffer()) });
}
await writeAttachmentChunks(batchId, chunks);
return NextResponse.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}

/** POST → 200 { batchId, kind, name, path, size, fileCount } once every byte arrived. */
export async function POST(_request: Request, { params }: Params) {
try {
const { batchId } = await params;
return NextResponse.json(await completeAttachmentBatch(batchId));
} catch (error) {
return errorResponse(error);
}
}
37 changes: 37 additions & 0 deletions app/api/attachments/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { NextResponse } from "next/server";
import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import {
AttachmentError,
createAttachmentBatch,
maybePruneAttachmentBatches,
parseAttachmentBatchRequest,
} from "@/lib/attachment-store";

export const dynamic = "force-dynamic";

// 2,000 paths of up to 1,024 characters each, plus JSON punctuation.
const MAX_BATCH_REQUEST_BYTES = 3 * 1024 * 1024;

/** POST { kind, name, files: [{ path, size }] } → 201 { batchId }. Every cap
* and path is checked here, before any file byte is uploaded. */
export async function POST(request: Request) {
try {
let body: unknown;
try {
body = await parseJsonWithinLimit<unknown>(request, MAX_BATCH_REQUEST_BYTES);
} catch (error) {
if (error instanceof RequestBodyTooLargeError) {
return NextResponse.json({ error: "Attachment manifest is too large", code: "attachment_manifest_too_large" }, { status: 413 });
}
return NextResponse.json({ error: "Invalid JSON body", code: "invalid_attachment" }, { status: 400 });
}
const batch = parseAttachmentBatchRequest(body);
await maybePruneAttachmentBatches();
return NextResponse.json(await createAttachmentBatch(batch), { status: 201 });
} catch (error) {
if (error instanceof AttachmentError) {
return NextResponse.json({ error: error.message, code: error.code }, { status: error.status });
}
return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
10 changes: 8 additions & 2 deletions components/ChatInput-draft-attachments.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ChatDraftFile, ChatDraftImage } from "@/lib/draft-store";
import type { AttachedTextFileData } from "@/lib/chat-attachments";
import type { ChatDraftFile, ChatDraftImage, ChatDraftReference } from "@/lib/draft-store";
import { isAttachmentReferenceData, type AttachedTextFileData, type AttachmentReferenceData } from "@/lib/chat-attachments";
import { isBase64ImageWithinLimits } from "@/lib/image-attachments";

export interface AttachedImage {
Expand All @@ -9,6 +9,7 @@ export interface AttachedImage {
}

export type AttachedTextFile = AttachedTextFileData;
export type AttachedReference = AttachmentReferenceData;

export function imageToDraftImage(image: AttachedImage): ChatDraftImage {
return { data: image.data, mimeType: image.mimeType };
Expand Down Expand Up @@ -45,6 +46,11 @@ export function draftFilesToAttachedFiles(files: ChatDraftFile[] | undefined): A
&& file.size >= 0);
}

/** Uploaded paths are plain data; keep every well-formed one. */
export function draftReferencesToAttachedReferences(references: ChatDraftReference[] | undefined): AttachedReference[] {
return (references ?? []).filter(isAttachmentReferenceData);
}

export function revokeImagePreview(image: AttachedImage): void {
if (image.previewUrl.startsWith("blob:")) {
URL.revokeObjectURL(image.previewUrl);
Expand Down
Loading
Loading