aee4fc190e
- Changes panel: **Discard all** beside Commit discards every non-conflicted file in one `discard`, after a dialog naming how many untracked files go. - Terminal: a `claude` pane gets dropped/pasted images as bare paths (shown as `[Image #n]`) and other files as `@` mentions (`claudePastes`); a local browser's copied `file://` paths and text-drag file lists paste by path. - `POST /api/run/drop-file`: a loopback browser outside server mode may drop up to 2 GB, streamed to disk; remote stays 20 MB. - cc-config skills/commands/plugins read the USER scope of the account the pane runs as (S3 member home by `cwd`), never another user's or the host's for a non-admin without an account; the run form passes its cwd to plugins.
262 lines
10 KiB
TypeScript
262 lines
10 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`, checked by the server in `sameFilesHere` —
|
|
* `POST /api/run/local-paths` —, `localAttachment`). An attachment is a path
|
|
* sent with the prompt; that check is the one call 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);
|
|
return paths && paths.length === files.length ? paths : null;
|
|
}
|
|
|
|
/** 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;
|
|
}
|
|
}
|
|
|
|
/** 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 {
|
|
return {
|
|
// A space would end the mention: Claude Code reads `@"…"` whole.
|
|
path: /\s/.test(path) ? `@"${path}"` : `@${path}`,
|
|
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 */
|
|
}
|
|
}
|