diff --git a/layouts/ovis-composer.json b/layouts/ovis-composer.json index 7e4fc7a..bfd7887 100644 --- a/layouts/ovis-composer.json +++ b/layouts/ovis-composer.json @@ -162,6 +162,8 @@ "size": { "px": 260 }, + "min": 120, + "max": 520, "focus": { "border": { "width": 1, @@ -183,7 +185,7 @@ } } ], - "resizable": false + "resizable": true } ], "background": "canvas", diff --git a/mod/ovis-composer/attachments.js b/mod/ovis-composer/attachments.js index 45bd8ca..e7d446d 100644 --- a/mod/ovis-composer/attachments.js +++ b/mod/ovis-composer/attachments.js @@ -177,3 +177,18 @@ function standalone(before, after, afterNext) { if (after === "." && PATH_CHAR.test(afterNext)) return false; return true; } + +/** + * A size for a tile: `512 B`, `1,5 KB`, `5 MB`. + * + * @param {number|undefined|null} bytes + * @returns {string} nothing when the size is not known + */ +export function formatBytes(bytes) { + if (!Number.isFinite(bytes) || bytes < 0) return ""; + const unit = (value, name) => `${String(Math.round(value * 10) / 10).replace(".", ",")} ${name}`; + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return unit(bytes / 1024, "KB"); + if (bytes < 1024 * 1024 * 1024) return unit(bytes / 1024 / 1024, "MB"); + return unit(bytes / 1024 / 1024 / 1024, "GB"); +} diff --git a/mod/ovis-composer/history.js b/mod/ovis-composer/history.js index bc8f0e1..8d91f10 100644 --- a/mod/ovis-composer/history.js +++ b/mod/ovis-composer/history.js @@ -141,3 +141,96 @@ function freshId(list, now) { while (taken.has(id)) id = `f${now}-${(n += 1)}`; return id; } + +// --- what the panel shows --------------------------------------------------- +// +// The panel (panel.js) only draws. What it draws - which rows, which part of a +// row is lit, the line under the text, which empty state - is decided here, so +// it is tested in plain Node. + +/** + * A text cut into the parts that match the query and the parts that do not. + * + * @param {string} text + * @param {[number, number][]} ranges - as `search` returns them + * @returns {{text:string, hit:boolean}[]} + */ +export function segments(text, ranges) { + const source = String(text ?? ""); + const out = []; + let at = 0; + for (const [start, end] of Array.isArray(ranges) ? ranges : []) { + const from = Math.max(at, Math.min(start, source.length)); + const to = Math.min(end, source.length); + if (to <= from) continue; + if (from > at) out.push({ text: source.slice(at, from), hit: false }); + out.push({ text: source.slice(from, to), hit: true }); + at = to; + } + if (at < source.length) out.push({ text: source.slice(at), hit: false }); + return out; +} + +/** + * A moment as `DD.MM HH:MM`, in the time of this computer. + * + * @param {number} ms + * @returns {string} + */ +export function formatMoment(ms) { + if (!Number.isFinite(ms)) return ""; + const date = new Date(ms); + const two = (n) => String(n).padStart(2, "0"); + return `${two(date.getDate())}.${two(date.getMonth() + 1)} ${two(date.getHours())}:${two(date.getMinutes())}`; +} + +/** + * The line under the text of a row: when, in which space, to which agent - or, + * for a favourite, when it was saved. + * + * @param {HistoryEntry|Favorite} item + * @param {"history"|"favorites"} tab + * @returns {string} + */ +export function entryMeta(item, tab) { + if (tab === "favorites") return `zapisano ${formatMoment(item.createdAt)}`; + const space = item.spaceName || "?"; + const agent = item.tabName || item.agentName || "?"; + return `${formatMoment(item.sentAt)} · ${space} · ${agent}`; +} + +/** + * Everything the panel draws, for one tab and one query. + * + * `empty` says which empty state to show: the whole list is empty + * (`"history"` / `"favorites"`), or only the query found nothing (`"query"`). + * + * @param {{history:HistoryEntry[], favorites:Favorite[], tab:"history"|"favorites", query:string}} input + * @returns {{tab:string, counts:{history:number, favorites:number}, hits:Hit[], empty:null|"history"|"favorites"|"query"}} + */ +export function panelState({ history, favorites, tab, query }) { + const source = tab === "favorites" ? favorites : history; + const hits = search(source, query); + let empty = null; + if (!source || source.length === 0) empty = tab === "favorites" ? "favorites" : "history"; + else if (hits.length === 0) empty = "query"; + return { tab, counts: { history: history.length, favorites: favorites.length }, hits, empty }; +} + +/** + * The row after a step up or down - past the end it comes round. + * + * @param {number} index + * @param {number} step + * @param {number} count + * @returns {number} + */ +export function moveIndex(index, step, count) { + if (count <= 0) return 0; + return (index + step + count) % count; +} + +/** The other tab. */ +export function otherTab(tab) { + return tab === "history" ? "favorites" : "history"; +} diff --git a/mod/ovis-composer/main.js b/mod/ovis-composer/main.js index a98ebb3..bb37c6a 100644 --- a/mod/ovis-composer/main.js +++ b/mod/ovis-composer/main.js @@ -18,8 +18,8 @@ // 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 { 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, @@ -40,7 +40,7 @@ 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 } from "./attachments.js"; +import { LIMITS, validate, mention, removeMention, kindOf, formatBytes } from "./attachments.js"; import { clipboardScript, parseClipboardResult, @@ -52,7 +52,8 @@ import { supportsImages, } from "./clipboard.js"; import * as storage from "./storage.js"; -import { record } from "./history.js"; +import { record, panelState, moveIndex, otherTab, toggleFavorite, isFavorite } from "./history.js"; +import { renderPanel, renderPreview } from "./panel.js"; import { agentKey, agentName, @@ -151,7 +152,7 @@ export default class Composer extends View { this.closed = false; this.textarea = TextareaState.new({ value: "", placeholder: PLACEHOLDER, rows: 1 }); - this.textarea.set_auto_grow(1, 6); + 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)); @@ -169,6 +170,30 @@ export default class Composer extends View { }); 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; + 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 @@ -479,7 +504,7 @@ export default class Composer extends View { return { hasKeyboard: this.hasKeyboard, menuOpen: !!this.menu && (this.menu.items ?? []).length > 0, - panelOpen: this.panelOpen === true, + panelOpen: this.panel !== null, empty: this.value.trim() === "", status: agent ? this.statusOf(agent) : null, }; @@ -551,14 +576,209 @@ export default class Composer extends View { if (command === "escape") this.intent({ key: "escape" }, cx); } - /** Task 7: the history panel. Nothing to open yet. */ - openPanel() {} + // --- the History | Favourites panel --------------------------------------- - /** Task 7: the history panel. Nothing to close yet. */ - closePanel() {} + /** 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. + } + + 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; + this.textarea.focus(); + if (restore) this.restoreSelection(caret); + } + + /** 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.closePanel(); + } else if (key === "arrowdown" || key === "down") { + this.movePanel(1, view); + } else if (key === "arrowup" || key === "up") { + this.movePanel(-1, view); + } else if (key === "tab") { + this.panelTab(otherTab(this.panel.tab), 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(); + } + + 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(); + } + + /** 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; + + const { caret } = this.panel; + this.panel = null; + this.textarea.focus(); + this.restoreSelection(caret); + this.textarea.replace(hit.item.text); + this.scheduleDraftSave(cx); + 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 }, @@ -1058,6 +1278,19 @@ export default class Composer extends View { } } + /** "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.discard(agent, id, cx); + this.scheduleDraftSave(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); @@ -1120,9 +1353,15 @@ export default class Composer extends View { 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]); @@ -1621,6 +1860,7 @@ export default class Composer extends View { return v_flex() .id("ovis-composer") + .relative() .track_focus(this.handle) .key_context(CONTEXT) .on_key_down((event, cx) => this.key(event, cx)) @@ -1647,10 +1887,39 @@ export default class Composer extends View { 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; @@ -1786,16 +2055,21 @@ export default class Composer extends View { } 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), - ), - ); - } + // 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, "Odrzuć", `drop-${item.id}`, (event, cx) => this.discard(agent, item.id, cx)), + 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); @@ -1890,25 +2164,75 @@ export default class Composer extends View { .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), + // 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.renderChip(t, agent, status)) + .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() @@ -1937,56 +2261,91 @@ export default class Composer extends View { .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) + .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() - .child( - div() - .text_size(11.5) - .text_color(file.state === "error" ? t.blocked : t.foreground) - .truncate() - .child(file.name), - ) - .when(file.state === "adding", (el) => - el.child(div().text_size(10.5).text_color(t.dim).child("dodawanie…")), - ) - .when(file.state === "error", (el) => - el.child( - div() - .id(`file-retry-${file.id}`) - .px(4) - .text_size(11) - .text_color(t.blocked) - .cursor_pointer() - .hover((s) => s.text_color(t.foreground)) - .on_click((event, cx) => this.retryFile(agent, file.id, cx)) - .child("Ponów"), - ), - ) - .child( - div() - .id(`file-x-${file.id}`) - .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("✕"), - ), + .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) { + renderChip(t, agent, status, fileCount = 0) { if (!agent) { return div() .px(8) @@ -2000,7 +2359,7 @@ export default class Composer extends View { .child("brak agenta"); } - const name = agent.program?.name ?? agentName(agent); + const name = agent.tab_name || agent.program?.name || agentName(agent); const color = t[status] ?? t.dim; return h_flex() @@ -2012,7 +2371,8 @@ export default class Composer extends View { .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))); + .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. */ @@ -2069,8 +2429,15 @@ export default class Composer extends View { .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() + .truncate() + .child( + [agent?.space_name, context.cwd ? shortPath(context.cwd) : "", context.branch ? `⑂ ${context.branch}` : ""] + .filter(Boolean) + .join(" · "), + ), + ) .child(div().flex_1()) .child( div() diff --git a/mod/ovis-composer/panel.js b/mod/ovis-composer/panel.js new file mode 100644 index 0000000..e032f8a --- /dev/null +++ b/mod/ovis-composer/panel.js @@ -0,0 +1,305 @@ +// panel.js - the view of the History | Favourites panel and of the image +// preview. GPUI only: no logic, no state of its own. main.js owns the state and +// hands in what to draw (`view`) and what to do (`on`); what a row says and +// which parts of it are lit is decided in history.js. +// +// The look follows docs/mockups/herdr-unified-prompt.html (`.pop.hist`, +// `.hrow`, `.hfoot`, `.empty`). The colors come from `theme()`. +// +// Limit of the list: rows of a `v_virtual_list` cannot carry their own click +// handlers (the host refuses a handler inside the item renderer) - one +// `on_item_click` serves the whole list and names the row by its key. So a row +// click inserts the text; the star of a row is a sign, not a button (the +// favourites are toggled with Ctrl+D or a right click - `on_item_secondary_click`). + +import { div, image } from "gpui-kit"; +import { v_flex, h_flex, Input, Scrollbar, v_virtual_list } from "gpui-base"; +import { segments, entryMeta } from "./history.js"; + +/** The height of one row - the list is virtual, so every row has the same. */ +export const ROW_HEIGHT = 56; + +/** The text lines of a row (the rest is cut). */ +const TEXT_HEIGHT = 34; + +/** + * The panel. + * + * @param {Record} t - theme() + * @param {{ + * tab: "history"|"favorites", + * state: {counts:{history:number, favorites:number}, hits:{item:any, ranges:[number,number][]}[], empty:null|string}, + * query: string, + * index: number, + * input: object, + * scroll: object, + * isFavorite: (text:string) => boolean, + * }} view + * @param {{ + * key: (event:any, cx:any) => void, + * tab: (tab:string, cx:any) => void, + * pick: (key:string, cx:any) => void, + * toggle: (key:string, cx:any) => void, + * clear: (cx:any) => void, + * }} on + */ +export function renderPanel(t, view, on) { + const { state } = view; + + return v_flex() + .id("composer-panel") + .key_context("ovis-composer-panel") + .on_key_down((event, cx) => on.key(event, cx)) + .size_full() + .rounded(12) + .border(1) + .border_color(t.border) + .bg(t.popover) + .overflow_hidden() + .children([ + renderTop(t, view, on), + v_flex() + .id("composer-panel-body") + .flex_1() + .min_h(0) + .relative() + .child(state.empty ? renderEmpty(t, view, on) : renderList(t, view, on)), + renderFoot(t), + ]); +} + +/** The tabs and the search field. */ +function renderTop(t, view, on) { + const { counts } = view.state; + + return h_flex() + .id("composer-panel-top") + .gap(6) + .items_center() + .px(8) + .py(8) + .border_b(1) + .border_color(t.border) + .children([ + renderTab(t, "history", `Historia ${counts.history}`, view.tab === "history", on), + renderTab(t, "favorites", `Ulubione ${counts.favorites}`, view.tab === "favorites", on), + h_flex() + .id("composer-panel-search") + .flex_1() + .min_w(0) + .items_center() + .gap(6) + .child(Input.new(view.input).flex_1().min_w(0).text_size(12.5)) + .when(view.query !== "", (el) => + el.child( + div() + .id("composer-panel-clear") + .px(6) + .text_size(12) + .text_color(t.dim) + .cursor_pointer() + .hover((s) => s.text_color(t.foreground)) + .on_click((event, cx) => on.clear(cx)) + .child("✕"), + ), + ), + ]); +} + +/** One tab. */ +function renderTab(t, name, label, on, handlers) { + return div() + .id(`composer-panel-tab-${name}`) + .px(10) + .h(26) + .flex() + .items_center() + .flex_none() + .rounded(6) + .text_size(12.5) + .text_color(on ? t.foreground : t.dim) + .when(on, (el) => el.bg(t.hover)) + .cursor_pointer() + .on_click((event, cx) => handlers.tab(name, cx)) + .child(label); +} + +/** The list - virtual, so five hundred rows cost what twenty do. */ +function renderList(t, view, on) { + const hits = view.state.hits; + + return v_flex() + .size_full() + .relative() + .child( + v_virtual_list( + "composer-panel-list", + hits.length, + ROW_HEIGHT, + (index) => String(hits[index].item.id), + (range) => hits.slice(range.start, range.end).map((hit, i) => renderRow(t, view, hit, range.start + i)), + ) + .track_scroll(view.scroll) + .size_full() + .on_item_click((key, cx) => on.pick(key, cx)) + .on_item_secondary_click((key, event, cx) => on.toggle(key, cx)), + ) + .child(Scrollbar.vertical("composer-panel-list").absolute().inset_0()); +} + +/** One row: the text with the match lit, the line under it, the star. */ +function renderRow(t, view, hit, index) { + const on = index === view.index; + const fav = view.isFavorite(hit.item.text); + + return h_flex() + .id(`composer-panel-row-${hit.item.id}`) + .h(ROW_HEIGHT) + .gap(10) + .px(10) + .py(7) + .items_start() + .rounded(7) + .when(on, (el) => el.bg(t.hover)) + .child( + v_flex() + .flex_1() + .min_w(0) + .gap(2) + .child(renderText(t, hit)) + .child( + div() + .text_size(11.5) + .text_color(t.dim) + .truncate() + .child(entryMeta(hit.item, view.tab)), + ), + ) + .child( + div() + .flex_none() + .size(24) + .flex() + .items_center() + .justify_center() + .text_size(14) + .text_color(fav ? t.working : t.dim) + .child(fav ? "★" : "☆"), + ); +} + +/** The text of a row: two lines, the parts that match the query lit. */ +function renderText(t, hit) { + const parts = []; + for (const part of segments(hit.item.text, hit.ranges)) { + // Words are separate children so the line breaks between words; a newline + // in the message is one space here. + for (const word of part.text.replace(/\s+/g, " ").match(/\S+\s*|\s+/g) ?? []) { + parts.push( + div() + .flex_none() + .text_size(12.8) + .text_color(t.foreground) + .when(part.hit, (el) => el.bg(t.selected).rounded(2)) + .child(word), + ); + } + } + return h_flex().flex_wrap().h(TEXT_HEIGHT).overflow_hidden().children(parts); +} + +/** What is said when there is nothing to list. */ +function renderEmpty(t, view, on) { + const { empty } = view.state; + const [title, body] = + empty === "history" + ? ["Historia jest pusta", "Wysłane wiadomości pojawią się tutaj — z każdej przestrzeni i od każdego agenta."] + : empty === "favorites" + ? ["Brak ulubionych", "Kliknij ☆ przy edytorze, aby zapisać prompt na stałe."] + : [`Brak wyników dla „${view.query.trim()}”`, "Spróbuj krótszego fragmentu albo"]; + + return v_flex() + .id("composer-panel-empty") + .size_full() + .items_center() + .justify_center() + .gap(4) + .px(16) + .child(div().text_size(13).text_color(t.foreground).child(title)) + .child(div().text_size(12).text_color(t.dim).child(body)) + .when(empty === "query", (el) => + el.child( + div() + .id("composer-panel-clear-query") + .mt(4) + .px(10) + .h(26) + .flex() + .items_center() + .rounded(6) + .bg(t.chrome) + .text_size(12) + .text_color(t.muted) + .cursor_pointer() + .hover((s) => s.bg(t.hover).text_color(t.foreground)) + .on_click((event, cx) => on.clear(cx)) + .child("wyczyść wyszukiwanie"), + ), + ); +} + +/** The line of keys at the bottom. */ +function renderFoot(t) { + const keys = [ + "↑↓ wybór", + "Enter wstaw w miejscu kursora (nie wysyła)", + "Tab Historia/Ulubione", + "Ctrl+D ulubiony", + "Esc wróć do edytora", + ]; + + return h_flex() + .id("composer-panel-foot") + .gap(14) + .flex_wrap() + .px(12) + .py(6) + .border_t(1) + .border_color(t.border) + .text_size(11.5) + .text_color(t.dim) + .children(keys.map((text) => div().child(text))); +} + +/** + * The preview of an image: the whole image on a dark scrim, its name and size + * under it. A click or Esc closes it (main.js). + * + * @param {Record} t + * @param {{path:string, caption:string}} preview + * @param {object} handle - FocusHandle of the overlay + * @param {{close: (cx:any) => void}} on + */ +export function renderPreview(t, preview, handle, on) { + return v_flex() + .id("composer-preview") + .track_focus(handle) + .key_context("ovis-composer-preview") + .on_key_down((event, cx) => { + if (String(event.key).toLowerCase() === "escape") { + on.close(cx); + cx.stop_propagation(); + } + }) + .absolute() + .inset_0() + .items_center() + .justify_center() + .gap(8) + .p(16) + .bg("#000000cc") + .cursor_pointer() + .on_click((event, cx) => on.close(cx)) + .child(image(preview.path).max_w("90%").max_h("80%").rounded(8)) + .child(div().text_size(12).text_color(t.muted).child(preview.caption)); +} diff --git a/mod/ovis-composer/state.js b/mod/ovis-composer/state.js index 812a725..9a59714 100644 --- a/mod/ovis-composer/state.js +++ b/mod/ovis-composer/state.js @@ -348,7 +348,10 @@ function discard(state, action) { } /** - * A held entry goes back to the queue. + * A held entry goes back to the queue - and so does an `uncertain` one: the + * person looked at "Nie potwierdzono" and chose "Ponów", knowing the message + * may have reached the agent. Only their click does this; nothing else ever + * sends an uncertain entry again. * * The hold said "the agent is waiting for you"; the person answered by asking * for the message to go out anyway. The entry waits in the queue like any @@ -358,7 +361,7 @@ function discard(state, action) { function requeue(state, action) { const items = list(state.queue, action.agent); const item = items.find((entry) => entry.id === action.id); - if (!item || item.state !== "held") return state; + if (!item || (item.state !== "held" && item.state !== "uncertain")) return state; return { ...state, queue: { diff --git a/tests/attachments.test.mjs b/tests/attachments.test.mjs index 3c12820..fb3a145 100644 --- a/tests/attachments.test.mjs +++ b/tests/attachments.test.mjs @@ -58,3 +58,15 @@ test("removeMention takes the quoted form and the bare form out", () => { assert.equal(removeMention("see @/a/ęą.png now", "/a/ęą.png"), "see now"); assert.equal(removeMention('see @"/a b/c.png"x now', "/a b/c.png"), 'see @"/a b/c.png"x now'); }); + +import { formatBytes } from "../mod/ovis-composer/attachments.js"; + +test("formatBytes", () => { + assert.equal(formatBytes(0), "0 B"); + assert.equal(formatBytes(512), "512 B"); + assert.equal(formatBytes(2048), "2 KB"); + assert.equal(formatBytes(1536), "1,5 KB"); + assert.equal(formatBytes(5 * 1024 * 1024), "5 MB"); + assert.equal(formatBytes(undefined), ""); + assert.equal(formatBytes(NaN), ""); +}); diff --git a/tests/history.test.mjs b/tests/history.test.mjs index 77147fe..97b2071 100644 --- a/tests/history.test.mjs +++ b/tests/history.test.mjs @@ -106,3 +106,50 @@ test("storage: old favourites (at) load as createdAt", () => { store.set(KEYS.favorites, [{ id: "f", text: "x", at: 4 }]); assert.equal(loadFavorites(store)[0].createdAt, 4); }); + +import { segments, formatMoment, entryMeta, panelState, moveIndex, otherTab } from "../mod/ovis-composer/history.js"; + +test("segments splits a text on the ranges", () => { + assert.deepEqual(segments("uruchom testy", [[8, 12]]), [ + { text: "uruchom ", hit: false }, { text: "test", hit: true }, { text: "y", hit: false }, + ]); + assert.deepEqual(segments("ab", []), [{ text: "ab", hit: false }]); + assert.deepEqual(segments("abab", [[0, 2], [2, 4]]), [{ text: "ab", hit: true }, { text: "ab", hit: true }]); + assert.deepEqual(segments("", []), []); + assert.deepEqual(segments("ab", [[0, 99]]), [{ text: "ab", hit: true }]); +}); + +test("formatMoment is DD.MM HH:MM in local time", () => { + assert.equal(formatMoment(new Date(2026, 10, 19, 9, 5).getTime()), "19.11 09:05"); + assert.equal(formatMoment(new Date(2026, 0, 2, 23, 59).getTime()), "02.01 23:59"); + assert.equal(formatMoment(NaN), ""); +}); + +test("entryMeta: history says when, where and who; a favourite says when it was saved", () => { + const at = new Date(2026, 10, 19, 9, 5).getTime(); + assert.equal(entryMeta({ sentAt: at, spaceName: "herdr", tabName: "Ovis Fast", agentName: "claude-code" }, "history"), "19.11 09:05 · herdr · Ovis Fast"); + assert.equal(entryMeta({ sentAt: at, spaceName: "", agentName: "" }, "history"), "19.11 09:05 · ? · ?"); + assert.equal(entryMeta({ sentAt: at, spaceName: "s", tabName: "", agentName: "codex" }, "history"), "19.11 09:05 · s · codex"); + assert.equal(entryMeta({ createdAt: at }, "favorites"), "zapisano 19.11 09:05"); +}); + +test("panelState: counts, hits, and which empty state to show", () => { + const h = [entry(1, "alfa"), entry(2, "beta")]; + const f = [{ id: "f", text: "gamma", createdAt: 3 }]; + let s = panelState({ history: h, favorites: f, tab: "history", query: "" }); + assert.deepEqual([s.counts, s.hits.length, s.empty], [{ history: 2, favorites: 1 }, 2, null]); + s = panelState({ history: h, favorites: f, tab: "favorites", query: "gam" }); + assert.deepEqual([s.hits.length, s.empty], [1, null]); + assert.equal(panelState({ history: [], favorites: f, tab: "history", query: "" }).empty, "history"); + assert.equal(panelState({ history: h, favorites: [], tab: "favorites", query: "" }).empty, "favorites"); + assert.equal(panelState({ history: h, favorites: f, tab: "history", query: "zzz" }).empty, "query"); +}); + +test("moveIndex wraps; otherTab flips", () => { + assert.equal(moveIndex(0, -1, 3), 2); + assert.equal(moveIndex(2, 1, 3), 0); + assert.equal(moveIndex(1, 1, 3), 2); + assert.equal(moveIndex(0, 1, 0), 0); + assert.equal(otherTab("history"), "favorites"); + assert.equal(otherTab("favorites"), "history"); +}); diff --git a/tests/state.test.mjs b/tests/state.test.mjs index 0085175..c3aca81 100644 --- a/tests/state.test.mjs +++ b/tests/state.test.mjs @@ -212,3 +212,10 @@ test("attachment states: adding -> ready with the remote path, or error; retry g assert.equal(s.attachments.a[0].error, undefined); assert.equal(reduce(s, { type: "attachment_update", agent: "a", id: "zz", patch: { state: "ready" } }), s); }); + +test("requeue takes an uncertain entry back to the queue too (the person's \"Ponów\")", () => { + const s = reduce(mk(it("u", "uncertain", { reason: "x" })), { type: "requeue", agent: "a", id: "u" }); + assert.deepEqual(s.queue.a[0], { id: "u", text: "u", state: "queued", createdAt: 1 }); + const q = mk(it("q", "queued")); + assert.equal(reduce(q, { type: "requeue", agent: "a", id: "q" }), q); +});