// main.js - the composer: the visible message bar under the terminal. // // The field, the queue above it, the suggestion menu, the attachments, the // context strip and the agent chip. What needs no GPUI lives in view.js // (tests/main.test.mjs); the state model is state.js, the sending is // delivery.js, the suggestions are suggest.js and catalog.js, the limits are // attachments.js and the persistence is storage.js. // // The composer talks to one agent at a time - the focused one. Everything that // belongs to an agent (the draft, the queue, the attachments) is keyed by the // agent's address, so switching agents never mixes two of them. // // The keyboard belongs to the composer: the terminal only shows. The field // takes the keyboard back when it loses it, and the shortcuts that belong to // the agent's own program (Ctrl+C, Esc) are passed on with `hc`. // // `hc send` does not confirm a delivery - it pastes the text and presses // Enter. The composer says "Wysłano do terminala" and takes the confirmation // from the agent's status. import { View, div, image } from "gpui-kit"; import { v_flex, h_flex, TextareaState, Textarea, InputState, VirtualListScrollHandle } from "gpui-base"; import { agents as liveAgents, panes as livePanes, focused as liveFocused, theme, exec, hc, home, run, settings, shared, setShared, notify, nextCommand, } from "herdr"; import * as fs from "fs/promises"; import { createState, reduce } from "./state.js"; 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, validate, mention, removeMention, kindOf, formatBytes } from "./attachments.js"; import { clipboardScript, parseClipboardResult, pickerScript, parsePickerResult, sizeScript, parseSizeResult, staleFiles, supportsImages, } from "./clipboard.js"; import * as storage from "./storage.js"; import { record, panelState, moveIndex, otherTab, toggleFavorite, isFavorite } from "./history.js"; import { renderPanel, renderPreview } from "./panel.js"; import { agentKey, agentName, agentStatus, applySuggestion, canAutoSend, closeGate, createGate, drainAll, failedHookOutcome, gatePasses, groupItems, guardedStore, hcOk, insertMentions, insertedNewline, isPlainEnter, menuAction, moveCaret, openGate, overLimit, paneContext, parseJson, queueLabel, shortPath, statusText, targetAgent, } from "./view.js"; /** 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."; /** A block lower than this (px) is made taller while the panel is open... */ const PANEL_MIN_BLOCK = 320; /** ...to this. */ const PANEL_BLOCK_PX = 360; /** How many rows the menu of the suggestions shows at most. */ const MENU_LIMIT = 20; /** How much room the menu takes - the same with one row and with twenty. */ const MENU_HEIGHT = 118; /** The key context of the composer - the bindings of the mod sit on it. */ const CONTEXT = "ovis-composer"; export default class Composer extends View { init(_props, cx) { this.state = createState(); this.store = guardedStore({ get: shared, set: setShared }); // The one place every send of a message passes: the direct send, the // queue, the countdown and "Wyślij teraz" all call `hc send` through it, // so the history gets exactly one entry per send that `hc` accepted. this.sendHc = (args) => this.runSend(args); // Per agent: the turn gate, whether a drain is in flight, and whether the // queue of that agent was read from the disk. this.gates = new Map(); this.draining = new Set(); this.restored = new Set(); // The queue counts down when the agent is idle (see `tickQueues`): the // last status seen per agent, and the agents the composer stopped itself // (Stop, Esc) - until their turn is over, the queue does not start. this.prevStatus = new Map(); this.stopped = new Set(); // Drafts: the identity of each terminal (`hc get`, cached per address), // the agents whose draft was read from the disk (or is being read), and // the timer that writes the draft 500 ms after the last change. this.identities = new Map(); this.draftReady = new Set(); 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; this.retry = null; this.retryAttempt = 0; // The text of the field and the text before the newline that Enter put in. this.value = ""; this.enterText = null; this.enterCaret = 0; this.currentKey = ""; this.counter = 0; this.closed = false; this.textarea = TextareaState.new({ value: "", placeholder: PLACEHOLDER, rows: 1 }); this.textarea.set_auto_grow(1, 10); 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; }); this.textarea.on("blur", (event, cx) => { this.hasKeyboard = false; // Focus follows the click: the composer never grabs the keyboard back. // It takes it when the person clicks the field or presses // Ctrl+Shift+Space (the "focus" command). }); this.handle = cx.focus_handle(); // The History | Favourites panel (null when closed): the tab, the row that // is picked, where the caret was when it opened, and the history as it was // read then. Each tab has a search field of its own. this.panel = null; // The height of the composer block (reported by its root) and the height // to give back when a panel that made the block taller closes. this.blockHeight = null; this.panelRestorePx = null; this.panelInputs = { history: InputState.new({ placeholder: "Szukaj w historii…" }), favorites: InputState.new({ placeholder: "Szukaj w ulubionych…" }), }; for (const input of Object.values(this.panelInputs)) { input.on("change", (event, cx) => { if (!this.panel) return; this.panel.index = 0; this.scrollPanel(0); cx.notify(); }); input.on("submit", (event, cx) => this.panelPick(this.panel?.index ?? 0, cx)); } this.panelScroll = VirtualListScrollHandle.new(); this.favorites = storage.loadFavorites(this.store); // The preview of an image (null when closed). this.preview = null; this.previewHandle = cx.focus_handle(); // The keys the field swallows: it binds the arrows and Tab to its own // actions and eats them before they reach the element. Ctrl+C is not bound // here - it stays "copy". The composer takes these keys as actions of its // own - the app hands every action named "." to the mod's // nextCommand(). // // The keymap is application-wide, so a plain "Input" context would also // match the text fields of other mods and swallow their keys. The // bindings use the descendant predicate "ovis-composer > Input": only a // field that sits inside the composer's own key context (see // key_context(CONTEXT) on the root) matches. // // What the composer does with the key depends on the keyboard: only the // copy of the composer whose own field has the keyboard acts - the other // copies (a composer in another pane) leave the key alone. cx.bind_keys([ { keystroke: "up", action: "ovis-composer.up", context: `${CONTEXT} > Input` }, { keystroke: "down", action: "ovis-composer.down", context: `${CONTEXT} > Input` }, { keystroke: "tab", action: "ovis-composer.accept", context: `${CONTEXT} > Input` }, { keystroke: "ctrl-r", action: "ovis-composer.panel", context: `${CONTEXT} > Input` }, { keystroke: "ctrl-enter", action: "ovis-composer.send_now", context: `${CONTEXT} > Input` }, { keystroke: "alt-enter", action: "ovis-composer.hold", context: `${CONTEXT} > Input` }, { keystroke: "escape", action: "ovis-composer.escape", context: `${CONTEXT} > Input` }, ]); // 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 // follow, so the composer watches who it talks to. cx.timer.every(500, (cx) => { this.syncAgent(cx); }); // Once a second: the end of a turn starts the countdown of the queue and // the countdown counts down. cx.timer.every(1000, (cx) => { this.tickQueues(cx); }); cx.spawn(async (cx) => { for (;;) { const command = await nextCommand(); if (command === "focus") this.textarea.focus(); this.runAction(command, cx); cx.notify(); } }); } /** The copy is gone - it must not take the keyboard with it. */ close(cx) { this.closed = true; this.saveDraftNow(); } // --- the agent ----------------------------------------------------------- /** The agent the composer talks to. */ target() { return targetAgent(liveAgents(), liveFocused()); } /** * The composer follows the agent under the focus. * * The draft of the agent we leave goes back to the state, the draft of the * agent we come to comes out of it, and the queue of that agent comes back * from the disk. */ syncAgent(cx) { const agent = this.target(); const key = agent ? agentKey(agent) : ""; if (key === this.currentKey) return; // The draft of the agent we leave goes to the disk at once. this.saveDraftNow(); this.confirmImage = null; this.currentKey = key; if (!key) return; this.restoreQueue(key); this.showDraft(key); this.restoreDraft(agent, key, cx); cx.notify(); } /** The draft of the agent (and its caret) goes into the field. */ showDraft(key) { const draft = this.state.drafts[key] ?? ""; if (draft !== this.textarea.value()) { this.textarea.set_value(draft); this.value = draft; } const caret = this.state.carets?.[key]; this.restoreCaret(Number.isInteger(caret) ? Math.min(caret, draft.length) : draft.length); } /** * The draft of an agent comes back from the disk - once per address. * * The identity of the terminal (`created_ms` from `hc get`) says whether it * is the terminal the draft was written for. Nothing is written to the disk * for the agent before this is done: a draft written with an identity that * is not known yet would wipe the one that is waiting there. */ restoreDraft(agent, key, cx) { if (this.draftReady.has(key) || this.draftLoading.has(key)) return; this.draftLoading.add(key); cx.spawn(async (cx) => { try { const identity = await this.fetchIdentity(agent); this.identities.set(key, identity); const stored = storage.loadDraft(this.store, key); const here = key === this.currentKey; const typed = here ? this.textarea.value() : (this.state.drafts[key] ?? ""); const untouched = typed === "" && (this.state.attachments[key] ?? []).length === 0; // The identity is compared always; what the person typed while it // was read is not overwritten (`keepCurrent`). this.state = reduce(this.state, { type: "restore_draft", agent: key, draft: stored, identity, keepCurrent: !untouched, }); this.persistQueue(key); if (here && stored && untouched) this.showDraft(key); } catch { // Nothing is known about the terminal: the queue waits for the person // and the saving of drafts is not blocked for ever. if (!this.identities.has(key)) this.identities.set(key, { created_ms: null, app: null }); try { this.state = reduce(this.state, { type: "hold_queue", agent: key }); this.persistQueue(key); } catch { // The queue stays as it is. } } this.draftLoading.delete(key); this.draftReady.add(key); // The queue that came back from the disk and was trusted goes on: after // the turn of the agent, or at once when the agent is idle. this.resumeRestored(agent, key, cx); cx.notify(); }); } /** Who the terminal is: when it was created (`hc get`) and its program. */ async fetchIdentity(agent) { const app = typeof agent.app === "string" && agent.app.trim() !== "" ? agent.app.trim() : null; try { const res = await hc(["get", agent.address, "--json"]); const payload = hcOk(res) ? parseJson(res.stdout) : null; const created = payload && Number.isFinite(payload.created_ms) ? payload.created_ms : null; return { created_ms: created, app }; } catch { return { created_ms: null, app }; } } /** The draft goes to the disk 500 ms after the last change. */ scheduleDraftSave(cx) { if (this.draftTimer) { this.draftTimer.cancel(); this.draftTimer = null; } this.draftTimer = cx.timer.after(500, () => { this.draftTimer = null; this.saveDraftNow(); }); } /** The draft of the agent under the focus goes to the disk now. */ saveDraftNow() { if (this.draftTimer) { this.draftTimer.cancel(); this.draftTimer = null; } const key = this.currentKey; if (!key) return; // The field is the truth: the state follows it. this.state = reduce(this.state, { type: "draft", agent: key, text: this.textarea.value(), caret: this.caret(), }); const identity = this.identities.get(key); if (!identity || !this.draftReady.has(key)) return; try { storage.saveDraft(this.store, key, { text: this.state.drafts[key] ?? "", caret: this.state.carets?.[key] ?? 0, attachments: this.state.attachments[key] ?? [], identity, savedAt: Date.now(), }); } catch (err) { this.notice(`Nie udało się zapisać szkicu: ${errorText(err)}`, "error"); } } /** The queue of an agent comes back from the disk; what was on the wire is uncertain. */ restoreQueue(key) { if (this.restored.has(key)) return; this.restored.add(key); const items = storage.loadQueue(this.store, key); if (items.length === 0) return; this.state = reduce(this.state, { type: "restore", agent: key, items }); this.state = reduce(this.state, { type: "restart", agent: key }); this.persistQueue(key); } /** The turn gate of an agent. */ gateFor(key) { let gate = this.gates.get(key); if (!gate) { gate = createGate(); this.gates.set(key, gate); } return gate; } /** The status of an agent; the gate learns that a turn began. */ statusOf(agent) { const live = liveAgents().find((entry) => entry.address === agent.address); const status = agentStatus(live ?? agent); if (status === "working") this.gateFor(agentKey(agent)).sawWorking = true; return status; } // --- the field ----------------------------------------------------------- /** Where the cursor is in the field. */ caret() { try { const range = this.textarea.selected_range(); return Number.isInteger(range?.end) ? range.end : 0; } catch { return 0; } } /** The field changed: the draft follows and the menu looks at the new text. */ changed(cx) { 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. const inserted = insertedNewline(previous, next); this.enterText = inserted ? previous : null; this.enterCaret = inserted ? inserted.index : this.caret(); const agent = this.target(); if (agent) { this.state = reduce(this.state, { type: "draft", agent: agentKey(agent), text: next, caret: this.caret(), }); this.scheduleDraftSave(cx); } // The newline of the keyboard does not move the menu. if (!inserted) this.updateSuggestions(agent, cx); cx.notify(); } /** Enter in the field: the message goes out, or the menu takes the key. */ submitted(event, cx) { // The newline that Enter put into the field is not part of the message - // the text of the field as it was before it. const text = this.enterText ?? this.value; const caret = this.enterText !== null ? this.enterCaret : this.caret(); this.enterText = null; // Shift+Enter is a new line and the secondary Enter (the one an IME // sends) is not a message either. if (!isPlainEnter(event)) return; if (this.intentOf({ key: "enter" }) !== "send") return; // The menu takes the key - but only when it has something to offer. if (this.menu && (this.menu.items ?? []).length > 0) { this.accept(cx, text, caret); return; } this.submit(text, cx); } /** The context the key intents are decided in. */ intentContext() { const agent = this.target(); return { hasKeyboard: this.hasKeyboard, menuOpen: !!this.menu && (this.menu.items ?? []).length > 0, panelOpen: this.panel !== null, empty: this.value.trim() === "", status: agent ? this.statusOf(agent) : null, }; } /** What the key means right now (see keys.js). */ intentOf(partial) { return keyIntent( { key: "", shift: false, ctrl: false, alt: false, composing: false, ...partial }, this.intentContext(), ); } /** Does what a key means. Returns true when the key was ours. */ intent(partial, cx) { const intent = this.intentOf(partial); switch (intent) { case "menu_down": this.arrow(1, cx); break; case "menu_up": this.arrow(-1, cx); break; case "menu_accept": this.acceptFromKey(cx); break; case "close_menu": this.closeMenu(); break; case "close_panel": this.closePanel(); break; case "open_panel": this.openPanel(); break; case "interrupt": { const agent = this.target(); if (agent) this.interrupt(agent, cx); break; } case "send_now": // Out right away, whatever the agent's status says. this.submit(this.value, cx, "now"); break; case "hold": // Into the queue in state "held": waits for "Wyślij teraz". this.submit(this.value, cx, "hold"); break; default: return false; } cx.notify(); return true; } /** One of the composer's bound actions (the names bind_keys uses, without the prefix). */ runAction(command, cx) { // The same press may arrive twice (element action and nextCommand); the // second delivery within 40 ms is the same key. const now = Date.now(); if (this.lastAction && this.lastAction.command === command && now - this.lastAction.at < 40) return; this.lastAction = { command, at: now }; // While the panel is open the keys are the panel's - the keyboard is in // its search field, not in the composer's, and the bindings of the // composer (`ovis-composer > Input`) catch these keys as actions first. if (this.panel) { if (command === "up") this.panelCommand("up", cx); else if (command === "down") this.panelCommand("down", cx); else if (command === "accept") this.panelCommand("tab", cx); else if (command === "escape" || command === "panel") this.panelCommand("escape", cx); cx.notify(); return; } if (command === "up") this.arrow(-1, cx); if (command === "down") this.arrow(1, cx); if (command === "accept") this.acceptFromKey(cx); if (command === "panel") this.intent({ key: "r", ctrl: true }, cx); if (command === "send_now") this.intent({ key: "enter", ctrl: true }, cx); if (command === "hold") this.intent({ key: "enter", alt: true }, cx); if (command === "escape") this.intent({ key: "escape" }, cx); } // --- the History | Favourites panel --------------------------------------- /** The panel opens over the composer; the caret of the field is remembered. */ openPanel(tab = "history") { if (!this.target()) { this.notice("Wybierz agenta, aby otworzyć historię.", "error"); return; } this.closeMenu(); let caret = { start: 0, end: 0 }; try { const range = this.textarea.selected_range(); caret = { start: range.start, end: range.end }; } catch { // The caret is unknown - the text goes in at the start. } // A low block leaves no room for a list: it is made taller while the // panel is open, and goes back to its height when the panel closes. The // height is remembered once, BEFORE the resize, in the units `layout.resize` // takes (see `layoutPx`), and nothing overwrites it while the panel is open. if (this.panelRestorePx === null) { const px = this.layoutPx(); if (px !== null && px < PANEL_MIN_BLOCK) { this.panelRestorePx = px; this.resizeBlock(PANEL_BLOCK_PX); } } this.favorites = storage.loadFavorites(this.store); this.panel = { tab, index: 0, caret, history: storage.loadHistory(this.store) }; for (const input of Object.values(this.panelInputs)) input.set_value(""); this.panelInputs[tab].focus(); this.scrollPanel(0); } /** The panel closes; the field gets the keyboard and the caret back. */ closePanel(restore = true) { if (!this.panel) return; const { caret } = this.panel; this.panel = null; if (this.panelRestorePx !== null) { this.resizeBlock(this.panelRestorePx); this.panelRestorePx = null; } this.textarea.focus(); if (restore) this.restoreSelection(caret); } /** * The height of the block in the pixels of the layout (`layout.resize {px}`). * * The root reports LOGICAL pixels - the layout's pixels times the zoom of * the app (settings().zoom, 1.2 here: 260 px in the layout is 312 reported). * Giving the reported number back to `layout.resize` would make the block * taller by the zoom factor, so it is divided by it. * * @returns {number|null} null while the root has not reported a height */ layoutPx() { if (!Number.isFinite(this.blockHeight)) return null; let zoom = 1; try { const value = Number(settings()?.zoom); if (Number.isFinite(value) && value > 0) zoom = value; } catch { // Unknown zoom: 1, the reported height is taken as it is. } return Math.round(this.blockHeight / zoom); } /** The composer block gets another height (`layout.resize`); a refusal is said, not worked around. */ resizeBlock(px) { try { run("layout.resize", { id: "composer", px }); } catch (err) { this.notice(`Nie udało się zmienić wysokości composera: ${errorText(err)}`, "error"); } } /** The selection (or the caret) of the field. */ restoreSelection(range) { try { this.textarea.set_selected_range({ start: range.start, end: range.end }); } catch { // The field does not answer - the selection stays where it is. } } /** The row that is picked scrolls into view. */ scrollPanel(index) { try { this.panelScroll.scroll_to_item(index); } catch { // The list is not drawn yet - it starts at the top anyway. } } /** What the panel draws. */ panelView() { const tab = this.panel.tab; const query = this.panelInputs[tab].value(); const state = panelState({ history: this.panel.history, favorites: this.favorites, tab, query }); const index = Math.min(this.panel.index, Math.max(0, state.hits.length - 1)); return { tab, state, query, index, input: this.panelInputs[tab], scroll: this.panelScroll, isFavorite: (text) => isFavorite(this.favorites, text), }; } /** The keys of the panel - on the panel itself, not on the composer's actions. */ panelKey(event, cx) { if (!this.panel) return; const key = String(event.key ?? "").toLowerCase(); const m = event.modifiers ?? {}; const view = this.panelView(); if (key === "escape") { this.panelCommand("escape", cx); } else if (key === "arrowdown" || key === "down") { this.panelCommand("down", cx); } else if (key === "arrowup" || key === "up") { this.panelCommand("up", cx); } else if (key === "tab") { this.panelCommand("tab", cx); } else if (key === "r" && m.control === true) { this.panelCommand("escape", cx); } else if (key === "enter") { this.panelPick(view.index, cx); } else if (key === "d" && m.control === true) { const hit = view.state.hits[view.index]; if (hit) this.toggleFavoriteText(hit.item.text, cx); } else { return; } cx.stop_propagation(); cx.notify(); } /** * A key of the panel: up, down, tab, escape. The same press can arrive twice * (as an action of the composer and as a key of the panel), so the second * delivery within 40 ms is dropped. */ panelCommand(command, cx) { if (!this.panel) return; const now = Date.now(); if (this.lastPanelCommand && this.lastPanelCommand.command === command && now - this.lastPanelCommand.at < 40) return; this.lastPanelCommand = { command, at: now }; if (command === "escape") this.closePanel(); else if (command === "tab") this.panelTab(otherTab(this.panel.tab), cx); else this.movePanel(command === "down" ? 1 : -1, this.panelView()); } movePanel(step, view) { this.panel.index = moveIndex(view.index, step, view.state.hits.length); this.scrollPanel(this.panel.index); } /** The other tab; what was searched for goes with the person. */ panelTab(tab, cx) { if (!this.panel || tab === this.panel.tab) return; const query = this.panelInputs[this.panel.tab].value(); this.panel.tab = tab; this.panel.index = 0; this.panelInputs[tab].set_value(query); this.panelInputs[tab].focus(); this.scrollPanel(0); cx.notify(); } /** * `replace` may or may not report a `change`: what the field says is read * back, and the draft (state and disk) follows it. */ syncFieldAfterReplace() { this.value = this.textarea.value(); this.saveDraftNow(); } /** The search is cleared. */ panelClear(cx) { if (!this.panel) return; this.panelInputs[this.panel.tab].set_value(""); this.panelInputs[this.panel.tab].focus(); this.panel.index = 0; cx.notify(); } /** A row was clicked: it is named by its key (the id of the entry). */ panelPickKey(key, cx) { if (!this.panel) return; const index = this.panelView().state.hits.findIndex((hit) => String(hit.item.id) === key); if (index >= 0) this.panelPick(index, cx); } /** * The row goes into the field at the place the caret was - nothing is sent. * The panel closes, the field gets the keyboard and the selection back, and * `replace` puts the text in as typing would. */ panelPick(index, cx) { if (!this.panel) return; const hit = this.panelView().state.hits[index]; if (!hit) return; this.closePanel(); this.textarea.replace(hit.item.text); this.syncFieldAfterReplace(); this.notice("Wstawiono w miejscu kursora — nic nie zostało wysłane."); cx.notify(); } /** A row was right-clicked: its text is a favourite, or no longer. */ panelToggleKey(key, cx) { if (!this.panel) return; const hit = this.panelView().state.hits.find((entry) => String(entry.item.id) === key); if (hit) this.toggleFavoriteText(hit.item.text, cx); } /** The star next to the field: the text of the field is a favourite, or no longer. */ toggleCurrentFavorite(cx) { if (this.value.trim() === "") { this.notice("Wpisz tekst, aby dodać go do ulubionych.", "error", cx); return; } this.toggleFavoriteText(this.value, cx); } toggleFavoriteText(text, cx) { this.favorites = toggleFavorite(this.favorites, text, Date.now()); try { storage.saveFavorites(this.store, this.favorites); } catch (err) { this.notice(`Nie udało się zapisać ulubionych: ${errorText(err)}`, "error"); } if (this.panel) this.panel.index = Math.min(this.panel.index, Math.max(0, this.panelView().state.hits.length - 1)); cx.notify(); } // --- the preview of an image ---------------------------------------------- openPreview(file, cx) { this.preview = { path: file.path, caption: `${file.name} · ${formatBytes(file.bytes) || "?"} · Esc zamyka` }; // The overlay is drawn on the next frame; it takes the keyboard then. cx.timer.after(30, () => { try { this.previewHandle.focus(); } catch { // Esc still reaches the composer's own handler. } }); cx.notify(); } closePreview(cx) { this.preview = null; cx.notify(); } /** The keyboard of the composer. */ key(event, cx) { if (this.preview && String(event.key).toLowerCase() === "escape") { this.closePreview(cx); cx.stop_propagation(); return; } const m = event.modifiers ?? {}; const handled = this.intent( { key: event.key, shift: m.shift === true, ctrl: m.control === true, alt: m.alt === true }, cx, ); // Escape is never left to the field; the other keys only when they were ours. if (handled || String(event.key).toLowerCase() === "escape") cx.stop_propagation(); } /** * The menu moves one row up or down. * * The arrows come as actions of the mod: the field binds them to the * movement of the cursor and eats them before they reach the element. The * cursor goes back to where the menu was opened, so the text does not move * under the person. */ /** * The up and down arrows. * * With the menu open they move the menu; without it they move the cursor * between the lines of the field - the field of this app version does not do * that by itself. */ arrow(step, cx) { if (!this.hasKeyboard) return; if (menuAction(this.hasKeyboard, this.menu, step < 0 ? "up" : "down") === "menu") { this.moveMenu(step, cx); return; } this.moveCaret(step); } /** The cursor goes one line up or down. */ moveCaret(step) { const caret = this.caret(); const moved = moveCaret(this.value, caret, step); if (moved === caret) return; this.textarea.set_selected_range({ start: moved, end: moved }); } moveMenu(step, cx) { if (menuAction(this.hasKeyboard, this.menu, step < 0 ? "up" : "down") !== "menu") return; const menu = this.menu; const count = (menu.items ?? []).length; menu.index = (menu.index + step + count) % count; this.restoreCaret(menu.caret); cx.notify(); } /** The picked row goes into the field - the keyboard way (Tab). */ acceptFromKey(cx) { if (menuAction(this.hasKeyboard, this.menu, "tab") !== "accept") return; this.accept(cx); } /** The caret goes back where it was - the menu moves, the text does not. */ restoreCaret(at) { if (!Number.isInteger(at)) return; try { this.textarea.set_selected_range({ start: at, end: at }); } catch { // The field does not answer - the caret stays where it is. } } // --- sending ------------------------------------------------------------- /** The message goes out, or it waits in the queue. */ 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); return; } const body = text.trim(); if (body === "") return; const over = overLimit(text); if (over > 0) { this.notice(`Limit ${LIMITS.messageChars} znaków · ${over} za dużo`, "error", cx); return; } const key = agentKey(agent); const attached = this.state.attachments[key] ?? []; const broken = attached.find((file) => file.state === "error"); 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 — 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 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. */ clearField(cx) { this.textarea.set_value(""); this.value = ""; this.enterText = null; this.closeMenu(); // A sent draft must not come back after a restart. this.scheduleDraftSave(cx); cx.notify(); } /** The message goes out now or waits in the queue - the agent's status decides. */ finish(agent, message, cx, mode = "auto") { const key = agentKey(agent); // "now" (Ctrl+Enter) skips the status check; "hold" (Alt+Enter) always // queues as held. Task 4 finalizes the queue semantics. const decision = mode === "now" ? { kind: "send" } : mode === "hold" ? { kind: "hold" } : decide(this.statusOf(agent)); // Not before the draft and the identity of the agent were checked - the // person's own "send now" (Ctrl+Enter) is the exception. const allowed = mode === "now" || canAutoSend(this.draftReady, key); // A message that is on the wire, or one that counts down, goes first: the // new one waits behind it in the queue instead of vanishing or jumping // the line (Ctrl+Enter is the person's own order and does jump). const busy = this.draining.has(key) || (mode !== "now" && (this.state.queue[key] ?? []).some((entry) => entry.state === "countdown")); if (decision.kind === "send" && allowed && !busy) { this.sendNow(agent, message, cx); return; } const held = decision.kind === "hold"; const item = { id: this.newId(), text: message, createdAt: Date.now(), state: held ? "held" : "queued", ...(held ? { reason: mode === "hold" ? "Wstrzymana przez Ciebie" : "Agent czeka na Ciebie" } : {}), }; this.state = reduce(this.state, { type: "queue", agent: key, item }); this.persistQueue(key); if (!held) { // A new message after a stop is not the stopped one: it waits for the // agent like any other. this.stopped.delete(key); // It waits because the agent is not ready: once it is, the message may // go (the gate counts a status that was not "working" too). if (decision.kind === "queue") { this.gates.set(key, { ...this.gateFor(key), sawWorking: true }); } } if (held) { this.notice( mode === "hold" ? "Wiadomość wstrzymana — czeka na „Wyślij teraz”." : "Agent czeka na Ciebie — wiadomość czeka na „Wyślij teraz”.", mode === "hold" ? undefined : "error", ); } else { this.notice("Wiadomość w kolejce — następna tura."); } cx.notify(); } /** The message goes to the terminal now. */ async sendNow(agent, message, cx) { const key = agentKey(agent); if (this.draining.has(key)) { this.notice("Ta wiadomość jest już w locie.", "error", cx); return; } this.draining.add(key); const id = this.newId(); // The entry goes to the disk before it goes on the wire: a crash in the // middle must not send the message a second time. this.state = reduce(this.state, { type: "queue", agent: key, item: { id, text: message, createdAt: Date.now() }, }); this.state = reduce(this.state, { type: "claim", agent: key, id }); if (!this.claimed(key, id)) { // The entry did not go on the wire - it must not be sent. this.draining.delete(key); return; } this.persistQueue(key); try { const result = await sendToTerminal({ terminal: agent.address, hc: this.sendHc }, message); if (result.ok) { this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" }); this.persistQueue(key); this.gates.set(key, closeGate(this.gateFor(key))); this.notice("Wysłano do terminala."); } else { this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "uncertain", reason: result.message, }); this.persistQueue(key); this.notice(result.message, "error"); } } finally { this.draining.delete(key); cx.notify(); } } /** Did the entry go on the wire? An entry that did not must not be sent. */ claimed(key, id) { const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id); return Boolean(item && item.state === "sending"); } /** * Once a second: the status of every agent is read, the stop flag is kept * honest, and the queue counts down when the state says so * (`shouldStartCountdown`) - not only when a change was seen, so a turn that * was too short for the poll does not leave a message waiting for ever. */ tickQueues(cx) { if (this.closed) return; for (const agent of liveAgents()) { const key = agentKey(agent); if (!key) continue; const status = this.statusOf(agent); const prev = this.prevStatus.get(key); this.prevStatus.set(key, status); // The flag is read before it is cleared: the change that ends the // stopped turn still counts as stopped. const stopped = this.stopped.has(key); if (stopped) { // The turn the composer stopped is over (shouldDrain without the // flag says so), or a new turn began after it: either way the flag // is used up. const over = shouldDrain(prev, status, false); const again = status === "working" && prev !== undefined && prev !== "working" && prev !== "blocked"; if (over || again) this.stopped.delete(key); } const queue = this.state.queue[key] ?? []; if (queue.length === 0) continue; const open = gatePasses(this.gateFor(key), status); if (canAutoSend(this.draftReady, key) && shouldStartCountdown({ status, queue, gateOpen: open, stopped })) { this.beginCountdown(agent, key, cx); } this.advanceCountdown(agent, key, status, cx); } } /** * The first queued message starts to count down: it goes out in a few * seconds unless the person cancels it. Only when the queue is known to * belong to this agent (`canAutoSend`). */ beginCountdown(agent, key, cx) { if (!canAutoSend(this.draftReady, key)) return; const first = (this.state.queue[key] ?? []).find((item) => item.state === "queued"); if (!first) return; const before = this.state; this.state = reduce(this.state, { type: "countdown_start", agent: key, id: first.id }); if (this.state === before) return; this.persistQueue(key); cx.notify(); } /** A second passes; at 0 the message goes through the usual drain. */ advanceCountdown(agent, key, status, cx) { const item = (this.state.queue[key] ?? []).find((entry) => entry.state === "countdown"); if (!item) return; if (status !== "idle" && status !== "done") { // The agent went back to work - the message waits for the next turn. this.state = reduce(this.state, { type: "countdown_reset", agent: key, id: item.id }); this.gates.set(key, closeGate(this.gateFor(key))); this.persistQueue(key); cx.notify(); return; } if (!canAutoSend(this.draftReady, key)) return; if (item.left > 0) { this.state = reduce(this.state, { type: "countdown_tick", agent: key, id: item.id }); cx.notify(); } const now = (this.state.queue[key] ?? []).find((entry) => entry.id === item.id); if (now && now.state === "countdown" && !(now.left > 0)) this.drainQueue(agent, cx); } /** The person does not want the message that counts down - it is held. */ cancelCountdown(agent, id, cx) { const key = agentKey(agent); this.state = reduce(this.state, { type: "countdown_cancel", agent: key, id }); this.gates.set(key, closeGate(this.gateFor(key))); this.persistQueue(key); cx.notify(); } /** * The queue that came back from the disk is followed again. * * Entries that are still `queued` here passed the identity check (the others * were held). An idle agent starts the countdown at once, a working one * after its turn. */ resumeRestored(agent, key, cx) { if (!(this.state.queue[key] ?? []).some((item) => item.state === "queued")) return; const status = this.statusOf(agent); this.prevStatus.set(key, status); if (status === "idle" || status === "done") { // After a restart no turn was seen - the restored queue is trusted, so // the gate steps aside for this one send. this.gates.set(key, openGate(this.gateFor(key))); this.beginCountdown(agent, key, cx); } } /** * The queue of an agent goes out when the agent is ready and the gate is * open - one message after another, while the gate is open. */ async drainQueue(agent, cx) { const key = agentKey(agent); // The queue came back from the disk, but whose is it? Not before the check. if (!canAutoSend(this.draftReady, key)) return; // One drain at a time per agent: the state it works on is immutable, so // two of them would send the same message twice. if (this.draining.has(key)) return; this.draining.add(key); let claimed = ""; let sent = false; try { const result = await drainAll( { agent: key, terminal: agent.address, hc: this.sendHc, status: () => this.statusOf(agent), // One message per turn: after the first send the gate is shut. gate: () => !sent && gatePasses(this.gateFor(key), this.statusOf(agent)), onState: (next) => { const items = next.queue?.[key] ?? []; const sending = items.find((item) => item.state === "sending"); if (sending) { // The entry is on the wire: the state goes to the disk at once, // so a crash now leaves "sending" behind and the restart turns // it into "uncertain" instead of sending the message again. const mine = (this.state.queue[key] ?? []).find((item) => item.id === sending.id); if (mine && mine.state === "sending") return; claimed = sending.id; this.state = reduce(this.state, { type: "claim", agent: key, id: sending.id }); this.persistQueue(key); return; } // The entry's fate is known: it left the queue (sent) or it // became uncertain (the send failed). if (!claimed) return; const left = !items.some((item) => item.id === claimed); const failed = items.find((item) => item.id === claimed && item.state === "uncertain"); if (left) { this.state = reduce(this.state, { type: "settle", agent: key, id: claimed, outcome: "sent" }); this.persistQueue(key); sent = true; } else if (failed) { this.state = reduce(this.state, { type: "settle", agent: key, id: claimed, outcome: "uncertain", ...(failed.reason ? { reason: failed.reason } : {}), }); this.persistQueue(key); } }, }, this.state, ); if (result.sent > 0) { this.gates.set(key, closeGate(this.gateFor(key))); this.notice("Wysłano do terminala."); } else if (claimed && !sent) { this.notice("Wiadomość nie poszła do terminala.", "error"); } } catch (err) { // A hook that fails after the message went out must not send it again: // the entry left the queue, so it is sent. const outcome = claimed ? failedHookOutcome(this.state.queue[key], claimed) : "uncertain"; if (outcome === "sent") { this.notice("Wysłano do terminala."); } else { if (claimed) { this.state = reduce(this.state, { type: "settle", agent: key, id: claimed, outcome: "uncertain", reason: errorText(err), }); this.persistQueue(key); } this.notice(errorText(err), "error"); } } finally { this.draining.delete(key); cx.notify(); } } /** The queued message goes out now, whatever the agent is doing. */ async sendQueued(agent, id, cx) { const key = agentKey(agent); if (this.draining.has(key)) { this.notice("Ta wiadomość jest już w locie.", "error", cx); return; } // Only an entry that waits (or that the person chose to try again) goes. const waiting = (this.state.queue[key] ?? []).find((entry) => entry.id === id); if (!waiting || !["held", "uncertain", "queued"].includes(waiting.state)) return; // A held entry goes back to the queue first, and the turn gate of the // agent steps aside - this is a send outside a turn. this.state = reduce(this.state, { type: "requeue", agent: key, id }); this.gates.set(key, openGate(this.gateFor(key))); const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id); if (!item) { // Nothing to send - the gate closes again right away. this.gates.set(key, closeGate(this.gateFor(key))); return; } this.draining.add(key); this.state = reduce(this.state, { type: "claim", agent: key, id }); if (!this.claimed(key, id)) { // The entry did not go on the wire - it must not be sent. this.draining.delete(key); this.gates.set(key, closeGate(this.gateFor(key))); this.notice("Wiadomość nie poszła na drogę — nie została wysłana.", "error", cx); return; } this.persistQueue(key); try { const result = await sendToTerminal({ terminal: agent.address, hc: this.sendHc }, item.text); if (result.ok) { this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" }); this.persistQueue(key); // The gate closes again: the next message waits for the next turn. this.gates.set(key, closeGate(this.gateFor(key))); this.notice("Wysłano do terminala."); } else { this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "uncertain", reason: result.message, }); this.persistQueue(key); // The send outside a turn is over - the gate closes again. this.gates.set(key, closeGate(this.gateFor(key))); this.notice(result.message, "error"); } } finally { this.draining.delete(key); cx.notify(); } } /** "Edytuj": the message comes off the queue and goes into the field, at the caret. */ editQueued(agent, id, cx) { const key = agentKey(agent); const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id); if (!item || item.state === "sending") return; this.textarea.focus(); this.textarea.replace(item.text); this.syncFieldAfterReplace(); this.discard(agent, id, cx); this.notice("Wiadomość wróciła do edytora — nic nie zostało wysłane.", undefined, cx); } /** The queued message is not wanted any more. */ discard(agent, id, cx) { const key = agentKey(agent); this.state = reduce(this.state, { type: "discard", agent: key, id }); this.persistQueue(key); // The notice about the queue is stale now. if (!(this.state.queue[key] ?? []).length) { this.state = reduce(this.state, { type: "notice", notice: null }); } cx.notify(); } /** * 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)) { reason = resultError(res, payload); } else { remote = landedPath(payload, res.stdout); if (!remote) reason = "Agent nie podał ścieżki pliku."; } } catch (err) { 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 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) { // The person may be typing: the caret stays where it was in the text, // pushed on by what went in before it. const caret = this.caret(); const result = insertMentions(this.value, [token]); const inserted = result.value.length - this.value.length; const at = result.caret - inserted; this.textarea.set_value(result.value); this.value = result.value; this.restoreCaret(caret >= at ? caret + inserted : caret); 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. 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); 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) => { let bytes = file.bytes; if (!Number.isFinite(bytes)) { const measured = (await this.measure([file.path])).files[0]; bytes = measured && Number.isFinite(measured.bytes) ? measured.bytes : undefined; } const check = bytes === undefined ? null : validate({ ...file, bytes }); 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; } this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { bytes } }); await this.putAttachment(agent, { ...file, bytes }, cx); }); } /** * The stop key of the agent's program. * * The queue is held first (nothing goes out on its own to an agent the * person just stopped), and the turn that ends because of the stop does not * start it again. */ interrupt(agent, cx) { const key = agentKey(agent); const status = this.statusOf(agent); const flagged = status === "working" || status === "blocked"; if (flagged) this.stopped.add(key); this.state = reduce(this.state, { type: "hold_all", agent: key }); this.gates.set(key, closeGate(this.gateFor(key))); this.persistQueue(key); this.notice("Przerwano agenta. Kolejka wstrzymana — nic nie wyśle się samo."); cx.notify(); cx.spawn(async (cx) => { try { const res = await hc(["interrupt", agent.address, "--json"]); const payload = parseJson(res.stdout); if (res.code !== 0 || (payload && payload.error)) { if (flagged) this.stopped.delete(key); this.notice(`Nie udało się zatrzymać agenta: ${resultError(res, payload)}`, "error"); } } catch (err) { if (flagged) this.stopped.delete(key); this.notice(`Nie udało się zatrzymać agenta: ${errorText(err)}`, "error"); } cx.notify(); }); } /** The shortcut of the agent's own program - the keyboard here is not the terminal's. */ passKey(agent, keys, cx) { cx.spawn(async (cx) => { try { const res = await hc(["keys", agent.address, keys, "--json"]); if (!hcOk(res)) { this.notice(`Klawisz nie dotarł do agenta: ${resultError(res, parseJson(res.stdout))}`, "error"); } } catch { // The core is gone - the key goes nowhere. } cx.notify(); }); } // --- the suggestions ----------------------------------------------------- /** The caret sits in a `/` or `@` token - the menu looks at it. */ updateSuggestions(agent, cx) { const token = detectTrigger(this.value, this.caret()); if (!token || !agent) { this.closeMenu(); return; } this.scheduleLoad(agent, token, cx); } /** The menu is closed and the pending load with it. */ closeMenu() { if (this.debounce) { this.debounce.cancel(); this.debounce = null; } if (!this.menu) return; this.menu = null; } /** The catalog is read after a moment - the person is still typing. */ scheduleLoad(agent, token, cx) { if (this.debounce) { this.debounce.cancel(); this.debounce = null; } this.debounce = cx.timer.after(catalog.DEBOUNCE_MS, (cx) => { this.debounce = null; this.loadSuggestions(agent, token, cx); }); } /** The catalog of the suggestions, read from the workspace. */ async loadSuggestions(agent, token, cx) { const text = this.value; const cwd = paneContext(livePanes(), agent.address).cwd ?? ""; let failed = false; const onReadError = () => { failed = true; this.scheduleRetry(agent, token, cx); }; let items = []; try { if (token.trigger === "/") { const raw = await catalog.commands(cwd, exec, { agent: agentName(agent), snippets: [], onReadError, }); const usage = storage.loadUsage(this.store); const withUses = raw.map((item) => ({ ...item, uses: usage[item.key] ?? 0 })); items = token.needle === "" ? merge(groupItems(withUses)) : rank(withUses, token.needle, { atLineStart: startsLine(text, token.start) }); } else { items = await catalog.files(cwd, exec, { needle: token.needle, onReadError }); } } catch (err) { failed = true; this.scheduleRetry(agent, token, cx); } // The field moved on while the catalog was read - the next change asks // again. if (this.value !== text) return; this.menu = { ...token, caret: this.caret(), items, index: 0, error: failed }; if (!failed) this.retryAttempt = 0; cx.notify(); } /** A read that failed is tried again: 2 s, 5 s, 15 s, 30 s. */ scheduleRetry(agent, token, cx) { if (this.retry) { this.retry.cancel(); this.retry = null; } const delay = catalog.retryDelay(this.retryAttempt); this.retryAttempt += 1; this.retry = cx.timer.after(delay, (cx) => { this.retry = null; this.loadSuggestions(agent, token, cx); }); } /** The picked suggestion goes into the field, at the place of the trigger. */ accept(cx, text = this.value, caret = this.caret()) { const menu = this.menu; if (!menu) return; const item = (menu.items ?? [])[menu.index]; if (!item) return; const result = applySuggestion(text, caret, menu, item.insert ?? item.key); this.textarea.set_value(result.value); this.value = result.value; this.enterText = null; this.menu = null; this.restoreCaret(result.caret); this.countUse(item.key); cx.notify(); } /** * The command was used - the ranking breaks its ties with that number. * * The counters live in the shared store, so they are the same in every pane * and they outlive the app. */ countUse(key) { const name = String(key ?? "").replace(/^\//, ""); if (!name) return; try { const usage = storage.loadUsage(this.store); usage[name] = (usage[name] ?? 0) + 1; storage.saveUsage(this.store, usage); } catch { // A counter that cannot be written is not worth a notice. } } // --- the attachments ----------------------------------------------------- /** Files were dropped on the composer: measured in one call, then the pipeline. */ drop(event, 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); // A path that is not there any more is said, not skipped in silence. if (measured.missing.length) { this.notice(`Nie znaleziono pliku: ${measured.missing.map(nameOf).join(", ")}`, "error", 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) }; } } /** * 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. 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 {{path:string, bytes:number|null}[]} entries * @param {"drop"|"paste"|"picker"} origin */ addFiles(entries, origin, cx) { const agent = this.target(); if (!agent) { this.notice("Wybierz agenta — nie ma do kogo dodać pliku.", "error", cx); return; } const key = agentKey(agent); 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 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, }; }); // The whole batch may be 100 files at most; every file is judged on its // own - a file that is too big does not take the good ones with it. if ((this.state.attachments[key] ?? []).length + files.length > LIMITS.filesPerAction) { this.notice(`Za dużo plików (limit ${LIMITS.filesPerAction})`, "error", cx); return; } const known = []; let problem = ""; for (const file of files) { let error = ""; if (file.bytes === undefined) { error = SIZE_ERROR; } else { const check = validate(file); if (!check.ok) error = check.reason; } if (error) problem = error; else known.push(file); this.state = reduce(this.state, { type: "attach", agent: key, file: error ? { ...file, state: "error", error } : { ...file, state: "adding" }, }); } if (problem) this.notice(problem, "error"); this.scheduleDraftSave(cx); cx.notify(); cx.spawn(async (cx) => { for (const file of known) 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 if (result.kind === "dirs") { this.notice(DIR_NOTICE, "error"); } else { if (result.dirs.length) this.notice(DIR_NOTICE, "error"); this.addFiles(result.files, "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 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 { 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); const file = (this.state.attachments[key] ?? []).find((entry) => entry.id === id); if (!file) return; this.state = reduce(this.state, { type: "removeAttachment", agent: key, id }); const text = file.remotePath ? removeMention(this.value, file.remotePath) : this.value; if (text !== this.value) { this.textarea.set_value(text); this.value = text; } this.scheduleDraftSave(cx); cx.notify(); } // --- the state on the disk ----------------------------------------------- /** * `hc` for the sends: runs the call and, when it was a `send` that `hc` * accepted (exit code 0 and no "error" in the JSON - `hcOk`), writes the * message into the history. A history that cannot be written does not * change the result of the send. */ async runSend(args) { const res = await hc(args); if (args[0] === "send" && hcOk(res)) this.recordSent(String(args[1]), String(args[2] ?? "")); return res; } /** The history gets the message that went to the terminal. */ recordSent(address, text) { try { const agent = liveAgents().find((entry) => entry.address === address); const entry = { id: this.newId(), text, sentAt: Date.now(), agent: address, agentName: agent ? agentName(agent) : "", space: agent?.space ?? "", spaceName: agent?.space_name ?? "", tabName: agent?.tab_name ?? "", }; storage.saveHistory(this.store, record(storage.loadHistory(this.store), entry)); } catch (err) { this.notice(`Nie udało się zapisać historii: ${errorText(err)}`, "error"); } } /** The queue of an agent goes to the disk at once - a crash must not send a message twice. */ persistQueue(key) { try { storage.saveQueue(this.store, key, this.state.queue[key] ?? []); } catch (err) { this.notice(`Nie udało się zapisać kolejki: ${errorText(err)}`, "error"); } } /** * What the composer says under the card. * * The notice is part of the state, so the composer has to be redrawn for it * to show up - the caller says when that happens. */ notice(text, level = "info", cx = null) { this.state = reduce(this.state, { type: "notice", notice: { text, level } }); if (level === "error") { notify({ title: "Composer", body: text, level: "error" }); } cx?.notify(); } /** An id of its own - the queue and the attachments count on it. */ newId() { this.counter += 1; return `${Date.now().toString(36)}-${this.counter.toString(36)}`; } // --- the view ------------------------------------------------------------ render(cx) { const t = theme(); const agent = this.target(); const key = agent ? agentKey(agent) : ""; const status = agent ? this.statusOf(agent) : "idle"; return v_flex() .id("ovis-composer") .relative() .on_size_change((size) => { this.blockHeight = size.height; }) .track_focus(this.handle) .key_context(CONTEXT) .on_key_down((event, cx) => this.key(event, cx)) // Actions that cx.bind_keys dispatches reach the element tree, not // nextCommand() (that one only serves keys.json). The field sits inside // this root, so the actions arrive here. .on_action("ovis-composer.up", (e, cx) => this.runAction("up", cx)) .on_action("ovis-composer.down", (e, cx) => this.runAction("down", cx)) .on_action("ovis-composer.accept", (e, cx) => this.runAction("accept", cx)) .on_action("ovis-composer.panel", (e, cx) => this.runAction("panel", cx)) .on_action("ovis-composer.send_now", (e, cx) => this.runAction("send_now", cx)) .on_action("ovis-composer.hold", (e, cx) => this.runAction("hold", cx)) .on_action("ovis-composer.escape", (e, cx) => this.runAction("escape", cx)) .size_full() .p(8) .gap(6) .bg(t.canvas) .text_color(t.foreground) .children( [ this.renderMenu(t), this.renderQueue(t, agent, key), this.renderImageConfirm(t), this.renderNotice(t), this.renderCard(t, agent, key, status), this.renderContext(t, agent), this.renderPanelLayer(t), this.renderPreviewLayer(t), ].filter(Boolean), ); } /** The History | Favourites panel: it covers the composer while it is open. */ renderPanelLayer(t) { if (!this.panel) return null; return div() .id("composer-panel-layer") .absolute() .inset_0() .p(6) .bg(t.canvas) .child( renderPanel(t, this.panelView(), { key: (event, cx) => this.panelKey(event, cx), tab: (tab, cx) => this.panelTab(tab, cx), pick: (key, cx) => this.panelPickKey(key, cx), toggle: (key, cx) => this.panelToggleKey(key, cx), clear: (cx) => this.panelClear(cx), }), ); } /** The preview of an image, over everything. */ renderPreviewLayer(t) { if (!this.preview) return null; return renderPreview(t, this.preview, this.previewHandle, { close: (cx) => this.closePreview(cx) }); } /** The menu of the suggestions, above the card. */ renderMenu(t) { const menu = this.menu; if (!menu) return null; const all = menu.items ?? []; const items = all.slice(0, MENU_LIMIT); const empty = menu.error ? catalog.READ_ERROR_MESSAGE : menu.trigger === "@" ? catalog.NO_FILE_MATCH_MESSAGE : catalog.NO_MATCH_MESSAGE; return v_flex() .id("composer-menu") .gap(1) .p(6) .rounded(10) .border(1) .border_color(t.border) .bg(t.popover) // The menu takes the same room whether it has one row or twenty - the // card under it does not move while the person types. .child( v_flex() .id("composer-menu-list") .h(MENU_HEIGHT) .overflow_y_scroll() .gap(1) .children( [ menu.error || all.length === 0 ? div().px(6).py(5).text_size(11.5).text_color(menu.error ? t.blocked : t.dim).child(empty) : null, ...items.map((item, index) => this.renderMenuItem(t, item, index, menu)), all.length > items.length ? div().px(6).py(3).text_size(11).text_color(t.dim).child(`…i jeszcze ${all.length - items.length}`) : null, ].filter(Boolean), ), ); } /** One row of the menu: the name of the item and what it says about itself. */ renderMenuItem(t, item, index, menu) { const on = index === menu.index; const items = menu.items ?? []; const group = typeof item.group === "string" ? item.group : ""; const before = index > 0 ? items[index - 1] : null; // The group is named once - at its first item. const named = group !== "" && (!before || before.group !== group); return div() .id(`menu-${index}`) .px(6) .py(3) .rounded(6) .cursor_pointer() .when(on, (el) => el.bg(t.selected)) .hover((s) => s.bg(t.hover)) .on_click((event, cx) => this.acceptIndex(index, cx)) .children( [ named ? div().text_size(10).text_color(t.dim).child(group) : null, h_flex() .gap(8) .items_center() .child(div().flex_none().text_size(12.5).text_color(t.foreground).child(item.key)) .when( item.desc, (el) => el.child(div().flex_1().min_w(0).truncate().text_size(11).text_color(t.dim).child(item.desc)), ), ].filter(Boolean), ); } /** The picked row goes into the field. */ acceptIndex(index, cx) { if (!this.menu) return; this.menu.index = index; this.accept(cx); } /** The queue of the agent, above the card. */ renderQueue(t, agent, key) { const items = this.state.queue[key] ?? []; if (!items.length) return null; return v_flex() .id("composer-queue") .gap(4) .children(items.map((item) => this.renderQueueRow(t, agent, item))); } /** One row of the queue. */ renderQueueRow(t, agent, item) { const color = item.state === "uncertain" ? (t.unknown ?? t.dim) : item.state === "held" ? t.blocked : t.accent; return h_flex() .id(`queue-${item.id}`) .gap(8) .items_center() .px(8) .py(6) .rounded(8) .bg(t.surface) .child(div().size(7).rounded(4).flex_none().bg(color)) .child(div().flex_1().min_w(0).truncate().text_size(12).text_color(t.foreground).child(queueLabel(item))) .when(item.reason, (el) => el.child(div().text_size(11).text_color(t.dim).truncate().child(item.reason))) .child(this.renderQueueButtons(t, agent, item)); } /** The buttons of a queue row. */ renderQueueButtons(t, agent, item) { if (item.state === "sending") { return div().text_size(11).text_color(t.dim).child("wysyłanie…"); } if (item.state === "countdown") { return h_flex() .gap(6) .flex_none() .child( this.renderButton(t, "Anuluj", `cancel-${item.id}`, (event, cx) => this.cancelCountdown(agent, item.id, cx), ), ); } const buttons = []; // An uncertain entry may have reached the agent: it is never sent on its // own, only when the person says "Ponów" (the same road as "Wyślij teraz"). buttons.push( this.renderButton( t, item.state === "uncertain" ? "Ponów" : "Wyślij teraz", `send-${item.id}`, (event, cx) => this.sendQueued(agent, item.id, cx), ), ); buttons.push( this.renderButton(t, "Edytuj", `edit-${item.id}`, (event, cx) => this.editQueued(agent, item.id, cx)), ); buttons.push( this.renderButton(t, "Usuń", `drop-${item.id}`, (event, cx) => this.discard(agent, item.id, cx)), ); return h_flex().gap(6).flex_none().children(buttons); } /** A small button of the composer. */ renderButton(t, text, id, action) { return div() .id(id) .px(8) .h(22) .rounded(6) .flex() .items_center() .text_size(11.5) .text_color(t.muted) .bg(t.chrome) .cursor_pointer() .hover((s) => s.bg(t.hover).text_color(t.foreground)) .on_click(action) .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(this.value, cx, ask.mode, true), ), ), ); } /** What the composer says under the card. */ renderNotice(t) { const notice = this.state.notice; if (!notice) return null; const error = notice.level === "error"; return div() .id("composer-notice") .px(10) .py(6) .rounded(8) .bg(error ? t.blocked + "26" : t.chrome) .text_size(11.5) .text_color(error ? t.blocked : t.dim) .child(notice.text); } /** The card: the files, the field and the row of controls. */ renderCard(t, agent, key, status) { const files = this.state.attachments[key] ?? []; const active = Boolean(agent); const over = overLimit(this.value); const stop = !this.value.trim() && status === "working"; return v_flex() .id("composer-card") .gap(8) .p(10) .rounded(12) .border(1) .border_color(active ? t.border : t.input) .bg(t.raised) .on_drop((event, cx) => this.drop(event, cx)) .children( [ files.length ? this.renderFiles(t, agent) : null, // The focus is on a terminal that is not an agent: the field is // silent and says why; the draft stays where it is. active ? Textarea.new(this.textarea) .w_full() .px(10) .py(8) .rounded(8) .bg(t.background) .text_color(t.foreground) .text_size(13) : div() .id("composer-inactive") .w_full() .px(10) .py(8) .rounded(8) .bg(t.background) .text_size(13) .text_color(t.dim) .child("Ten terminal nie jest agentem. Wybierz agenta z listy, aby pisać."), h_flex() .gap(8) .items_center() .child(this.renderPlus(t, agent)) .child( this.renderIcon(t, "composer-history", "🕘", false, active, (event, cx) => { this.openPanel("history"); cx.notify(); }), ) .child( this.renderIcon( t, "composer-star", isFavorite(this.favorites, this.value) ? "★" : "☆", isFavorite(this.favorites, this.value), active, (event, cx) => this.toggleCurrentFavorite(cx), ), ) .child(div().flex_1()) .child(this.renderChip(t, agent, status, files.length)) .child(stop ? this.renderStop(t, agent) : this.renderSend(t, agent, over)), ].filter(Boolean), ); } /** A round icon button next to the field (history, star). */ renderIcon(t, id, glyph, lit, enabled, action) { return div() .id(id) .size(28) .rounded(999) .flex_none() .flex() .items_center() .justify_center() .bg(t.chrome) .text_size(14) .text_color(lit ? t.working : enabled ? t.muted : t.dim) .cursor_pointer() .hover((s) => s.bg(t.hover).text_color(lit ? t.working : t.foreground)) .on_click((event, cx) => { if (enabled) action(event, cx); }) .child(glyph); } /** 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); const files = this.state.attachments[key] ?? []; return h_flex() .id("composer-files") .gap(6) .flex_wrap() .children(files.map((file) => this.renderTile(t, agent, file))); } /** One tile: the thumbnail (or the extension), the name, the size or the reason, the buttons. */ renderTile(t, agent, file) { const error = file.state === "error"; const adding = file.state === "adding"; const extension = (file.name.split(".").pop() || "").slice(0, 4); const thumb = file.kind === "image" ? div() .id(`file-thumb-${file.id}`) .size(36) .flex_none() .rounded(5) .overflow_hidden() .cursor_pointer() .when(adding, (el) => el.opacity(0.35)) .on_click((event, cx) => this.openPreview(file, cx)) .child(image(file.path).size(36)) : div() .size(36) .flex_none() .rounded(5) .bg(t.hover) .flex() .items_center() .justify_center() .text_size(10) .text_color(t.dim) .child(extension); return h_flex() .id(`file-${file.id}`) .gap(7) .h(44) .px(4) .items_center() .rounded(8) .border(1) .border_color(error ? t.blocked : t.border) .bg(t.chrome) .child(thumb) .child( v_flex() .min_w(0) .max_w(190) .child(div().text_size(12).text_color(t.foreground).truncate().child(file.name)) .child( div() .text_size(11) .text_color(error ? t.blocked : t.dim) .truncate() .child(error ? file.error ?? "" : adding ? "dodawanie…" : formatBytes(file.bytes)), ), ) .when(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}`) .px(4) .text_size(12) .text_color(t.dim) .cursor_pointer() .hover((s) => s.text_color(t.foreground)) .on_click((event, cx) => this.removeFile(agent, file.id, cx)) .child("✕"), ); } /** The chip of the agent: its program and what it is doing. */ renderChip(t, agent, status, fileCount = 0) { if (!agent) { return div() .px(8) .h(24) .rounded(12) .bg(t.chrome) .flex() .items_center() .text_size(11.5) .text_color(t.dim) .child("brak agenta"); } const name = agent.tab_name || agent.program?.name || agentName(agent); const color = t[status] ?? t.dim; return h_flex() .px(8) .h(24) .rounded(12) .gap(6) .items_center() .bg(t.chrome) .child(div().size(7).rounded(4).flex_none().bg(color)) .child(div().text_size(11.5).text_color(t.foreground).child(name)) .child(div().text_size(11).text_color(color).child(statusText(status))) .when(fileCount > 0, (el) => el.child(div().text_size(11).text_color(t.dim).child(`📎 ${fileCount}`))); } /** The button that sends the message. */ renderSend(t, agent, over) { const disabled = !agent || over > 0; return div() .id("composer-send") .size(32) .rounded(999) .bg(disabled ? t.chrome : t.solid) .flex() .items_center() .justify_center() .cursor_pointer() .when(!disabled, (el) => el.hover((s) => s.opacity(0.88))) .on_click((event, cx) => { if (!disabled) this.submit(this.value, cx); }) .child( div() .text_size(13) .font_semibold() .text_color(disabled ? t.dim : t.solid_foreground) .child("↵"), ); } /** The button that stops the agent. */ renderStop(t, agent) { return div() .id("composer-stop") .size(32) .rounded(999) .bg(t.foreground) .flex() .items_center() .justify_center() .cursor_pointer() .hover((s) => s.opacity(0.85)) .on_click((event, cx) => this.interrupt(agent, cx)) .child(div().size(10).rounded(2).bg(t.background)); } /** The strip under the card: where the agent works and how long the message is. */ renderContext(t, agent) { const context = agent ? paneContext(livePanes(), agent.address) : { cwd: null, branch: null }; const over = overLimit(this.value); return h_flex() .id("composer-context") .gap(10) .items_center() .px(2) .text_size(11) .text_color(t.dim) .child( div() .truncate() .child( [agent?.space_name, context.cwd ? shortPath(context.cwd) : "", context.branch ? `⑂ ${context.branch}` : ""] .filter(Boolean) .join(" · "), ), ) .child(div().flex_1()) .child( div() .flex_none() .text_color(over > 0 ? t.blocked : t.dim) .child( over > 0 ? `Limit ${LIMITS.messageChars} znaków · ${over} za dużo` : `${this.value.length} / ${LIMITS.messageChars}`, ), ); } } // --- helpers ---------------------------------------------------------------- /** The name of a file out of its path. */ function nameOf(path) { const parts = String(path ?? "").split(/[\\/]/); return parts[parts.length - 1] || String(path ?? ""); } /** The text of an error - an exception, a string or the error of a payload. */ function errorText(value) { if (value === null || value === undefined) return ""; if (typeof value === "string") return value; if (typeof value.message === "string" && value.message) return value.message; if (typeof value.kind === "string" && value.kind) return value.kind; return String(value); } /** The text of a failed `hc` call - its stderr or the error of the payload. */ function resultError(res, payload) { const stderr = String(res?.stderr ?? "").trim(); if (stderr) return stderr; if (payload?.error) return errorText(payload.error); return `hc zakończone kodem ${res?.code ?? 0}`; } /** The path the file got on the agent's machine. */ function landedPath(payload, stdout) { if (payload) { for (const key of ["path", "landed", "file", "target", "destination", "dst", "remote"]) { if (typeof payload[key] === "string" && payload[key].trim() !== "") return payload[key].trim(); } } const lines = String(stdout ?? "") .trim() .split(/\r?\n/) .filter(Boolean); return lines.length ? lines[lines.length - 1].trim() : ""; }