fix: file sizes from PowerShell, quoted mentions, dedupe and BOM

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 11:40:40 +01:00
1 parent 761a80004a
commit 1ed04fe9be
5 files changed
+328 -83

No files matched your search

+6 -1
View File
@@ -79,13 +79,18 @@ export function validateMany(files) {
/**
* The mention of an attachment - the path as the agent sees it.
*
* A path with whitespace in it is quoted - `@"/a b/c.png"` - or the agent
* would read only the part up to the first space; any other path stays bare
* (`@/a/c.png`). `removeMention` takes out exactly the form built here.
*
* @param {string} path - the path on the agent's machine
* @returns {string} the mention, or nothing when there is no path
*/
export function mention(path) {
if (typeof path !== "string") return "";
const clean = path.trim();
return clean === "" ? "" : `@${clean}`;
if (clean === "") return "";
return /\s/.test(clean) ? `@"${clean}"` : `@${clean}`;
}
/**
+130 -24
View File
@@ -1,5 +1,5 @@
// clipboard.js - what the composer asks the system for: the clipboard, the
// file picker, and the old files of the paste folder.
// file picker, the sizes of files, and the old files of the paste folder.
//
// Pure: no gpui-kit, no gpui-base, no herdr. The scripts are PowerShell text
// (run by main.js with `exec("powershell", ["-NoProfile", "-STA", "-Command",
@@ -7,10 +7,16 @@
// machine), and the parsers read what the scripts print, so both halves are
// tested in plain Node (tests/clipboard.test.mjs).
//
// The mods have no `stat` (fs/promises: no size, no mtime), so the SIZE of
// every file comes from PowerShell, in the same call that finds the file.
//
// The scripts print one fact per line, the fields separated by a tab:
// FILES<TAB><path> (one line per file) - files copied in the Explorer
// IMAGE<TAB><path> - an image, saved as a PNG
// FILES<TAB><path><TAB><bytes> (one line per file) - files from the Explorer
// IMAGE<TAB><path><TAB><bytes> - an image, saved as a PNG
// DIR<TAB><path> - a folder (not carried)
// NONE - nothing to paste
// An empty or missing <bytes> means the size could not be read: the caller
// does not let such a file through (fail closed).
/** How long a pasted image stays in the paste folder. */
export const PASTE_MAX_AGE_MS = 7 * 864e5;
@@ -19,8 +25,8 @@ export const PASTE_MAX_AGE_MS = 7 * 864e5;
const IMAGE_APPS = new Set(["claude-code", "codex", "gemini", "opencode"]);
/**
* The PowerShell that reads the clipboard: files first, then an image (saved
* as `<outDir>\paste-<stamp>.png`), otherwise `NONE`.
* The PowerShell that reads the clipboard: files first (folders apart), then
* an image (saved as `<outDir>\paste-<stamp>.png`), otherwise `NONE`.
*
* @param {string} outDir - where a pasted image is saved
* @param {string} stamp - what makes the file name its own (a moment)
@@ -37,7 +43,15 @@ export function clipboardScript(outDir, stamp) {
"$tab = [char]9",
"$files = [System.Windows.Forms.Clipboard]::GetFileDropList()",
"if ($files -ne $null -and $files.Count -gt 0) {",
' foreach ($f in $files) { Write-Output ("FILES" + $tab + $f) }',
" foreach ($f in $files) {",
" if (Test-Path -LiteralPath $f -PathType Container) {",
' Write-Output ("DIR" + $tab + $f)',
" } else {",
" $len = ''",
" try { $len = (Get-Item -LiteralPath $f -ErrorAction Stop).Length } catch { }",
' Write-Output ("FILES" + $tab + $f + $tab + $len)',
" }",
" }",
" exit 0",
"}",
"$img = [System.Windows.Forms.Clipboard]::GetImage()",
@@ -46,7 +60,9 @@ export function clipboardScript(outDir, stamp) {
" New-Item -ItemType Directory -Force -Path $dir | Out-Null",
` $path = Join-Path $dir '${name}'`,
" $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png)",
' Write-Output ("IMAGE" + $tab + $path)',
" $len = ''",
" try { $len = (Get-Item -LiteralPath $path -ErrorAction Stop).Length } catch { }",
' Write-Output ("IMAGE" + $tab + $path + $tab + $len)',
" exit 0",
"}",
"Write-Output 'NONE'",
@@ -56,8 +72,12 @@ export function clipboardScript(outDir, stamp) {
/**
* What the clipboard script printed.
*
* `files` are the things to attach (an image comes as one file); `dirs` are
* folders, which are not carried. Only folders: `{kind:"dirs"}`.
*
* @param {{code?:number, stdout?:string, stderr?:string}|null} res
* @returns {{kind:"image", paths:string[]} | {kind:"files", paths:string[]} | {kind:"none"} | {kind:"error", message:string}}
* @returns {{kind:"image"|"files", files:{path:string, bytes:number|null}[], dirs:string[]}
* | {kind:"dirs", dirs:string[]} | {kind:"none"} | {kind:"error", message:string}}
*/
export function parseClipboardResult(res) {
if (!res || typeof res !== "object") return { kind: "error", message: "Brak wyniku z PowerShell" };
@@ -68,25 +88,25 @@ export function parseClipboardResult(res) {
}
const files = [];
let image = "";
const dirs = [];
let image = null;
for (const line of lines(res.stdout)) {
const tab = line.indexOf("\t");
if (tab < 0) continue;
const kind = line.slice(0, tab);
const path = line.slice(tab + 1).trim();
if (path === "") continue;
if (kind === "FILES") files.push(path);
if (kind === "IMAGE" && image === "") image = path;
const [kind, path, size] = fields(line);
if (!path) continue;
if (kind === "FILES") files.push({ path, bytes: toBytes(size) });
if (kind === "IMAGE" && image === null) image = { path, bytes: toBytes(size) };
if (kind === "DIR") dirs.push(path);
}
if (files.length > 0) return { kind: "files", paths: files };
if (image !== "") return { kind: "image", paths: [image] };
if (files.length > 0) return { kind: "files", files, dirs };
if (image) return { kind: "image", files: [image], dirs };
if (dirs.length > 0) return { kind: "dirs", dirs };
return { kind: "none" };
}
/**
* The PowerShell that opens the file dialog (several files may be picked) and
* prints one path per line. Cancel prints nothing.
* prints `<path><TAB><bytes>` per line. Cancel prints nothing.
*
* @returns {string}
*/
@@ -94,24 +114,85 @@ export function pickerScript() {
return [
"Add-Type -AssemblyName System.Windows.Forms",
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
"$tab = [char]9",
"$dialog = New-Object System.Windows.Forms.OpenFileDialog",
"$dialog.Multiselect = $true",
"$dialog.Title = 'Wybierz pliki'",
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {",
" foreach ($f in $dialog.FileNames) { Write-Output $f }",
" foreach ($f in $dialog.FileNames) {",
" $len = ''",
" try { $len = (Get-Item -LiteralPath $f -ErrorAction Stop).Length } catch { }",
' Write-Output ($f + $tab + $len)',
" }",
"}",
].join("\n");
}
/**
* The paths the dialog printed; cancel, or a failed run, is no path at all.
* The files the dialog printed; cancel, or a failed run, is no file at all.
*
* @param {{code?:number, stdout?:string}|null} res
* @returns {string[]}
* @returns {{path:string, bytes:number|null}[]}
*/
export function parsePickerResult(res) {
if (!res || typeof res !== "object" || res.code !== 0) return [];
return lines(res.stdout);
return lines(res.stdout).map((line) => {
const [path, size] = fieldsLast(line);
return { path, bytes: toBytes(size) };
});
}
/**
* The PowerShell that measures a batch of paths in one call: `SIZE` for a
* file, `DIR` for a folder, `MISSING` for what is not there.
*
* @param {string[]} paths
* @returns {string}
*/
export function sizeScript(paths) {
const list = (Array.isArray(paths) ? paths : []).map(quote).join(", ");
return [
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
"$tab = [char]9",
`$paths = @(${list})`,
"foreach ($p in $paths) {",
" if (Test-Path -LiteralPath $p -PathType Container) {",
' Write-Output ("DIR" + $tab + $p)',
" } elseif (Test-Path -LiteralPath $p -PathType Leaf) {",
" $len = ''",
" try { $len = (Get-Item -LiteralPath $p -ErrorAction Stop).Length } catch { }",
' Write-Output ("SIZE" + $tab + $p + $tab + $len)',
" } else {",
' Write-Output ("MISSING" + $tab + $p)',
" }",
"}",
].join("\n");
}
/**
* What `sizeScript` printed. A run that failed has no sizes at all: `error`
* says why, and the caller does not attach anything on a guess.
*
* @param {{code?:number, stdout?:string, stderr?:string}|null} res
* @returns {{files:{path:string, bytes:number|null}[], dirs:string[], missing:string[], error:string|null}}
*/
export function parseSizeResult(res) {
const empty = { files: [], dirs: [], missing: [], error: null };
if (!res || typeof res !== "object") return { ...empty, error: "Brak wyniku z PowerShell" };
if (res.code !== 0) {
const stderr = String(res.stderr ?? "").trim();
return { ...empty, error: stderr || `PowerShell zakończył się kodem ${res.code}` };
}
const out = { files: [], dirs: [], missing: [], error: null };
for (const line of lines(res.stdout)) {
const [kind, path, size] = fields(line);
if (!path) continue;
if (kind === "SIZE") out.files.push({ path, bytes: toBytes(size) });
if (kind === "DIR") out.dirs.push(path);
if (kind === "MISSING") out.missing.push(path);
}
return out;
}
/**
@@ -139,14 +220,39 @@ export function supportsImages(app) {
return typeof app === "string" && IMAGE_APPS.has(app.trim());
}
/** The non-empty lines of an output. */
/** The non-empty lines of an output; a BOM in front of it is not part of it. */
function lines(text) {
return String(text ?? "")
.replace(/^/, "")
.split(/\r?\n/)
.map((line) => line.replace(/\r$/, ""))
.filter((line) => line.trim() !== "");
}
/** `KIND<TAB>path<TAB>size` -> [kind, path, size]. */
function fields(line) {
const first = line.indexOf("\t");
if (first < 0) return [line, "", ""];
const rest = line.slice(first + 1);
const second = rest.indexOf("\t");
return second < 0
? [line.slice(0, first), rest.trim(), ""]
: [line.slice(0, first), rest.slice(0, second).trim(), rest.slice(second + 1).trim()];
}
/** `path<TAB>size` -> [path, size] (the size is behind the last tab). */
function fieldsLast(line) {
const at = line.lastIndexOf("\t");
return at < 0 ? [line.trim(), ""] : [line.slice(0, at).trim(), line.slice(at + 1).trim()];
}
/** A size in bytes, or null when it is not a size. */
function toBytes(text) {
if (typeof text !== "string" || text.trim() === "") return null;
const value = Number(text);
return Number.isFinite(value) && value >= 0 ? value : null;
}
/** A PowerShell single-quoted string. */
function quote(text) {
return `'${String(text).replace(/'/g, "''")}'`;
+109 -40
View File
@@ -40,12 +40,14 @@ import { keyIntent } from "./keys.js";
import { decide, shouldDrain, shouldStartCountdown, sendNow as sendToTerminal } from "./delivery.js";
import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js";
import * as catalog from "./catalog.js";
import { LIMITS, validateMany, mention, removeMention, kindOf } from "./attachments.js";
import { LIMITS, validate, validateMany, mention, removeMention, kindOf } from "./attachments.js";
import {
clipboardScript,
parseClipboardResult,
pickerScript,
parsePickerResult,
sizeScript,
parseSizeResult,
staleFiles,
supportsImages,
} from "./clipboard.js";
@@ -83,6 +85,12 @@ import {
/** The placeholder of the field. */
const PLACEHOLDER = "Napisz do agenta…";
/** What the composer says when a size cannot be read (the file does not go on a guess). */
const SIZE_ERROR = "Nie można odczytać rozmiaru pliku";
/** Folders are not carried - only files. */
const DIR_NOTICE = "Foldery nie są obsługiwane — dodaj pliki.";
/** How many rows the menu of the suggestions shows at most. */
const MENU_LIMIT = 20;
@@ -419,6 +427,8 @@ export default class Composer extends View {
const next = this.textarea.value();
const previous = this.value;
this.value = next;
// The question was about that text - another text, another question.
if (this.confirmImage && this.confirmImage.text !== next) this.confirmImage = null;
// Enter puts a newline into the field before the composer sends it - the
// newline is not part of the message.
@@ -1119,7 +1129,10 @@ export default class Composer extends View {
this.state = reduce(this.state, { type: "draft", agent: key, text: result.value });
}
/** "Ponów": the tile that failed is sent to the agent again. */
/**
* "Ponów": the tile that failed is sent to the agent again. A file whose
* size was never read is measured first - it does not go on a guess.
*/
retryFile(agent, id, cx) {
const key = agentKey(agent);
const file = (this.state.attachments[key] ?? []).find((entry) => entry.id === id);
@@ -1128,7 +1141,24 @@ export default class Composer extends View {
this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { state: "adding" } });
cx.notify();
cx.spawn(async (cx) => {
await this.putAttachment(agent, file, cx);
let current = file;
if (!Number.isFinite(file.bytes)) {
const measured = (await this.measure([file.path])).files[0];
const check = measured && Number.isFinite(measured.bytes) ? validate({ ...file, bytes: measured.bytes }) : null;
if (!check || !check.ok) {
this.state = reduce(this.state, {
type: "attachment_update",
agent: key,
id,
patch: { state: "error", error: check ? check.reason : SIZE_ERROR },
});
cx.notify();
return;
}
current = { ...file, bytes: measured.bytes };
this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { bytes: measured.bytes } });
}
await this.putAttachment(agent, current, cx);
});
}
@@ -1309,9 +1339,30 @@ export default class Composer extends View {
// --- the attachments -----------------------------------------------------
/** Files were dropped on the composer. */
/** Files were dropped on the composer: measured in one call, then the pipeline. */
drop(event, cx) {
this.addFiles(Array.isArray(event.paths) ? event.paths : [], "drop", cx);
const paths = Array.isArray(event.paths) ? event.paths.filter((p) => typeof p === "string" && p !== "") : [];
if (!paths.length) return;
cx.spawn(async (cx) => {
const measured = await this.measure(paths);
if (measured.error) {
// The sizes are unknown: the files get a tile with the reason, they
// do not go through on a guess.
this.addFiles(paths.map((path) => ({ path, bytes: null })), "drop", cx);
return;
}
if (measured.dirs.length) this.notice(DIR_NOTICE, "error");
this.addFiles(measured.files, "drop", cx);
});
}
/** PowerShell measures a batch of paths (the mods have no `stat`). Never throws. */
async measure(paths) {
try {
return parseSizeResult(await exec("powershell", ["-NoProfile", "-STA", "-Command", sizeScript(paths)]));
} catch (err) {
return { files: [], dirs: [], missing: [], error: errorText(err) };
}
}
/**
@@ -1319,46 +1370,72 @@ export default class Composer extends View {
*
* The files are checked (size, count, type), get a tile in the state
* `adding`, go to the agent with `hc put`, and only then - `ready` - the
* mention with the path the agent sees goes into the message.
* mention with the path the agent sees goes into the message. A file whose
* size is unknown (`bytes` null) gets an `error` tile and goes nowhere. A
* file that is attached already is not added a second time.
*
* @param {string[]} paths
* @param {{path:string, bytes:number|null}[]} entries
* @param {"drop"|"paste"|"picker"} origin
*/
addFiles(paths, origin, cx) {
addFiles(entries, origin, cx) {
const agent = this.target();
if (!agent) {
this.notice("Wybierz agenta — nie ma do kogo dodać pliku.", "error", cx);
return;
}
const list = [...new Set((Array.isArray(paths) ? paths : []).filter((path) => typeof path === "string" && path !== ""))];
if (!list.length) return;
const key = agentKey(agent);
cx.spawn(async (cx) => {
const files = [];
for (const path of list) {
const name = nameOf(path);
files.push({ id: this.newId(), name, path, bytes: await sizeOf(path), kind: kindOf({ name }), origin });
const have = new Set((this.state.attachments[key] ?? []).map((file) => file.path.toLowerCase()));
const fresh = [];
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry.path !== "string" || entry.path === "") continue;
const id = entry.path.toLowerCase();
if (have.has(id)) continue;
have.add(id);
fresh.push(entry);
}
if (!fresh.length) {
if ((entries ?? []).length) this.notice("Ten plik jest już dodany.", "error", cx);
return;
}
const check = validateMany(files);
const files = fresh.map((entry) => {
const name = nameOf(entry.path);
return {
id: this.newId(),
name,
path: entry.path,
bytes: Number.isFinite(entry.bytes) ? entry.bytes : undefined,
kind: kindOf({ name }),
origin,
};
});
const known = files.filter((file) => file.bytes !== undefined);
const check = validateMany(known);
if (!check.ok) {
this.notice(check.reason, "error");
return cx.notify();
this.notice(check.reason, "error", cx);
return;
}
const total = (this.state.attachments[key] ?? []).length + files.length;
if (total > LIMITS.filesPerAction) {
this.notice(`Za dużo plików (limit ${LIMITS.filesPerAction})`, "error");
return cx.notify();
if ((this.state.attachments[key] ?? []).length + files.length > LIMITS.filesPerAction) {
this.notice(`Za dużo plików (limit ${LIMITS.filesPerAction})`, "error", cx);
return;
}
for (const file of files) {
this.state = reduce(this.state, { type: "attach", agent: key, file: { ...file, state: "adding" } });
const unknown = file.bytes === undefined;
this.state = reduce(this.state, {
type: "attach",
agent: key,
file: unknown ? { ...file, state: "error", error: SIZE_ERROR } : { ...file, state: "adding" },
});
}
if (files.some((file) => file.bytes === undefined)) this.notice(SIZE_ERROR, "error");
this.scheduleDraftSave(cx);
cx.notify();
for (const file of files) await this.putAttachment(agent, file, cx);
cx.spawn(async (cx) => {
for (const file of known) await this.putAttachment(agent, file, cx);
});
}
@@ -1383,8 +1460,11 @@ export default class Composer extends View {
this.notice("Schowek nie zawiera tekstu ani obrazu, który można wkleić.", "error");
} else if (result.kind === "error") {
this.notice(`Nie udało się odczytać schowka: ${result.message}`, "error");
} else if (result.kind === "dirs") {
this.notice(DIR_NOTICE, "error");
} else {
this.addFiles(result.paths, "paste", cx);
if (result.dirs.length) this.notice(DIR_NOTICE, "error");
this.addFiles(result.files, "paste", cx);
}
cx.notify();
});
@@ -1400,8 +1480,8 @@ export default class Composer extends View {
const res = await exec("powershell", ["-NoProfile", "-STA", "-Command", pickerScript()], {
timeout: 600000,
});
const paths = parsePickerResult(res);
if (paths.length) this.addFiles(paths, "picker", cx);
const picked = parsePickerResult(res);
if (picked.length) this.addFiles(picked, "picker", cx);
} catch (err) {
this.notice(`Nie udało się otworzyć okna wyboru plików: ${errorText(err)}`, "error");
} finally {
@@ -1759,7 +1839,7 @@ export default class Composer extends View {
)
.child(
this.renderButton(t, "Wyślij mimo to", "image-send", (event, cx) =>
this.submit(ask.text, cx, ask.mode, true),
this.submit(this.value, cx, ask.mode, true),
),
),
);
@@ -2034,14 +2114,3 @@ function landedPath(payload, stdout) {
.filter(Boolean);
return lines.length ? lines[lines.length - 1].trim() : "";
}
/** The size of a file, when it can be measured. */
async function sizeOf(path) {
try {
const info = await fs.stat(path);
return Number.isFinite(info?.size) ? info.size : undefined;
} catch {
// A size that could not be measured is not a size that broke the limit.
return undefined;
}
}
+14 -4
View File
@@ -26,8 +26,11 @@ test("validateMany enforces count limit", () => {
assert.equal(validateMany(files.slice(0, 100)).ok, true);
});
test("mention", () => {
test("mention: bare path, or quoted when it has whitespace", () => {
assert.equal(mention(" /a/b "), "@/a/b");
assert.equal(mention("/a b/c"), '@"/a b/c"');
assert.equal(mention("C:\\Moje pliki\\x.png"), '@"C:\\Moje pliki\\x.png"');
assert.equal(mention("/a\tb"), '@"/a\tb"');
assert.equal(mention(""), "");
assert.equal(mention(5), "");
});
@@ -39,12 +42,19 @@ test("removeMention removes only the standalone token", () => {
test("mention and removeMention with a space and Polish letters in the path", () => {
const path = "/home/zażółć/gęsia jaźń/ęą.png";
assert.equal(mention(path), `@${path}`);
assert.equal(removeMention(`zobacz @${path} proszę`, path), "zobacz proszę");
assert.equal(removeMention(`@${path}`, path), "");
assert.equal(mention(path), `@"${path}"`);
assert.equal(removeMention(`zobacz @"${path}" proszę`, path), "zobacz proszę");
assert.equal(removeMention(`@"${path}"`, path), "");
});
test("removeMention leaves a mention glued to a Polish letter alone", () => {
assert.equal(removeMention("@src/aę a", "src/a"), "@src/aę a");
assert.equal(removeMention("ę@src/a", "src/a"), "ę@src/a");
});
test("removeMention takes the quoted form and the bare form out", () => {
assert.equal(removeMention('see @"/a b/ęą.png" now', "/a b/ęą.png"), "see now");
assert.equal(removeMention('@"/a b/ęą.png"', "/a b/ęą.png"), "");
assert.equal(removeMention("see @/a/ęą.png now", "/a/ęą.png"), "see now");
assert.equal(removeMention('see @"/a b/c.png"x now', "/a b/c.png"), 'see @"/a b/c.png"x now');
});
+69 -14
View File
@@ -1,45 +1,69 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
clipboardScript, parseClipboardResult, pickerScript, parsePickerResult, staleFiles, supportsImages,
clipboardScript, parseClipboardResult, pickerScript, parsePickerResult,
sizeScript, parseSizeResult, staleFiles, supportsImages,
} from "../mod/ovis-composer/clipboard.js";
const ok = (stdout) => ({ code: 0, stdout, stderr: "" });
test("clipboardScript: files first, then image, then NONE", () => {
const s = clipboardScript("C:\out dir", "123");
test("clipboardScript: files first (with sizes, directories apart), then image, then NONE", () => {
const s = clipboardScript("C:\\out dir", "123");
assert.ok(s.indexOf("GetFileDropList") >= 0);
assert.ok(s.indexOf("GetFileDropList") < s.indexOf("GetImage"));
assert.ok(s.includes("paste-123.png"));
assert.ok(s.includes("FILES"));
assert.ok(s.includes("DIR"));
assert.ok(s.includes("Container"));
assert.ok(s.includes(".Length"));
assert.ok(s.includes("IMAGE"));
assert.ok(s.includes("NONE"));
assert.ok(s.includes("C:\out dir"));
assert.ok(s.includes("C:\\out dir"));
});
test("clipboardScript quotes a path with an apostrophe", () => {
assert.ok(clipboardScript("C:\o'brien", "1").includes("C:\o''brien"));
assert.ok(clipboardScript("C:\\o'brien", "1").includes("C:\\o''brien"));
});
test("parseClipboardResult: image", () => {
assert.deepEqual(parseClipboardResult(ok("IMAGE\tC:\data\paste-1.png\r\n")), {
kind: "image", paths: ["C:\data\paste-1.png"],
test("parseClipboardResult: image with its size", () => {
assert.deepEqual(parseClipboardResult(ok("IMAGE\tC:\\data\\paste-1.png\t2048\r\n")), {
kind: "image", files: [{ path: "C:\\data\\paste-1.png", bytes: 2048 }], dirs: [],
});
});
test("parseClipboardResult: files with spaces and Polish letters", () => {
const out = "FILES\tC:\Moje pliki\zażółć gęślą.txt\r\nFILES\tD:\a b\c.png\r\n";
test("parseClipboardResult: files with spaces and Polish letters, sizes", () => {
const out = "FILES\tC:\\Moje pliki\\zażółć gęślą.txt\t10\r\nFILES\tD:\\a b\\c.png\t0\r\n";
assert.deepEqual(parseClipboardResult(ok(out)), {
kind: "files", paths: ["C:\Moje pliki\zażółć gęślą.txt", "D:\a b\c.png"],
kind: "files",
files: [{ path: "C:\\Moje pliki\\zażółć gęślą.txt", bytes: 10 }, { path: "D:\\a b\\c.png", bytes: 0 }],
dirs: [],
});
});
test("parseClipboardResult: a file without a readable size has bytes null", () => {
assert.deepEqual(parseClipboardResult(ok("FILES\tC:\\a.txt\t\r\nFILES\tC:\\b.txt\r\n")).files, [
{ path: "C:\\a.txt", bytes: null }, { path: "C:\\b.txt", bytes: null },
]);
});
test("parseClipboardResult: directories are reported apart", () => {
const r = parseClipboardResult(ok("DIR\tC:\\folder\r\nFILES\tC:\\a.txt\t5\r\n"));
assert.equal(r.kind, "files");
assert.deepEqual(r.dirs, ["C:\\folder"]);
assert.deepEqual(parseClipboardResult(ok("DIR\tC:\\folder\r\n")), { kind: "dirs", dirs: ["C:\\folder"] });
});
test("parseClipboardResult: NONE, empty, rubbish", () => {
assert.deepEqual(parseClipboardResult(ok("NONE\r\n")), { kind: "none" });
assert.deepEqual(parseClipboardResult(ok("")), { kind: "none" });
assert.deepEqual(parseClipboardResult(ok("what\r\n")), { kind: "none" });
});
test("parseClipboardResult: a BOM in front of the output is ignored", () => {
assert.deepEqual(parseClipboardResult(ok("\uFEFFNONE\r\n")), { kind: "none" });
assert.equal(parseClipboardResult(ok("\uFEFFIMAGE\tC:\\p.png\t1\r\n")).kind, "image");
});
test("parseClipboardResult: a failed run is an error with stderr", () => {
assert.deepEqual(parseClipboardResult({ code: 1, stdout: "", stderr: "boom\n" }), { kind: "error", message: "boom" });
const r = parseClipboardResult({ code: 3, stdout: "", stderr: "" });
@@ -48,21 +72,52 @@ test("parseClipboardResult: a failed run is an error with stderr", () => {
assert.equal(parseClipboardResult(null).kind, "error");
});
test("pickerScript: multiselect dialog, one path per line", () => {
test("pickerScript: multiselect dialog, path and size per line", () => {
const s = pickerScript();
assert.ok(s.includes("OpenFileDialog"));
assert.ok(s.includes("Multiselect"));
assert.ok(s.includes("$true"));
assert.ok(s.includes(".Length"));
});
test("parsePickerResult: paths, cancelled -> []", () => {
assert.deepEqual(parsePickerResult(ok("C:\a b\c.txt\r\nD:\d.png\r\n")), ["C:\a b\c.txt", "D:\d.png"]);
test("parsePickerResult: path and bytes, cancelled -> []", () => {
assert.deepEqual(parsePickerResult(ok("C:\\a b\\c.txt\t7\r\nD:\\d.png\t9\r\n")), [
{ path: "C:\\a b\\c.txt", bytes: 7 }, { path: "D:\\d.png", bytes: 9 },
]);
assert.deepEqual(parsePickerResult(ok("\uFEFFC:\\a.txt\t\r\n")), [{ path: "C:\\a.txt", bytes: null }]);
assert.deepEqual(parsePickerResult(ok("C:\\a.txt\r\n")), [{ path: "C:\\a.txt", bytes: null }]);
assert.deepEqual(parsePickerResult(ok("")), []);
assert.deepEqual(parsePickerResult(ok("\r\n")), []);
assert.deepEqual(parsePickerResult({ code: 1, stdout: "x", stderr: "e" }), []);
assert.deepEqual(parsePickerResult(null), []);
});
test("sizeScript: one call for the whole batch, paths quoted", () => {
const s = sizeScript(["C:\\a b\\it's.txt", "D:\\x.png"]);
assert.ok(s.includes("'C:\\a b\\it''s.txt'"));
assert.ok(s.includes("'D:\\x.png'"));
assert.ok(s.includes("-LiteralPath"));
assert.ok(s.includes("DIR"));
assert.ok(s.includes("SIZE"));
});
test("parseSizeResult: sizes, directories, missing, unknown sizes", () => {
const out = "SIZE\tC:\\a b\\ż.txt\t12\r\nDIR\tC:\\folder\r\nMISSING\tC:\\gone\r\nSIZE\tC:\\c\t\r\n";
assert.deepEqual(parseSizeResult(ok(out)), {
files: [{ path: "C:\\a b\\ż.txt", bytes: 12 }, { path: "C:\\c", bytes: null }],
dirs: ["C:\\folder"],
missing: ["C:\\gone"],
error: null,
});
});
test("parseSizeResult: a failed run fails closed", () => {
const r = parseSizeResult({ code: 1, stdout: "", stderr: "nope\n" });
assert.deepEqual([r.files, r.dirs, r.error], [[], [], "nope"]);
assert.ok(parseSizeResult(null).error.length > 0);
assert.equal(parseSizeResult(ok("\uFEFFSIZE\tC:\\a\t3\r\n")).files[0].bytes, 3);
});
test("staleFiles: 6 days stay, 8 days go", () => {
const now = 100 * 864e5;
const entries = [