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 <[email protected]>
This commit is contained in:
FactorandClaude Sonnet 5.5 committed 2026-11-19 11:10:01 +01:00
1 parent c05e252d79
commit 5761825ac8
4 files changed
+237 -128

No files matched your search

+45
View File
@@ -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";
}
+108 -125
View File
@@ -35,6 +35,7 @@ import {
import * as fs from "fs/promises"; import * as fs from "fs/promises";
import { createState, reduce } from "./state.js"; import { createState, reduce } from "./state.js";
import { keyIntent } from "./keys.js";
import { decide, sendNow as sendToTerminal } from "./delivery.js"; import { decide, sendNow as sendToTerminal } from "./delivery.js";
import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js"; import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js";
import * as catalog from "./catalog.js"; import * as catalog from "./catalog.js";
@@ -104,7 +105,6 @@ export default class Composer extends View {
this.enterText = null; this.enterText = null;
this.enterCaret = 0; this.enterCaret = 0;
this.currentKey = ""; this.currentKey = "";
this.focusTerminal = null;
this.counter = 0; this.counter = 0;
this.closed = false; this.closed = false;
@@ -118,15 +118,15 @@ export default class Composer extends View {
}); });
this.textarea.on("blur", (event, cx) => { this.textarea.on("blur", (event, cx) => {
this.hasKeyboard = false; this.hasKeyboard = false;
// The composer does not grab the keyboard back here: the field may have // Focus follows the click: the composer never grabs the keyboard back.
// lost it to another field of the app. It takes it back when the app's // It takes it when the person clicks the field or presses
// focus moves to a terminal (see watchFocus). // Ctrl+Shift+Space (the "focus" command).
}); });
this.handle = cx.focus_handle(); this.handle = cx.focus_handle();
// The keys the field swallows: it binds Ctrl+C to "copy" and the arrows // The keys the field swallows: it binds the arrows to the movement of the
// to the movement of the cursor, and it eats them before they reach the // cursor, and it eats them before they reach the element. Ctrl+C is not
// element. The composer takes them as actions of its own - the app hands // bound here - it stays "copy". The composer takes them as actions of its own - the app hands
// every action named "<mod>.<command>" to the mod's nextCommand(). // every action named "<mod>.<command>" to the mod's nextCommand().
// //
// The bindings sit on the "Input" context - the context of a text field - // 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 // copy of the composer whose own field has the keyboard acts - the other
// copies (a composer in another pane) leave the key alone. // copies (a composer in another pane) leave the key alone.
cx.bind_keys([ cx.bind_keys([
{ keystroke: "ctrl-c", action: "ovis-composer.interrupt", context: "Input" },
{ keystroke: "up", action: "ovis-composer.up", context: "Input" }, { keystroke: "up", action: "ovis-composer.up", context: "Input" },
{ keystroke: "down", action: "ovis-composer.down", context: "Input" }, { keystroke: "down", action: "ovis-composer.down", context: "Input" },
{ keystroke: "tab", action: "ovis-composer.accept", 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 // Focus follows the click: nothing here takes the keyboard on its own.
// back when the terminal takes it (see reclaim).
this.textarea.focus();
cx.timer.after(600, () => this.textarea.focus());
this.syncAgent(cx); this.syncAgent(cx);
// The agent under the focus can change without the composer being // 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. // follow, so the composer watches who it talks to.
cx.timer.every(500, (cx) => { cx.timer.every(500, (cx) => {
this.syncAgent(cx); this.syncAgent(cx);
this.watchFocus(cx);
}); });
cx.spawn(async (cx) => { cx.spawn(async (cx) => {
for (;;) { for (;;) {
const command = await nextCommand(); const command = await nextCommand();
if (command === "focus") this.textarea.focus(); if (command === "focus") this.textarea.focus();
if (command === "interrupt") this.interruptKey(cx);
if (command === "up") this.arrow(-1, 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 === "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(); cx.notify();
} }
}); });
@@ -287,12 +289,12 @@ export default class Composer extends View {
// the text of the field as it was before it. // the text of the field as it was before it.
const text = this.enterText ?? this.value; const text = this.enterText ?? this.value;
const caret = this.enterText !== null ? this.enterCaret : this.caret(); const caret = this.enterText !== null ? this.enterCaret : this.caret();
const plain = isPlainEnter(event);
this.enterText = null; this.enterText = null;
// Shift+Enter is a new line and the secondary Enter (the one an IME // Shift+Enter is a new line and the secondary Enter (the one an IME
// sends) is not a message either. // 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. // The menu takes the key - but only when it has something to offer.
if (this.menu && (this.menu.items ?? []).length > 0) { if (this.menu && (this.menu.items ?? []).length > 0) {
@@ -302,50 +304,83 @@ export default class Composer extends View {
this.submit(text, cx); 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. */ /** The keyboard of the composer. */
key(event, cx) { key(event, cx) {
const menu = this.menu; const m = event.modifiers ?? {};
const handled = this.intent(
if (menu) { { key: event.key, shift: m.shift === true, ctrl: m.control === true, alt: m.alt === true },
// The arrows and Tab come as actions of the mod (the field swallows cx,
// them); this is the way in when they do arrive. );
if (event.key === "down" || event.key === "arrowdown") { // Escape is never left to the field; the other keys only when they were ours.
this.arrow(1, cx); if (handled || String(event.key).toLowerCase() === "escape") cx.stop_propagation();
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;
}
} }
/** /**
@@ -395,39 +430,6 @@ export default class Composer extends View {
this.accept(cx); 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. */ /** The caret goes back where it was - the menu moves, the text does not. */
restoreCaret(at) { restoreCaret(at) {
if (!Number.isInteger(at)) return; if (!Number.isInteger(at)) return;
@@ -441,7 +443,7 @@ export default class Composer extends View {
// --- sending ------------------------------------------------------------- // --- sending -------------------------------------------------------------
/** The message goes out, or it waits in the queue. */ /** The message goes out, or it waits in the queue. */
submit(text, cx) { submit(text, cx, mode = "auto") {
const agent = this.target(); const agent = this.target();
if (!agent) { if (!agent) {
this.notice("Composer nie ma do kogo pisać — brak agenta.", "error", cx); 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)); 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. */ /** 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 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 // A message that is already on the wire: the new one waits in the queue
// instead of vanishing. // instead of vanishing.
@@ -518,13 +523,18 @@ export default class Composer extends View {
text: message, text: message,
createdAt: Date.now(), createdAt: Date.now(),
state: held ? "held" : "queued", 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.state = reduce(this.state, { type: "queue", agent: key, item });
this.persistQueue(key); this.persistQueue(key);
if (held) { 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 { } else {
this.notice("Wiadomość w kolejce — następna tura."); this.notice("Wiadomość w kolejce — następna tura.");
this.watch(agent, cx); 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 suggestions -----------------------------------------------------
/** The caret sits in a `/` or `@` token - the menu looks at it. */ /** The caret sits in a `/` or `@` token - the menu looks at it. */
@@ -1460,19 +1456,6 @@ export default class Composer extends View {
// --- helpers ---------------------------------------------------------------- // --- 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. */ /** The name of a file out of its path. */
function nameOf(path) { function nameOf(path) {
const parts = String(path ?? "").split(/[\\/]/); const parts = String(path ?? "").split(/[\\/]/);
+39 -3
View File
@@ -35,9 +35,34 @@ function Remove-Junction([string]$Path) {
if ($LASTEXITCODE -ne 0) { throw "rmdir failed for $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 { 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) { if ($Uninstall) {
@@ -61,13 +86,24 @@ if ($Uninstall) {
Write-Host "Restored keys.json" Write-Host "Restored keys.json"
} }
herdr-app do layout.switch '{"name":"main"}' 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 exit 0
} }
# 1. Mod directory -> junction to the repo. # 1. Mod directory -> junction to the repo.
$relink = $false
if (Test-Junction $Junction) { if (Test-Junction $Junction) {
$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" Write-Host "Junction already in place: $Junction"
} else { } 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 $Junction) {
if (Test-Path -LiteralPath $ModBackup) { throw "$ModBackup already exists - resolve by hand." } if (Test-Path -LiteralPath $ModBackup) { throw "$ModBackup already exists - resolve by hand." }
Move-Item -LiteralPath $Junction -Destination $ModBackup Move-Item -LiteralPath $Junction -Destination $ModBackup
+45
View File
@@ -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");
});