/** * @file promptAttach.ts * @description What a prompt box can attach besides a fresh upload: a project * file or folder dragged from the Files panel (`ATTACH_MIME`, read back by * `PromptEditor`'s drop) or from a Chat pane's activity panel * (`dragAttachments`, `dragSkill`: a skill becomes the prompt's `/command`) and the files uploaded through a prompt box in the * last day (`recentUploads`, kept in this browser). An attachment is a path * sent with the prompt, so nothing here touches the server. * @author Nguyễn Ngọc Trí Vĩ */ import type { DragEvent } from "react"; /** One attachment, shaped like `PromptImage`: what is sent, and its label. */ export interface Attachment { path: string; name: string; url?: string; } export const ATTACH_MIME = "application/x-agenthub-attach"; /** A project path (relative to the box's folder) as Claude Code's `@` mention. */ export function projectAttachment(rel: string): Attachment { const name = rel.replace(/\/$/, "").split("/").pop() || rel; return { path: `@${rel}`, name: rel.endsWith("/") ? `${name}/` : name }; } /** Start a drag carrying `rel` (a Files panel row) to a prompt box; plain * text too, so a drop elsewhere (a terminal, an editor) gets the path. A row * under a `data-drag-root` (an extra folder's section) lies outside the * pane's folder, so it carries its absolute path instead. */ export function dragProjectPath(e: DragEvent, rel: string) { const root = (e.currentTarget as HTMLElement | null)?.closest?.("[data-drag-root]") ?.dataset.dragRoot; const path = root ? `${root.replace(/[\\/]+$/, "")}/${rel}` : rel; e.dataTransfer.setData(ATTACH_MIME, JSON.stringify(projectAttachment(path))); e.dataTransfer.setData("text/plain", path); e.dataTransfer.effectAllowed = "copy"; } /** Start a drag carrying attachments as they are (an activity panel's files, * already absolute); plain text too, like `dragProjectPath`. */ export function dragAttachments(e: DragEvent, items: Attachment[]) { e.dataTransfer.setData(ATTACH_MIME, JSON.stringify(items)); e.dataTransfer.setData("text/plain", items.map((a) => a.path.replace(/^@/, "")).join(" ")); e.dataTransfer.effectAllowed = "copy"; } /** The attachments a drop carries, if they are ours: one, or a list. */ export function droppedAttachments(dt: DataTransfer | null | undefined): Attachment[] { try { const v: unknown = JSON.parse(dt?.getData(ATTACH_MIME) || "null"); return (Array.isArray(v) ? v : [v]) .filter( (a): a is Attachment => !!a && typeof (a as Attachment).path === "string" && typeof (a as Attachment).name === "string" ) .map((a) => ({ path: a.path, name: a.name })); } catch { return []; } } /** A drop that carries no file and none of ours, only text — a file manager * or an editor (VS Code) that hands over `file://` URIs, a selection, a * link: the local `file://` URIs as `@path` attachments, else the text to * insert, as a terminal pastes it. */ export function droppedText( dt: DataTransfer | null | undefined ): { attachments: Attachment[] } | { text: string } | null { try { const paths = (dt?.getData("text/uri-list") ?? "") .split(/\r?\n/) .filter((l) => l && !l.startsWith("#")) .map((l) => { try { const u = new URL(l.trim()); return u.protocol === "file:" && (!u.host || u.host === "localhost") ? decodeURIComponent(u.pathname) : null; } catch { return null; } }); if (paths.length && paths.every(Boolean)) { return { attachments: (paths as string[]).map((p) => ({ // A space would end the mention: Claude Code reads `@"…"` whole. path: /\s/.test(p) ? `@"${p}"` : `@${p}`, name: p.replace(/\/$/, "").split("/").pop() || p, })), }; } const text = dt?.getData("text/plain") ?? ""; return text.trim() ? { text } : null; } catch { return null; } } export const SKILL_MIME = "application/x-agenthub-skill"; // A skill's name as Claude Code types it: `name` or `plugin:name`. const SKILL_RE = /^[\w.-]+(?::[\w.-]+)?$/; /** Start a drag carrying a skill; dropped on a prompt box it becomes `/name`. */ export function dragSkill(e: DragEvent, name: string) { e.dataTransfer.setData(SKILL_MIME, name); e.dataTransfer.setData("text/plain", `/${name}`); e.dataTransfer.effectAllowed = "copy"; } /** The skill a drop carries, if it is one of ours. */ export function droppedSkill(dt: DataTransfer | null | undefined): string | null { try { const name = dt?.getData(SKILL_MIME) ?? ""; return SKILL_RE.test(name) ? name : null; } catch { return null; } } /** `prev` plus whichever of `items` it does not hold yet. */ export function addAttachments(prev: T[], items: T[]): T[] { const fresh = items.filter( (a, i) => !prev.some((p) => p.path === a.path) && items.findIndex((b) => b.path === a.path) === i ); return fresh.length ? [...prev, ...fresh] : prev; } const RECENT_KEY = "agenthub.prompt.recentUploads"; const RECENT_MAX = 20; // The server prunes an upload a day after it was written (`saveDrop`). // ponytail: a client-side guess of that TTL, a few minutes short; a listing // route instead if uploads must outlive it or follow the user to another browser. const RECENT_TTL_MS = 23.9 * 60 * 60_000; interface Recent extends Attachment { at: number; } function readRecent(): Recent[] { try { const v: unknown = JSON.parse(localStorage.getItem(RECENT_KEY) || "[]"); const cutoff = Date.now() - RECENT_TTL_MS; return (Array.isArray(v) ? (v as Recent[]) : []).filter( (r) => typeof r?.path === "string" && typeof r.name === "string" && r.at > cutoff ); } catch { return []; } } export function recentUploads(): Attachment[] { return readRecent().map(({ path, name, url }) => ({ path, name, ...(url ? { url } : {}) })); } /** Remember uploads just saved, newest first; an image keeps a thumbnail * through `GET /api/run/drop/:name` (its local blob URL dies with the page). */ export function rememberUploads(items: { path: string; name: string; image: boolean }[]) { const at = Date.now(); const added: Recent[] = items.map(({ path, name, image }) => ({ path, name, at, ...(image ? { url: `/api/run/drop/${encodeURIComponent(path.split("/").pop() || "")}` } : {}), })); const kept = readRecent().filter((r) => !added.some((a) => a.path === r.path)); try { localStorage.setItem(RECENT_KEY, JSON.stringify([...added, ...kept].slice(0, RECENT_MAX))); } catch { /* storage full or blocked: the list is a convenience */ } }