@operad-io/tui 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,15 +1,14 @@
1
1
  {
2
2
  "name": "@operad-io/tui",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
7
- "./app": "./src/app.ts",
8
- "./view": "./src/view/index.ts"
7
+ "./app": "./src/app.ts"
9
8
  },
10
9
  "dependencies": {
11
10
  "@opentui/core": "0.6.8",
12
- "@operad-io/engine": "0.1.1"
11
+ "@operad-io/engine": "0.3.0"
13
12
  },
14
13
  "description": "operad: the terminal client",
15
14
  "repository": {
package/src/actions.ts CHANGED
@@ -4,9 +4,11 @@
4
4
  * state; the shell sends the request this code leaves in `actionRequest`.
5
5
  */
6
6
 
7
- import type { ViewAction, ViewRow } from "@operad-io/engine";
7
+
8
+ import { bareId, type AskQuestionAnswer, type ViewAction, type ViewRow } from "@operad-io/engine";
8
9
  import { argFields, narrowField, parseArg, type ArgField } from "./args.ts";
9
10
  import type { TuiSetting, TuiTypeInfo } from "./client.ts";
11
+ import { chatCommands, commandEntries, commandText, filterCommands } from "./commands.ts";
10
12
  import { sanitize } from "./sanitize.ts";
11
13
  import type { TuiAnswer, TuiBinding, TuiInput, TuiState } from "./state.ts";
12
14
  import { graphemes } from "./wrap.ts";
@@ -117,11 +119,6 @@ export function keyOf(
117
119
  );
118
120
  }
119
121
 
120
- function bareId(id: string): string {
121
- const at = id.indexOf(":");
122
- return at < 0 ? id : id.slice(at + 1);
123
- }
124
-
125
122
  /**
126
123
  * The actions a page lists: those that do not create an object of another type.
127
124
  * A creating action belongs to that type's tab (`c` on the chat tab), not to the
@@ -131,8 +128,20 @@ export function pageActions(actions: readonly ViewAction[]): readonly ViewAction
131
128
  return actions.filter((action) => action.creates === undefined);
132
129
  }
133
130
 
131
+ /** The chat's stop action, while its reply is running. */
132
+ export function stopAction(state: TuiState): ViewAction | undefined {
133
+ const object = state.object;
134
+ if (object?.type !== "chat" || !object.row.running) return undefined;
135
+ return pageActions(object.actions).find(
136
+ (action) => action.plugin === "chat" && action.action === "stop",
137
+ );
138
+ }
139
+
134
140
  /** The first available action, the one the footer offers. */
135
141
  export function mainAction(state: TuiState): ViewAction | undefined {
142
+ // While a reply runs, its stop action is the one the main key offers.
143
+ const stop = stopAction(state);
144
+ if (stop !== undefined) return stop;
136
145
  // An action that ends the object is never the main one, even when it is alone.
137
146
  return pageActions(state.object?.actions ?? []).find((action) => action.ends !== true);
138
147
  }
@@ -293,7 +302,6 @@ export type TuiCommand =
293
302
  /** The objects a new `type` can be made under: every loaded row, or group, of a type that creating it works on. */
294
303
  export function creationParents(
295
304
  state: TuiState,
296
- type: string,
297
305
  parents: readonly string[],
298
306
  ): readonly string[] {
299
307
  const ids = new Set<string>();
@@ -314,7 +322,7 @@ export function creationParents(
314
322
  export function settingScopes(state: TuiState): readonly string[] {
315
323
  const object = state.object;
316
324
  if (object === undefined) return ["global"];
317
- const bare = object.id.slice(object.id.indexOf(":") + 1);
325
+ const bare = bareId(object.id);
318
326
  // A repository's own page is named by the repository; other objects carry it before the last slash.
319
327
  if (object.type === "repo") return ["global", bare];
320
328
  const slash = bare.lastIndexOf("/");
@@ -426,7 +434,7 @@ export function settingValue(text: string, type?: string | undefined): unknown {
426
434
  }
427
435
  }
428
436
 
429
- function commandEntries(state: TuiState): readonly TuiPaletteEntry[] {
437
+ function tuiCommandEntries(state: TuiState): readonly TuiPaletteEntry[] {
430
438
  const make = (
431
439
  name: string,
432
440
  title: string,
@@ -461,7 +469,7 @@ function commandEntries(state: TuiState): readonly TuiPaletteEntry[] {
461
469
  const creating = (here?.kind === "plugin" ? (here.types ?? []) : [])
462
470
  .filter((info) => state.object === undefined || !(info.parents ?? []).includes(state.object.type))
463
471
  .flatMap((info) =>
464
- creationParents(state, info.type, info.parents ?? []).map((parent) =>
472
+ creationParents(state, info.parents ?? []).map((parent) =>
465
473
  make(`new ${info.type}`, `start a new ${info.type} in ${parent}`, undefined, {
466
474
  kind: "create",
467
475
  parent,
@@ -513,7 +521,7 @@ export function paletteEntries(state: TuiState): readonly TuiPaletteEntry[] {
513
521
  .map((item) => item.entry);
514
522
  const all = [
515
523
  ...rank(actions),
516
- ...rank(commandEntries(state)),
524
+ ...rank(tuiCommandEntries(state)),
517
525
  ...rank(settingEntries(state)),
518
526
  ...rank(settingsObjectEntries(state)),
519
527
  ];
@@ -685,30 +693,136 @@ export function startAction(
685
693
  return afterArgs(closed, action.name, object.id, {}, note, action.confirm);
686
694
  }
687
695
 
688
- /** Opens the choice list of a pending question. */
696
+ /**
697
+ * Starts an action at its note, leaving every argument at the action's own
698
+ * defaults. A chat's first message is sent this way, so the create action does
699
+ * not ask for an agent, model or effort the bot already chose.
700
+ */
701
+ export function startNote(state: TuiState, name: string): TuiState {
702
+ const object = state.object;
703
+ const closed: TuiState = { ...state, input: undefined };
704
+ if (object === undefined) return withNotice(closed, "no object is selected");
705
+ if (state.acting) return withNotice(closed, "the last action has not answered yet");
706
+ const action = object.actions.find((candidate) => candidate.name === name);
707
+ if (action === undefined) {
708
+ return withNotice(closed, `${name} is not available for ${bareId(object.id)}`);
709
+ }
710
+ if (action.note === undefined) return startAction(state, name);
711
+ return {
712
+ ...closed,
713
+ input: {
714
+ kind: "note",
715
+ action: action.name,
716
+ id: object.id,
717
+ text: "",
718
+ required: action.noteRequired,
719
+ confirm: action.confirm,
720
+ },
721
+ };
722
+ }
723
+
724
+ /** Opens the choice list of a pending question, on the choice the asker recommends. */
689
725
  export function startAnswer(state: TuiState, answer: TuiAnswer): TuiState {
690
726
  const closed: TuiState = { ...state, input: undefined };
691
727
  if (state.acting) return withNotice(closed, "the last change has not answered yet");
728
+ const primary = answer.choices.findIndex((choice) => answer.choiceInfo?.[choice]?.role === "primary");
729
+ if (answer.questions !== undefined) {
730
+ return {
731
+ ...closed,
732
+ input: {
733
+ kind: "form",
734
+ answer,
735
+ question: 0,
736
+ cursor: primary < 0 ? 0 : primary,
737
+ text: "",
738
+ },
739
+ };
740
+ }
692
741
  return {
693
742
  ...closed,
694
- input: { kind: "answer", answer, cursor: 0 },
743
+ input: { kind: "answer", answer, cursor: primary < 0 ? 0 : primary },
695
744
  };
696
745
  }
697
746
 
747
+ /** The words a choice's line shows: the asker's label, or the raw choice. */
748
+ function choiceLabel(answer: TuiAnswer, choice: string): string {
749
+ return answer.choiceInfo?.[choice]?.label ?? choice;
750
+ }
751
+
698
752
  /** Sends the chosen answer and closes the choice list. */
699
- function sendAnswer(state: TuiState, answer: TuiAnswer, choice: string): TuiState {
753
+ function sendAnswer(state: TuiState, answer: TuiAnswer, choice: string, note?: string): TuiState {
754
+ return sendForm(state, answer, { choice }, note);
755
+ }
756
+
757
+ /** Sends one form answer (or one choice) and closes the question. */
758
+ function sendForm(
759
+ state: TuiState,
760
+ answer: TuiAnswer,
761
+ given: { readonly choice?: string | undefined; readonly answer?: AskQuestionAnswer | undefined },
762
+ note?: string,
763
+ ): TuiState {
764
+ const locked =
765
+ state.input?.kind === "note"
766
+ ? {
767
+ ...state.input,
768
+ sending: true,
769
+ error: undefined,
770
+ commandMenu: undefined,
771
+ commands: undefined,
772
+ }
773
+ : undefined;
700
774
  return {
701
775
  ...state,
702
- input: undefined,
776
+ ...(locked === undefined ? { input: undefined } : { input: locked }),
703
777
  acting: true,
704
778
  answerRequest: {
705
779
  runId: answer.runId,
706
780
  waitId: answer.waitId,
707
- choice,
781
+ ...(given.choice === undefined ? {} : { choice: given.choice }),
782
+ ...(given.answer === undefined ? {} : { answers: [given.answer] }),
783
+ ...(note === undefined || note === "" ? {} : { note }),
708
784
  },
709
785
  };
710
786
  }
711
787
 
788
+ /** The keys of a one-question form: its choices, or its free text. */
789
+ function formKey(
790
+ state: TuiState,
791
+ input: Extract<TuiInput, { readonly kind: "form" }>,
792
+ event: {
793
+ readonly text?: string | undefined;
794
+ readonly ctrl?: boolean | undefined;
795
+ readonly meta?: boolean | undefined;
796
+ },
797
+ key: string,
798
+ enter: boolean,
799
+ ): TuiState {
800
+ const question = input.answer.questions?.[input.question];
801
+ if (question === undefined) return { ...state, input: undefined };
802
+ const choices = question.choices ?? [];
803
+ if (choices.length > 0) {
804
+ const down = key === "down" || key === "arrowdown" || key === "j";
805
+ const up = key === "up" || key === "arrowup" || key === "k";
806
+ if (down || up) {
807
+ const cursor = Math.min(Math.max(0, input.cursor + (down ? 1 : -1)), choices.length - 1);
808
+ return { ...state, input: { ...input, cursor } };
809
+ }
810
+ if (!enter) return state;
811
+ const choice = choices[input.cursor];
812
+ if (choice === undefined) return state;
813
+ return sendForm(state, input.answer, { answer: { id: question.id, choices: [choice.label] } });
814
+ }
815
+ if (enter) {
816
+ const text = input.text;
817
+ return sendForm(state, input.answer, {
818
+ answer: text.trim() === "" ? { id: question.id, skipped: true } : { id: question.id, text },
819
+ });
820
+ }
821
+ if (key === "backspace") return { ...state, input: { ...input, text: dropLast(input.text) } };
822
+ const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
823
+ return text === undefined ? state : { ...state, input: { ...input, text: input.text + text } };
824
+ }
825
+
712
826
  /** The keys of a pending question's choice list. */
713
827
  function answerKey(
714
828
  state: TuiState,
@@ -727,7 +841,21 @@ function answerKey(
727
841
  }
728
842
  if (!enter) return state;
729
843
  const choice = input.answer.choices[input.cursor];
730
- return choice === undefined ? state : sendAnswer(state, input.answer, choice);
844
+ if (choice === undefined) return state;
845
+ const info = input.answer.choiceInfo?.[choice];
846
+ if (info?.note === undefined) return sendAnswer(state, input.answer, choice);
847
+ return {
848
+ ...state,
849
+ input: {
850
+ kind: "note",
851
+ action: choiceLabel(input.answer, choice),
852
+ id: input.answer.waitId,
853
+ text: "",
854
+ required: info.note === "required",
855
+ confirm: false,
856
+ answer: { answer: input.answer, choice },
857
+ },
858
+ };
731
859
  }
732
860
 
733
861
  type ArgsInput = Extract<TuiInput, { readonly kind: "args" }>;
@@ -796,6 +924,76 @@ function afterArgs(
796
924
  return send(state, { action, id, ...given });
797
925
  }
798
926
 
927
+ /** How often `part` is in `text`; the same count the section takes before a send. */
928
+ function countOf(text: string, part: string): number {
929
+ if (part === "") return 0;
930
+ let count = 0;
931
+ let at = 0;
932
+ for (;;) {
933
+ const found = text.indexOf(part, at);
934
+ if (found < 0) return count;
935
+ count += 1;
936
+ at = found + part.length;
937
+ }
938
+ }
939
+
940
+ /** Draws a chat message at the end of its transcript until the server's copy arrives. */
941
+ function withOptimistic(
942
+ state: TuiState,
943
+ request: {
944
+ action: string;
945
+ id: string;
946
+ note?: string;
947
+ args?: Readonly<Record<string, unknown>>;
948
+ confirmed?: boolean;
949
+ },
950
+ ): TuiState {
951
+ const object = state.object;
952
+ const text = request.note;
953
+ const sending = object?.actions.some(
954
+ (action) => action.name === request.action && action.plugin === "chat" && action.action === "send",
955
+ );
956
+ if (
957
+ object?.type !== "chat" ||
958
+ sending !== true ||
959
+ text === undefined ||
960
+ text.trim() === "" ||
961
+ text.startsWith("/")
962
+ ) {
963
+ return state;
964
+ }
965
+ const section = object.sections.find((one) => one.id === "transcript");
966
+ if (section === undefined) return state;
967
+ const id = state.optimisticSeq;
968
+ const entry = { id, text, baseline: countOf(section.markdown, text) };
969
+ const sections = object.sections.map((one) =>
970
+ one.id === section.id
971
+ ? { ...one, optimistic: [...(one.optimistic ?? []), entry] }
972
+ : one,
973
+ );
974
+ return {
975
+ ...state,
976
+ optimisticSeq: id + 1,
977
+ object: { ...object, sections },
978
+ send: { objectId: object.id, sectionId: section.id, id },
979
+ };
980
+ }
981
+
982
+ /** The message a failed send drew is no longer on its way. */
983
+ function dropOptimistic(state: TuiState): TuiState {
984
+ const sent = state.send;
985
+ const object = state.object;
986
+ if (sent === undefined || object === undefined || object.id !== sent.objectId) {
987
+ return state.send === undefined ? state : { ...state, send: undefined };
988
+ }
989
+ const sections = object.sections.map((section) =>
990
+ section.id === sent.sectionId && section.optimistic !== undefined
991
+ ? { ...section, optimistic: section.optimistic.filter((entry) => entry.id !== sent.id) }
992
+ : section,
993
+ );
994
+ return { ...state, object: { ...object, sections }, send: undefined };
995
+ }
996
+
799
997
  function send(
800
998
  state: TuiState,
801
999
  request: {
@@ -806,7 +1004,24 @@ function send(
806
1004
  confirmed?: boolean;
807
1005
  },
808
1006
  ): TuiState {
809
- return { ...state, input: undefined, acting: true, actionRequest: request };
1007
+ const optimistic = withOptimistic(state, request);
1008
+ // A note stays in its input, locked, until the server accepts it or refuses it.
1009
+ const note =
1010
+ optimistic.input?.kind === "note"
1011
+ ? {
1012
+ ...optimistic.input,
1013
+ sending: true,
1014
+ error: undefined,
1015
+ commandMenu: undefined,
1016
+ commands: undefined,
1017
+ }
1018
+ : undefined;
1019
+ return {
1020
+ ...optimistic,
1021
+ ...(note === undefined ? { input: undefined } : { input: note }),
1022
+ acting: true,
1023
+ actionRequest: request,
1024
+ };
810
1025
  }
811
1026
 
812
1027
  /** `a`, or a bound key: the key that reached the reducer, as a label. */
@@ -836,6 +1051,116 @@ export function dropLast(text: string): string {
836
1051
  return all.join("");
837
1052
  }
838
1053
 
1054
+ function noteMenu(cursor: number): { commandMenu: { cursor: number }; commands: { cursor: number } } {
1055
+ const menu = { cursor };
1056
+ return { commandMenu: menu, commands: menu };
1057
+ }
1058
+
1059
+ type NoteInput = Extract<TuiInput, { readonly kind: "note" }>;
1060
+
1061
+ function noteUnits(input: NoteInput): string[] {
1062
+ return graphemes(input.text);
1063
+ }
1064
+
1065
+ /** The cursor in a note, in display characters; the end for an older state. */
1066
+ function noteCursor(input: NoteInput): number {
1067
+ const units = noteUnits(input);
1068
+ const at = Math.trunc(input.cursor ?? units.length);
1069
+ return Math.min(Math.max(0, Number.isFinite(at) ? at : units.length), units.length);
1070
+ }
1071
+
1072
+ function clampAt(units: readonly string[], at: number): number {
1073
+ return Math.min(Math.max(0, Math.trunc(at)), units.length);
1074
+ }
1075
+
1076
+ /** The display indexes where the line around `at` starts and ends. */
1077
+ function lineBounds(units: readonly string[], at: number): { readonly start: number; readonly end: number } {
1078
+ let start = at;
1079
+ while (start > 0 && units[start - 1] !== "\n") start -= 1;
1080
+ let end = at;
1081
+ while (end < units.length && units[end] !== "\n") end += 1;
1082
+ return { start, end };
1083
+ }
1084
+
1085
+ function previousWord(units: readonly string[], at: number): number {
1086
+ let index = at;
1087
+ while (index > 0 && /\s/u.test(units[index - 1] ?? "")) index -= 1;
1088
+ while (index > 0 && !/\s/u.test(units[index - 1] ?? "")) index -= 1;
1089
+ return index;
1090
+ }
1091
+
1092
+ function nextWord(units: readonly string[], at: number): number {
1093
+ let index = at;
1094
+ while (index < units.length && !/\s/u.test(units[index] ?? "")) index += 1;
1095
+ while (index < units.length && /\s/u.test(units[index] ?? "")) index += 1;
1096
+ return index;
1097
+ }
1098
+
1099
+ function moveLine(units: readonly string[], at: number, delta: number): number {
1100
+ const line = lineBounds(units, at);
1101
+ const column = at - line.start;
1102
+ if (delta < 0) {
1103
+ if (line.start === 0) return 0;
1104
+ const before = lineBounds(units, line.start - 1);
1105
+ return Math.min(before.start + column, before.end);
1106
+ }
1107
+ if (line.end >= units.length) return units.length;
1108
+ const after = lineBounds(units, line.end + 1);
1109
+ return Math.min(after.start + column, after.end);
1110
+ }
1111
+
1112
+ /** A note's text after an edit: the cursor stays where the person put it. */
1113
+ function withNoteEdit(
1114
+ state: TuiState,
1115
+ input: NoteInput,
1116
+ text: string,
1117
+ cursor: number,
1118
+ menu = true,
1119
+ ): TuiState {
1120
+ const units = graphemes(text);
1121
+ const at = clampAt(units, cursor);
1122
+ const base = { ...input, text, cursor: at, error: undefined, commandMenu: undefined, commands: undefined };
1123
+ if (!menu || state.object === undefined || !text.startsWith("/") || /\s/.test(text)) {
1124
+ return { ...state, input: base };
1125
+ }
1126
+ const commands = chatCommands(state.object.actions, state.object.row);
1127
+ if (filterCommands(text.slice(1), commands).length === 0) return { ...state, input: base };
1128
+ return { ...state, input: { ...base, ...noteMenu(0) } };
1129
+ }
1130
+
1131
+ /** Pasted text as a note takes it: line breaks kept, other control bytes dropped. */
1132
+ function pasteText(text: string): string {
1133
+ return text
1134
+ .replace(/\r\n?/g, "\n")
1135
+ .replace(/\t/g, " ")
1136
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "");
1137
+ }
1138
+
1139
+ /** A paste reaches the note or a form's text at its cursor; it never sends. */
1140
+ export function pasteInto(state: TuiState, text: string): TuiState {
1141
+ const input = state.input;
1142
+ if (input?.kind === "form") {
1143
+ const clean = pasteText(text);
1144
+ if (clean === "") return state;
1145
+ return { ...state, input: { ...input, text: input.text + clean } };
1146
+ }
1147
+ if (input?.kind !== "note" || input.sending === true) return state;
1148
+ const clean = pasteText(text);
1149
+ if (clean === "") return state;
1150
+ const units = noteUnits(input);
1151
+ const at = noteCursor(input);
1152
+ const added = graphemes(clean);
1153
+ units.splice(at, 0, ...added);
1154
+ return withNoteEdit(state, input, units.join(""), at + added.length);
1155
+ }
1156
+
1157
+ function closeNoteMenu(
1158
+ state: TuiState,
1159
+ input: Extract<TuiInput, { readonly kind: "note" }>,
1160
+ ): TuiState {
1161
+ return { ...state, input: { ...input, commandMenu: undefined, commands: undefined } };
1162
+ }
1163
+
839
1164
  /** A key arrives while the palette, a note or a confirmation is open. */
840
1165
  export function inputKey(
841
1166
  state: TuiState,
@@ -863,8 +1188,14 @@ export function inputKey(
863
1188
  confirmed: true,
864
1189
  });
865
1190
  }
866
- if (escape) return { ...state, input: undefined };
1191
+ if (escape) {
1192
+ return input.kind === "note" && input.commandMenu !== undefined
1193
+ ? closeNoteMenu(state, input)
1194
+ : { ...state, input: undefined };
1195
+ }
1196
+ if (input.kind === "note" && input.sending === true) return state;
867
1197
  if (input.kind === "answer") return answerKey(state, input, key, enter);
1198
+ if (input.kind === "form") return formKey(state, input, event, key, enter);
868
1199
  if (input.kind === "setting") return settingKey(state, input, event, key, enter);
869
1200
  if (input.kind === "args") return argsKey(state, input, event, key, enter);
870
1201
  if (input.kind === "palette") {
@@ -897,12 +1228,71 @@ export function inputKey(
897
1228
  ? state
898
1229
  : { ...state, input: { ...input, query: input.query + text, cursor: 0 } };
899
1230
  }
900
- // A note: Enter sends, Shift-Enter or Ctrl-J adds a line.
1231
+ // A note: Enter sends, Shift-Enter or Ctrl-J adds a line. While a line that
1232
+ // starts with `/` names a command, the list takes the arrows and Enter picks.
1233
+ const units = noteUnits(input);
1234
+ let at = noteCursor(input);
1235
+ const move = (cursor: number): TuiState => ({
1236
+ ...state,
1237
+ input: { ...input, cursor: clampAt(units, cursor) },
1238
+ });
1239
+ const left = key === "left" || key === "arrowleft";
1240
+ const right = key === "right" || key === "arrowright";
1241
+ if (left || right) {
1242
+ const word = event.meta === true || event.ctrl === true;
1243
+ const cursor = word
1244
+ ? left ? previousWord(units, at) : nextWord(units, at)
1245
+ : at + (left ? -1 : 1);
1246
+ return move(cursor);
1247
+ }
1248
+ if (key === "home" || (event.ctrl === true && key === "a")) return move(lineBounds(units, at).start);
1249
+ if (key === "end" || (event.ctrl === true && key === "e")) return move(lineBounds(units, at).end);
1250
+ if (key === "delete") {
1251
+ if (at >= units.length) return state;
1252
+ units.splice(at, 1);
1253
+ return withNoteEdit(state, input, units.join(""), at);
1254
+ }
1255
+ if (key === "backspace") {
1256
+ if (at === 0) return state;
1257
+ units.splice(at - 1, 1);
1258
+ return withNoteEdit(state, input, units.join(""), at - 1);
1259
+ }
901
1260
  const newline = (enter && event.shift === true) || (event.ctrl === true && (key === "j" || key === "linefeed")) || key === "linefeed";
902
- if (newline) return { ...state, input: { ...input, text: `${input.text}\n` } };
1261
+ if (newline) {
1262
+ const added = graphemes("\n");
1263
+ units.splice(at, 0, ...added);
1264
+ return withNoteEdit(state, input, units.join(""), at + added.length);
1265
+ }
1266
+ if (input.commandMenu !== undefined) {
1267
+ const entries = commandEntries(state);
1268
+ const down = key === "down" || key === "arrowdown" || (event.ctrl === true && (key === "n" || key === "j"));
1269
+ const up = key === "up" || key === "arrowup" || (event.ctrl === true && (key === "p" || key === "k"));
1270
+ if (down || up) {
1271
+ const cursor = Math.min(
1272
+ Math.max(0, input.commandMenu.cursor + (down ? 1 : -1)),
1273
+ Math.max(0, entries.length - 1),
1274
+ );
1275
+ return { ...state, input: { ...input, ...noteMenu(cursor) } };
1276
+ }
1277
+ if (enter) {
1278
+ const chosen = entries[Math.min(input.commandMenu.cursor, entries.length - 1)];
1279
+ // A line that already spells the chosen command is sent now, not filled
1280
+ // again; a line that matches no command is sent as written.
1281
+ const filled = chosen === undefined ? undefined : commandText(chosen);
1282
+ if (filled !== undefined && filled !== input.text) {
1283
+ return withNoteEdit(state, input, filled, graphemes(filled).length, false);
1284
+ }
1285
+ }
1286
+ }
1287
+ if (key === "up" || key === "arrowup" || key === "down" || key === "arrowdown") {
1288
+ return move(moveLine(units, at, key === "up" || key === "arrowup" ? -1 : 1));
1289
+ }
903
1290
  if (enter) {
904
1291
  const note = input.text;
905
1292
  if (note.trim() === "" && input.required) return withNotice(state, "a note is required");
1293
+ if (input.answer !== undefined) {
1294
+ return sendAnswer(state, input.answer.answer, input.answer.choice, note);
1295
+ }
906
1296
  if (input.confirm) {
907
1297
  return {
908
1298
  ...state,
@@ -922,9 +1312,12 @@ export function inputKey(
922
1312
  ...(input.args === undefined ? {} : { args: input.args }),
923
1313
  });
924
1314
  }
925
- if (key === "backspace") return { ...state, input: { ...input, text: dropLast(input.text) } };
926
1315
  const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
927
- return text === undefined ? state : { ...state, input: { ...input, text: input.text + text } };
1316
+ if (text === undefined) return state;
1317
+ const added = graphemes(text);
1318
+ at = noteCursor(input);
1319
+ units.splice(at, 0, ...added);
1320
+ return withNoteEdit(state, input, units.join(""), at + added.length);
928
1321
  }
929
1322
 
930
1323
  /**
@@ -933,8 +1326,19 @@ export function inputKey(
933
1326
  * is dropped too.
934
1327
  */
935
1328
  export function actionFailed(state: TuiState, message: string): TuiState {
1329
+ const line = refusalLine(message);
1330
+ const cleared = dropOptimistic(state);
1331
+ if (cleared.input?.kind === "note" && cleared.input.sending === true) {
1332
+ return {
1333
+ ...cleared,
1334
+ input: { ...cleared.input, sending: false, error: line },
1335
+ acting: false,
1336
+ actionRequest: undefined,
1337
+ answerRequest: undefined,
1338
+ };
1339
+ }
936
1340
  return {
937
- ...withNotice(state, refusalLine(message)),
1341
+ ...withNotice(cleared, line),
938
1342
  acting: false,
939
1343
  actionRequest: undefined,
940
1344
  answerRequest: undefined,