Files
AgentHub/client/src/lib/promptAttach.ts
T
nntrivi2001 f2f1cd9b6c fix: per-user Today, native paste and drop on a local machine
- Today's spend in the status bar and the Claude Code statusline is the
  caller's own (`GET /api/pricing/cost?mine=1`, scope.ownSessionWhere), not
  every user's sum for an admin or analyst.
- A screenshot pasted into a local claude pane is sent as Claude Code's own
  image-paste key: Alt+V on Windows (Ctrl+V did nothing there), ^V elsewhere,
  and only when the machine can read its clipboard (wl-paste/xclip + a
  display on Linux), else it is uploaded (GET /api/run/native-paste {key}).
- A file manager's files pasted or dropped on a local browser go in by their
  own paths, read from the OS clipboard or the file manager's selection
  (server/lib/file-manager.js, POST /api/run/clipboard-files and
  /selected-files): no upload, no size limit. A copied image file is pasted
  by path, text that comes with a picture of it (spreadsheet cells) is
  pasted as text, Windows paths go in as `C:/…` mentions.
- Tab titles for Snapshot, Artifacts, Files and Administration.
- An npm tool AgentHub installed under ~/.local is updated there, not by its
  own updater into npm's global prefix.
2026-10-26 11:18:05 +07:00

354 lines
14 KiB
TypeScript

/**
* @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), and `claudeMention`, the
* `@` form a file is handed to `claude` in, and what a browser on the
* dashboard's own machine attaches by path instead of uploading
* (`localCandidates` — a drag's uri-list, or the plain-text paths a pasted
* file-manager copy carries —, checked by the server in `sameFilesHere` —
* `POST /api/run/local-paths` —, `localAttachment`), and the pasted or
* dropped files that machine's file manager holds (`fileManagerPaths`). An
* attachment is a path sent with the prompt; those checks are the calls here
* to the server.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import type { DragEvent } from "react";
import { api } from "./api";
/** 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?.<HTMLElement>("[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 [];
}
}
/** Whether this browser reaches the dashboard by a loopback address — a
* hint only: an SSH tunnel's browser does too, from another machine, so a
* dropped path is used only once `sameFilesHere` has checked it. */
export function isLocalBrowser(): boolean {
return /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/.test(window.location.hostname);
}
/** The `file://` paths a drop or paste carries beside its `files`, when this
* may be a browser on the dashboard's machine — read now: a DataTransfer is
* empty once its event is over. Null when there is nothing to check. */
export function localCandidates(
dt: DataTransfer | null | undefined,
files: File[]
): string[] | null {
if (!isLocalBrowser()) return null;
const paths = droppedFilePaths(dt);
if (paths) return paths.length === files.length ? paths : null;
// A PASTE of a file manager's copy has no uri-list: Chrome hands over the
// files and the paths as plain text only. Kept only when the names match
// the files one for one — `sameFilesHere` then checks the sizes.
const copied = textFilePaths(dt);
if (!copied || copied.length !== files.length) return null;
const base = (p: string) => p.split(/[\\/]/).pop() ?? "";
const want = files.map((f) => f.name).sort();
const have = copied.map(base).sort();
return have.every((n, i) => n === want[i]) ? copied : null;
}
/** A paste's plain text as absolute paths — every non-empty line a `file://`
* URI or an absolute path (a file manager's copy) — else null. */
function textFilePaths(dt: DataTransfer | null | undefined): string[] | null {
let lines: string[];
try {
lines = (dt?.getData("text/plain") ?? "")
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
} catch {
return null;
}
if (lines.length === 0) return null;
if (lines.every((l) => l.startsWith("file://"))) {
return droppedFilePaths({ getData: () => lines.join("\n") } as unknown as DataTransfer);
}
return lines.every((l) => /^(\/|[A-Za-z]:[\\/])/.test(l)) ? lines : null;
}
/** The `file://` paths a paste carries as text with no file beside it — a
* file manager's copy, as some browsers paste it — or null: its uri-list,
* else its plain text when every line is one. Plain absolute paths are NOT
* taken here: with no file to compare against, they are text to paste. */
export function copiedFilePaths(dt: DataTransfer | null | undefined): string[] | null {
const uris = droppedFilePaths(dt);
if (uris) return uris;
const text = dt?.getData("text/plain") ?? "";
if (!/^file:\/\//.test(text.trim())) return null;
return textFilePaths(dt);
}
/** Whether `paths` are the dropped `files` as the dashboard's machine sees
* them: every one a regular file there, and the sizes the same. Anything
* else (an SSH tunnel's laptop paths, server mode, an error) is false, and
* the caller uploads the bytes as before. */
export async function sameFilesHere(paths: string[], files: File[]): Promise<boolean> {
try {
const { sizes } = await api.run.localPaths(paths);
const want = files.map((f) => f.size).sort((a, b) => a - b);
const have = sizes.slice().sort((a, b) => (a ?? -1) - (b ?? -1));
return have.length === want.length && have.every((s, i) => s === want[i]);
} catch {
return false;
}
}
/** A pasted BITMAP (a screenshot), not a copied image FILE: browsers name the
* clipboard's picture `image.png`, while a file manager's copy keeps its own
* name. Only a bitmap goes to `claude`'s own image paste — a copied file is
* pasted by its path, as a native terminal does (`claude` finds no picture
* on a clipboard that holds a file) — and a bitmap that comes WITH text (a
* spreadsheet's cells, a page's selection) is the text's picture: a
* terminal pastes the text. */
export function isClipboardBitmap(f: File): boolean {
return f.type.startsWith("image/") && f.name === "image.png";
}
/** The pasted or dropped `files` by their own paths on the dashboard's
* machine, as its file manager holds them — a paste on its OS clipboard, a
* drop as its selection, which is what a drag from it carries
* (`POST /api/run/clipboard-files` / `selected-files`): a native terminal's
* paths, and the one way past the upload limit. Null when this is not a
* loopback browser, on a refusal (server mode), or when any file is not
* held under the same name and size (an SSH tunnel's browser pastes
* ANOTHER machine's files). Paths come back in `files`' order. */
export async function fileManagerPaths(
files: File[],
from: "paste" | "drop"
): Promise<string[] | null> {
if (!isLocalBrowser() || files.length === 0) return null;
try {
const { files: held } = await (from === "paste"
? api.run.clipboardFiles()
: api.run.selectedFiles());
const base = (p: string) =>
p
.replace(/[\\/]+$/, "")
.split(/[\\/]/)
.pop() ?? "";
const left = [...held];
const paths: string[] = [];
for (const f of files) {
const i = left.findIndex((h) => base(h.path) === f.name && (h.dir || h.size === f.size));
if (i < 0) return null;
paths.push(left[i]!.path.replace(/(.)[\\/]+$/, "$1"));
left.splice(i, 1);
}
return paths;
} catch {
return null;
}
}
/** The local files a drop or a paste names as `file://` URIs (a file
* manager's, an editor's), as absolute paths — or null when it names none,
* or anything that is not one. `file:///C:/x` is `C:/x`. */
export function droppedFilePaths(dt: DataTransfer | null | undefined): 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());
if (u.protocol !== "file:" || (u.host && u.host !== "localhost")) return null;
return decodeURIComponent(u.pathname).replace(/^\/([A-Za-z]:\/)/, "$1");
} catch {
return null;
}
});
return paths.length && paths.every(Boolean) ? (paths as string[]) : null;
} catch {
return null;
}
}
/** A file on this machine, by its absolute path, as an attachment. */
export function localAttachment(path: string): Attachment {
// A Windows path in `/` form, like `claudeMention` (Windows takes either).
const p = /^[A-Za-z]:\\/.test(path) ? path.replace(/\\/g, "/") : path;
return {
// A space would end the mention: Claude Code reads `@"…"` whole.
path: /\s/.test(p) ? `@"${p}"` : `@${p}`,
name:
path
.replace(/[\\/]$/, "")
.split(/[\\/]/)
.pop() || path,
};
}
/** 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 = droppedFilePaths(dt);
if (paths) return { attachments: paths.map(localAttachment) };
const text = dt?.getData("text/plain") ?? "";
return text.trim() ? { text } : null;
} catch {
return null;
}
}
/** An attached file as Claude Code's `@` mention, which `claude` reads at
* submit — an image as an image — whether it came on the command line or in
* a paste. A bare pasted PATH becomes `[Image #n]` only when the TUI catches
* the paste on its own and finishes before Enter: on Windows (psmux) it
* stayed a plain `C:\…\drops\…png` in the prompt, and on the command line
* a path is never an image at all. A Windows path's backslashes become `/`
* (Windows takes either); a path with a space is quoted. */
export function claudeMention(path: string): string {
if (path.startsWith("@")) return path;
const p = /^[A-Za-z]:\\/.test(path) ? path.replace(/\\/g, "/") : path;
return /\s/.test(p) ? `@"${p}"` : `@${p}`;
}
const IMAGE_PATH = /\.(png|jpe?g|gif|webp)$/i;
/** What a terminal pastes for files dropped or pasted on a `claude` pane, one
* paste per entry, as a local terminal hands them over: the images as their
* bare paths, each a paste of its own — the shape Claude Code turns into
* `[Image #n]`, as it does a native drop — and every other file as an `@`
* mention, together in one. A Windows path, or
* one with a space, stays a mention — the bare path stayed plain text there
* (see `claudeMention`). */
export function claudePastes(paths: string[]): string[] {
const bare = (p: string) => IMAGE_PATH.test(p) && p.startsWith("/") && !/\s/.test(p);
const images = paths.filter(bare);
const others = paths.filter((p) => !bare(p)).map(claudeMention);
return [...images, others.join(" ")].filter(Boolean);
}
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<T extends Attachment>(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 */
}
}