From 761a80004a9c29de505dbd7582d24f3a0bfc3b6c Mon Sep 17 00:00:00 2001 From: Factor Date: Thu, 19 Nov 2026 11:36:00 +0100 Subject: [PATCH] feat: unified attachment pipeline with clipboard image and file picker Co-Authored-By: Ovis Fast (Claude) --- mod/ovis-composer/attachments.js | 11 +- mod/ovis-composer/clipboard.js | 153 ++++++++++++++ mod/ovis-composer/main.js | 335 ++++++++++++++++++++++++++----- mod/ovis-composer/state.js | 39 +++- tests/attachments.test.mjs | 12 ++ tests/clipboard.test.mjs | 83 ++++++++ tests/state.test.mjs | 21 ++ 7 files changed, 597 insertions(+), 57 deletions(-) create mode 100644 mod/ovis-composer/clipboard.js create mode 100644 tests/clipboard.test.mjs diff --git a/mod/ovis-composer/attachments.js b/mod/ovis-composer/attachments.js index d3f519c..935a4dd 100644 --- a/mod/ovis-composer/attachments.js +++ b/mod/ovis-composer/attachments.js @@ -15,6 +15,9 @@ export const LIMITS = { messageChars: 20000, }; +/** A character that can be part of a path (letters of any alphabet too: "ęą"). */ +const PATH_CHAR = /[\p{L}\p{N}_/\\-]/u; + /** The extensions that make a file an image (the design's §13.8 list). */ const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"]); @@ -142,7 +145,7 @@ export function removeMention(text, path) { * @param {{name?:string, kind?:string}} file * @returns {string} */ -function kindOf(file) { +export function kindOf(file) { if (typeof file.kind === "string" && file.kind !== "") return file.kind.toLowerCase(); const name = typeof file.name === "string" ? file.name.toLowerCase() : ""; @@ -164,8 +167,8 @@ function kindOf(file) { * @returns {boolean} */ function standalone(before, after, afterNext) { - if (before !== "" && /[\w/\\-]/.test(before)) return false; - if (after !== "" && /[\w/\\-]/.test(after)) return false; - if (after === "." && /[\w/\\-]/.test(afterNext)) return false; + if (before !== "" && PATH_CHAR.test(before)) return false; + if (after !== "" && PATH_CHAR.test(after)) return false; + if (after === "." && PATH_CHAR.test(afterNext)) return false; return true; } diff --git a/mod/ovis-composer/clipboard.js b/mod/ovis-composer/clipboard.js new file mode 100644 index 0000000..bac07ac --- /dev/null +++ b/mod/ovis-composer/clipboard.js @@ -0,0 +1,153 @@ +// clipboard.js - what the composer asks the system for: the clipboard, the +// file picker, 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", +// script])` - `-Command`, because running script files is off on this +// machine), and the parsers read what the scripts print, so both halves are +// tested in plain Node (tests/clipboard.test.mjs). +// +// The scripts print one fact per line, the fields separated by a tab: +// FILES (one line per file) - files copied in the Explorer +// IMAGE - an image, saved as a PNG +// NONE - nothing to paste + +/** How long a pasted image stays in the paste folder. */ +export const PASTE_MAX_AGE_MS = 7 * 864e5; + +/** The programs that take an image (Global Constraints). */ +const IMAGE_APPS = new Set(["claude-code", "codex", "gemini", "opencode"]); + +/** + * The PowerShell that reads the clipboard: files first, then an image (saved + * as `\paste-.png`), otherwise `NONE`. + * + * @param {string} outDir - where a pasted image is saved + * @param {string} stamp - what makes the file name its own (a moment) + * @returns {string} + */ +export function clipboardScript(outDir, stamp) { + const dir = quote(outDir); + const name = `paste-${String(stamp).replace(/[^\w-]/g, "")}.png`; + + return [ + "Add-Type -AssemblyName System.Windows.Forms", + "Add-Type -AssemblyName System.Drawing", + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8", + "$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) }', + " exit 0", + "}", + "$img = [System.Windows.Forms.Clipboard]::GetImage()", + "if ($img -ne $null) {", + ` $dir = ${dir}`, + " 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)', + " exit 0", + "}", + "Write-Output 'NONE'", + ].join("\n"); +} + +/** + * What the clipboard script printed. + * + * @param {{code?:number, stdout?:string, stderr?:string}|null} res + * @returns {{kind:"image", paths:string[]} | {kind:"files", paths:string[]} | {kind:"none"} | {kind:"error", message:string}} + */ +export function parseClipboardResult(res) { + if (!res || typeof res !== "object") return { kind: "error", message: "Brak wyniku z PowerShell" }; + + if (res.code !== 0) { + const stderr = String(res.stderr ?? "").trim(); + return { kind: "error", message: stderr || `PowerShell zakończył się kodem ${res.code}` }; + } + + const files = []; + let image = ""; + 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; + } + + if (files.length > 0) return { kind: "files", paths: files }; + if (image !== "") return { kind: "image", paths: [image] }; + return { kind: "none" }; +} + +/** + * The PowerShell that opens the file dialog (several files may be picked) and + * prints one path per line. Cancel prints nothing. + * + * @returns {string} + */ +export function pickerScript() { + return [ + "Add-Type -AssemblyName System.Windows.Forms", + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8", + "$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 }", + "}", + ].join("\n"); +} + +/** + * The paths the dialog printed; cancel, or a failed run, is no path at all. + * + * @param {{code?:number, stdout?:string}|null} res + * @returns {string[]} + */ +export function parsePickerResult(res) { + if (!res || typeof res !== "object" || res.code !== 0) return []; + return lines(res.stdout); +} + +/** + * Which files of the paste folder are old enough to go. + * + * @param {{path:string, mtimeMs:number}[]} entries + * @param {number} now + * @param {number} [maxAgeMs] - 7 days by default + * @returns {string[]} + */ +export function staleFiles(entries, now, maxAgeMs = PASTE_MAX_AGE_MS) { + if (!Array.isArray(entries)) return []; + return entries + .filter((entry) => entry && Number.isFinite(entry.mtimeMs) && now - entry.mtimeMs > maxAgeMs) + .map((entry) => entry.path); +} + +/** + * Does the agent's program take an image? + * + * @param {string|null} app - `AgentInfo.app` + * @returns {boolean} + */ +export function supportsImages(app) { + return typeof app === "string" && IMAGE_APPS.has(app.trim()); +} + +/** The non-empty lines of an output. */ +function lines(text) { + return String(text ?? "") + .split(/\r?\n/) + .map((line) => line.replace(/\r$/, "")) + .filter((line) => line.trim() !== ""); +} + +/** A PowerShell single-quoted string. */ +function quote(text) { + return `'${String(text).replace(/'/g, "''")}'`; +} diff --git a/mod/ovis-composer/main.js b/mod/ovis-composer/main.js index 8fc688b..2731e87 100644 --- a/mod/ovis-composer/main.js +++ b/mod/ovis-composer/main.js @@ -27,6 +27,7 @@ import { theme, exec, hc, + home, shared, setShared, notify, @@ -39,7 +40,15 @@ 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 } from "./attachments.js"; +import { LIMITS, validateMany, mention, removeMention, kindOf } from "./attachments.js"; +import { + clipboardScript, + parseClipboardResult, + pickerScript, + parsePickerResult, + staleFiles, + supportsImages, +} from "./clipboard.js"; import * as storage from "./storage.js"; import { record } from "./history.js"; import { @@ -113,6 +122,12 @@ export default class Composer extends View { this.draftLoading = new Set(); this.draftTimer = null; + // Attachments: the message that waits for the answer to "this agent may + // not take images" (null when nothing waits), and whether the file dialog + // is open. + this.confirmImage = null; + this.picking = false; + // The menu of suggestions: what it shows, which row is picked. this.menu = null; this.debounce = null; @@ -132,6 +147,9 @@ export default class Composer extends View { this.textarea.set_soft_wrap(true); this.textarea.on("change", (event, cx) => this.changed(cx)); this.textarea.on("submit", (event, cx) => this.submitted(event, cx)); + // A paste that found no text (an image, files): the clipboard is read by + // PowerShell and goes through the same pipeline as a drop. + this.textarea.on("paste_other", (event, cx) => this.pasteOther(cx)); this.textarea.on("focus", () => { this.hasKeyboard = true; }); @@ -170,6 +188,7 @@ export default class Composer extends View { // Focus follows the click: nothing here takes the keyboard on its own. + this.cleanupPaste(); this.syncAgent(cx); // The agent under the focus can change without the composer being // touched - the sidebar, another pane. The draft that goes with it has to @@ -220,6 +239,7 @@ export default class Composer extends View { // The draft of the agent we leave goes to the disk at once. this.saveDraftNow(); + this.confirmImage = null; this.currentKey = key; if (!key) return; @@ -598,7 +618,7 @@ export default class Composer extends View { // --- sending ------------------------------------------------------------- /** The message goes out, or it waits in the queue. */ - submit(text, cx, mode = "auto") { + submit(text, cx, mode = "auto", force = false) { const agent = this.target(); if (!agent) { this.notice("Composer nie ma do kogo pisać — brak agenta.", "error", cx); @@ -619,33 +639,32 @@ export default class Composer extends View { if (broken) { // A file that did not make it to the agent is still in the way - the // person removes it or fixes it first. - this.notice(`Plik ${broken.name} nie dotarł do agenta — usuń go albo wyślij go jeszcze raz.`, "error", cx); + this.notice(`Plik ${broken.name} nie dotarł do agenta — kliknij „Ponów” albo usuń go.`, "error", cx); + return; + } + if (attached.some((file) => file.state === "adding")) { + this.notice("Pliki są jeszcze dodawane do agenta — poczekaj chwilę.", "error", cx); return; } const files = attached.filter((file) => file.state === "ready"); + // An image for a program that may not take it: the person decides. + if (!force && files.some((file) => file.kind === "image") && !supportsImages(agent.app)) { + this.confirmImage = { text, mode, program: agent.program?.name ?? agentName(agent) }; + cx.notify(); + return; + } + this.confirmImage = null; + // The field is free again - the message is on its way. this.clearField(cx); for (const file of files) { this.state = reduce(this.state, { type: "removeAttachment", agent: key, id: file.id }); } - // The files go to the agent's machine first; the mention in the text - // points at the path the agent sees, not at the path on this machine. - cx.spawn(async (cx) => { - let message = body; - for (const file of files) { - const landed = await this.putFile(agent, file); - if (!landed) { - // The agent cannot see that file - the message does not talk about - // it, and the tile stays with the reason. - message = removeMention(message, file.path); - continue; - } - message = message.split(mention(file.path)).join(mention(landed)); - } - this.finish(agent, message, cx, mode); - }); + // The files are on the agent's machine already (`addFiles`) and the text + // mentions them by the path the agent sees. + this.finish(agent, body, cx, mode); } /** The field is empty again. */ @@ -1041,30 +1060,75 @@ export default class Composer extends View { cx.notify(); } - /** The file lands beside the agent's terminal; the path it got is the one the agent sees. */ - async putFile(agent, file) { + /** + * The file lands beside the agent's terminal (`hc put`); the path it got is + * the one the agent sees, and the mention in the text uses it. A tile that + * failed stays, with the reason and a "Ponów" button. + */ + async putAttachment(agent, file, cx) { + const key = agentKey(agent); + let remote = ""; + let reason = ""; try { const res = await hc(["put", agent.address, file.path, "--json"]); const payload = parseJson(res.stdout); if (res.code !== 0 || (payload && payload.error)) { - this.putFailed(agent, file, resultError(res, payload)); - return ""; + reason = resultError(res, payload); + } else { + remote = landedPath(payload, res.stdout); + if (!remote) reason = "Agent nie podał ścieżki pliku."; } - return landedPath(payload, res.stdout); } catch (err) { - this.putFailed(agent, file, errorText(err)); - return ""; + reason = errorText(err); } + + // The tile was removed while the file was on its way. + if (!(this.state.attachments[key] ?? []).some((entry) => entry.id === file.id)) return; + + if (reason) { + this.state = reduce(this.state, { + type: "attachment_update", + agent: key, + id: file.id, + patch: { state: "error", error: reason }, + }); + this.notice(`Nie udało się dostarczyć pliku ${file.name}: ${reason}`, "error"); + } else { + this.state = reduce(this.state, { + type: "attachment_update", + agent: key, + id: file.id, + patch: { state: "ready", remotePath: remote }, + }); + this.addMention(key, remote); + } + this.scheduleDraftSave(cx); + cx.notify(); } - /** The file did not make it to the agent: the tile stays, with the reason. */ - putFailed(agent, file, reason) { + /** The mention of a file that reached the agent goes into the message of that agent. */ + addMention(key, remote) { + const token = mention(remote); + if (key === this.currentKey) { + const result = insertMentions(this.value, [token]); + this.textarea.set_value(result.value); + this.value = result.value; + return; + } + const result = insertMentions(this.state.drafts[key] ?? "", [token]); + this.state = reduce(this.state, { type: "draft", agent: key, text: result.value }); + } + + /** "Ponów": the tile that failed is sent to the agent again. */ + retryFile(agent, id, cx) { const key = agentKey(agent); - this.notice(`Nie udało się dostarczyć pliku ${file.name}: ${reason}`, "error"); - this.state = reduce(this.state, { - type: "attach", - agent: key, - file: { ...file, state: "error", error: reason }, + const file = (this.state.attachments[key] ?? []).find((entry) => entry.id === id); + if (!file || file.state !== "error") return; + + 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); }); } @@ -1247,15 +1311,34 @@ export default class Composer extends View { /** Files were dropped on the composer. */ drop(event, cx) { - const agent = this.target(); - if (!agent) return; - const paths = Array.isArray(event.paths) ? event.paths : []; - if (!paths.length) return; + this.addFiles(Array.isArray(event.paths) ? event.paths : [], "drop", cx); + } + /** + * The one way a file gets attached - dropped, pasted or picked with "+". + * + * 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. + * + * @param {string[]} paths + * @param {"drop"|"paste"|"picker"} origin + */ + addFiles(paths, 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 paths) { - files.push({ id: this.newId(), name: nameOf(path), path, bytes: await sizeOf(path) }); + 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 check = validateMany(files); @@ -1263,24 +1346,102 @@ export default class Composer extends View { this.notice(check.reason, "error"); return cx.notify(); } - - const key = agentKey(agent); - for (const file of files) { - this.state = reduce(this.state, { type: "attach", agent: key, file }); + 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(); } - // The mention of the file goes into the message. - const result = insertMentions( - this.value, - files.map((file) => mention(file.path)), - ); - this.textarea.set_value(result.value); - this.value = result.value; + for (const file of files) { + this.state = reduce(this.state, { type: "attach", agent: key, file: { ...file, state: "adding" } }); + } this.scheduleDraftSave(cx); cx.notify(); + + for (const file of files) await this.putAttachment(agent, file, cx); }); } + /** A paste found no text: the clipboard has files, an image - or nothing. */ + pasteOther(cx) { + if (!this.target()) return; + cx.spawn(async (cx) => { + let result; + try { + const res = await exec("powershell", [ + "-NoProfile", + "-STA", + "-Command", + clipboardScript(this.pasteDir(), String(Date.now())), + ]); + result = parseClipboardResult(res); + } catch (err) { + result = { kind: "error", message: errorText(err) }; + } + + if (result.kind === "none") { + 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 { + this.addFiles(result.paths, "paste", cx); + } + cx.notify(); + }); + } + + /** The "+" button: the file dialog, then the same pipeline. */ + pickFiles(cx) { + if (this.picking || !this.target()) return; + this.picking = true; + cx.spawn(async (cx) => { + try { + // The person may take their time with the dialog. + const res = await exec("powershell", ["-NoProfile", "-STA", "-Command", pickerScript()], { + timeout: 600000, + }); + const paths = parsePickerResult(res); + if (paths.length) this.addFiles(paths, "picker", cx); + } catch (err) { + this.notice(`Nie udało się otworzyć okna wyboru plików: ${errorText(err)}`, "error"); + } finally { + this.picking = false; + cx.notify(); + } + }); + } + + /** Where pasted images are saved before they go to the agent. */ + pasteDir() { + return [home(), ".config", "herdr-app", "data", "ovis-composer", "paste"].join("\\"); + } + + /** + * The pasted images older than 7 days go. The moment is in the name + * (`paste-.png`) - the file API of the mods has no `stat` for mtime - + * and only files of that shape are ever touched. + */ + async cleanupPaste() { + try { + const dir = this.pasteDir(); + if (!(await fs.exists(dir))) return; + const entries = []; + for (const name of await fs.readdir(dir)) { + const match = /^paste-(\d+)\.png$/.exec(name); + if (match) entries.push({ path: `${dir}\\${name}`, mtimeMs: Number(match[1]) }); + } + for (const path of staleFiles(entries, Date.now())) { + try { + await fs.unlink(path); + } catch { + // A file that cannot be removed stays; the next start tries again. + } + } + } catch { + // No paste folder, nothing to clean. + } + } + /** The file is not wanted any more - the mention goes with it. */ removeFile(agent, id, cx) { const key = agentKey(agent); @@ -1289,7 +1450,7 @@ export default class Composer extends View { this.state = reduce(this.state, { type: "removeAttachment", agent: key, id }); - const text = removeMention(this.value, file.path); + const text = file.remotePath ? removeMention(this.value, file.remotePath) : this.value; if (text !== this.value) { this.textarea.set_value(text); this.value = text; @@ -1393,6 +1554,7 @@ export default class Composer extends View { [ this.renderMenu(t), this.renderQueue(t, agent, key), + this.renderImageConfirm(t), this.renderNotice(t), this.renderCard(t, agent, key, status), this.renderContext(t, agent), @@ -1568,6 +1730,41 @@ export default class Composer extends View { .child(text); } + /** The question about an image for a program that may not take it. */ + renderImageConfirm(t) { + const ask = this.confirmImage; + if (!ask) return null; + + return v_flex() + .id("composer-image-confirm") + .gap(6) + .px(10) + .py(6) + .rounded(8) + .bg(t.chrome) + .child( + div() + .text_size(11.5) + .text_color(t.foreground) + .child(`${ask.program} może nie obsługiwać obrazów — obraz trafi do agenta tylko jako ścieżka w tekście.`), + ) + .child( + h_flex() + .gap(6) + .child( + this.renderButton(t, "Anuluj", "image-cancel", (event, cx) => { + this.confirmImage = null; + cx.notify(); + }), + ) + .child( + this.renderButton(t, "Wyślij mimo to", "image-send", (event, cx) => + this.submit(ask.text, cx, ask.mode, true), + ), + ), + ); + } + /** What the composer says under the card. */ renderNotice(t) { const notice = this.state.notice; @@ -1615,6 +1812,7 @@ export default class Composer extends View { h_flex() .gap(8) .items_center() + .child(this.renderPlus(t, agent)) .child(this.renderChip(t, agent, status)) .child(div().flex_1()) .child(stop ? this.renderStop(t, agent) : this.renderSend(t, agent, over)), @@ -1622,6 +1820,25 @@ export default class Composer extends View { ); } + /** The "+" button: pick files with the system dialog. */ + renderPlus(t, agent) { + return div() + .id("composer-plus") + .size(28) + .rounded(999) + .flex_none() + .flex() + .items_center() + .justify_center() + .bg(t.chrome) + .text_size(15) + .text_color(agent ? t.muted : t.dim) + .cursor_pointer() + .hover((s) => s.bg(t.hover).text_color(t.foreground)) + .on_click((event, cx) => this.pickFiles(cx)) + .child("+"); + } + /** The tiles of the files that go with the message. */ renderFiles(t, agent) { const key = agentKey(agent); @@ -1648,6 +1865,22 @@ export default class Composer extends View { .truncate() .child(file.name), ) + .when(file.state === "adding", (el) => + el.child(div().text_size(10.5).text_color(t.dim).child("dodawanie…")), + ) + .when(file.state === "error", (el) => + el.child( + div() + .id(`file-retry-${file.id}`) + .px(4) + .text_size(11) + .text_color(t.blocked) + .cursor_pointer() + .hover((s) => s.text_color(t.foreground)) + .on_click((event, cx) => this.retryFile(agent, file.id, cx)) + .child("Ponów"), + ), + ) .child( div() .id(`file-x-${file.id}`) diff --git a/mod/ovis-composer/state.js b/mod/ovis-composer/state.js index 0d26c99..812a725 100644 --- a/mod/ovis-composer/state.js +++ b/mod/ovis-composer/state.js @@ -12,11 +12,12 @@ import { onRestart } from "./delivery.js"; /** * @typedef {"image"|"file"} AttachmentKind - * @typedef {"ready"|"error"} AttachmentState + * @typedef {"adding"|"ready"|"error"} AttachmentState * @typedef {object} Attachment * @property {string} id * @property {string} name * @property {string} path + * @property {string} [remotePath] - the path the agent sees (`hc put`) * @property {number} bytes * @property {AttachmentKind} kind * @property {AttachmentState} state @@ -133,6 +134,9 @@ export function reduce(state, action) { }, }; + case "attachment_update": + return attachmentUpdate(state, action); + case "removeAttachment": return { ...state, @@ -177,6 +181,30 @@ export function reduce(state, action) { } } +/** + * One attachment changes: it was added to the agent (`ready` with the path + * the agent sees), it failed (`error`), or it is tried again (`adding`). An + * `error` text belongs to the `error` state only. + */ +function attachmentUpdate(state, action) { + const files = list(state.attachments, action.agent); + const file = files.find((entry) => entry.id === action.id); + if (!file) return state; + + const { error, ...rest } = file; + const next = { ...rest, ...action.patch }; + if (next.state === "error") next.error = action.patch?.error ?? error ?? ""; + else delete next.error; + + return { + ...state, + attachments: { + ...state.attachments, + [action.agent]: files.map((entry) => (entry.id === action.id ? next : entry)), + }, + }; +} + /** * The draft of an agent comes back from the disk. * @@ -207,7 +235,13 @@ function restoreDraft(state, action) { carets: { ...(state.carets ?? {}), [agent]: Number.isInteger(draft.caret) ? draft.caret : draft.text.length }, attachments: { ...state.attachments, - [agent]: (draft.attachments ?? []).map((file) => ({ ...file })), + // A file that was still being added when the app went down is not on + // the agent: the tile says so and can be tried again. + [agent]: (draft.attachments ?? []).map((file) => + file.state === "adding" + ? { ...file, state: "error", error: "Dodawanie przerwane — ponów." } + : { ...file }, + ), }, }; } @@ -426,6 +460,7 @@ function toAttachment(file) { bytes: file.bytes, kind: file.kind ?? "file", state: file.state ?? "ready", + ...(file.remotePath !== undefined ? { remotePath: file.remotePath } : {}), ...(file.error !== undefined ? { error: file.error } : {}), }; } diff --git a/tests/attachments.test.mjs b/tests/attachments.test.mjs index fc6f750..a363b38 100644 --- a/tests/attachments.test.mjs +++ b/tests/attachments.test.mjs @@ -36,3 +36,15 @@ test("removeMention removes only the standalone token", () => { assert.equal(removeMention("see @src/a.rs now", "src/a.rs"), "see now"); assert.equal(removeMention("see @src/a.rsx now", "src/a.rs"), "see @src/a.rsx now"); }); + +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), ""); +}); + +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"); +}); diff --git a/tests/clipboard.test.mjs b/tests/clipboard.test.mjs new file mode 100644 index 0000000..4df074c --- /dev/null +++ b/tests/clipboard.test.mjs @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + clipboardScript, parseClipboardResult, pickerScript, parsePickerResult, 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"); + 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("IMAGE")); + assert.ok(s.includes("NONE")); + 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")); +}); + +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: 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"; + assert.deepEqual(parseClipboardResult(ok(out)), { + kind: "files", paths: ["C:\Moje pliki\zażółć gęślą.txt", "D:\a b\c.png"], + }); +}); + +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 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: "" }); + assert.equal(r.kind, "error"); + assert.ok(r.message.length > 0); + assert.equal(parseClipboardResult(null).kind, "error"); +}); + +test("pickerScript: multiselect dialog, one path per line", () => { + const s = pickerScript(); + assert.ok(s.includes("OpenFileDialog")); + assert.ok(s.includes("Multiselect")); + assert.ok(s.includes("$true")); +}); + +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"]); + assert.deepEqual(parsePickerResult(ok("")), []); + assert.deepEqual(parsePickerResult(ok("\r\n")), []); + assert.deepEqual(parsePickerResult({ code: 1, stdout: "x", stderr: "e" }), []); + assert.deepEqual(parsePickerResult(null), []); +}); + +test("staleFiles: 6 days stay, 8 days go", () => { + const now = 100 * 864e5; + const entries = [ + { path: "new.png", mtimeMs: now - 6 * 864e5 }, + { path: "old.png", mtimeMs: now - 8 * 864e5 }, + { path: "bad", mtimeMs: NaN }, + ]; + assert.deepEqual(staleFiles(entries, now), ["old.png"]); + assert.deepEqual(staleFiles(entries, now, 5 * 864e5), ["new.png", "old.png"]); + assert.deepEqual(staleFiles(null, now), []); +}); + +test("supportsImages", () => { + for (const app of ["claude-code", "codex", "gemini", "opencode"]) assert.equal(supportsImages(app), true, app); + assert.equal(supportsImages("aider"), false); + assert.equal(supportsImages(null), false); + assert.equal(supportsImages(""), false); +}); diff --git a/tests/state.test.mjs b/tests/state.test.mjs index 3f264d9..0085175 100644 --- a/tests/state.test.mjs +++ b/tests/state.test.mjs @@ -191,3 +191,24 @@ test("restart turns a countdown into held", () => { const s = reduce(mk(it("c", "countdown", { left: 2 })), { type: "restart", agent: "a" }); assert.deepEqual(states(s), ["held"]); }); + +test("restore_draft turns an unfinished attachment into an error", () => { + const att = (id, state) => ({ id, name: id, path: "p", bytes: 1, kind: "file", state }); + const draft = { text: "t", caret: 1, attachments: [att("a", "adding"), att("b", "ready")], identity: { created_ms: 5, app: null }, savedAt: 1 }; + const s = reduce(createState(), { type: "restore_draft", agent: "t2", draft, identity: { created_ms: 5, app: null } }); + assert.equal(s.attachments.t2[0].state, "error"); + assert.ok(s.attachments.t2[0].error.length > 0); + assert.equal(s.attachments.t2[1].state, "ready"); +}); + +test("attachment states: adding -> ready with the remote path, or error; retry goes back to adding", () => { + let s = reduce(createState(), { type: "attach", agent: "a", file: { id: "1", name: "f", path: "p", bytes: 1, state: "adding" } }); + assert.equal(s.attachments.a[0].state, "adding"); + s = reduce(s, { type: "attachment_update", agent: "a", id: "1", patch: { state: "ready", remotePath: "/r/f" } }); + assert.deepEqual([s.attachments.a[0].state, s.attachments.a[0].remotePath], ["ready", "/r/f"]); + s = reduce(s, { type: "attachment_update", agent: "a", id: "1", patch: { state: "error", error: "x" } }); + assert.equal(s.attachments.a[0].error, "x"); + s = reduce(s, { type: "attachment_update", agent: "a", id: "1", patch: { state: "adding" } }); + assert.equal(s.attachments.a[0].error, undefined); + assert.equal(reduce(s, { type: "attachment_update", agent: "a", id: "zz", patch: { state: "ready" } }), s); +});