Files
herdrMario/mod/ovis-composer/main.js
T
FactorandClaude Sonnet 5.5 e7deca480a fix: handle composer key actions with on_action on the root
bind_keys actions dispatch through the element tree; nextCommand only
serves keys.json. Register on_action for all seven composer actions.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-19 11:16:16 +01:00

1646 lines
53 KiB
JavaScript

// 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 } from "gpui-kit";
import { v_flex, h_flex, TextareaState, Textarea } from "gpui-base";
import {
agents as liveAgents,
panes as livePanes,
focused as liveFocused,
theme,
exec,
hc,
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, 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 * as storage from "./storage.js";
import {
agentKey,
agentName,
agentStatus,
applySuggestion,
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…";
/** 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 });
// Per agent: the turn gate, whether a drain is in flight, whether the
// core is already waiting for the agent, and whether the queue of that
// agent was read from the disk.
this.gates = new Map();
this.draining = new Set();
this.waiting = new Set();
this.restored = 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;
// 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, 6);
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));
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 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 "<mod>.<command>" 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.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);
});
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.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;
// What the person typed while the identity was read is not
// overwritten.
if (stored && untouched) {
this.state = reduce(this.state, { type: "restore_draft", agent: key, draft: stored, identity });
this.persistQueue(key);
if (here) this.showDraft(key);
}
} catch {
// The draft stays on the disk; the next switch to this agent tries again.
this.draftLoading.delete(key);
return;
}
this.draftLoading.delete(key);
this.draftReady.add(key);
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;
// 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.panelOpen === true,
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 };
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);
}
/** Task 7: the history panel. Nothing to open yet. */
openPanel() {}
/** Task 7: the history panel. Nothing to close yet. */
closePanel() {}
/** The keyboard of the composer. */
key(event, cx) {
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") {
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 — usuń go albo wyślij go jeszcze raz.`, "error", cx);
return;
}
const files = attached.filter((file) => file.state === "ready");
// 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 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));
// A message that is already on the wire: the new one waits in the queue
// instead of vanishing.
if (decision.kind === "send" && !this.draining.has(key)) {
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) {
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.");
this.watch(agent, cx);
}
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 }, 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);
this.watchAgain(agent, cx);
cx.notify();
}
}
/**
* The queue is watched again.
*
* A message that waited for a send to finish would sit in the queue for
* ever: the watch that was waiting for the agent has already returned. The
* composer starts a new one - but only when the agent is working, so an idle
* agent does not spin the wait in a loop.
*/
watchAgain(agent, cx) {
const key = agentKey(agent);
const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued");
if (!waiting) return;
if (this.statusOf(agent) !== "working") return;
this.watch(agent, cx);
}
/** 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");
}
/** The core tells us when the agent stops working - then the queue may go out. */
watch(agent, cx) {
const key = agentKey(agent);
if (this.waiting.has(key)) return;
this.waiting.add(key);
cx.spawn(async (cx) => {
try {
const res = await hc(["wait", agent.address, "--json"]);
if (!hcOk(res)) {
// The core did not wait for anything - the queue stays where it is.
return;
}
} catch {
// The core is gone - the queue stays where it is.
return;
} finally {
this.waiting.delete(key);
}
await this.drainQueue(agent, 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);
// One drain at a time per agent: the state it works on is immutable, so
// two of them would send the same message twice. The queue is watched
// anyway - the drain that is in flight will not empty it.
if (this.draining.has(key)) {
this.watchAgain(agent, cx);
return;
}
this.draining.add(key);
let claimed = "";
let sent = false;
try {
const result = await drainAll(
{
agent: key,
terminal: agent.address,
hc,
status: () => this.statusOf(agent),
gate: () => 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);
// The agent may have gone back to work with the queue not empty - the
// queue is watched again, so it empties itself.
const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued");
if (waiting && this.statusOf(agent) === "working") this.watch(agent, cx);
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;
}
// 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 }, 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);
this.watchAgain(agent, cx);
cx.notify();
}
}
/** 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; the path it got is the one the agent sees. */
async putFile(agent, file) {
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 "";
}
return landedPath(payload, res.stdout);
} catch (err) {
this.putFailed(agent, file, errorText(err));
return "";
}
}
/** The file did not make it to the agent: the tile stays, with the reason. */
putFailed(agent, file, reason) {
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 },
});
}
/** The stop key of the agent's program. */
interrupt(agent, cx) {
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)) {
this.notice(`Nie udało się zatrzymać agenta: ${resultError(res, payload)}`, "error");
}
} catch (err) {
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. */
drop(event, cx) {
const agent = this.target();
if (!agent) return;
const paths = Array.isArray(event.paths) ? event.paths : [];
if (!paths.length) return;
cx.spawn(async (cx) => {
const files = [];
for (const path of paths) {
files.push({ id: this.newId(), name: nameOf(path), path, bytes: await sizeOf(path) });
}
const check = validateMany(files);
if (!check.ok) {
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 });
}
// 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;
this.scheduleDraftSave(cx);
cx.notify();
});
}
/** 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 = removeMention(this.value, file.path);
if (text !== this.value) {
this.textarea.set_value(text);
this.value = text;
}
this.scheduleDraftSave(cx);
cx.notify();
}
// --- the state on the disk -----------------------------------------------
/** 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")
.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.renderNotice(t),
this.renderCard(t, agent, key, status),
this.renderContext(t, agent),
].filter(Boolean),
);
}
/** 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…");
}
const buttons = [];
// An uncertain entry may have reached the agent - it is not sent again.
if (item.state !== "uncertain") {
buttons.push(
this.renderButton(t, "Wyślij teraz", `send-${item.id}`, (event, cx) =>
this.sendQueued(agent, item.id, cx),
),
);
}
buttons.push(
this.renderButton(t, "Odrzuć", `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);
}
/** 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,
Textarea.new(this.textarea)
.w_full()
.px(10)
.py(8)
.rounded(8)
.bg(t.background)
.text_color(active ? t.foreground : t.dim)
.text_size(13),
h_flex()
.gap(8)
.items_center()
.child(this.renderChip(t, agent, status))
.child(div().flex_1())
.child(stop ? this.renderStop(t, agent) : this.renderSend(t, agent, over)),
].filter(Boolean),
);
}
/** 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) =>
h_flex()
.id(`file-${file.id}`)
.gap(6)
.px(8)
.h(24)
.rounded(8)
.bg(file.state === "error" ? t.blocked + "26" : t.chrome)
.items_center()
.child(
div()
.text_size(11.5)
.text_color(file.state === "error" ? t.blocked : t.foreground)
.truncate()
.child(file.name),
)
.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) {
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.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)));
}
/** 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(context.cwd ? shortPath(context.cwd) : ""))
.when(context.branch, (el) => el.child(div().flex_none().child(context.branch)))
.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() : "";
}
/** The size of a file, when it can be measured. */
async function sizeOf(path) {
try {
const info = await fs.stat(path);
return Number.isFinite(info?.size) ? info.size : undefined;
} catch {
// A size that could not be measured is not a size that broke the limit.
return undefined;
}
}