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.
This commit is contained in:
2026-10-26 11:18:05 +07:00
parent c59e196e41
commit f2f1cd9b6c
33 changed files with 1046 additions and 60 deletions
+31
View File
@@ -109,6 +109,13 @@ before(async () => {
})
);
write("selfy.json", tool("selfy", { update: { kind: "self", args: ["update", "--yes"] } }));
write(
"selfnpm.json",
tool("selfnpm", {
install: { kind: "npm", package: "selfnpm-pkg" },
update: { kind: "self", args: ["update"] },
})
);
write("plain.json", tool("plain"));
exe(path.join(shellBin, "npm"));
exe(path.join(serverBin, "npm"));
@@ -241,6 +248,30 @@ describe("a system-wide npm prefix", () => {
aiTools.refresh();
}
});
it("updates an npm tool with its own updater under ~/.local through npm --prefix", async () => {
const pkg = path.join(user, "lib", "node_modules", "selfnpm-pkg", "cli.js");
exe(pkg);
fs.symlinkSync(pkg, path.join(serverBin, "selfnpm"));
aiTools.refresh();
try {
assert.deepEqual(await jobs.stepsFor("selfnpm", "update"), [
{
argv: [
path.join(shellBin, "npm"),
"install",
"-g",
"--prefix",
user,
"selfnpm-pkg@latest",
],
},
]);
} finally {
fs.rmSync(path.join(serverBin, "selfnpm"));
aiTools.refresh();
}
});
});
describe("versions", () => {
+28 -1
View File
@@ -8,7 +8,7 @@
*/
const { describe, it, beforeEach, afterEach } = require("node:test");
const assert = require("node:assert/strict");
const { desktopEnv, FORWARDED, __setExecImpl } = require("../lib/desktop-env");
const { desktopEnv, canReadClipboard, FORWARDED, __setExecImpl } = require("../lib/desktop-env");
const saved = {};
@@ -61,3 +61,30 @@ describe("desktopEnv", () => {
assert.equal(desktopEnv().WAYLAND_DISPLAY, undefined);
});
});
describe("canReadClipboard", () => {
const has =
(...names) =>
(n) =>
names.includes(n) ? `/usr/bin/${n}` : null;
it("needs wl-paste for a Wayland display, xclip for an X one", () => {
const wl = { WAYLAND_DISPLAY: "wayland-0" };
const x = { DISPLAY: ":0" };
assert.equal(canReadClipboard({ platform: "linux", env: wl, which: has("wl-paste") }), true);
assert.equal(canReadClipboard({ platform: "linux", env: wl, which: has("xclip") }), false);
assert.equal(canReadClipboard({ platform: "linux", env: x, which: has("xclip") }), true);
assert.equal(canReadClipboard({ platform: "linux", env: x, which: has() }), false);
});
it("is false with no display at all — a headless box", () => {
assert.equal(
canReadClipboard({ platform: "linux", env: {}, which: has("xclip", "wl-paste") }),
false
);
});
it("is true off Linux, where the clipboard tools are built in", () => {
assert.equal(canReadClipboard({ platform: "darwin", env: {}, which: has() }), true);
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* @file file-manager.test.js
* @description server/lib/file-manager.js: the files a file manager's Copy
* put on the OS clipboard (Windows GetFileDropList, macOS NSPasteboard, Linux
* text/uri-list / gnome-copied-files) and the ones selected in it — what a
* drag carries (Windows Shell.Application, macOS Finder) — kept only when
* they exist here, with their sizes; a missing reader is no files.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after, afterEach } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const {
clipboardFiles,
selectedFiles,
uriListPaths,
__setExecImpl,
} = require("../lib/file-manager");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "fm-files-"));
const big = path.join(TMP, "big file.mp4");
const dir = path.join(TMP, "folder");
before(() => {
fs.writeFileSync(big, Buffer.alloc(1234));
fs.mkdirSync(dir);
});
after(() => fs.rmSync(TMP, { recursive: true, force: true }));
afterEach(() => __setExecImpl(async () => ""));
describe("uriListPaths", () => {
it("decodes file URIs and skips a gnome list's verb, comments and other hosts", () => {
assert.deepEqual(
uriListPaths("copy\nfile:///home/u/a%20b.png\r\n# c\nfile://other/x\nhttps://x/y\n"),
["/home/u/a b.png"]
);
});
});
describe("clipboardFiles", () => {
it("reads Windows' file drop list with powershell -Sta", async () => {
let seen;
__setExecImpl(async (cmd, args) => {
seen = [cmd, args];
return `${big}\r\n${dir}\r\n${path.join(TMP, "gone.txt")}\r\n`;
});
assert.deepEqual(await clipboardFiles("win32"), [
{ path: big, size: 1234, dir: false },
{ path: dir, size: null, dir: true },
]);
assert.equal(seen[0], "powershell");
assert.ok(seen[1].includes("-Sta"));
assert.match(seen[1].at(-1), /GetFileDropList/);
});
it("reads macOS file URLs through JXA", async () => {
let seen;
__setExecImpl(async (cmd, args) => {
seen = [cmd, args];
return `${big}\n`;
});
assert.deepEqual(await clipboardFiles("darwin"), [{ path: big, size: 1234, dir: false }]);
assert.equal(seen[0], "osascript");
assert.deepEqual(seen[1].slice(0, 2), ["-l", "JavaScript"]);
});
it("reads Linux text/uri-list with the desktop's display", async () => {
const saved = process.env.DISPLAY;
process.env.DISPLAY = ":0";
try {
const calls = [];
__setExecImpl(async (cmd, args, env) => {
calls.push([cmd, args.join(" "), env.DISPLAY]);
return cmd === "xclip" ? `file://${encodeURI(big)}\n` : "";
});
assert.deepEqual(await clipboardFiles("linux"), [{ path: big, size: 1234, dir: false }]);
assert.deepEqual(calls.at(-1), ["xclip", "-selection clipboard -t text/uri-list -o", ":0"]);
} finally {
if (saved === undefined) delete process.env.DISPLAY;
else process.env.DISPLAY = saved;
}
});
it("answers no files when the reader is missing or prints relative paths", async () => {
__setExecImpl(async () => "");
assert.deepEqual(await clipboardFiles("win32"), []);
__setExecImpl(async () => "relative/x.txt\n");
assert.deepEqual(await clipboardFiles("darwin"), []);
});
it("reads Explorer's selection (and the desktop's) for a drop, once per path", async () => {
let seen;
__setExecImpl(async (cmd, args) => {
seen = [cmd, args];
return `${big}\r\n${big}\r\n`;
});
assert.deepEqual(await selectedFiles("win32"), [{ path: big, size: 1234, dir: false }]);
assert.equal(seen[0], "powershell");
assert.match(seen[1].at(-1), /Shell\.Application[\s\S]*SelectedItems[\s\S]*FindWindowSW/);
});
it("reads Finder's selection on macOS, a folder with its trailing slash", async () => {
let seen;
__setExecImpl(async (cmd, args) => {
seen = [cmd, args];
return `${dir}/\n`;
});
assert.deepEqual(await selectedFiles("darwin"), [{ path: `${dir}/`, size: null, dir: true }]);
assert.equal(seen[0], "osascript");
assert.ok(seen[1].includes("repeat with a in (selection as alias list)"));
});
it("has no selection to read on Linux", async () => {
let called = false;
__setExecImpl(async () => {
called = true;
return big;
});
assert.deepEqual(await selectedFiles("linux"), []);
assert.equal(called, false);
});
});
+15
View File
@@ -82,6 +82,21 @@ describe("scope", () => {
}
});
it("narrows ownSessionWhere to the caller's own sessions whatever the role", () => {
const own = (req) => {
const w = scope.ownSessionWhere(req);
return db
.prepare(`SELECT id FROM sessions WHERE ${w.where} ORDER BY id`)
.all(...w.params)
.map((r) => r.id);
};
assert.deepEqual(own(member(1)), ["s-unstamped", "s1"]);
assert.deepEqual(own(admin), []);
assert.deepEqual(own({ user: { ...admin.user, id: 2 } }), ["s2"]);
assert.deepEqual(own(analyst), []);
assert.equal(own(local).length, 5);
});
it("answers per-id checks for lanes, sessions, agents and runs", () => {
const m = member(1);
assert.equal(scope.canSeeLane(m, 1), true);
+1 -1
View File
@@ -101,7 +101,7 @@ describe("todayCost", () => {
it("reads today's row and caches it", async () => {
const file = path.join(TMP, "cache-a.json");
assert.equal(await todayCost({ url, file }), 3.5);
assert.equal(lastUrl, `/api/pricing/cost?tz_offset=${new Date().getTimezoneOffset()}`);
assert.equal(lastUrl, `/api/pricing/cost?tz_offset=${new Date().getTimezoneOffset()}&mine=1`);
assert.equal(await todayCost({ url, file }), 3.5);
assert.equal(hits, 1);
// A different dashboard URL is a cache miss.
+8 -1
View File
@@ -67,7 +67,14 @@ async function stepsFor(id, action) {
}
if (!tool.update) throw makeErr("ENOUPDATE", `${tool.label} has no update command`);
if (!d.installed) throw makeErr("ENOTINSTALLED", `${tool.label} is not installed`);
if (tool.update.kind === "self") return [{ argv: [d.path, ...tool.update.args] }];
if (tool.update.kind === "self") {
// An npm package's own updater (`codex update`) reinstalls into npm's
// GLOBAL prefix; one we installed under ~/.local must be updated there.
if (tool.install?.kind === "npm" && (await versions.managedBy(id)) === "user") {
return [{ argv: npmArgv(tool.install.package, ["--prefix", versions.userPrefix()]) }];
}
return [{ argv: [d.path, ...tool.update.args] }];
}
if (tool.update.kind === "script") {
return [{ script: tool.install.url, redirect: tool.install.redirect }];
}
+19 -1
View File
@@ -64,4 +64,22 @@ function desktopEnv() {
return out;
}
module.exports = { desktopEnv, FORWARDED, __setExecImpl };
/**
* Whether a CLI in a pane started now can read this desktop's clipboard — what
* a native image paste (`^V`, the terminal's `lib/nativePaste.ts`) relies on.
* On Linux Claude Code shells out to `wl-paste` (Wayland) or `xclip` (X11);
* neither ships with a stock Ubuntu, and with neither — or with no display to
* reach — the `^V` pastes nothing at all, so the browser must upload instead.
* macOS and Windows read their clipboard with built-in tools.
*/
function canReadClipboard({
platform = process.platform,
env = null,
which = (name) => require("./ai-tools").which(name),
} = {}) {
if (platform !== "linux") return true;
const e = env || desktopEnv();
return !!((e.WAYLAND_DISPLAY && which("wl-paste")) || (e.DISPLAY && which("xclip")));
}
module.exports = { desktopEnv, canReadClipboard, FORWARDED, __setExecImpl };
+194
View File
@@ -0,0 +1,194 @@
/**
* @file file-manager.js
* @description The files THIS machine's file manager (Explorer, Finder,
* Nautilus/Dolphin) is handing the browser, by their own absolute paths —
* what a native terminal pastes or types for them. A browser gives a page a
* pasted or dropped file as bytes and a name only (Chrome: never its path),
* so the terminal and the prompt box would upload a copy, capped in size.
* Two sources, each answered only to a loopback browser of a local-mode
* dashboard; the client uses a path only when its name and size match the
* file the browser holds, so an SSH tunnel's browser still uploads:
* - `clipboardFiles` (`POST /api/run/clipboard-files`, a paste): what a Copy
* put on the clipboard — Windows `powershell -Sta` +
* `Clipboard.GetFileDropList()` (Claude Code reads its images the same
* way), macOS JXA over `NSPasteboard` file URLs, Linux `wl-paste`/`xclip`
* for `text/uri-list` or `x-special/gnome-copied-files`;
* - `selectedFiles` (`POST /api/run/selected-files`, a drop): a drag from
* a file manager carries the items selected in it, so its selection —
* Windows `Shell.Application` (every Explorer window, and the desktop),
* macOS Finder's `selection` (macOS asks once to let AgentHub control
* Finder). Linux file managers publish no selection: a drop there takes
* the `file://` list the browser already hands over, else uploads.
* Nothing is searched for on disk. Every reader is a fixed argv, nothing from
* the request; a missing reader or an empty answer is an empty list.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { execFile } = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const MAX_FILES = 100;
const TIMEOUT_MS = 4000;
let execImpl = (cmd, args, env) =>
new Promise((resolve) => {
execFile(
cmd,
args,
{ encoding: "utf8", timeout: TIMEOUT_MS, maxBuffer: 1024 * 1024, env, windowsHide: true },
(err, stdout) => resolve(err ? "" : String(stdout || ""))
);
});
/** Test seam: `(cmd, args, env) => Promise<stdout>`. */
function __setExecImpl(fn) {
execImpl = fn;
}
const WIN_SCRIPT =
"[Console]::OutputEncoding = [Text.Encoding]::UTF8; Add-Type -AssemblyName System.Windows.Forms; " +
"[System.Windows.Forms.Clipboard]::GetFileDropList() | ForEach-Object { $_ }";
const MAC_SCRIPT = [
'ObjC.import("AppKit");',
"const pb = $.NSPasteboard.generalPasteboard;",
"const urls = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }));",
"const out = [];",
"if (urls) for (let i = 0; i < urls.count; i++) out.push(urls.objectAtIndex(i).path.js);",
'out.join("\\n");',
].join("\n");
/** `file://` URIs (and a gnome list's leading `copy`/`cut`) as local paths. */
function uriListPaths(text) {
const out = [];
for (const raw of String(text || "").split(/\r?\n/)) {
const line = raw.trim();
if (!line || line.startsWith("#") || line === "copy" || line === "cut") continue;
try {
const u = new URL(line);
if (u.protocol !== "file:" || (u.host && u.host !== "localhost")) continue;
out.push(decodeURIComponent(u.pathname));
} catch {
/* not a URI */
}
}
return out;
}
/** The raw paths on the clipboard, per platform; [] when it holds none. */
async function clipboardPaths(platform = process.platform) {
if (platform === "win32") {
const out = await execImpl(
"powershell",
["-NoProfile", "-NonInteractive", "-Sta", "-Command", WIN_SCRIPT],
process.env
);
return out
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
}
if (platform === "darwin") {
const out = await execImpl("osascript", ["-l", "JavaScript", "-e", MAC_SCRIPT], process.env);
return out
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
}
// Linux: the desktop session's variables, which a user service lacks.
const env = { ...process.env, ...require("./desktop-env").desktopEnv() };
const tries = [];
if (env.WAYLAND_DISPLAY) {
tries.push(["wl-paste", ["--no-newline", "--type", "text/uri-list"]]);
tries.push(["wl-paste", ["--no-newline", "--type", "x-special/gnome-copied-files"]]);
}
if (env.DISPLAY) {
tries.push(["xclip", ["-selection", "clipboard", "-t", "text/uri-list", "-o"]]);
tries.push(["xclip", ["-selection", "clipboard", "-t", "x-special/gnome-copied-files", "-o"]]);
}
for (const [cmd, args] of tries) {
const paths = uriListPaths(await execImpl(cmd, args, env));
if (paths.length) return paths;
}
return [];
}
const WIN_SELECTION =
"[Console]::OutputEncoding = [Text.Encoding]::UTF8; $sh = New-Object -ComObject Shell.Application; " +
"foreach ($w in @($sh.Windows())) { try { foreach ($i in $w.Document.SelectedItems()) { $i.Path } } catch {} }; " +
// The desktop is no Explorer window: ShellWindows.FindWindowSW(SWC_DESKTOP).
"try { $d = $sh.Windows().FindWindowSW(0, $null, 8, [ref]0, 1); foreach ($i in $d.Document.SelectedItems()) { $i.Path } } catch {}";
const MAC_SELECTION = [
'tell application "Finder"',
'set out to ""',
"repeat with a in (selection as alias list)",
"set out to out & POSIX path of a & linefeed",
"end repeat",
"return out",
"end tell",
];
/** The paths a file manager has selected, per platform; [] when unknown. */
async function selectionPaths(platform = process.platform) {
let out = "";
if (platform === "win32") {
out = await execImpl(
"powershell",
["-NoProfile", "-NonInteractive", "-Sta", "-Command", WIN_SELECTION],
process.env
);
} else if (platform === "darwin") {
out = await execImpl(
"osascript",
MAC_SELECTION.flatMap((l) => ["-e", l]),
process.env
);
}
return out
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
}
/** `[{ path, size, dir }]` for each absolute path that exists here (`size`
* null for a folder), at most 100, without repeats. */
function existing(paths) {
const out = [];
const seen = new Set();
for (const p of paths.slice(0, MAX_FILES)) {
if (!path.isAbsolute(p) && !/^[A-Za-z]:[\\/]/.test(p)) continue;
if (seen.has(p)) continue;
seen.add(p);
try {
const st = fs.statSync(p);
if (st.isFile()) out.push({ path: p, size: st.size, dir: false });
else if (st.isDirectory()) out.push({ path: p, size: null, dir: true });
} catch {
/* gone since the copy */
}
}
return out;
}
/** The clipboard's files (a file manager's Copy); [] when it holds none. */
async function clipboardFiles(platform = process.platform) {
try {
return existing(await clipboardPaths(platform));
} catch {
return [];
}
}
/** The files selected in the file manager — what a drag from it carries;
* [] when none, or on a platform whose file manager publishes none. */
async function selectedFiles(platform = process.platform) {
try {
return existing(await selectionPaths(platform));
} catch {
return [];
}
}
module.exports = { clipboardFiles, selectedFiles, uriListPaths, __setExecImpl };
+15 -5
View File
@@ -36,7 +36,19 @@ const ownerFor = (req) => (req?.user ? req.user.id : null);
* unrestricted. `col` is the session id expression, `laneCol` its lane id.
*/
function sessionWhere(req, col = "id", laneCol = "lane_id") {
const uid = memberId(req);
return ownedSessionWhere(memberId(req), col, laneCol);
}
/**
* `sessionWhere` for the requesting user's OWN sessions, whatever their role —
* a personal figure (the status bar's Today) that must not be every user's sum
* for an admin or analyst. "1" in local mode, where there is no user.
*/
function ownSessionWhere(req, col = "id", laneCol = "lane_id") {
return ownedSessionWhere(req?.user ? req.user.id : null, col, laneCol);
}
function ownedSessionWhere(uid, col, laneCol) {
if (uid == null) return { where: "1", params: [] };
return {
where: `(${laneCol} IN (SELECT id FROM lanes WHERE owner_id = ?)
@@ -155,10 +167,7 @@ const PATH_RULES = [
[/^\/workflows\/runs\/([^/]+)/i, (req, m) => canSeeRowSession(req, "workflows", m[1], "run_id")],
[/^\/alerts\/([^/]+)\/ack/i, (req, m) => canSeeRowSession(req, "alert_events", m[1])],
// `/artifacts/<id>…`: the owner's, or a shared one (server/lib/artifacts.js).
[
/^\/artifacts\/(\d+)(?:\/|$)/i,
(req, m) => require("./artifacts").canSeeId(req, m[1]),
],
[/^\/artifacts\/(\d+)(?:\/|$)/i, (req, m) => require("./artifacts").canSeeId(req, m[1])],
[
/^\/snapshots\/([^/]+)$/i,
(req, m) => req.method !== "DELETE" || canSeeRowSession(req, "session_snapshots", m[1]),
@@ -449,6 +458,7 @@ module.exports = {
memberId,
ownerFor,
sessionWhere,
ownSessionWhere,
bySessionWhere,
laneWhere,
canSeeLane,
+65
View File
@@ -161,6 +161,71 @@ const paths = {
},
},
},
"/api/run/clipboard-files": {
post: {
tags: ["Run"],
summary: "The files a file manager's Copy put on this machine's clipboard",
operationId: "runClipboardFiles",
description:
"For a browser on this machine: the files the OS clipboard holds (Windows GetFileDropList, macOS NSPasteboard file URLs, Linux text/uri-list via wl-paste/xclip), each that exists here with its size (`null` for a folder), at most 100 — so a pasted copy is attached by its own path, with no upload and no size limit. The client uses a path only when name and size match the pasted file. 403 EREMOTE in server mode or for any non-loopback (or proxied) request.",
responses: {
200: ok("The clipboard's files; empty when it holds none or no reader is installed.", {
files: {
type: "array",
items: {
type: "object",
properties: {
path: { type: "string" },
size: { type: "integer", nullable: true },
dir: { type: "boolean" },
},
},
},
}),
403: errs("EREMOTE."),
},
},
},
"/api/run/selected-files": {
post: {
tags: ["Run"],
summary: "The files selected in this machine's file manager (what a drag carries)",
operationId: "runSelectedFiles",
description:
"For a browser on this machine: the items selected in Explorer (every window, and the desktop) or Finder — a drag from the file manager carries exactly those — each that exists here with its size (`null` for a folder), at most 100, so a dropped file is attached by its own path with no upload and no size limit. Linux file managers publish no selection: always empty there. Nothing is searched for on disk. 403 EREMOTE in server mode or for any non-loopback (or proxied) request.",
responses: {
200: ok("The selected files; empty when none or no reader is available.", {
files: {
type: "array",
items: {
type: "object",
properties: {
path: { type: "string" },
size: { type: "integer", nullable: true },
dir: { type: "boolean" },
},
},
},
}),
403: errs("EREMOTE."),
},
},
},
"/api/run/native-paste": {
get: {
tags: ["Run"],
summary: "Whether a claude pane can read this machine's clipboard itself",
operationId: "runNativePaste",
description:
"`native`: local mode, a loopback request, and on Linux a reachable display plus `wl-paste` or `xclip` — then the terminal hands a pasted screenshot to `claude` as its image-paste key instead of uploading it. `key`: that chord on this machine — `alt+v` on Windows, `ctrl+v` elsewhere (Claude Code's own bindings).",
responses: {
200: ok("The answer.", {
native: { type: "boolean" },
key: { type: "string", enum: ["ctrl+v", "alt+v"] },
}),
},
},
},
"/api/run/interrupted": {
get: {
tags: ["Run"],
+10 -2
View File
@@ -576,7 +576,14 @@ function costScope(req, res) {
res.status(400).json(BAD_TOOL);
return null;
}
return costWhere({ scope: parseScope(req), lane });
// `mine=1`: the caller's own sessions even for an admin/analyst, who would
// otherwise get every user's sum (the status bar's Today is a personal figure).
const extra = [];
if (req.query.mine === "1") {
const own = require("../lib/scope").ownSessionWhere(req, "s.id", "s.lane_id");
if (own.where !== "1") extra.push({ clause: own.where, params: own.params });
}
return costWhere({ scope: parseScope(req), lane, extra });
}
/**
@@ -625,7 +632,8 @@ function computeCost(
// / analytics endpoints so the Dashboard "total cost" tracks the selector, plus
// `?lane=<id>` (the sessions that workspace owns), `?from=&to=` (local
// dates, see computeCost) and `?date=` (one local day, its `daily_costs` too —
// the status bar's Today). `by_tool` splits the total.
// the status bar's Today) and `?mine=1` (only the caller's own sessions, even
// for an admin or analyst — server mode; a no-op locally). `by_tool` splits the total.
router.get("/cost", (req, res) => {
const rawOffset = parseInt(req.query.tz_offset, 10);
const tzModifier = Number.isFinite(rawOffset) ? `${-rawOffset} minutes` : "+0 minutes";
+44 -1
View File
@@ -116,7 +116,9 @@ const DROP_TYPES = {
const DROP_MAX_BYTES = 20 * 1024 * 1024;
// A browser on this machine (loopback, never server mode) crosses no network:
// its drop is streamed to disk, so a video or a dump is no reason to refuse.
// Chrome hands a dropped file no `file://` path, so it cannot attach by path.
// Chrome hands a dropped file no `file://` path; the client first asks for
// the file manager's own (`/selected-files`, `/clipboard-files`) and only
// uploads what that cannot place.
const DROP_LOCAL_MAX_BYTES = 2 * 1024 ** 3;
const DROP_TTL_MS = 24 * 60 * 60_000;
const localDrop = (req) => !require("../lib/auth").isServerMode() && isLocalRequest(req);
@@ -314,6 +316,47 @@ router.post("/local-paths", (req, res) => {
});
});
// The files this machine's file manager is handing the browser, by their own
// paths (server/lib/file-manager.js): a browser gives a page a pasted or
// dropped file as bytes only — Chrome never with its path — so a big file
// could not be attached. A paste reads the clipboard (`clipboard-files`), a
// drop the file manager's selection, which is what a drag from it carries
// (`selected-files`). Same rule as /local-paths: local mode and a loopback
// request only; the client uses a path only when name and size match.
function fileManagerRoute(read) {
return async (req, res) => {
if (require("../lib/auth").isServerMode() || !isLocalRequest(req)) {
return res.status(403).json({
error: { code: "EREMOTE", message: "the file manager is read only for a local browser" },
});
}
res.json({ files: await read() });
};
}
router.post(
"/clipboard-files",
fileManagerRoute(() => require("../lib/file-manager").clipboardFiles())
);
router.post(
"/selected-files",
fileManagerRoute(() => require("../lib/file-manager").selectedFiles())
);
// Whether a `claude` pane can take an image paste natively (its image-paste
// key — `^V`, Alt+V on Windows: it reads
// this machine's clipboard itself) — only for a browser on this machine, in
// local mode, and only when a clipboard reader is installed and a display is
// reachable. Otherwise the browser uploads the image, which always works.
router.get("/native-paste", (req, res) => {
const local = !require("../lib/auth").isServerMode() && isLocalRequest(req);
// `key`: the chord Claude Code binds to its image paste here — Alt+V on
// Windows (Ctrl+V there is the terminal's text paste), Ctrl+V elsewhere.
res.json({
native: local && require("../lib/desktop-env").canReadClipboard(),
key: process.platform === "win32" ? "alt+v" : "ctrl+v",
});
});
router.get("/history", (req, res) => {
let dr = null;
try {