happier-tui 0.1.1 → 0.2.1

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/dist/app.js CHANGED
@@ -1,13 +1,16 @@
1
1
  import { appendFileSync } from "node:fs";
2
- import { CombinedAutocompleteProvider, Editor, isKeyRelease, isKeyRepeat, Key, matchesKey, ProcessTerminal, ScrollView, truncateToWidth, TuiAltScreen, VStack, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
2
+ import { isKeyRelease, isKeyRepeat, Key, matchesKey, ProcessTerminal, ScrollView, truncateToWidth, TuiAltScreen, VStack, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
3
3
  import { HappierError, isBusy, pendingRequests, sessionModels, sessionTitle, } from "./happier/client.js";
4
- import { Transcript } from "./happier/transcript.js";
4
+ import { CLAUDE_EFFORT_LEVELS, effortOverride, isWaitingForLimit, sessionGoal, sessionModes, sessionOptions, usageLimit } from "./happier/controls.js";
5
+ import { latestOptions, Transcript } from "./happier/transcript.js";
5
6
  import { attentionChange, FOCUS_IN, FOCUS_OUT, notificationSequence, } from "./ui/notify.js";
6
7
  import { NewSessionFlow } from "./new-session.js";
7
- import { errorText, justify, machineName, questionsOf, requestSummary, shortHost } from "./ui/format.js";
8
+ import { errorText, justify, machineName, questionsOf, requestSummary, shortHost, untilText } from "./ui/format.js";
9
+ import { SessionAutocomplete } from "./ui/autocomplete.js";
10
+ import { PromptEditor } from "./ui/prompt-editor.js";
8
11
  import { Picker } from "./ui/picker.js";
9
12
  import { Home, sortSessions, statusGlyph } from "./ui/home.js";
10
- import { c, clean, editorTheme, shortPath, SPINNER } from "./ui/theme.js";
13
+ import { agoText, c, clean, editorTheme, shortPath, SPINNER } from "./ui/theme.js";
11
14
  import { TranscriptView } from "./ui/transcript-view.js";
12
15
  const PERMISSION_MODES = ["default", "read-only", "safe-yolo", "yolo", "plan"];
13
16
  /** Without input for this long the user counts as away, even if the terminal still has focus. */
@@ -15,8 +18,14 @@ const PRESENCE_IDLE_MS = 3 * 60_000;
15
18
  const LOCAL_COMMANDS = [
16
19
  { name: "sessions", description: "Back to the session list (ctrl+s)" },
17
20
  { name: "new-session", description: "Start a new agent session on a machine (ctrl+n)" },
18
- { name: "mode", description: "Change the permission mode" },
21
+ { name: "mode", description: "Change the agent mode or the permission mode" },
19
22
  { name: "model", description: "Change the model" },
23
+ { name: "effort", description: "Change the thinking level (reasoning effort)" },
24
+ { name: "rename", description: "Rename this session" },
25
+ { name: "queue", description: "Edit or cancel messages waiting to be sent" },
26
+ { name: "tree", description: "Branch into a new session from an earlier message" },
27
+ { name: "goal", description: "Show, set or clear the session's goal" },
28
+ { name: "limit", description: "After a usage limit: resume automatically, check now" },
20
29
  { name: "abort", description: "Interrupt the current turn (esc)" },
21
30
  { name: "stop-session", description: "Stop the session's agent process" },
22
31
  { name: "archive", description: "Archive this session" },
@@ -56,6 +65,7 @@ export class App {
56
65
  client;
57
66
  initialSession;
58
67
  notify;
68
+ launch;
59
69
  tui;
60
70
  view = new TranscriptView();
61
71
  scroll;
@@ -90,14 +100,26 @@ export class App {
90
100
  connection = "connecting";
91
101
  timer = null;
92
102
  commandsKey = "";
103
+ files = new Map();
104
+ /** Prompts waiting in each session's pending queue, as last fetched. */
105
+ queued = new Map();
106
+ /** The session's pending count when its queue was last fetched. */
107
+ queuedCount = new Map();
108
+ /** A queued prompt being edited in the editor; enter saves it back to the queue. */
109
+ editingQueued = null;
110
+ /** Transcript version last seen at the bottom, to tell about output arriving while scrolled up. */
111
+ seen = { id: null, version: 0 };
93
112
  resolveDone = () => { };
94
113
  done = new Promise((r) => {
95
114
  this.resolveDone = r;
96
115
  });
97
- constructor(client, initialSession, notify = { osc: true, bell: true }) {
116
+ constructor(client, initialSession, notify = { osc: true, bell: true },
117
+ /** Start a session on this computer right away instead of showing the start screen. */
118
+ launch) {
98
119
  this.client = client;
99
120
  this.initialSession = initialSession;
100
121
  this.notify = notify;
122
+ this.launch = launch;
101
123
  // The alt-screen renderer enables terminal focus reporting and consumes the focus events in
102
124
  // its own input listener, which runs before ours. Observe them at the terminal instead.
103
125
  const terminal = new ProcessTerminal();
@@ -111,7 +133,7 @@ export class App {
111
133
  scrollToEndIndicator: () => c.accent(" ↓ jump to latest "),
112
134
  });
113
135
  this.scroll = new ScrollView(this.view, { follow: "end", primary: true, scrollbar: "auto" });
114
- this.editor = new Editor(this.tui, editorTheme, { paddingX: 1 });
136
+ this.editor = new PromptEditor(this.tui, editorTheme, { paddingX: 1 });
115
137
  this.editor.onSubmit = (text) => void this.submit(text);
116
138
  this.home = new Home(() => {
117
139
  const machines = [...this.client.machines.values()];
@@ -155,6 +177,18 @@ export class App {
155
177
  { component: new Lines((w) => this.renderRequests(w)), basis: "auto", shrink: 0 },
156
178
  ]);
157
179
  this.showHome();
180
+ this.view.isBusy = () => {
181
+ const s = this.current();
182
+ return !!s && this.busy(s);
183
+ };
184
+ // Keep the clicked line where it is while what is below it unfolds.
185
+ this.view.onToggle = () => this.scroll.scrollTo(this.scroll.scrollTop, { disableFollow: true });
186
+ this.view.onOption = (option) => void this.submit(option);
187
+ this.view.onSubagent = (callId) => {
188
+ const s = this.current();
189
+ if (s)
190
+ void this.loadSubagent(s, callId);
191
+ };
158
192
  this.newSessionFlow = new NewSessionFlow({
159
193
  client: this.client,
160
194
  pick: (opts) => this.pick(opts),
@@ -192,6 +226,10 @@ export class App {
192
226
  else
193
227
  this.flash(`No session matches "${wanted}"`, "warn");
194
228
  }
229
+ else if (this.launch) {
230
+ const launch = this.launch;
231
+ this.run(() => this.newSession(launch));
232
+ }
195
233
  this.tui.requestRender();
196
234
  }
197
235
  /** Shows the start screen, which doubles as the session switcher. */
@@ -256,6 +294,8 @@ export class App {
256
294
  if (s.id === this.currentId) {
257
295
  if (isBusy(s))
258
296
  this.awaiting.delete(s.id);
297
+ if (s.pendingCount !== (this.queuedCount.get(s.id) ?? 0))
298
+ void this.refreshQueue(s);
259
299
  this.refreshCommands(s);
260
300
  this.promptForRequests(s);
261
301
  }
@@ -283,6 +323,12 @@ export class App {
283
323
  if (isAgent)
284
324
  this.unread.add(sid);
285
325
  }
326
+ else {
327
+ // The turn's last message may land after the session reported the turn over.
328
+ const s = this.current();
329
+ if (s)
330
+ this.promptForRequests(s);
331
+ }
286
332
  this.tui.requestRender();
287
333
  });
288
334
  cl.on("stream-segment", (sid, row) => {
@@ -406,9 +452,37 @@ export class App {
406
452
  this.view.hasEarlier = entry.hasEarlier;
407
453
  this.scroll.scrollToEnd();
408
454
  }
455
+ if (s.pendingCount > 0)
456
+ void this.refreshQueue(s);
409
457
  this.promptForRequests(s);
410
458
  this.tui.requestRender();
411
459
  }
460
+ async refreshQueue(s) {
461
+ this.queuedCount.set(s.id, s.pendingCount);
462
+ const list = await this.client.listQueue(s).catch(() => this.queued.get(s.id) ?? []);
463
+ this.queued.set(s.id, list);
464
+ this.tui.requestRender();
465
+ return list;
466
+ }
467
+ /** Loads a subagent's transcript the first time its tool call is shown. */
468
+ async loadSubagent(s, callId) {
469
+ const entry = this.entries.get(s.id);
470
+ if (!entry)
471
+ return;
472
+ entry.transcript.sidechain(callId); // marks it as requested
473
+ let before;
474
+ for (let page = 0; page < 10; page++) {
475
+ const res = await this.client.fetchMessages(s, { sidechainId: callId, beforeSeq: before, limit: 500 }).catch(() => null);
476
+ if (!res)
477
+ break;
478
+ for (const m of res.messages)
479
+ entry.transcript.upsert({ ...m, sidechainId: callId }, m.record);
480
+ if (!res.hasMore || res.nextBeforeSeq === null)
481
+ break;
482
+ before = res.nextBeforeSeq;
483
+ }
484
+ this.tui.requestRender();
485
+ }
412
486
  maybeLoadEarlier() {
413
487
  const s = this.current();
414
488
  const entry = s && this.entries.get(s.id);
@@ -469,7 +543,21 @@ export class App {
469
543
  if (key === this.commandsKey)
470
544
  return;
471
545
  this.commandsKey = key;
472
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...LOCAL_COMMANDS, ...remote], process.cwd()));
546
+ void this.sessionFiles(s); // warm the `@` index; a large tree takes seconds to list
547
+ this.editor.placeholder = `Message ${s.metadata.flavor ?? "the agent"} · @ files · / commands`;
548
+ this.editor.setAutocompleteProvider(new SessionAutocomplete([...LOCAL_COMMANDS, ...remote], () => this.sessionFiles(s)));
549
+ }
550
+ /** The session's file list for `@` completion, fetched once per session and kept for a minute. */
551
+ sessionFiles(s) {
552
+ const cached = this.files.get(s.id);
553
+ if (cached && Date.now() - cached.at < 60_000)
554
+ return cached.list;
555
+ const list = this.client.listFiles(s).catch((e) => {
556
+ debug(`file list for ${s.id}: ${errorText(e)}`);
557
+ return [];
558
+ });
559
+ this.files.set(s.id, { at: Date.now(), list });
560
+ return list;
473
561
  }
474
562
  // --- input ---
475
563
  /** Global keys. Returns true when the key was handled and must not reach the focused component. */
@@ -507,7 +595,15 @@ export class App {
507
595
  }
508
596
  if (matchesKey(data, Key.escape)) {
509
597
  const s = this.current();
510
- if (this.editor.isShowingAutocomplete() || !s || !this.busy(s))
598
+ if (this.editor.isShowingAutocomplete())
599
+ return false;
600
+ if (this.editingQueued) {
601
+ this.editingQueued = null;
602
+ this.editor.setText("");
603
+ this.flash("Stopped editing; the queued message is unchanged.", "info");
604
+ return true;
605
+ }
606
+ if (!s || !this.busy(s))
511
607
  return false;
512
608
  void this.abort();
513
609
  return true;
@@ -575,6 +671,20 @@ export class App {
575
671
  }
576
672
  const s = this.current();
577
673
  const entry = s && this.entries.get(s.id);
674
+ const editing = this.editingQueued;
675
+ if (s && editing?.sessionId === s.id) {
676
+ this.editingQueued = null;
677
+ try {
678
+ await this.client.editQueued(s, editing.localId, text);
679
+ this.flash("Queued message updated.", "info");
680
+ }
681
+ catch (e) {
682
+ this.editor.setText(raw);
683
+ this.flash(`Not updated: ${errorText(e)}`, "error", 8000);
684
+ }
685
+ void this.refreshQueue(s);
686
+ return;
687
+ }
578
688
  if (!s || !entry) {
579
689
  this.flash("No session open — ctrl+s for the session list.", "warn");
580
690
  this.editor.setText(raw);
@@ -619,24 +729,30 @@ export class App {
619
729
  this.flash("Reloaded.", "info");
620
730
  return;
621
731
  }
622
- case "mode": {
732
+ case "mode":
733
+ return s && this.chooseMode(s, arg);
734
+ case "effort":
735
+ return s && this.chooseEffort(s, arg);
736
+ case "rename": {
623
737
  if (!s)
624
738
  return;
625
- const current = typeof s.metadata.permissionMode === "string" ? s.metadata.permissionMode : "default";
626
- const mode = PERMISSION_MODES.includes(arg)
627
- ? arg
628
- : await this.pick({
629
- title: "Permission mode",
630
- noFilter: true,
631
- selected: current,
632
- items: PERMISSION_MODES.map((m) => ({ value: m, label: m, description: m === current ? "current" : "" })),
633
- });
634
- if (!mode)
739
+ if (!arg.trim()) {
740
+ this.editor.setText(`/rename ${sessionTitle(s)}`);
741
+ this.flash("Edit the title and press enter.", "info");
635
742
  return;
636
- await this.client.setPermissionMode(s, mode);
637
- this.flash(`Permission mode: ${mode} (applies from your next message)`, "info");
743
+ }
744
+ await this.client.rename(s, arg.trim());
745
+ this.flash(`Renamed to "${arg.trim()}".`, "info");
638
746
  return;
639
747
  }
748
+ case "queue":
749
+ return s && this.manageQueue(s);
750
+ case "tree":
751
+ return s && this.branch(s);
752
+ case "goal":
753
+ return s && this.goal(s, arg.trim());
754
+ case "limit":
755
+ return s && this.limit(s);
640
756
  case "model": {
641
757
  if (!s)
642
758
  return;
@@ -712,6 +828,202 @@ export class App {
712
828
  const ok = await this.client.abort(s);
713
829
  this.flash(ok ? "Interrupt sent." : "Nothing to interrupt (no agent attached).", ok ? "info" : "warn");
714
830
  }
831
+ // --- session controls ---
832
+ /** Agent modes (when the agent reports its own) and permission modes, in one list. */
833
+ async chooseMode(s, arg) {
834
+ const agent = sessionModes(s.metadata);
835
+ const permission = typeof s.metadata.permissionMode === "string" ? s.metadata.permissionMode : "default";
836
+ const items = [
837
+ ...agent.available.map((m) => ({
838
+ value: `agent:${m.value}`,
839
+ label: m.name,
840
+ description: ["agent mode", m.value === agent.current ? "current" : "", m.description].filter(Boolean).join(" · "),
841
+ })),
842
+ ...PERMISSION_MODES.map((m) => ({ value: `perm:${m}`, label: m, description: `permissions${m === permission ? " · current" : ""}` })),
843
+ ];
844
+ const byArg = arg && items.find((i) => i.value.endsWith(`:${arg}`) || i.label === arg)?.value;
845
+ const choice = byArg ||
846
+ (await this.pick({
847
+ title: "Mode",
848
+ noFilter: items.length < 10,
849
+ selected: agent.current ? `agent:${agent.current}` : `perm:${permission}`,
850
+ items,
851
+ }));
852
+ if (!choice)
853
+ return;
854
+ const value = choice.slice(choice.indexOf(":") + 1);
855
+ if (choice.startsWith("agent:"))
856
+ await this.client.setMode(s, value);
857
+ else
858
+ await this.client.setPermissionMode(s, value);
859
+ this.flash(`Mode: ${value} (applies from your next message)`, "info");
860
+ }
861
+ async chooseEffort(s, arg) {
862
+ const model = sessionModels(s).current;
863
+ const reported = sessionOptions(s.metadata, model).find((o) => o.id === "reasoning_effort");
864
+ // Claude takes an effort even when the session did not publish the model's levels.
865
+ const effort = reported ??
866
+ (s.metadata.flavor === "claude"
867
+ ? { current: effortOverride(s.metadata) ?? "", choices: CLAUDE_EFFORT_LEVELS.map((l) => ({ value: l, name: l })) }
868
+ : undefined);
869
+ if (!effort) {
870
+ this.flash(`${model || "This model"} does not report thinking levels.`, "warn");
871
+ return;
872
+ }
873
+ const value = effort.choices.find((ch) => ch.value === arg || ch.name.toLowerCase() === arg.toLowerCase())?.value ??
874
+ (await this.pick({
875
+ title: `Thinking level · ${model}`,
876
+ hint: reported ? undefined : "this session did not report its levels; the model may not take them all",
877
+ noFilter: true,
878
+ selected: effort.current,
879
+ items: effort.choices.map((ch) => ({ value: ch.value, label: ch.name, description: ch.value === effort.current ? "current" : "" })),
880
+ }));
881
+ if (!value || value === effort.current)
882
+ return;
883
+ await this.client.setOption(s, "reasoning_effort", value);
884
+ this.flash(`Thinking level: ${value} (applies from your next message)`, "info");
885
+ }
886
+ async manageQueue(s) {
887
+ const queued = await this.refreshQueue(s);
888
+ if (queued.length === 0) {
889
+ this.flash("No message is waiting to be sent.", "info");
890
+ return;
891
+ }
892
+ const id = await this.pick({
893
+ title: `Waiting to be sent (${queued.length})`,
894
+ items: queued.map((q) => ({
895
+ value: q.localId,
896
+ label: oneLine(q.text),
897
+ description: q.delivering ? "being delivered" : agoText(q.createdAt),
898
+ })),
899
+ });
900
+ const q = queued.find((x) => x.localId === id);
901
+ if (!q)
902
+ return;
903
+ if (q.delivering) {
904
+ this.flash("That message is already being handed to the agent; it can no longer be changed.", "info");
905
+ return;
906
+ }
907
+ const action = await this.pick({
908
+ title: oneLine(q.text),
909
+ noFilter: true,
910
+ items: [
911
+ { value: "edit", label: "Edit", description: "load it in the editor; enter saves, esc leaves it as is" },
912
+ { value: "cancel", label: "Cancel", description: "remove it from the queue" },
913
+ ],
914
+ });
915
+ if (action === "cancel") {
916
+ await this.client.cancelQueued(s, q.localId);
917
+ await this.refreshQueue(s);
918
+ this.flash("Cancelled.", "info");
919
+ }
920
+ else if (action === "edit") {
921
+ this.editingQueued = { sessionId: s.id, localId: q.localId };
922
+ this.editor.setText(q.text);
923
+ this.flash("Editing a queued message: enter saves it, esc leaves it unchanged.", "info", 10_000);
924
+ }
925
+ }
926
+ /**
927
+ * Branches the conversation into a new session, like Pi's /tree: the new session holds what
928
+ * came before the chosen message, which is put back in the editor to rewrite. Codex sessions
929
+ * can instead be rolled back in place.
930
+ */
931
+ async branch(s) {
932
+ const prompts = (this.entries.get(s.id)?.transcript.list() ?? [])
933
+ .filter((r) => r.seq !== undefined && r.items[0]?.kind === "user")
934
+ .reverse();
935
+ const textOf = (r) => (r.items[0]?.kind === "user" ? r.items[0].text : "");
936
+ const choice = await this.pick({
937
+ title: "Branch from",
938
+ hint: "a new session continues from just before the message you pick (scroll up first to reach older ones)",
939
+ maxVisible: 14,
940
+ items: [
941
+ { value: "latest", label: "The whole conversation", description: "copy everything so far" },
942
+ ...prompts.map((r) => ({ value: String(r.seq), label: oneLine(textOf(r)), description: agoText(r.createdAt) })),
943
+ ],
944
+ });
945
+ if (!choice)
946
+ return;
947
+ const row = prompts.find((r) => String(r.seq) === choice);
948
+ if (row && s.metadata.flavor === "codex" && s.active) {
949
+ const how = await this.pick({
950
+ title: oneLine(textOf(row)),
951
+ noFilter: true,
952
+ items: [
953
+ { value: "fork", label: "Branch into a new session", description: "this session stays as it is" },
954
+ { value: "rollback", label: "Roll back this session", description: "undo this message and everything after it" },
955
+ ],
956
+ });
957
+ if (!how)
958
+ return;
959
+ if (how === "rollback") {
960
+ if (!(await this.confirm("Undo this message and everything after it in this session?")))
961
+ return;
962
+ await this.client.rollback(s, row.seq);
963
+ this.entries.delete(s.id);
964
+ await this.openSession(s.id);
965
+ this.editor.setText(textOf(row));
966
+ this.flash("Rolled back; the message is back in the editor.", "info");
967
+ return;
968
+ }
969
+ }
970
+ this.flash("Creating the branch…", "info", 180_000);
971
+ const childId = await this.client.fork(s, row ? row.seq : null);
972
+ await this.client.waitForSession(childId);
973
+ this.notice = null;
974
+ await this.openSession(childId);
975
+ if (row)
976
+ this.editor.setText(textOf(row));
977
+ this.flash(row ? "New branch; rewrite the message and press enter." : "New branch with the whole conversation.", "info", 8000);
978
+ }
979
+ async goal(s, arg) {
980
+ if (arg === "clear") {
981
+ await this.client.setGoal(s, null);
982
+ this.flash("Goal cleared.", "info");
983
+ return;
984
+ }
985
+ if (arg) {
986
+ await this.client.setGoal(s, arg);
987
+ this.flash("Goal set.", "info");
988
+ return;
989
+ }
990
+ const goal = sessionGoal(s.metadata);
991
+ if (!goal) {
992
+ this.editor.setText("/goal ");
993
+ this.flash("Type the goal after /goal and press enter (Claude and Codex sessions).", "info", 8000);
994
+ return;
995
+ }
996
+ const action = await this.pick({
997
+ title: `Goal · ${goal.status}: ${oneLine(goal.title)}`,
998
+ noFilter: true,
999
+ items: [
1000
+ { value: "edit", label: "Change it" },
1001
+ { value: "clear", label: "Clear it" },
1002
+ ],
1003
+ });
1004
+ if (action === "edit")
1005
+ this.editor.setText(`/goal ${goal.title}`);
1006
+ else if (action === "clear")
1007
+ return this.goal(s, "clear");
1008
+ }
1009
+ async limit(s) {
1010
+ const u = usageLimit(s.metadata);
1011
+ const waiting = isWaitingForLimit(u);
1012
+ const action = await this.pick({
1013
+ title: waiting ? `Waiting for the usage limit${u?.resetAt ? ` to reset at ${untilText(u.resetAt)}` : ""}` : "Usage limit",
1014
+ noFilter: true,
1015
+ items: [
1016
+ ...(waiting
1017
+ ? [{ value: "waitResume.cancel", label: "Stop waiting", description: "do not resume this session by itself" }]
1018
+ : [{ value: "waitResume.enable", label: "Resume automatically", description: "continue this session when the limit resets" }]),
1019
+ { value: "checkNow", label: "Check now", description: "resume right away if the limit has reset" },
1020
+ ],
1021
+ });
1022
+ if (!action)
1023
+ return;
1024
+ const res = await this.client.usageLimitAction(s, action);
1025
+ this.flash(`Usage limit: ${String(res.status ?? "done").replace(/_/g, " ")}`, "info");
1026
+ }
715
1027
  // --- overlays ---
716
1028
  pick(opts) {
717
1029
  return new Promise((resolve) => {
@@ -738,23 +1050,53 @@ export class App {
738
1050
  });
739
1051
  return v === "yes";
740
1052
  }
1053
+ /**
1054
+ * Opens the answer picker for what the open session waits on: each permission request once,
1055
+ * and choices the agent offered once its turn ends, unless you have started typing.
1056
+ */
741
1057
  promptForRequests(s) {
742
1058
  if (this.overlay || this.mode !== "chat" || s.id !== this.currentId)
743
1059
  return;
744
1060
  const next = pendingRequests(s).find((r) => !this.prompted.has(`${s.id}:${r.id}`));
745
- if (!next)
1061
+ if (next) {
1062
+ this.prompted.add(`${s.id}:${next.id}`);
1063
+ this.run(() => this.answer(s, next));
1064
+ return;
1065
+ }
1066
+ const options = this.offeredOptions(s);
1067
+ const key = `${s.id}:options:${this.entries.get(s.id)?.transcript.maxSeq}`;
1068
+ if (options.length === 0 || this.prompted.has(key) || this.editor.getText().trim())
746
1069
  return;
747
- this.prompted.add(`${s.id}:${next.id}`);
748
- this.run(() => this.answer(s, next));
1070
+ this.prompted.add(key);
1071
+ this.run(() => this.chooseOption(options));
749
1072
  }
1073
+ /** ctrl+r: answer what the agent is waiting for: a permission request, else its offered choices. */
750
1074
  async answerRequest() {
751
1075
  const s = this.current();
752
1076
  const req = s && pendingRequests(s)[0];
753
- if (!s || !req) {
754
- this.flash("No pending permission request in this session.", "info");
1077
+ if (s && req)
1078
+ return this.answer(s, req);
1079
+ const options = s ? this.offeredOptions(s) : [];
1080
+ if (!s || options.length === 0) {
1081
+ this.flash("Nothing to answer in this session.", "info");
755
1082
  return;
756
1083
  }
757
- await this.answer(s, req);
1084
+ await this.chooseOption(options);
1085
+ }
1086
+ async chooseOption(options) {
1087
+ const choice = await this.pick({
1088
+ title: "Reply with",
1089
+ noFilter: true,
1090
+ hint: `1–${options.length} or ↑↓ enter · esc to write your own reply (ctrl+r brings this back)`,
1091
+ items: options.map((o, i) => ({ value: o, label: `${i + 1}. ${oneLine(o)}` })),
1092
+ });
1093
+ if (choice)
1094
+ await this.submit(choice);
1095
+ }
1096
+ /** Choices the agent offered at the end of its last turn, while it waits for the reply. */
1097
+ offeredOptions(s) {
1098
+ const entry = this.entries.get(s.id);
1099
+ return entry && !this.busy(s) ? latestOptions(entry.transcript) : [];
758
1100
  }
759
1101
  async answer(s, req) {
760
1102
  const questions = questionsOf(req);
@@ -790,8 +1132,8 @@ export class App {
790
1132
  return;
791
1133
  await this.client.respondPermission(s, req, choice);
792
1134
  }
793
- async newSession() {
794
- const sessionId = await this.newSessionFlow.run();
1135
+ async newSession(local) {
1136
+ const sessionId = await this.newSessionFlow.run(local);
795
1137
  if (sessionId)
796
1138
  await this.openSession(sessionId);
797
1139
  }
@@ -867,8 +1209,8 @@ export class App {
867
1209
  : c.err("○ offline — retrying");
868
1210
  let left = ` ${c.accent.bold("happier")}`;
869
1211
  if (s) {
870
- left += ` ${statusGlyph(s, this.frame)} ${c.bold(clean(sessionTitle(s)).replace(/\s+/g, " "))}`;
871
- left += c.dim(` ${s.metadata.flavor ?? "?"} · ${this.hostOf(s)} · ${shortPath(s.metadata.path, s.metadata.homeDir)}`);
1212
+ left += ` ${statusGlyph(s, this.frame)} ${c.bold.whiteBright(clean(sessionTitle(s)).replace(/\s+/g, " "))}`;
1213
+ left += c.faint(` ${s.metadata.flavor ?? "?"} · ${this.hostOf(s)} · ${shortPath(s.metadata.path, s.metadata.homeDir)}`);
872
1214
  }
873
1215
  else {
874
1216
  left += c.dim(` ${this.client.config.serverName}`);
@@ -878,8 +1220,38 @@ export class App {
878
1220
  renderRequests(width) {
879
1221
  const lines = [];
880
1222
  const s = this.current();
1223
+ const version = (s && this.entries.get(s.id)?.transcript.version) ?? 0;
1224
+ if (this.scroll.isFollowingEnd || s?.id !== this.seen.id)
1225
+ this.seen = { id: s?.id ?? null, version };
1226
+ else if (version > this.seen.version)
1227
+ lines.push(` ${c.accent("↓ new messages below")} ${c.faint("· pgdn to read")}`);
881
1228
  if (s) {
1229
+ const goal = sessionGoal(s.metadata);
1230
+ if (goal && !["complete", "cancelled"].includes(goal.status)) {
1231
+ const status = goal.reason ? `${goal.status}, ${goal.reason}` : goal.status;
1232
+ lines.push(truncateToWidth(` ${c.accent("◎")} ${c.dim(`goal (${status}):`)} ${clean(oneLine(goal.title))}`, width));
1233
+ }
1234
+ const limit = usageLimit(s.metadata);
1235
+ if (limit) {
1236
+ const when = limit.resetAt ? ` at ${untilText(limit.resetAt)}` : "";
1237
+ const text = isWaitingForLimit(limit)
1238
+ ? `Usage limit: resumes by itself${when}`
1239
+ : `Usage limit: ${limit.status}${when} · /limit`;
1240
+ lines.push(` ${c.warn("⏸")} ${c.warn(text)}`);
1241
+ }
1242
+ const queued = this.queued.get(s.id) ?? [];
1243
+ for (const q of queued.slice(0, 3)) {
1244
+ const label = q.delivering ? "⧗ sending:" : "⧗ queued:";
1245
+ lines.push(truncateToWidth(` ${c.dim(label)} ${clean(oneLine(q.text))}`, width));
1246
+ }
1247
+ if (queued.length > 0) {
1248
+ const more = queued.length > 3 ? `+${queued.length - 3} more · ` : "";
1249
+ lines.push(c.faint(` ${more}/queue to edit or cancel`));
1250
+ }
882
1251
  const reqs = pendingRequests(s);
1252
+ const offered = reqs.length === 0 ? this.offeredOptions(s).length : 0;
1253
+ if (offered > 0)
1254
+ lines.push(` ${c.accent("❯")} ${c.dim(`${offered} choices above · click one, or ctrl+r`)}`);
883
1255
  const first = reqs[0];
884
1256
  if (first) {
885
1257
  const more = reqs.length > 1 ? c.dim(` (+${reqs.length - 1} more)`) : "";
@@ -907,13 +1279,19 @@ export class App {
907
1279
  const model = sessionModels(s).current;
908
1280
  if (model)
909
1281
  parts.push(c.dim(model));
1282
+ const effort = sessionOptions(s.metadata, model).find((o) => o.id === "reasoning_effort")?.current ?? effortOverride(s.metadata);
1283
+ if (effort)
1284
+ parts.push(c.dim(`thinking ${effort}`));
910
1285
  const usage = this.entries.get(s.id)?.transcript.usage;
911
1286
  if (usage?.contextUsed && usage.contextWindow) {
912
1287
  const pct = Math.round((usage.contextUsed / usage.contextWindow) * 100);
913
- parts.push((pct >= 85 ? c.warn : c.dim)(`ctx ${pct}%`));
1288
+ const of = `${tokens(usage.contextUsed)}/${tokens(usage.contextWindow)}`;
1289
+ parts.push((pct >= 85 ? c.warn : c.dim)(`context ${pct}% (${of})`));
914
1290
  }
915
- if (s.pendingCount > 0)
916
- parts.push(c.dim(`${s.pendingCount} queued`));
1291
+ else if (usage?.contextUsed)
1292
+ parts.push(c.dim(`context ${tokens(usage.contextUsed)}`));
1293
+ if (usage?.cost)
1294
+ parts.push(c.dim(`$${usage.cost.toFixed(2)}`));
917
1295
  let state;
918
1296
  if (this.busy(s))
919
1297
  state = c.warn(`${SPINNER[this.frame % SPINNER.length]} working`) + c.dim(" · esc to interrupt");
@@ -921,10 +1299,20 @@ export class App {
921
1299
  state = c.dim("inactive · sending resumes it");
922
1300
  else
923
1301
  state = c.ok("ready");
924
- return [justify(` ${state}${c.dim(" · ")}${parts.join(c.dim(" · "))}`, c.dim("ctrl+s sessions · /keys "), width)];
1302
+ const right = `${this.busy(s) ? "" : `last activity ${agoText(s.activityAt)} · `}ctrl+s sessions · /keys `;
1303
+ return [justify(` ${state}${c.dim(" · ")}${parts.join(c.dim(" · "))}`, c.faint(right), width)];
925
1304
  }
926
1305
  }
927
1306
  const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1307
+ const oneLine = (text) => text.replace(/\s+/g, " ").trim();
1308
+ /** 126443 → "126k", 1000000 → "1M". */
1309
+ function tokens(n) {
1310
+ if (n >= 1_000_000)
1311
+ return `${Number((n / 1_000_000).toFixed(1))}M`;
1312
+ if (n >= 1000)
1313
+ return `${Math.round(n / 1000)}k`;
1314
+ return String(n);
1315
+ }
928
1316
  function isDirect(s) {
929
1317
  return isObj(s.metadata.directSessionV1) && s.seq === 0;
930
1318
  }