From 5761825ac8aec989364146a79815536c6bff1e08 Mon Sep 17 00:00:00 2001 From: Factor Date: Thu, 19 Nov 2026 11:10:01 +0100 Subject: [PATCH] feat: focus follows click, composer key intents Remove focus reclaim (watchFocus/reclaim/timer), debug notice and the Ctrl+C binding (Ctrl+C is copy). Add pure keyIntent (keys.js) and route Enter/Escape/menu keys through it; bind ctrl-r, ctrl-enter, alt-enter, escape. install.ps1: merge ctrl-shift-space into keys.json (backup), relink wrong junction, warn on failed layout.switch. Co-Authored-By: Claude Sonnet 5.5 --- mod/ovis-composer/keys.js | 45 ++++++++ mod/ovis-composer/main.js | 233 ++++++++++++++++++-------------------- scripts/install.ps1 | 44 ++++++- tests/keys.test.mjs | 45 ++++++++ 4 files changed, 238 insertions(+), 129 deletions(-) create mode 100644 mod/ovis-composer/keys.js create mode 100644 tests/keys.test.mjs diff --git a/mod/ovis-composer/keys.js b/mod/ovis-composer/keys.js new file mode 100644 index 0000000..9b4aa8b --- /dev/null +++ b/mod/ovis-composer/keys.js @@ -0,0 +1,45 @@ +// Pure key intents of the composer: what a key press means, given the state of +// the composer. No gpui, no herdr - main.js acts on the answer. + +/** + * @typedef {"none"|"send"|"send_now"|"hold"|"newline"|"interrupt"|"close_menu"|"close_panel"|"open_panel"|"menu_up"|"menu_down"|"menu_accept"} Intent + */ + +/** + * What a key press means. + * + * @param {{key:string, shift?:boolean, ctrl?:boolean, alt?:boolean, composing?:boolean}} e + * @param {{hasKeyboard:boolean, menuOpen:boolean, panelOpen:boolean, empty:boolean, status:string|null}} ctx + * @returns {Intent} + */ +export function keyIntent(e, ctx) { + // Only the copy whose own field has the keyboard acts; an IME in the middle + // of a composition owns the key. + if (!e || !ctx || !ctx.hasKeyboard || e.composing) return "none"; + + const key = String(e.key ?? "").toLowerCase(); + + if (key === "enter") { + if (e.ctrl) return "send_now"; + if (e.alt) return "hold"; + if (e.shift) return "newline"; + return "send"; + } + + if (key === "escape") { + if (ctx.menuOpen) return "close_menu"; + if (ctx.panelOpen) return "close_panel"; + if (ctx.empty && ctx.status === "working") return "interrupt"; + return "none"; + } + + if (key === "r" && e.ctrl && !e.alt && !e.shift) return "open_panel"; + + if (ctx.menuOpen) { + if (key === "tab") return "menu_accept"; + if (key === "up" || key === "arrowup") return "menu_up"; + if (key === "down" || key === "arrowdown") return "menu_down"; + } + + return "none"; +} diff --git a/mod/ovis-composer/main.js b/mod/ovis-composer/main.js index d7e5d15..2d6ae28 100644 --- a/mod/ovis-composer/main.js +++ b/mod/ovis-composer/main.js @@ -35,6 +35,7 @@ import { 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"; @@ -104,7 +105,6 @@ export default class Composer extends View { this.enterText = null; this.enterCaret = 0; this.currentKey = ""; - this.focusTerminal = null; this.counter = 0; this.closed = false; @@ -118,15 +118,15 @@ export default class Composer extends View { }); this.textarea.on("blur", (event, cx) => { this.hasKeyboard = false; - // The composer does not grab the keyboard back here: the field may have - // lost it to another field of the app. It takes it back when the app's - // focus moves to a terminal (see watchFocus). + // 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 Ctrl+C to "copy" and the arrows - // to the movement of the cursor, and it eats them before they reach the - // element. The composer takes them as actions of its own - the app hands + // The keys the field swallows: it binds the arrows to the movement of the + // cursor, and it eats them before they reach the element. Ctrl+C is not + // bound here - it stays "copy". The composer takes them as actions of its own - the app hands // every action named "." to the mod's nextCommand(). // // The bindings sit on the "Input" context - the context of a text field - @@ -139,16 +139,16 @@ export default class Composer extends View { // 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: "ctrl-c", action: "ovis-composer.interrupt", context: "Input" }, { keystroke: "up", action: "ovis-composer.up", context: "Input" }, { keystroke: "down", action: "ovis-composer.down", context: "Input" }, { keystroke: "tab", action: "ovis-composer.accept", context: "Input" }, + { keystroke: "ctrl-r", action: "ovis-composer.panel", context: "Input" }, + { keystroke: "ctrl-enter", action: "ovis-composer.send_now", context: "Input" }, + { keystroke: "alt-enter", action: "ovis-composer.hold", context: "Input" }, + { keystroke: "escape", action: "ovis-composer.escape", context: "Input" }, ]); - // The keyboard belongs to the composer: the field takes it, and takes it - // back when the terminal takes it (see reclaim). - this.textarea.focus(); - cx.timer.after(600, () => this.textarea.focus()); + // 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 @@ -156,17 +156,19 @@ export default class Composer extends View { // follow, so the composer watches who it talks to. cx.timer.every(500, (cx) => { this.syncAgent(cx); - this.watchFocus(cx); }); cx.spawn(async (cx) => { for (;;) { const command = await nextCommand(); if (command === "focus") this.textarea.focus(); - if (command === "interrupt") this.interruptKey(cx); if (command === "up") this.arrow(-1, cx); - if (command === "down") { const before = this.menu; this.arrow(1, cx); this.notice(`dbg down kb=${this.hasKeyboard} index=${this.menu?.index} same=${before === this.menu}`, "error"); } + 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); cx.notify(); } }); @@ -287,12 +289,12 @@ export default class Composer extends View { // 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(); - const plain = isPlainEnter(event); this.enterText = null; // Shift+Enter is a new line and the secondary Enter (the one an IME // sends) is not a message either. - if (!plain) return; + 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) { @@ -302,50 +304,83 @@ export default class Composer extends View { 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; + } + + /** 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 menu = this.menu; - - if (menu) { - // The arrows and Tab come as actions of the mod (the field swallows - // them); this is the way in when they do arrive. - if (event.key === "down" || event.key === "arrowdown") { - this.arrow(1, cx); - cx.stop_propagation(); - return; - } - if (event.key === "up" || event.key === "arrowup") { - this.arrow(-1, cx); - cx.stop_propagation(); - return; - } - if (event.key === "tab") { - this.acceptFromKey(cx); - cx.stop_propagation(); - return; - } - if (event.key === "escape") { - this.closeMenu(); - cx.stop_propagation(); - return cx.notify(); - } - } - - if (event.key === "escape") { - const agent = this.target(); - if (agent && this.value.trim() === "" && this.statusOf(agent) === "working") { - this.interrupt(agent, cx); - } - cx.stop_propagation(); - return; - } - - if (isControlC(event)) { - const agent = this.target(); - if (agent) this.passKey(agent, "ctrl+c", 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(); } /** @@ -395,39 +430,6 @@ export default class Composer extends View { this.accept(cx); } - /** - * The keyboard belongs to the composer: the terminal only shows. - * - * The composer takes the keyboard back only when the focus that left it went - * to a terminal. The app says which terminal has the focus, and a click in - * another field of the app does not change that - so that field keeps the - * keyboard it took. The composer follows the app's focus: it takes the - * keyboard back when the focus moves to a terminal. - */ - reclaim(cx) { - if (this.closed) return; - if (!this.target()) return; - - const focus = liveFocused(); - if (!focus || !focus.terminal) return; - - try { - this.textarea.focus(); - } catch { - // The copy is going away - there is nothing to focus any more. - } - } - - /** The app's focus moved - a terminal may have taken the keyboard. */ - watchFocus(cx) { - const focus = liveFocused(); - const terminal = focus?.terminal ?? null; - if (terminal === this.focusTerminal) return; - this.focusTerminal = terminal; - if (this.hasKeyboard) return; - this.reclaim(cx); - } - /** The caret goes back where it was - the menu moves, the text does not. */ restoreCaret(at) { if (!Number.isInteger(at)) return; @@ -441,7 +443,7 @@ export default class Composer extends View { // --- sending ------------------------------------------------------------- /** The message goes out, or it waits in the queue. */ - submit(text, cx) { + submit(text, cx, mode = "auto") { const agent = this.target(); if (!agent) { this.notice("Composer nie ma do kogo pisać — brak agenta.", "error", cx); @@ -487,7 +489,7 @@ export default class Composer extends View { } message = message.split(mention(file.path)).join(mention(landed)); } - this.finish(agent, message, cx); + this.finish(agent, message, cx, mode); }); } @@ -501,9 +503,12 @@ export default class Composer extends View { } /** The message goes out now or waits in the queue - the agent's status decides. */ - finish(agent, message, cx) { + finish(agent, message, cx, mode = "auto") { const key = agentKey(agent); - const decision = decide(this.statusOf(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. @@ -518,13 +523,18 @@ export default class Composer extends View { text: message, createdAt: Date.now(), state: held ? "held" : "queued", - ...(held ? { reason: "Agent czeka na Ciebie" } : {}), + ...(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("Agent czeka na Ciebie — wiadomość czeka na „Wyślij teraz”.", "error"); + 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); @@ -854,20 +864,6 @@ export default class Composer extends View { }); } - /** - * Ctrl+C reaches the agent's program. - * - * The binding is on every field of the app (the composer cannot tell its - * own field from another one by the key alone), so the composer only acts - * when its own field holds the keyboard. - */ - interruptKey(cx) { - if (!this.hasKeyboard) return; - const agent = this.target(); - if (!agent) return; - this.passKey(agent, "ctrl+c", cx); - } - // --- the suggestions ----------------------------------------------------- /** The caret sits in a `/` or `@` token - the menu looks at it. */ @@ -1460,19 +1456,6 @@ export default class Composer extends View { // --- helpers ---------------------------------------------------------------- -/** - * Is this the Ctrl+C of the agent's own program? - * - * The keyboard here is not the terminal's: Ctrl+C has to be passed on with - * `hc keys`. GPUI spells the chord with a hyphen ("ctrl-c"); the key and the - * modifier are the surer way to recognise it. - */ -function isControlC(event) { - if (!event) return false; - if (event.keystroke === "ctrl-c" || event.keystroke === "ctrl+c") return true; - return event.key === "c" && event.modifiers?.control === true; -} - /** The name of a file out of its path. */ function nameOf(path) { const parts = String(path ?? "").split(/[\\/]/); diff --git a/scripts/install.ps1 b/scripts/install.ps1 index a98ad89..964424b 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -35,9 +35,34 @@ function Remove-Junction([string]$Path) { if ($LASTEXITCODE -ne 0) { throw "rmdir failed for $Path" } } -# Task 2 adds the key binding here (keys.json.bak-$Stamp is taken first). +# Merge "ctrl-shift-space": "ovis-composer.focus" into keys.json "global", +# leaving every other entry alone. Backs the file up once; idempotent. function Install-KeyEntry { - # TODO(Task 2): back up keys.json once as $KeysBak, then add the entry. + $chord = 'ctrl-shift-space' + $action = 'ovis-composer.focus' + if (-not (Test-Path -LiteralPath $KeysFile)) { + $obj = [pscustomobject]@{ global = [pscustomobject]@{ $chord = $action } } + } else { + $raw = [IO.File]::ReadAllText($KeysFile) + $obj = $raw | ConvertFrom-Json + if ($obj -isnot [pscustomobject]) { throw "keys.json is not a JSON object - resolve by hand." } + if (-not $obj.PSObject.Properties['global']) { + $obj | Add-Member -NotePropertyName 'global' -NotePropertyValue ([pscustomobject]@{}) + } + $global = $obj.global + if ($global.PSObject.Properties[$chord] -and $global.$chord -eq $action) { + Write-Host "keys.json already has $chord" + return + } + if (-not (Test-Path -LiteralPath $KeysBak)) { + Copy-Item -LiteralPath $KeysFile -Destination $KeysBak + Write-Host "Backed up keys.json to $KeysBak" + } + $global | Add-Member -NotePropertyName $chord -NotePropertyValue $action -Force + } + $json = $obj | ConvertTo-Json -Depth 32 + [IO.File]::WriteAllText($KeysFile, $json, (New-Object Text.UTF8Encoding($false))) + Write-Host "keys.json: $chord -> $action" } if ($Uninstall) { @@ -61,13 +86,24 @@ if ($Uninstall) { Write-Host "Restored keys.json" } herdr-app do layout.switch '{"name":"main"}' + if ($LASTEXITCODE -ne 0) { Write-Warning "layout.switch to main failed (exit $LASTEXITCODE) - switch the layout by hand." } exit 0 } # 1. Mod directory -> junction to the repo. +$relink = $false if (Test-Junction $Junction) { - Write-Host "Junction already in place: $Junction" -} else { + $target = (Get-Item -LiteralPath $Junction -Force).Target + if ($target -is [array]) { $target = $target[0] } + if ($target -and ([IO.Path]::GetFullPath($target).TrimEnd([char]92) -ieq [IO.Path]::GetFullPath($ModSource).TrimEnd([char]92))) { + Write-Host "Junction already in place: $Junction" + } else { + Write-Host "Junction points at '$target' - recreating it for $ModSource" + Remove-Junction $Junction + $relink = $true + } +} else { $relink = $true } +if ($relink) { if (Test-Path -LiteralPath $Junction) { if (Test-Path -LiteralPath $ModBackup) { throw "$ModBackup already exists - resolve by hand." } Move-Item -LiteralPath $Junction -Destination $ModBackup diff --git a/tests/keys.test.mjs b/tests/keys.test.mjs new file mode 100644 index 0000000..11358c0 --- /dev/null +++ b/tests/keys.test.mjs @@ -0,0 +1,45 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { keyIntent } from "../mod/ovis-composer/keys.js"; + +const ev = (key, mods = {}) => ({ key, shift: false, ctrl: false, alt: false, composing: false, ...mods }); +const ctx = (o = {}) => ({ hasKeyboard: true, menuOpen: false, panelOpen: false, empty: false, status: null, ...o }); + +test("no keyboard -> always none", () => { + const c = ctx({ hasKeyboard: false }); + assert.equal(keyIntent(ev("Enter"), c), "none"); + assert.equal(keyIntent(ev("v", { ctrl: true }), c), "none"); + assert.equal(keyIntent(ev("Escape"), { ...c, menuOpen: true }), "none"); +}); + +test("composing -> none", () => { + assert.equal(keyIntent(ev("Enter", { composing: true }), ctx()), "none"); +}); + +test("enter variants", () => { + assert.equal(keyIntent(ev("Enter"), ctx()), "send"); + assert.equal(keyIntent(ev("Enter", { shift: true }), ctx()), "newline"); + assert.equal(keyIntent(ev("Enter", { ctrl: true }), ctx()), "send_now"); + assert.equal(keyIntent(ev("Enter", { alt: true }), ctx()), "hold"); +}); + +test("escape", () => { + assert.equal(keyIntent(ev("Escape"), ctx({ menuOpen: true })), "close_menu"); + assert.equal(keyIntent(ev("Escape"), ctx({ panelOpen: true })), "close_panel"); + assert.equal(keyIntent(ev("Escape"), ctx({ empty: true, status: "working" })), "interrupt"); + assert.equal(keyIntent(ev("Escape"), ctx({ empty: false, status: "working" })), "none"); + assert.equal(keyIntent(ev("Escape"), ctx({ empty: true, status: "idle" })), "none"); +}); + +test("ctrl+r opens the panel; ctrl+v is not ours", () => { + assert.equal(keyIntent(ev("r", { ctrl: true }), ctx()), "open_panel"); + assert.equal(keyIntent(ev("v", { ctrl: true }), ctx()), "none"); +}); + +test("menu keys", () => { + assert.equal(keyIntent(ev("Tab"), ctx({ menuOpen: true })), "menu_accept"); + assert.equal(keyIntent(ev("ArrowUp"), ctx({ menuOpen: true })), "menu_up"); + assert.equal(keyIntent(ev("ArrowDown"), ctx({ menuOpen: true })), "menu_down"); + assert.equal(keyIntent(ev("ArrowUp"), ctx()), "none"); + assert.equal(keyIntent(ev("Tab"), ctx()), "none"); +});