@tiens.nguyen/gu-cli 1.0.931 → 1.0.932

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/gu-repl.mjs CHANGED
@@ -146,7 +146,7 @@ import {
146
146
  trimWords,
147
147
  } from "./terminal-layout.mjs";
148
148
  import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
149
- import { isScaffoldStep, isGroupableStep, stepGroupMark, stepGroupRows, relativizePaths } from "./step-group.mjs";
149
+ import { isScaffoldStep, isGroupableStep, stepGroupRows, stepRowSpans, relativizePaths } from "./step-group.mjs";
150
150
  import { clearLogsNoticeText } from "./clear-logs.mjs";
151
151
  import { commandAllowedIn, commandAllowProject, commandAllowSource, commandForget, commandProjectAllowed, sourcedFileOf, PROJECT_CHOICE } from "./command-allow.mjs";
152
152
  import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
@@ -159,6 +159,7 @@ import { readHooks } from "./hooks-config.mjs";
159
159
  import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
160
160
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
161
161
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
162
+ import { focusReport, createMouseParking } from "./terminal-layout.mjs"; // GH #558
162
163
  import { createTurnQueue, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
163
164
  import { sendNote, takeUnread, sweepOldNotes, parseUserNote, questionWithNotes, USERNOTE_PREFIX } from "./turn-notes.mjs"; // GH #506: …or go to the running turn
164
165
  import { globalPrefixOf } from "./install-path.mjs";
@@ -173,6 +174,9 @@ import {
173
174
  parseModelFallback,
174
175
  } from "./model-fallback.mjs";
175
176
  import { codingChoiceTags, coderDisplayName, coderWhere, whereOfActiveCoder } from "./coding-choice-tags.mjs";
177
+ import { LSP_OFFER_MS, OFFER_CHOICES, allLanguages, applyOfferAnswer, canInstall, lspById, lspHostPath, lspStatePath, offerRows, readLspState, resolveServer, writeLspState } from "./lsp-registry.mjs";
178
+ import { AUTOCOMPACT_ASK_MS, applyChoice, autocompactPath, commandChoices, describeAutocompact, parseAutocompactArg, readAutocompact, startupChoices, startupText, writeAutocompact } from "./autocompact.mjs";
179
+ import { ghostText, shouldSuggest, suggestNext, suggestionsOnFromFile, suggestionsToggle } from "./next-suggestion.mjs";
176
180
  import { TITLE_POP, TITLE_PUSH, idleTitle, needsSummary, summariseForTitle, titleModel, titleSeq, trimTitle } from "./terminal-title.mjs";
177
181
  import { IMAGE_NEEDS_CLAUDE, coderTakesImagesFor, loadCloudImageCoders, saveCloudImageCoders, clipboardImageToFile, fitImageNotice, imageMarkersForDisplay, createImageStore, imagePasteKey, imagePathFromPaste, isClaudeCoderUrl, isImagePasteKey, storeImageFile } from "./image-paste.mjs";
178
182
  import {
@@ -602,8 +606,7 @@ const PICK_MANY_HINT = "↑/↓ · space toggles · ctrl+a all · Enter saves ·
602
606
  // grows past it). A server saved with more before the rule keeps them: see extraModelRoom.
603
607
  const MAX_ALT_CODERS = 2;
604
608
  const BULLET = "●"; // a neutral completed action (informational step)
605
- const CHECK = "✓"; // a step that succeeded
606
- const CROSS = "✗"; // a step that FAILED
609
+ const CROSS = "✗"; // a step that FAILED (one that is not a command's — those join the group, GH #530)
607
610
  const brightText = (s) => s; // default terminal colour (un-dimmed) — the "pops" text weight
608
611
  // The "spotlight the answer" hierarchy: successes and neutral steps RECEDE (dim), a FAILURE
609
612
  // POPS (red ✗ + full-bright text) — the one thing the user must not miss while everything
@@ -612,9 +615,11 @@ const brightText = (s) => s; // default terminal colour (un-dimmed) — the "pop
612
615
  // forward reference here is a startup crash, not a lint warning.
613
616
  const BULLET_STYLE = {
614
617
  fail: { mark: CROSS, markColor: red, textColor: brightText },
615
- // A look-up (grep/pgrep/rg…) that found nothing: not an error — a dim grey ✗, dim text.
616
- soft: { mark: CROSS, markColor: dim, textColor: dim },
617
- ok: { mark: CHECK, markColor: accent, textColor: dim },
618
+ // GH #530: commands (finished, failed, or a look-up that found nothing) and searches go into the
619
+ // counted group with NO mark — the ✓ in front of every one was noise. These two are what an
620
+ // ungroupable one falls back to: no mark (the slot stays a space so the text does not move).
621
+ soft: { mark: " ", markColor: dim, textColor: dim },
622
+ ok: { mark: " ", markColor: dim, textColor: dim },
618
623
  // #383 (GitHub #173): a "●" row that stands alone is the agent saying something — a warning, a
619
624
  // wait for approval — so its text is white. Look-ups and finished commands are activity and go
620
625
  // into the dim counted group instead (step-group.mjs); they never reach this style.
@@ -734,6 +739,20 @@ if (REPL_LOG) {
734
739
  console.log(dim(" --log: detailed logging is on for this run (~/.gonext/worker.log); back to minimal when gu closes."));
735
740
  }
736
741
 
742
+ // WHAT THE INSTALL DID, FIRST (GH #557 follow-up): npm hides postinstall output, so gu says what
743
+ // it changed for the user (PATH, PowerShell's `gu` alias) before anything else it prints or asks.
744
+ // On this computer's first start it also checks those itself — npm can skip install scripts.
745
+ // Done, then said; never a reason not to start.
746
+ if (process.stdout.isTTY) {
747
+ try {
748
+ const { startupSetupReport } = await import("./setup-fixes.mjs");
749
+ const text = await startupSetupReport({ here: DIR, color: true });
750
+ if (text) console.log("\n" + text.replace(/^/gm, " ") + "\n");
751
+ } catch {
752
+ /* never blocks gu */
753
+ }
754
+ }
755
+
737
756
  // THE AGENT'S PYTHON PACKAGES COME FIRST (GH #308), before the first-run setup and the terminal below create their readline and
738
757
  // raw keyboard — and before stdout is hooked for the pinned input bar (whose state does not exist yet here): the install ran from inside the live terminal and froze it on a new Windows 11 machine.
739
758
  {
@@ -1070,6 +1089,9 @@ const COMMANDS = [
1070
1089
  // has already confused the person who built both. The descriptions carry the distinction.
1071
1090
  { name: "/model", desc: "switch the CODING model (the one that writes code) for this session" },
1072
1091
  { name: "/quick-models", desc: "pick up to 2 coding models to flip between with ← / → at the prompt" },
1092
+ { name: "/lsp", desc: "language servers: the agent sees compile/type errors after each edit — status, on/off, restart" },
1093
+ { name: "/autocompact", desc: "when older steps are compacted: near 400k tokens (default), another size, or near the model's limit" },
1094
+ { name: "/suggestions", desc: "turn the suggested next message (Tab takes it) on or off" },
1073
1095
  // /provider IS NOT LISTED HERE ANY MORE — see HIDDEN_COMMANDS. It was promoted to a top-level
1074
1096
  // command when editing a provider was genuinely unreachable, and by the very next change
1075
1097
  // /model carried "add or change a provider — Claude API, OpenAI, Kimi…" as a row in EVERY branch of
@@ -1368,6 +1390,13 @@ const CLICK_TO_POSITION_ENABLED = true;
1368
1390
  // readline's own reader).
1369
1391
  const PASTE_MODE_ON = "\x1b[?2004h"; // ask the terminal to bracket pastes
1370
1392
  const PASTE_MODE_OFF = "\x1b[?2004l";
1393
+ // Focus reporting (GH #558): the terminal sends ESC[I / ESC[O as the window gains and loses
1394
+ // focus, and gu lets go of the mouse while it is away — see createMouseParking.
1395
+ const FOCUS_MODE_ON = "\x1b[?1004h";
1396
+ const FOCUS_MODE_OFF = "\x1b[?1004l";
1397
+ // Assigned next to the mouse modes it switches (further down); `let` so input that arrives
1398
+ // before then finds null instead of a TDZ error.
1399
+ let mouseParking = null;
1371
1400
  // The paste is BUFFERED here rather than passed through: readline never sees a single byte of
1372
1401
  // it, so its newlines cannot submit the turn, and at paste-end we decide what to show — a
1373
1402
  // short paste goes in literally, a long one becomes "[Pasted text #N +M lines]" with the real
@@ -1397,6 +1426,17 @@ function mouseFlush() {
1397
1426
  _mouseTimer = null;
1398
1427
  mouseReplay(mouseReader.flush());
1399
1428
  }
1429
+ /**
1430
+ * GH #558: the window gained or lost focus → let go of / take back the mouse; true = it was a
1431
+ * focus report, swallow it. Anything else that reaches _ttyWrite is someone at the window.
1432
+ */
1433
+ function onFocusOrActivity(key) {
1434
+ const focus = focusReport(key);
1435
+ if (focus === "out") mouseParking?.focusOut();
1436
+ else if (focus === "in") mouseParking?.focusIn();
1437
+ else mouseParking?.activity();
1438
+ return focus !== null;
1439
+ }
1400
1440
  const _origTtyWrite = rl._ttyWrite.bind(rl);
1401
1441
  rl._ttyWrite = (str, key) => {
1402
1442
  // A LIST PICKER OWNS EVERY KEY WHILE IT IS UP, and this has to happen HERE rather than in the
@@ -1413,7 +1453,9 @@ rl._ttyWrite = (str, key) => {
1413
1453
  // is up there is no line to edit, so anything readline does to `rl.line` — kill-to-end,
1414
1454
  // word-delete, history — is invisible work on a buffer the user cannot see, which then
1415
1455
  // surfaces the moment the picker closes.
1456
+ if (onFocusOrActivity(key)) return; // GH #558: focus in/out is not a key, whoever owns them
1416
1457
  if (listPickerActive) return;
1458
+ if (nextHint && nextHintKey(str, key)) return; // GH #536: Tab takes the suggestion
1417
1459
  if (key?.name === "paste-start") {
1418
1460
  pasteBuffer = "";
1419
1461
  return; // swallow the marker
@@ -1488,6 +1530,8 @@ rl._ttyWrite = (str, key) => {
1488
1530
  }
1489
1531
  if (verdict.action === "consume") {
1490
1532
  mouseClearTimer();
1533
+ if (verdict.focus === "out") mouseParking?.focusOut(); // the ESC-timed-out shape (GH #558)
1534
+ else if (verdict.focus === "in") mouseParking?.focusIn();
1491
1535
  if (verdict.report) applyMouseReport(verdict.report); // null: focus in/out, a win32 record
1492
1536
  return;
1493
1537
  }
@@ -1837,9 +1881,9 @@ function applyClick({ row, col }) {
1837
1881
  rl._refreshLine();
1838
1882
  }
1839
1883
  if (IS_TTY) {
1840
- ui(PASTE_MODE_ON);
1841
- // Never leave the terminal in bracketed-paste mode — the user's shell would inherit it.
1842
- process.on("exit", () => _stdoutWrite(PASTE_MODE_OFF));
1884
+ ui(PASTE_MODE_ON + FOCUS_MODE_ON);
1885
+ // Never leave the terminal in bracketed-paste or focus mode — the user's shell would inherit it.
1886
+ process.on("exit", () => _stdoutWrite(PASTE_MODE_OFF + FOCUS_MODE_OFF));
1843
1887
  }
1844
1888
 
1845
1889
  // THE TAB SAYS WHAT IS BEING WORKED ON (task #357) — see terminal-title.mjs. Until the first
@@ -1858,6 +1902,231 @@ if (TITLE_ON) {
1858
1902
  process.on("exit", () => _stdoutWrite(titleSeq("") + TITLE_POP));
1859
1903
  }
1860
1904
 
1905
+ // ---------- language servers (GH #539/#540) --------------------------------------------------
1906
+ // The choices live in ~/.gonext/lsp-state.json (the offer and /lsp write it); the worker's host
1907
+ // (lsp-host.mjs) reads it, runs the servers, and says what is running on /status.
1908
+ const loadLspState = () => {
1909
+ try {
1910
+ return readLspState(readFileSync(lspStatePath(homedir()), "utf8"));
1911
+ } catch {
1912
+ return readLspState("");
1913
+ }
1914
+ };
1915
+ function saveLspState(state) {
1916
+ try {
1917
+ mkdirSync(dirname(lspStatePath(homedir())), { recursive: true });
1918
+ writeFileSync(lspStatePath(homedir()), writeLspState(state));
1919
+ } catch (e) {
1920
+ console.log(GUTTER + yellow(`could not save the language-server choice (${e?.message || e})`));
1921
+ }
1922
+ }
1923
+
1924
+ /** Ask the worker's host something (GET /status, POST /stop). null when no worker is running it. */
1925
+ async function lspHostCall(path, body = null) {
1926
+ try {
1927
+ const { url, token } = JSON.parse(readFileSync(lspHostPath(homedir()), "utf8"));
1928
+ const res = await fetch(url + path, {
1929
+ method: body ? "POST" : "GET",
1930
+ headers: { "X-Gu-Lsp-Token": token, "Content-Type": "application/json" },
1931
+ body: body ? JSON.stringify(body) : undefined,
1932
+ signal: AbortSignal.timeout(3000),
1933
+ });
1934
+ return res.ok ? await res.json() : null;
1935
+ } catch {
1936
+ return null;
1937
+ }
1938
+ }
1939
+
1940
+ /** One line per language: the choice, whether its server is here, and what is running. */
1941
+ function lspStatusLine(row) {
1942
+ const choice = { on: "on", off: "off", never: "off (never offered)" }[row.choice] ?? "not set — offered on the first edit";
1943
+ const where = row.installing ? "installing…" : row.installError ? `install failed: ${row.installError}` : row.found ? `${row.server} found` : row.canInstall ? `${row.server} not installed (gu can install it)` : `${row.server} not found${row.hint ? ` — ${row.hint}` : ""}`;
1944
+ const running = (row.running?.length ? ` · running in ${row.running.length} project${row.running.length > 1 ? "s" : ""}` : "") +
1945
+ // A heavy server (Java, Kotlin) can take minutes to read a project the first time (GH #543).
1946
+ (row.starting?.length ? ` · starting in ${row.starting.length} project${row.starting.length > 1 ? "s" : ""} (a first start can take minutes)` : "");
1947
+ return `${row.name}: ${choice} · ${where}${running}`;
1948
+ }
1949
+
1950
+ /** /lsp — what each language server is doing, and turn one on or off. */
1951
+ async function lspCommand(arg) {
1952
+ const [verb = "", which = ""] = String(arg ?? "").trim().toLowerCase().split(/\s+/);
1953
+ const ws = resolve(process.cwd());
1954
+ const langs = allLanguages({ home: homedir(), workspace: ws });
1955
+ const live = (await lspHostCall(`/status?workspace=${encodeURIComponent(ws)}`))?.languages;
1956
+ const st = loadLspState();
1957
+ const rows = live ?? langs.map((l) => ({
1958
+ id: l.id, name: l.name, server: l.server, choice: st.languages[l.id] ?? "", hint: l.hint ?? "",
1959
+ found: Boolean(resolveServer(l, { home: homedir() })), canInstall: canInstall(l), running: [],
1960
+ }));
1961
+ const set = async (id, on) => {
1962
+ const lang = lspById(id, langs);
1963
+ if (!lang) {
1964
+ console.log(GUTTER + dim(`no language "${id}" — ${langs.map((l) => l.id).join(", ")}`) + "\n");
1965
+ return;
1966
+ }
1967
+ const next = loadLspState();
1968
+ next.languages[id] = on ? "on" : "off";
1969
+ saveLspState(next);
1970
+ if (!on) await lspHostCall("/stop", { lang: id });
1971
+ const row = rows.find((r) => r.id === id);
1972
+ console.log(GUTTER + accent(`✓ ${lang.name} code intelligence ${on ? "on" : "off"}`) +
1973
+ dim(on && row && !row.found && canInstall(lang) ? ` — gu installs ${lang.server} at the next ${lang.name} edit` : "") + "\n");
1974
+ };
1975
+ if (verb === "on" || verb === "off") return set(which, verb === "on");
1976
+ if (verb === "restart") {
1977
+ await lspHostCall("/stop", { lang: which });
1978
+ console.log(GUTTER + dim("stopped — each server starts again at the next edit of its language.") + "\n");
1979
+ return;
1980
+ }
1981
+ console.log(GUTTER + accent("Language servers") + dim(" — the agent sees compile/type errors right after each edit"));
1982
+ for (const r of rows) console.log(GUTTER + " " + dim(lspStatusLine(r)));
1983
+ if (!live) console.log(GUTTER + dim(" (the worker is not running one right now)"));
1984
+ const items = [...rows.map((r) => (r.choice === "on" ? `Turn off ${r.name}` : `Turn on ${r.name}`)), "Restart all servers"];
1985
+ const idx = await pickFromList(items, 0);
1986
+ if (idx < 0) return console.log(GUTTER + dim("(unchanged)") + "\n");
1987
+ if (idx === rows.length) {
1988
+ await lspHostCall("/stop", { lang: "" });
1989
+ return console.log(GUTTER + dim("stopped — each server starts again at the next edit of its language.") + "\n");
1990
+ }
1991
+ await set(rows[idx].id, rows[idx].choice !== "on");
1992
+ }
1993
+
1994
+ // ---------- autocompact (GH #538) ------------------------------------------------------------
1995
+ // When the agent compacts a turn's older steps: asked once per computer (no answer = 400k, all
1996
+ // models), changed with /autocompact. The agent reads the same file. See autocompact.mjs.
1997
+ const AUTOCOMPACT_FILE = autocompactPath(homedir());
1998
+ const loadAutocompact = () => {
1999
+ try {
2000
+ return readAutocompact(readFileSync(AUTOCOMPACT_FILE, "utf8"));
2001
+ } catch {
2002
+ return readAutocompact("");
2003
+ }
2004
+ };
2005
+ function saveAutocompact(state) {
2006
+ mkdirSync(dirname(AUTOCOMPACT_FILE), { recursive: true });
2007
+ writeFileSync(AUTOCOMPACT_FILE, writeAutocompact(state));
2008
+ }
2009
+
2010
+ /** The startup question — only when it has never been answered, and only on a terminal. */
2011
+ async function askAutocompactOnce() {
2012
+ if (!process.stdin.isTTY || loadAutocompact().answered) return;
2013
+ const model = activeCodingModelId();
2014
+ const { title, body } = startupText();
2015
+ console.log(GUTTER + accent(title) + dim(` (no answer in ${AUTOCOMPACT_ASK_MS / 1000}s = Apply, all models)`));
2016
+ console.log(wrapGutter(body, dim));
2017
+ const choices = startupChoices(model);
2018
+ const idx = await pickFromList(choices.map((c) => c.label), 0, { timeoutMs: AUTOCOMPACT_ASK_MS, timeoutIndex: 0 });
2019
+ // Esc (or anything that is not a row) is "not choosing" — and not choosing means the default.
2020
+ const pick = choices[idx] ?? choices[0];
2021
+ const state = applyChoice(loadAutocompact(), pick.apply, model);
2022
+ try {
2023
+ saveAutocompact(state);
2024
+ console.log(GUTTER + accent("✓ " + describeAutocompact(state, model)) + "\n");
2025
+ } catch (e) {
2026
+ console.log(GUTTER + yellow(`could not save the autocompact choice (${e?.message || e}) — gu will ask again next time.`) + "\n");
2027
+ }
2028
+ }
2029
+
2030
+ /** /autocompact [<tokens>|keep] — a picker without an argument, all models with one. */
2031
+ async function autocompactCommand(arg) {
2032
+ const model = activeCodingModelId();
2033
+ let state = loadAutocompact();
2034
+ if (String(arg ?? "").trim()) {
2035
+ const parsed = parseAutocompactArg(arg);
2036
+ if (!parsed) {
2037
+ console.log(GUTTER + dim("usage: /autocompact · /autocompact 400k · /autocompact keep") + "\n");
2038
+ return;
2039
+ }
2040
+ state = applyChoice(state, { scope: "all", cap: parsed.cap }, model);
2041
+ } else {
2042
+ console.log(GUTTER + dim(describeAutocompact(state, model)));
2043
+ const { rows, current } = commandChoices(state, model);
2044
+ const idx = await pickFromList(rows.map((r) => r.label), current);
2045
+ if (idx < 0 || !rows[idx]) {
2046
+ console.log(GUTTER + dim("(unchanged)") + "\n");
2047
+ return;
2048
+ }
2049
+ state = applyChoice(state, rows[idx].apply, model);
2050
+ }
2051
+ try {
2052
+ saveAutocompact(state);
2053
+ console.log(GUTTER + accent("✓ " + describeAutocompact(state, model)) + dim(" · from the next turn") + "\n");
2054
+ } catch (e) {
2055
+ console.log(GUTTER + yellow(`could not save it (${e?.message || e})`) + "\n");
2056
+ }
2057
+ }
2058
+
2059
+ // ---------- the next message, suggested (GH #536) -------------------------------------------
2060
+ // After SOME turns the empty input shows a dim suggestion; Tab puts it in the input. See
2061
+ // next-suggestion.mjs for when (two gates: cheap rules, then the coder answering NONE or a reply).
2062
+ const SUGGESTIONS_FILE = join(homedir(), ".gonext", "prompt-suggestions");
2063
+ let suggestionsOn = (() => {
2064
+ try {
2065
+ return suggestionsOnFromFile(readFileSync(SUGGESTIONS_FILE, "utf8"));
2066
+ } catch {
2067
+ return true; // never set: on
2068
+ }
2069
+ })();
2070
+ let nextHint = ""; // the suggestion on screen now, "" when none
2071
+ let _nextHintSeq = 0; // bumped by anything that makes a pending suggestion stale
2072
+
2073
+ /** Take the suggestion away (typing, Esc, a new question, a later turn). */
2074
+ function clearNextHint() {
2075
+ _nextHintSeq++;
2076
+ if (!nextHint) return;
2077
+ nextHint = "";
2078
+ paintBar();
2079
+ }
2080
+
2081
+ /**
2082
+ * A key while a suggestion is shown (called from _ttyWrite). Tab TAKES it into the input — not
2083
+ * sent, to edit or Enter — and the key is used up (→ true). Anything else the user does with the
2084
+ * keyboard (typing, Esc, arrows, Enter, a paste) puts it away and goes on as usual; Shift+Tab
2085
+ * (the edit mode) leaves it.
2086
+ */
2087
+ function nextHintKey(str, key) {
2088
+ if (key?.name === "tab" && !key.shift && !key.ctrl && !key.meta && promptIdleForHint()) {
2089
+ const take = nextHint;
2090
+ clearNextHint();
2091
+ rl.line = take;
2092
+ rl.cursor = take.length;
2093
+ rl._refreshLine();
2094
+ paintBar();
2095
+ return true;
2096
+ }
2097
+ const typing = (key?.name && key.name !== "tab") || (typeof str === "string" && str.length > 0 && !str.startsWith("\x1b"));
2098
+ if (typing) clearNextHint();
2099
+ return false;
2100
+ }
2101
+
2102
+ /** Is the prompt idle and empty — the only state a suggestion may be drawn into? */
2103
+ const promptIdleForHint = () =>
2104
+ barPinned() && footerActive && inputVisible && !following && rl.line === "" && !askWaiting && !secretInput
2105
+ && !inlinePrompt && !slashOverlayActive && !listPickerActive && !approvalActive && !zonePanel;
2106
+
2107
+ /**
2108
+ * After a completed turn: ask the coder it ran on for the obvious next message, in the background.
2109
+ * Fire-and-forget like the title: never delays anything, never prints, and a reply that arrives
2110
+ * after the user started typing (or asked something else) is thrown away.
2111
+ */
2112
+ function offerNextHint(question, answer) {
2113
+ clearNextHint();
2114
+ if (!shouldSuggest({ question, answer, enabled: suggestionsOn })) return;
2115
+ const mine = _nextHintSeq;
2116
+ void (async () => {
2117
+ const settings = await fetchWorkerSettings();
2118
+ if (!settings || mine !== _nextHintSeq) return;
2119
+ const target = titleModel(settings, { url: activeCodingUrl(), model: activeCodingModelId() });
2120
+ if (!target) return;
2121
+ const key = target.backendId ? await fetchKeyForBackend(target.backendId) : null;
2122
+ if (mine !== _nextHintSeq) return;
2123
+ const hint = await suggestNext({ question, answer }, { fetchImpl: doctorFetch, target, apiKey: key?.apiKey ?? "" });
2124
+ if (!hint || mine !== _nextHintSeq || !promptIdleForHint()) return;
2125
+ nextHint = hint;
2126
+ paintBar();
2127
+ })().catch(() => {});
2128
+ }
2129
+
1861
2130
  /**
1862
2131
  * A new question: the trimmed text now, and — only when it had to be cut — the agent model's
1863
2132
  * few-word summary whenever it arrives. Fire-and-forget by design: it never delays the turn,
@@ -3386,6 +3655,8 @@ function frozenZone() {
3386
3655
  // clipboard.
3387
3656
  selection: secretInput ? null : inputSelection,
3388
3657
  highlight: highlightRow,
3658
+ // GH #536: the suggested next message, while the prompt is idle and empty.
3659
+ ghost: nextHint && promptIdleForHint() ? dim(ghostText(nextHint)) : "",
3389
3660
  });
3390
3661
  const footer = footerBuilt();
3391
3662
  const rows = status.concat(notice ? [notice.row] : [], zone.rows, askHintRows(width), footer.rows);
@@ -3967,6 +4238,23 @@ const hoverCtl = createHoverController({
3967
4238
  * lines 2×", one row until it is clicked open. They differ only in how their rows are made, so
3968
4239
  * that is the one place they are told apart.
3969
4240
  */
4241
+ /**
4242
+ * One row of a step group, painted (GH #530): dim, or bright while hovered; the command count bold
4243
+ * and "1 failed" red — the only part of the row that asks to be read. Hovered, the row is one
4244
+ * bright run (the cue it opens): neighbouring spans of one colour are painted together.
4245
+ */
4246
+ const paintStepRow = (text, hovered) => {
4247
+ const plain = (s) => (hovered ? hoverThought(s) : dim(s));
4248
+ const spanPaint = { count: hovered ? plain : bold, failed: red };
4249
+ const runs = [];
4250
+ for (const sp of stepRowSpans(text)) {
4251
+ const fn = spanPaint[sp.style] ?? plain;
4252
+ if (runs.length && runs[runs.length - 1].fn === fn) runs[runs.length - 1].text += sp.text;
4253
+ else runs.push({ fn, text: sp.text });
4254
+ }
4255
+ return runs.map((x) => x.fn(x.text)).join("");
4256
+ };
4257
+
3970
4258
  const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3971
4259
  if (block.kind === "command") {
3972
4260
  // #204: the Allow prompt's command — wrapped under its own indent, long ones collapsed.
@@ -3974,12 +4262,8 @@ const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3974
4262
  return commandBlockRows(block.text, { width: commandWidth(), indent: GUTTER, collapsed, maxRows: COMMAND_COLLAPSED_ROWS }).map(paint);
3975
4263
  }
3976
4264
  if (block.kind === "steps") {
3977
- // Activity (look-ups, finished commands): dim, like a ✓ row; bright while hovered.
3978
- const paint = (r) => (hovered ? hoverThought(r) : dim(r));
3979
- const ok = stepGroupMark(block.items) === "ok";
3980
- return stepGroupRows(block.items, { width: thoughtWidth(), collapsed }).map(
3981
- (r) => (r.head ? markLine(ok ? accent(CHECK) : dim(BULLET)) : GUTTER) + paint(r.text)
3982
- );
4265
+ // Activity (look-ups, commands): dim, bright while hovered, NO mark (GH #530).
4266
+ return stepGroupRows(block.items, { width: thoughtWidth(), collapsed }).map((r) => GUTTER + paintStepRow(r.text, hovered));
3983
4267
  }
3984
4268
  // THE AGENT'S OWN WORDS ARE WHITE (#383, GitHub #173) — what it found, what it will do next.
3985
4269
  // They were grey scaffolding (#148), as dim as the commands, and the user missed them; now
@@ -4836,6 +5120,7 @@ if (process.stdin.isTTY) {
4836
5120
  // for the whole paste window; `pasteBuffer` is opened on the paste-start event, which is
4837
5121
  // fully dispatched before the first payload key arrives.
4838
5122
  if (pasteBuffer !== null) return;
5123
+ if (focusReport(key)) return; // switching windows is not typing (GH #558)
4839
5124
  // The wheel is not the keyboard (see trackMouseKey): scrolling must not count as typing,
4840
5125
  // or it undoes itself.
4841
5126
  if (trackMouseKey(_ch, key)) return;
@@ -4858,6 +5143,7 @@ if (process.stdin.isTTY) {
4858
5143
  // re-rendered the slash overlay (the line still starts with "/" from before the paste) and
4859
5144
  // re-walked the paste store. Same for a mouse report's characters, which are not keys.
4860
5145
  if (pasteBuffer !== null) return;
5146
+ if (focusReport(key)) return; // GH #558
4861
5147
  if (inMouseKeyWindow()) {
4862
5148
  turnTyping.reset(); // a held "[" was the start of that report (GH #382)
4863
5149
  return;
@@ -5042,7 +5328,7 @@ const MOUSE_OFF = "\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1006l";
5042
5328
  let _mouseEnabled = false;
5043
5329
  const enableMouse = () => {
5044
5330
  if (!hoverMouse || _mouseEnabled || !process.stdin.isTTY) return;
5045
- ui(MOUSE_ON);
5331
+ if (!mouseParking?.parked()) ui(MOUSE_ON); // away (GH #558): focus-in turns it on
5046
5332
  _mouseEnabled = true;
5047
5333
  };
5048
5334
  const disableMouse = () => {
@@ -5051,7 +5337,7 @@ const disableMouse = () => {
5051
5337
  _mouseEnabled = false;
5052
5338
  // MOUSE_OFF clears ?1000/?1006 as well, which is OUR wheel + click capture (task #141) —
5053
5339
  // put it straight back, or scrolling silently returns to the terminal after a /hover turn.
5054
- if (_clickEnabled) ui(CLICK_ON);
5340
+ if (_clickEnabled && !mouseParking?.parked()) ui(CLICK_ON);
5055
5341
  };
5056
5342
  // ---------- click-to-position the caret at the PROMPT (task #137) ------------------------
5057
5343
  // BUTTON-ONLY reporting (?1000h), NOT the any-motion ?1003h the hover feature uses: a click
@@ -5085,8 +5371,10 @@ const enableClickToPosition = () => {
5085
5371
  if (_clickEnabled || !process.stdin.isTTY) return;
5086
5372
  // Never fight the hover mode: ?1003h already reports clicks, so if it's on, leave it alone.
5087
5373
  // Bracketed paste is enabled once at startup (see the _ttyWrite wrap), not here.
5088
- if (CLICK_TO_POSITION_ENABLED && !_mouseEnabled) ui(CLICK_ON);
5374
+ if (CLICK_TO_POSITION_ENABLED && !_mouseEnabled && !mouseParking?.parked()) ui(CLICK_ON);
5089
5375
  _clickEnabled = true;
5376
+ // A new prompt starts the idle clock over SSH (GH #558) without taking a let-go mouse back.
5377
+ mouseParking?.arm();
5090
5378
  };
5091
5379
  const disableClickToPosition = () => {
5092
5380
  if (!_clickEnabled) return;
@@ -5098,6 +5386,21 @@ const disableClickToPosition = () => {
5098
5386
  _clickEnabled = false;
5099
5387
  };
5100
5388
 
5389
+ // GH #558: let go of the mouse while the window is away, so a gu that dies without exiting (an
5390
+ // SSH connection reset, kill -9) cannot leave the terminal reporting every move to the shell.
5391
+ // The idle release is for SSH only: a local gu that exits clears the modes itself.
5392
+ const MOUSE_IDLE_MS = 3 * 60 * 1000;
5393
+ mouseParking = createMouseParking({
5394
+ idleMs: process.env.SSH_CONNECTION || process.env.SSH_TTY ? MOUSE_IDLE_MS : 0,
5395
+ release: () => {
5396
+ if (_mouseEnabled || _clickEnabled) ui(MOUSE_OFF);
5397
+ },
5398
+ restore: () => {
5399
+ if (_mouseEnabled) ui(MOUSE_ON);
5400
+ else if (_clickEnabled && CLICK_TO_POSITION_ENABLED) ui(CLICK_ON);
5401
+ },
5402
+ });
5403
+ process.on("exit", () => mouseParking.stop());
5101
5404
  // Safety net: never leave the user's terminal in mouse-reporting mode (would break their
5102
5405
  // shell's selection) if we exit ungracefully.
5103
5406
  process.on("exit", disableMouse);
@@ -7837,6 +8140,7 @@ function withTerminalHandedOver(run, { keepScreen = false } = {}) {
7837
8140
  disableMouse();
7838
8141
  disableClickToPosition();
7839
8142
  ui(PASTE_MODE_OFF);
8143
+ ui(FOCUS_MODE_OFF); // an editor or pager must not receive our focus reports
7840
8144
  if (!keepScreen) unpinBar();
7841
8145
  const wasRaw = Boolean(process.stdin.isRaw);
7842
8146
  try {
@@ -7855,6 +8159,7 @@ function withTerminalHandedOver(run, { keepScreen = false } = {}) {
7855
8159
  }
7856
8160
  rl.resume();
7857
8161
  ui(PASTE_MODE_ON);
8162
+ ui(FOCUS_MODE_ON);
7858
8163
  if (hadHover) enableMouse();
7859
8164
  if (hadClick) enableClickToPosition();
7860
8165
  // The window may have been resized while the editor ran, and no resize event reached us.
@@ -11857,6 +12162,8 @@ const MCPTOOL_PREFIX = "__MCPTOOL__::";
11857
12162
  // The agent's first use of the browser in a turn (#150): "<folder>\t<what it is about to do>".
11858
12163
  // "Always" puts the folder on ~/.gonext/browser-allow.json, which the agent reads before asking.
11859
12164
  const BROWSER_PREFIX = "__BROWSER__::";
12165
+ // GH #540: the agent edited a file whose language has a server gu could use — offer it.
12166
+ const LSP_PREFIX = "__LSP__::";
11860
12167
  // How long the browser question waits before "Yes, this time" (GH #411).
11861
12168
  const BROWSER_APPROVAL_MS = 10_000;
11862
12169
  async function approvalPrompt(command) {
@@ -11916,6 +12223,42 @@ async function approvalPrompt(command) {
11916
12223
  );
11917
12224
  return { allow: idx === 0, dontAsk: false };
11918
12225
  }
12226
+ if (command.startsWith(LSP_PREFIX)) {
12227
+ // Claude Code's rules: Yes / Not now / Never for this language / Never ask; no answer in 30 s
12228
+ // counts as ignored, and after 5 ignored offers gu stops offering. Every answer is saved here —
12229
+ // the worker's host only reads the file. Only "Yes" lets the agent go on to use it now.
12230
+ const [id = "", name = "", server = "", how = "", size = ""] = command.slice(LSP_PREFIX.length).split("\t");
12231
+ const lang = lspById(id, allLanguages({ home: homedir(), workspace: resolve(process.cwd()) }));
12232
+ if (!lang || !process.stdin.isTTY) return { allow: false, dontAsk: false };
12233
+ const needsInstall = how === "install";
12234
+ const where = lang.custom
12235
+ // A project's lsp.json names a program to run — say exactly which, and from which file, so a
12236
+ // cloned repo cannot start something unseen (GH #542).
12237
+ ? ` It runs: ${[lang.command, ...lang.args].join(" ")} (set in ${lang.source.replace(homedir(), "~")}).`
12238
+ : !needsInstall
12239
+ ? " It is already on this computer — nothing to download."
12240
+ : lang.tool
12241
+ ? ` gu runs \`${lang.tool.what}\` (${size || lang.size}). It is open source (${lang.licence}).`
12242
+ : ` gu installs it from npm (${size || lang.size}, into ~/.gonext/lsp — no admin rights). It is open source (${lang.licence}).`;
12243
+ process.stdout.write(
12244
+ // GH #554: on the gutter like every other line of the turn — it sat two columns to the left.
12245
+ "\n" + GUTTER + accent(`${name} code intelligence`) + dim(` (no answer in ${LSP_OFFER_MS / 1000}s = not now)`) + "\n" +
12246
+ wrapGutter(
12247
+ `The agent just edited a ${name} file. With ${server} (a language server) it sees compile and type errors right after each edit and fixes them before it says it is done.` + where,
12248
+ dim,
12249
+ ) + "\n",
12250
+ );
12251
+ const idx = await pickFromList(offerRows(lang, { needsInstall }), 0, { timeoutMs: LSP_OFFER_MS, timeoutIndex: -2 });
12252
+ const choice = idx === -2 ? "ignored" : OFFER_CHOICES[idx] ?? "not-now";
12253
+ saveLspState(applyOfferAnswer(loadLspState(), id, choice));
12254
+ const said = {
12255
+ yes: needsInstall ? `installing ${server} — errors are checked from the next edit. /lsp shows it.` : `${name} code intelligence is on. /lsp turns it off.`,
12256
+ never: `won't offer ${name} again — /lsp turns it on.`,
12257
+ "never-ask": "won't offer language servers again — /lsp turns one on.",
12258
+ }[choice];
12259
+ if (said) process.stdout.write(GUTTER + dim(said) + "\n");
12260
+ return { allow: choice === "yes", dontAsk: false };
12261
+ }
11919
12262
  if (command.startsWith(BROWSER_PREFIX)) {
11920
12263
  const [folder = "", what = ""] = command.slice(BROWSER_PREFIX.length).split("\t");
11921
12264
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
@@ -15433,15 +15776,28 @@ async function main() {
15433
15776
  // anyway: one is already bound to the port. On loopback a 15s wait rather than an
15434
15777
  // instant refusal almost always means the API is up but stuck on MongoDB.
15435
15778
  const hung = isTimeout(err);
15779
+ // Name the storage this computer actually uses (GH #557 follow-up): a gudb computer has no
15780
+ // MongoDB, and telling its owner to look at one sends them after a program they never had.
15781
+ let onGudb = false;
15782
+ try {
15783
+ const { readLocalDb } = await import("./client-expert-api.mjs");
15784
+ onGudb = readLocalDb() === "gudb";
15785
+ } catch {
15786
+ /* unknown — say MongoDB, as before */
15787
+ }
15436
15788
  console.error(
15437
15789
  red("gu: the local API " + (hung ? "is not answering on " : "isn't running on ") + apiBase + ".") +
15438
- dim("\n Local mode keeps your conversations in MongoDB on this machine, and that") +
15439
- dim("\n API is what reads it. It does not survive a reboot on its own.\n")
15790
+ dim(
15791
+ onGudb
15792
+ ? "\n Local mode keeps your conversations in a database file on this machine, and"
15793
+ : "\n Local mode keeps your conversations in MongoDB on this machine, and that"
15794
+ ) +
15795
+ dim(onGudb ? "\n that API is what reads it. It does not survive a reboot on its own.\n" : "\n API is what reads it. It does not survive a reboot on its own.\n")
15440
15796
  );
15441
15797
  // ASK MONGODB ITSELF before telling the reader to (task #329). It can die AFTER the startup
15442
15798
  // check passed, and "is mongod running?" is a question this process answers in milliseconds.
15443
15799
  let mongoDown = "";
15444
- if (hung) {
15800
+ if (hung && !onGudb) {
15445
15801
  try {
15446
15802
  const { localMongoDown } = await import("./client-expert-run.mjs");
15447
15803
  const { localMongoUri } = await import("./client-expert-api.mjs");
@@ -15460,11 +15816,11 @@ async function main() {
15460
15816
  // Do NOT try to start it — the port is taken by the process that is failing to answer.
15461
15817
  console.error(
15462
15818
  dim(" Something IS listening there but did not reply within ") +
15463
- dim(`${API_CALL_TIMEOUT_MS / 1000}s, so the API is running and stuck —`) +
15464
- dim("\n usually on MongoDB. Check, in this order:") +
15819
+ dim(`${API_CALL_TIMEOUT_MS / 1000}s, so the API is running and stuck` + (onGudb ? "." : " —")) +
15820
+ dim(onGudb ? "\n Check, in this order:" : "\n usually on MongoDB. Check, in this order:") +
15465
15821
  dim("\n gu-cli api status does it answer at all?") +
15466
15822
  dim("\n ~/.gonext/local-api.log what it was doing when it stopped answering") +
15467
- dim("\n is mongod running? the API waits on it and never times out itself") +
15823
+ (onGudb ? "" : dim("\n is mongod running? the API waits on it and never times out itself")) +
15468
15824
  dim("\n Then restart it: gu-cli api stop && gu-cli api start\n")
15469
15825
  );
15470
15826
  } else {
@@ -15506,6 +15862,7 @@ async function main() {
15506
15862
  }
15507
15863
  delete process.env.GU_API_REOPENED; // GH #397: started — the next start may re-open again
15508
15864
  console.log(wrapGutter("Ask about this repo. Type / to see commands (Tab completes). Ctrl-C aborts a running turn.", dim) + "\n");
15865
+ await askAutocompactOnce(); // GH #538: once per computer — no answer means 400k, all models
15509
15866
  // #221: gu runs, but its own npm folder is not on PATH (npm skipped the postinstall that adds it).
15510
15867
  try {
15511
15868
  const { pathNoticeLine } = await import("./env-check.mjs");
@@ -15749,6 +16106,7 @@ async function main() {
15749
16106
  if (turnQueue.size > 0 && _lineQueue.length === 0) _lineQueue.push(turnQueue.shift());
15750
16107
  for (;;) {
15751
16108
  lineRaw = await nextLine();
16109
+ clearNextHint(); // GH #536: whatever was sent, the suggestion was for the moment before it
15752
16110
  const echoed = enterEchoed;
15753
16111
  enterEchoed = false;
15754
16112
  if (lineRaw === null || lineRaw.trim()) break;
@@ -15868,6 +16226,30 @@ async function main() {
15868
16226
  printCommands();
15869
16227
  continue;
15870
16228
  }
16229
+ if (line === "/lsp" || line.startsWith("/lsp ")) {
16230
+ await lspCommand(line.slice("/lsp".length));
16231
+ continue;
16232
+ }
16233
+ if (line === "/autocompact" || line.startsWith("/autocompact ")) {
16234
+ await autocompactCommand(line.slice("/autocompact".length));
16235
+ continue;
16236
+ }
16237
+ if (line === "/suggestions" || line.startsWith("/suggestions ")) {
16238
+ // GH #536: the suggested next message after a turn — on by default, remembered for every folder.
16239
+ suggestionsOn = suggestionsToggle(line.slice("/suggestions".length), suggestionsOn);
16240
+ try {
16241
+ mkdirSync(dirname(SUGGESTIONS_FILE), { recursive: true });
16242
+ writeFileSync(SUGGESTIONS_FILE, suggestionsOn ? "on\n" : "off\n");
16243
+ } catch {}
16244
+ if (!suggestionsOn) clearNextHint();
16245
+ console.log(
16246
+ GUTTER + (suggestionsOn ? accent("suggestions: ON") : dim("suggestions: OFF")) +
16247
+ dim(suggestionsOn
16248
+ ? " — after some answers a next message appears in the input; Tab takes it.\n"
16249
+ : " — no suggested next message after a turn. /suggestions on brings it back.\n")
16250
+ );
16251
+ continue;
16252
+ }
15871
16253
  if (line === "/hover") {
15872
16254
  // Mouse hover/click on the thinking line (#96) vs. scrolling during a turn: the terminal
15873
16255
  // only reports wheel events to US when mouse tracking is on, so they're exclusive. Off by
@@ -16446,6 +16828,8 @@ async function main() {
16446
16828
  // #343: the turn's own record of the fallback, under its answer — the bar's row can be
16447
16829
  // gone by the next turn, and the scrollback is where "which model wrote this?" is asked.
16448
16830
  if (fellBack) printFallbackLine(fellBack);
16831
+ // GH #536: maybe a suggested next message — not when a queued question runs next anyway.
16832
+ if (turnQueue.size === 0 && _lineQueue.length === 0) offerNextHint(taskLine, answer);
16449
16833
  } else {
16450
16834
  // A turn that ended WITHOUT an answer (Ctrl+C cancel, or an abort/failure) must not
16451
16835
  // silently launch another turn. Any keystrokes the user typed DURING the dead turn