@tiens.nguyen/gu-cli 1.0.843 → 1.0.845

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.
@@ -223,3 +223,19 @@ export function embedNotice({ state, model } = {}) {
223
223
  if (state === "off" && model) return `⚠ RAG is switched off — ${model} is set · /embed-model turns it on`;
224
224
  return "⚠ no embed model — RAG is off · /embed-model";
225
225
  }
226
+
227
+ /**
228
+ * WHICH SETUP ROWS THE BOTTOM BAR SHOWS (first-run noise, #188). A fresh install used to stack
229
+ * three warnings at once. Now they come in order of need, and pure (no OS-specific logic):
230
+ * - nothing to answer with → ONLY "coding model not set" (the one thing to do first);
231
+ * - a coding model exists but no agent model → the agent row (the coding model stands in);
232
+ * - no embed model → NOTHING until embedding was actually needed (`embedNeeded`: the agent tried
233
+ * a RAG tool, or the user opened /embed-model), then the embed row.
234
+ */
235
+ export function setupNoticeRows({ noModel = false, agentMissing = false, embedMissing = false, embedNeeded = false, embedWhy } = {}) {
236
+ if (noModel) return ["⚠ coding model not set · /model"];
237
+ return [
238
+ ...(agentMissing ? ["⚠ agent model not set — using the coding model · /agent-model"] : []),
239
+ ...(embedMissing && embedNeeded ? [embedNotice(embedWhy) || "⚠ no embed model — RAG is off · /embed-model"] : []),
240
+ ];
241
+ }
@@ -6662,6 +6662,13 @@ def _looks_like_timeout(err) -> bool:
6662
6662
  return isinstance(err, TimeoutError) or "timed out" in str(err or "").lower()
6663
6663
 
6664
6664
 
6665
+ # What to tell the user/model to use when RAG can't run. NEVER the bare word "grep": on Windows 11
6666
+ # there is no grep, and people read it as the shell command. grep_repo is gu's own tool (pure Python
6667
+ # re + file walk), so it works the same on Windows, macOS and Linux. (issue #186)
6668
+ _NO_RAG_ALTERNATIVE = ("the built-in code search instead (grep_repo / read_file_lines — they run "
6669
+ "inside gu, so no shell grep is needed, also on Windows 11)")
6670
+
6671
+
6665
6672
  def _rag_embed_failure_hint(err) -> str:
6666
6673
  """One line a user can act on, from an embedding failure.
6667
6674
 
@@ -14343,20 +14350,26 @@ def run_agent_chat(cfg):
14343
14350
  the wrong place. The embedding model is the usual one and has no fallback: chat
14344
14351
  and code model servers don't embed, so nothing can stand in for it.
14345
14352
  """
14353
+ # #188: the terminal keeps the embed warning off the bar until embedding is actually
14354
+ # needed — this is that moment. A step, so it works when the agent is on another machine.
14355
+ try:
14356
+ _emit({"type": "step", "text": "__EMBEDNEEDED__::" + ("rag-off" if not rag_enabled else "no-embedder")})
14357
+ except Exception: # noqa: BLE001
14358
+ pass
14346
14359
  if not rag_enabled:
14347
14360
  return ("Error: RAG is turned off for this account — enable it in "
14348
- "Settings -> Agent -> RAG. Use grep_repo/read_file_lines instead.")
14361
+ "Settings -> Agent -> RAG. Meanwhile, use " + _NO_RAG_ALTERNATIVE + ".")
14349
14362
  if not rag_embed_base:
14350
14363
  if _CLIENT_MODE:
14351
14364
  # This machine runs the agent but hosts no models — `doctor` here can't
14352
14365
  # help, and pointing the user at it would waste their time.
14353
- return ("Error: EMBEDDING MODEL NOT FOUND — this machine runs the agent but "
14366
+ return ("Error: the RAG embedding model is not set up here — this machine runs the agent but "
14354
14367
  "hosts no models, so there is no embedder here. RAG runs on your MODEL "
14355
- "machine; use grep_repo / read_file_lines for this project instead.")
14356
- return ("Error: EMBEDDING MODEL NOT FOUND — no embedding server is configured, "
14357
- "and there is no fallback (chat/code model servers cannot embed). Set the "
14368
+ "machine; for this project, use " + _NO_RAG_ALTERNATIVE + ".")
14369
+ return ("Error: the RAG embedding model is not set up yet — no embedding server is "
14370
+ "configured, and chat/code model servers cannot stand in for it. Set the "
14358
14371
  "embedding model folder in Settings -> Agent -> RAG, or run "
14359
- "`gu-cli doctor` to download and start it. Use grep_repo meanwhile.")
14372
+ "`gu-cli doctor` to download and start it. Meanwhile, use " + _NO_RAG_ALTERNATIVE + ".")
14360
14373
  if not _RAG_LOCAL:
14361
14374
  return ("Error: cloud RAG needs AWS credentials in Settings -> Agent -> RAG "
14362
14375
  "(or switch the terminal to local with /rag-cloud off).")
@@ -14837,7 +14850,7 @@ def run_agent_chat(cfg):
14837
14850
  "text": f"RAG indexing failed → {_rag_embed_failure_hint(e)}"})
14838
14851
  out = (f"Error: indexing failed: {type(e).__name__}: {e}. "
14839
14852
  f"The embedding server is {rag_embed_base or '(not configured)'} — check it is "
14840
- f"running (gu status / gu-cli doctor). Use grep_repo meanwhile.")
14853
+ f"running (gu status / gu-cli doctor). Meanwhile, use {_NO_RAG_ALTERNATIVE}.")
14841
14854
  _last_obs["text"] = out
14842
14855
  return out
14843
14856
 
@@ -14858,7 +14871,7 @@ def run_agent_chat(cfg):
14858
14871
  query, ((a, r) for a, r, _e in _rag_iter_text_files(root)))
14859
14872
  except Exception as e: # noqa: BLE001
14860
14873
  msg = (f"RAG is unavailable ({why}) and the keyword fallback failed: "
14861
- f"{type(e).__name__}: {e}. Use grep_repo(pattern) / read_file_lines.")
14874
+ f"{type(e).__name__}: {e}. Use {_NO_RAG_ALTERNATIVE}.")
14862
14875
  _last_obs["text"] = msg
14863
14876
  return msg
14864
14877
  _search_tally_bump("grep", res["hits"], " | ".join(res["terms"]) or query)
@@ -16176,7 +16189,8 @@ def run_agent_chat(cfg):
16176
16189
  return ""
16177
16190
  if not (_interactive_approval and _job_id and worker_api_base and worker_api_key):
16178
16191
  return ("The browser needs the user's permission and this session cannot ask. Tell the "
16179
- "user to allow it (/browser allow in the gu terminal), then carry on without it.")
16192
+ "user to run this in the gu terminal, where gu asks for permission (Allow once / Always in this folder), "
16193
+ "then carry on without it.")
16180
16194
  if _ws_request_approval(worker_api_base, worker_api_key, _job_id,
16181
16195
  f"__BROWSER__::{folder}\t{what}", "", deadline_s=180):
16182
16196
  _browser_consent["ok"] = True
@@ -16246,6 +16260,12 @@ def run_agent_chat(cfg):
16246
16260
  if refused:
16247
16261
  _last_obs["text"] = refused
16248
16262
  return refused
16263
+ if not _browser_consent.get("ext_checked"):
16264
+ # Task #401: on a new machine the extension is missing — find out, open its store
16265
+ # page, show the steps and wait for it, before falling back to gu's own window.
16266
+ _browser_consent["ext_checked"] = True
16267
+ _ext_ok, _browser_consent["ext_note"] = _gb.ensure_extension(
16268
+ log=_log, emit=lambda t: _emit({"type": "step", "text": t}))
16249
16269
  ok, res, not_connected = _gb.command(
16250
16270
  cmd, log=_log, own=True,
16251
16271
  on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
@@ -16255,9 +16275,9 @@ def run_agent_chat(cfg):
16255
16275
  _emit({"type": "step", "text": "Using gu's own Chrome window" if where == "chrome"
16256
16276
  else "Using your Chrome (gu extension)"})
16257
16277
  if not_connected:
16258
- _emit({"type": "step", "text": ("⚠ gu's browser bridge failed to start — /browser shows why"
16278
+ _emit({"type": "step", "text": ("⚠ gu's browser bridge failed to start"
16259
16279
  if str(res).startswith(_gb.BRIDGE_FAILED)
16260
- else "⚠ No browser gu can use — /browser shows why")})
16280
+ else "⚠ No browser gu can use")})
16261
16281
  msg = _gb.install_text(str(res))
16262
16282
  elif not ok:
16263
16283
  msg = f"Error: browser {a} failed: {res}"
@@ -16273,6 +16293,8 @@ def run_agent_chat(cfg):
16273
16293
  if ok and where == "chrome" and a == "open":
16274
16294
  msg = ("(gu's own Chrome window — a separate profile, not signed in to the user's "
16275
16295
  "accounts.)\n" + msg)
16296
+ if ok and where == "chrome" and _browser_consent.get("ext_note"):
16297
+ msg = _browser_consent.pop("ext_note") + "\n" + msg
16276
16298
  except Exception as ex: # noqa: BLE001
16277
16299
  msg = f"Error: browser {a} failed: {type(ex).__name__}: {ex}"
16278
16300
  _last_obs["text"] = msg
package/gu-repl.mjs CHANGED
@@ -150,8 +150,9 @@ import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.m
150
150
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
151
151
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
152
152
  import { globalPrefixOf } from "./install-path.mjs";
153
+ import { indentBlock } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189)
153
154
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
154
- import { embedNotice, embedState } from "./embed-model-command.mjs";
155
+ import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
155
156
  import {
156
157
  MODELFALLBACK_PREFIX, fallbackAfterTurn, fallbackHistoryLine, fallbackNotice, keyMissingNotice,
157
158
  parseModelFallback,
@@ -1741,10 +1742,25 @@ let embedMissing = false; // no embed model chosen → RAG is off until /embed-m
1741
1742
  let embedWhy = { state: "unset", model: "" };
1742
1743
  // One footer row; the two halves are independent so a model that IS set is never named.
1743
1744
  // ONE SHORT ROW EACH (#317): joined, they ran past 80 columns and were cut mid-word.
1744
- const missingNoticeRows = () => [
1745
- ...(agentMissing ? ["⚠ agent model not set — using the coding model · /agent-model"] : []),
1746
- ...(embedMissing ? [embedNotice(embedWhy) || "⚠ no embed model — RAG is off · /embed-model"] : []),
1747
- ];
1745
+ // FIRST-RUN QUIET (#188): no model at all → only "coding model not set"; the embed row waits
1746
+ // until embedding is actually needed (`embedNeeded`).
1747
+ let embedNeeded = false;
1748
+ const missingNoticeRows = () =>
1749
+ setupNoticeRows({ noModel: noModelAtAll, agentMissing, embedMissing, embedNeeded, embedWhy });
1750
+ async function refreshNoModelAtAll() {
1751
+ try {
1752
+ const refreshed = await fetchAgentPayload([{ role: "user", content: "." }]);
1753
+ if (refreshed?.payload) noModelAtAll = nothingToAnswerWith(refreshed.payload);
1754
+ } catch {
1755
+ /* cannot ask → keep what the bar says */
1756
+ }
1757
+ if (barPinned()) paintBar();
1758
+ }
1759
+ function markEmbedNeeded() {
1760
+ if (embedNeeded) return;
1761
+ embedNeeded = true;
1762
+ if (barPinned()) paintBar();
1763
+ }
1748
1764
 
1749
1765
  // ANOTHER MODEL STOOD IN (task #343). The agent reports it as a __MODELFALLBACK__:: step; it is
1750
1766
  // held here and shown in YELLOW on the bar — from the moment it happens, through the rest of the
@@ -7386,13 +7402,19 @@ function settingsArg(line, word) {
7386
7402
  * and gu's readline would keep reading the keys meant for the editor. Everything is switched off
7387
7403
  * first and switched back on — and the view repainted from the transcript — whatever happens.
7388
7404
  */
7389
- function withTerminalHandedOver(run) {
7405
+ function withTerminalHandedOver(run, { keepScreen = false } = {}) {
7406
+ // keepScreen — a GUI editor (Notepad, VS Code…) runs in its own window (#188): the screen, the
7407
+ // pinned bar and the scroll region stay exactly as they are. Clearing and re-cutting them was
7408
+ // the Windows 11 bug: ESC[2J pushes the screen into conhost/Windows Terminal scrollback, the
7409
+ // re-pin's newlines moved the live rows further down, and the name prompt was drawn BELOW the
7410
+ // visible window — typing showed nothing until the user scrolled down.
7390
7411
  const wasPinned = barPinned();
7391
7412
  const hadClick = _clickEnabled;
7413
+ const hadHover = _mouseEnabled;
7392
7414
  disableMouse();
7393
7415
  disableClickToPosition();
7394
7416
  ui(PASTE_MODE_OFF);
7395
- unpinBar();
7417
+ if (!keepScreen) unpinBar();
7396
7418
  const wasRaw = Boolean(process.stdin.isRaw);
7397
7419
  try {
7398
7420
  process.stdin.setRawMode?.(false);
@@ -7410,11 +7432,25 @@ function withTerminalHandedOver(run) {
7410
7432
  }
7411
7433
  rl.resume();
7412
7434
  ui(PASTE_MODE_ON);
7435
+ if (hadHover) enableMouse();
7413
7436
  if (hadClick) enableClickToPosition();
7414
- if (wasPinned) {
7415
- ui("\x1b[2J");
7437
+ // The window may have been resized while the editor ran, and no resize event reached us.
7438
+ try {
7439
+ process.stdout._refreshSize?.();
7440
+ } catch {
7441
+ /* not a TTY */
7442
+ }
7443
+ if (wasPinned && !keepScreen) {
7444
+ // HOME, then erase to the end — not ESC[2J: on Windows that scrolls the whole screen into
7445
+ // scrollback and leaves the live rows below what the user sees (#188). From row 1 the
7446
+ // first pin's newlines scroll nothing, and the repaint puts the transcript back.
7447
+ ui("\x1b[H\x1b[J");
7416
7448
  pinBar();
7417
7449
  paintLiveTail();
7450
+ } else if (wasPinned && !barPinned()) {
7451
+ pinBar();
7452
+ } else if (keepScreen && barPinned()) {
7453
+ paintBar();
7418
7454
  }
7419
7455
  }
7420
7456
  }
@@ -7565,7 +7601,7 @@ async function runOpenPresetsCommand(line) {
7565
7601
  const editor = ed.pickEditor({ readOnly: true });
7566
7602
  if (editor && process.stdin.isTTY) {
7567
7603
  console.log(GUTTER + dim(`Opening ${basename(editor.cmd)} read-only (${editor.saveHint}).`));
7568
- const r = withTerminalHandedOver(() => ed.editText(text, { editor, fileName: "gu-setup.json" }));
7604
+ const r = withTerminalHandedOver(() => ed.editText(text, { editor, fileName: "gu-setup.json" }), { keepScreen: ed.isGuiEditor(editor) });
7569
7605
  if (!r.ok) console.log(GUTTER + yellow(`couldn't show it — ${r.why}.`));
7570
7606
  } else {
7571
7607
  console.log(GUTTER + yellow(editor ? "an editor needs a terminal." : ed.NO_EDITOR_HINT + "."));
@@ -7604,7 +7640,7 @@ async function runOpenPresetsCommand(line) {
7604
7640
  console.log(GUTTER + dim(`Opening "${name}" in ${basename(editor.cmd)} — save a change, or just quit.`));
7605
7641
  let text = initial;
7606
7642
  for (;;) {
7607
- const r = withTerminalHandedOver(() => ed.editText(text, { editor, fileName: `${name}.json` }));
7643
+ const r = withTerminalHandedOver(() => ed.editText(text, { editor, fileName: `${name}.json` }), { keepScreen: ed.isGuiEditor(editor) });
7608
7644
  if (!r.ok) {
7609
7645
  console.log(GUTTER + `Not changed — ${r.why}.` + "\n");
7610
7646
  return;
@@ -7846,7 +7882,7 @@ async function fixPresetInEditor(ed, text, { editor = ed.pickEditor() } = {}) {
7846
7882
  }
7847
7883
  let t = text;
7848
7884
  for (;;) {
7849
- const r = withTerminalHandedOver(() => ed.editText(t, { editor, fileName: "preset.json" }));
7885
+ const r = withTerminalHandedOver(() => ed.editText(t, { editor, fileName: "preset.json" }), { keepScreen: ed.isGuiEditor(editor) });
7850
7886
  if (!r.ok) {
7851
7887
  console.log(GUTTER + `Not saved — ${r.why}.`);
7852
7888
  return null;
@@ -10681,6 +10717,8 @@ const RAGFILE_PREFIX = "__RAGFILE__::";
10681
10717
  // been written yet — otherwise the row would be blank and the flag would look broken, which
10682
10718
  // is exactly what happens on a client whose embedder is unreachable.
10683
10719
  const RAGSTATE_PREFIX = "__RAGSTATE__::";
10720
+ // The agent needed an embedder (a RAG tool ran) and none is set up: only now does the bar say so (#188).
10721
+ const EMBEDNEEDED_PREFIX = "__EMBEDNEEDED__::";
10684
10722
  // The tool ABOUT to run: "<label>\t<call>" (task #177). Swallowed from scrollback like
10685
10723
  // "Running → …" — it belongs to the live block, and the finished bullet replaces it.
10686
10724
  const RUNTOOL_PREFIX = "__RUNTOOL__::";
@@ -10759,7 +10797,7 @@ async function approvalPrompt(command) {
10759
10797
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
10760
10798
  process.stdout.write(
10761
10799
  "\n" + yellow("🌐 Allow gu to use a web browser?") + dim(" (no answer in ~3 min = Yes, this time)") + "\n" +
10762
- dim(` It wants to: ${what || "open a page"}`) + "\n" +
10800
+ indentBlock(`It wants to: ${what || "open a page"}`, { paint: dim }) + "\n" +
10763
10801
  dim(" In your Chrome if the gu extension is there, else in gu's own Chrome window.") + "\n"
10764
10802
  );
10765
10803
  // "Yes, this time" is THE default (#380, GitHub #167): highlighted, so Enter allows it once, and
@@ -10781,7 +10819,7 @@ async function approvalPrompt(command) {
10781
10819
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
10782
10820
  process.stdout.write(
10783
10821
  "\n" + yellow(`⚙ Allow the MCP tool ${server}/${tool}?`) + dim(" (no answer in ~3 min = No)") + "\n" +
10784
- (preview ? dim(" " + preview) + "\n" : "")
10822
+ (preview ? indentBlock(preview, { paint: dim }) + "\n" : "")
10785
10823
  );
10786
10824
  const idx = await pickFromList(
10787
10825
  ["Yes", `Yes, and always allow ${server}/${tool}`, `Yes, and always allow every ${server} tool`, "No"],
@@ -10825,8 +10863,8 @@ async function approvalPrompt(command) {
10825
10863
  return;
10826
10864
  }
10827
10865
  process.stdout.write(
10828
- "\n" + yellow("⚠ Allow running this command?") + "\n" + dim(" " + shown) + "\n" +
10829
- (why ? dim(" " + why) + "\n" : "")
10866
+ "\n" + yellow("⚠ Allow running this command?") + "\n" + indentBlock(shown, { paint: dim }) + "\n" +
10867
+ (why ? indentBlock(why, { paint: dim }) + "\n" : "")
10830
10868
  );
10831
10869
  approvalSel = 0;
10832
10870
  approvalResolve = resolve;
@@ -12558,6 +12596,11 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12558
12596
  lastContentAt = Date.now();
12559
12597
  continue;
12560
12598
  }
12599
+ if (line.startsWith(EMBEDNEEDED_PREFIX)) {
12600
+ markEmbedNeeded();
12601
+ lastContentAt = Date.now();
12602
+ continue;
12603
+ }
12561
12604
  if (line.startsWith(RAGSTATE_PREFIX)) {
12562
12605
  lastRagState = line.slice(RAGSTATE_PREFIX.length).trim();
12563
12606
  lastContentAt = Date.now();
@@ -14431,6 +14474,7 @@ async function main() {
14431
14474
  }
14432
14475
  if (line === "/model") {
14433
14476
  await chooseModel();
14477
+ await refreshNoModelAtAll(); // #188: a coding model may have just been set → drop its row
14434
14478
  continue;
14435
14479
  }
14436
14480
  if (line === "/provider" || line === "/providers") {
@@ -14439,11 +14483,13 @@ async function main() {
14439
14483
  }
14440
14484
  if (line === "/agent-model") {
14441
14485
  await chooseAgentModel();
14486
+ await refreshNoModelAtAll();
14442
14487
  agentMissing = false; // Task #14: an agent model was just chosen → clear its warning
14443
14488
  setModelFallback(null); // #343: so is the stand-in a fallback warning named
14444
14489
  continue;
14445
14490
  }
14446
14491
  if (line === "/embed-model") {
14492
+ markEmbedNeeded(); // #188: the person is asking about it — now the row is relevant
14447
14493
  await chooseEmbedModel();
14448
14494
  // Read back what is SAVED (#347). The warning used to be cleared here whatever happened —
14449
14495
  // a cancelled menu or a failed save removed it for the session, and it returned at the
package/gu_browser.py CHANGED
@@ -169,7 +169,7 @@ def install_text(reason="not connected"):
169
169
  return (f"BROWSER NOT AVAILABLE ({reason}): the gu Chrome extension (Chrome Web Store) is "
170
170
  "installed but not connected — Chrome is probably closed. STOP and ask the user to "
171
171
  "open Chrome (the extension reconnects within 30 seconds, or its icon → Connect now), "
172
- "then continue. /browser in the gu terminal shows the status.")
172
+ "then continue.")
173
173
  # gu's own Chrome window needs no extension (#150), so this is reached only when there is no
174
174
  # Chrome to start at all.
175
175
  return (
@@ -180,6 +180,201 @@ def install_text(reason="not connected"):
180
180
  + (f" To use their own Chrome instead, they can add the gu extension: {STORE_URL}" if STORE_URL else ""))
181
181
 
182
182
 
183
+ # ── a new machine: is the gu extension in Chrome at all? (task #401, GitHub #191) ──────────────
184
+ # The agent finds out itself and tells the user what to do — no command for the user to type.
185
+ STORE_ID = "ldfcjapmdbgdkdhlbdkbkiankneabagj"
186
+ EXT_NAME = "gu browser"
187
+ OFFER_EVERY_S = 24 * 3600 # open the store page at most once a day, so a "no thanks" is not nagged
188
+
189
+
190
+ def browser_roots(home=None, platform=None, env=None):
191
+ """[(browser, profiles dir)] for each Chromium browser — same list as browser-command.mjs."""
192
+ home = home or os.path.expanduser("~")
193
+ platform = platform or sys.platform
194
+ env = os.environ if env is None else env
195
+ j = os.path.join
196
+ if platform == "darwin":
197
+ a = j(home, "Library", "Application Support")
198
+ return [("Chrome", j(a, "Google", "Chrome")), ("Chrome Beta", j(a, "Google", "Chrome Beta")),
199
+ ("Chrome Canary", j(a, "Google", "Chrome Canary")), ("Chromium", j(a, "Chromium")),
200
+ ("Edge", j(a, "Microsoft Edge")), ("Brave", j(a, "BraveSoftware", "Brave-Browser"))]
201
+ if platform.startswith("win"):
202
+ l = env.get("LOCALAPPDATA") or j(home, "AppData", "Local")
203
+ return [("Chrome", j(l, "Google", "Chrome", "User Data")), ("Chrome Beta", j(l, "Google", "Chrome Beta", "User Data")),
204
+ ("Chrome Canary", j(l, "Google", "Chrome SxS", "User Data")), ("Chromium", j(l, "Chromium", "User Data")),
205
+ ("Edge", j(l, "Microsoft", "Edge", "User Data")), ("Brave", j(l, "BraveSoftware", "Brave-Browser", "User Data"))]
206
+ c = env.get("XDG_CONFIG_HOME") or j(home, ".config")
207
+ return [("Chrome", j(c, "google-chrome")), ("Chrome Beta", j(c, "google-chrome-beta")), ("Chromium", j(c, "chromium")),
208
+ ("Edge", j(c, "microsoft-edge")), ("Brave", j(c, "BraveSoftware", "Brave-Browser"))]
209
+
210
+
211
+ def _is_gu(ext_id, entry):
212
+ if ext_id == STORE_ID or (entry.get("manifest") or {}).get("name") == EXT_NAME:
213
+ return True
214
+ path = entry.get("path")
215
+ if isinstance(path, str) and os.path.isabs(path):
216
+ try:
217
+ with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f:
218
+ return json.load(f).get("name") == EXT_NAME
219
+ except (OSError, ValueError):
220
+ return False
221
+ return False
222
+
223
+
224
+ def find_installs(roots=None):
225
+ """→ [{browser, profile, id, kind: "store"|"developer", enabled}] for every browser profile with
226
+ the gu extension. Reads the profiles' Preferences only — gu never writes a browser's files."""
227
+ found = []
228
+ for browser, d in (browser_roots() if roots is None else roots):
229
+ try:
230
+ profiles = sorted(p for p in os.listdir(d) if p == "Default" or re.match(r"^Profile \d+$", p))
231
+ except OSError:
232
+ continue
233
+ for prof in profiles:
234
+ seen = set()
235
+ for fn in ("Secure Preferences", "Preferences"):
236
+ try:
237
+ with open(os.path.join(d, prof, fn), encoding="utf-8") as f:
238
+ settings = (json.load(f).get("extensions") or {}).get("settings") or {}
239
+ except (OSError, ValueError, AttributeError):
240
+ continue
241
+ for ext_id, e in settings.items():
242
+ if ext_id in seen or not isinstance(e, dict) or not _is_gu(ext_id, e):
243
+ continue
244
+ seen.add(ext_id)
245
+ reasons = e.get("disable_reasons")
246
+ enabled = not reasons and e.get("state", 1) != 0
247
+ found.append({"browser": browser, "profile": prof, "id": ext_id,
248
+ "kind": "store" if ext_id == STORE_ID else "developer", "enabled": enabled})
249
+ return found
250
+
251
+
252
+ def diagnose(installs):
253
+ """→ "missing" (not in any browser), "disabled" (only turned-off copies) or "installed"."""
254
+ if not installs:
255
+ return "missing"
256
+ return "installed" if any(i["enabled"] for i in installs) else "disabled"
257
+
258
+
259
+ def _offered_path():
260
+ return os.path.join(os.path.dirname(state_path()), "browser-extension-offered")
261
+
262
+
263
+ def should_offer(now=None):
264
+ try:
265
+ return (now or time.time()) - os.path.getmtime(_offered_path()) > OFFER_EVERY_S
266
+ except OSError:
267
+ return True
268
+
269
+
270
+ def mark_offered():
271
+ try:
272
+ os.makedirs(os.path.dirname(_offered_path()), exist_ok=True)
273
+ with open(_offered_path(), "w") as f:
274
+ f.write(str(int(time.time())))
275
+ except OSError:
276
+ pass
277
+
278
+
279
+ def open_store_page(url=None, platform=None):
280
+ """Open the extension's Chrome Web Store page — in Chrome when it is there. → whether it opened."""
281
+ url = url or STORE_URL
282
+ platform = platform or sys.platform
283
+ if not url or os.environ.get("GU_NO_OPEN_APPS"):
284
+ return False
285
+ try:
286
+ if platform == "darwin":
287
+ app = os.path.exists("/Applications/Google Chrome.app")
288
+ cmd = ["open", "-a", "Google Chrome", url] if app else ["open", url]
289
+ elif platform.startswith("win"):
290
+ cmd = ["cmd", "/c", "start", "", "chrome", url] if shutil.which("chrome") or os.path.exists(
291
+ os.path.join(os.environ.get("PROGRAMFILES", r"C:\Program Files"), "Google", "Chrome", "Application", "chrome.exe")) \
292
+ else ["explorer.exe", url]
293
+ else:
294
+ exe = next((shutil.which(n) for n in ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser")
295
+ if shutil.which(n)), None)
296
+ cmd = [exe, url] if exe else ["xdg-open", url]
297
+ subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
298
+ **({"start_new_session": True} if os.name != "nt" else {}))
299
+ return True
300
+ except OSError:
301
+ return False
302
+
303
+
304
+ def setup_steps(state, installs=(), opened=False, url=None):
305
+ """The exact steps for the user, by what was found — the transcript shows them and the model
306
+ relays them. Never a command for the user to type."""
307
+ url = url or STORE_URL
308
+ if state == "missing":
309
+ where = ("gu opened its Chrome Web Store page in Chrome." if opened
310
+ else f"Open its Chrome Web Store page in Chrome: {url}")
311
+ return ["The gu Chrome extension is not installed in Chrome on this computer.",
312
+ where,
313
+ "Click \"Add to Chrome\", then \"Add extension\" — gu connects within a few seconds",
314
+ "and then works in your Chrome (your logins, tabs you share)."]
315
+ names = ", ".join(sorted({f"{i['browser']} ({i['profile']})" for i in installs}))
316
+ if state == "disabled":
317
+ return [f"The gu Chrome extension is installed but turned off ({names}).",
318
+ "Open chrome://extensions in Chrome and switch \"gu browser\" on."]
319
+ return [f"The gu Chrome extension is installed ({names}) but not connected —",
320
+ "Chrome is closed or the extension is asleep. Open Chrome: it connects",
321
+ "within 30 s (or click the gu icon → Connect now)."]
322
+
323
+
324
+ def _mark_seen(s):
325
+ try:
326
+ with open(seen_path(), "w") as f:
327
+ json.dump({"version": s.get("version"), "installType": s.get("installType")}, f)
328
+ except OSError:
329
+ pass
330
+
331
+
332
+ def ensure_extension(log=None, emit=None, wait_s=120, installs=None):
333
+ """Prefer the user's Chrome (task #401). When the extension is not connected, find out why
334
+ (not installed / turned off / installed but Chrome closed), open the store page when it is
335
+ missing, show the steps, and wait for it to connect.
336
+ → (connected, note): note is "" when connected, else the steps for the model to relay."""
337
+ st, _ = connect(wait=False, log=log, own=True)
338
+ if not st:
339
+ return False, "" # the bridge itself failed: command() reports that
340
+ try:
341
+ s = _http(st, "GET", "/status", timeout=5)
342
+ except OSError:
343
+ return False, ""
344
+ if s.get("connected"):
345
+ return True, ""
346
+ installs = find_installs() if installs is None else installs
347
+ state = diagnose(installs)
348
+ opened = False
349
+ if state == "missing" and should_offer():
350
+ opened = open_store_page()
351
+ mark_offered()
352
+ steps = setup_steps(state, installs, opened)
353
+ say = emit or (lambda _t: None)
354
+ for line in steps:
355
+ say(line)
356
+ if log:
357
+ log(f"browser: extension {state}, store page opened={opened}")
358
+ wait_total = wait_s if opened else 30 if state == "installed" else 0
359
+ end = time.time() + wait_total
360
+ if wait_total:
361
+ say("Waiting for the gu extension to connect…")
362
+ while time.time() < end:
363
+ chunk = int(min(60, max(1, end - time.time())) * 1000)
364
+ try:
365
+ s = _http(st, "GET", f"/status?wait_ms={chunk}", timeout=chunk / 1000 + 5)
366
+ except OSError:
367
+ break
368
+ if s.get("connected"):
369
+ _mark_seen(s)
370
+ say("✓ The gu extension is connected — using your Chrome.")
371
+ return True, ""
372
+ say("Using gu's own Chrome window for now.")
373
+ return False, ("GU EXTENSION NOT CONNECTED — gu is using its own Chrome window (a separate profile, "
374
+ "not signed in) for now. Tell the user, in these words, what to do so gu can use "
375
+ "their Chrome: " + " ".join(steps))
376
+
377
+
183
378
  def _node():
184
379
  return os.environ.get("GU_NODE") or shutil.which("node") or "node"
185
380
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.843",
3
+ "version": "1.0.845",
4
4
  "description": "Gu CLI — the gu terminal plus the local worker that runs agent / OCR / PDF / embedding jobs on your Mac (Ollama / MLX / OpenAI-compatible).",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/preset-editor.mjs CHANGED
@@ -33,6 +33,17 @@ const clean = (v) => (typeof v === "string" ? v.trim() : "");
33
33
  /** GUI editors — no use in an SSH session or on a server with no display: they hang or fail. */
34
34
  const GUI_EDITORS = /^(code|code-insiders|cursor|codium|subl|sublime_text|gedit|kate|kwrite|mousepad|xed|pluma|atom|mate|zed|gvim|mvim|macvim|notepad\+\+|notepad|textedit|bbedit|open|xdg-open)(\.exe)?$/i;
35
35
 
36
+ /**
37
+ * Does `editor` open its OWN WINDOW (Notepad, VS Code, …) instead of drawing in this terminal? Such an
38
+ * editor never touches the terminal, so gu must not clear or re-cut the screen around it (#188: on
39
+ * Windows 11 that clear pushed the screen into scrollback and the name prompt was drawn below the
40
+ * visible window — "I can't type until I scroll down").
41
+ */
42
+ export function isGuiEditor(editor) {
43
+ const base = String(editor?.cmd ?? "").split(/[\\/]/).pop();
44
+ return Boolean(base) && GUI_EDITORS.test(base);
45
+ }
46
+
36
47
  /**
37
48
  * Are we in a terminal with no graphical display — an SSH session, or a Linux server? (#322: the user
38
49
  * often runs gu on an Ubuntu server over SSH.)
@@ -3214,3 +3214,17 @@ export function tokenRowWithPrice({ withTotal = "", withoutTotal = "", price = "
3214
3214
  if (visibleLen(withTotal) + visibleLen(price) <= room) return withTotal + price;
3215
3215
  return withoutTotal + price;
3216
3216
  }
3217
+
3218
+
3219
+ /**
3220
+ * Indent EVERY line of a multi-line block (#189). The "Allow running this command?" prompt used
3221
+ * `dim(" " + command)`, which indents only the first line: a multi-line command (export …, cd …,
3222
+ * mkdir …, if … fi) came out ragged, the later lines at column 0. CRLF / lone CR (a command typed on
3223
+ * Windows) is treated like LF, trailing blank lines are dropped, and each line is painted on its own
3224
+ * so a terminal that resets colour at a newline (Windows console) still shows every line dimmed.
3225
+ */
3226
+ export function indentBlock(text, { indent = " ", paint = (s) => s } = {}) {
3227
+ const lines = String(text ?? "").split(/\r\n|\r|\n/);
3228
+ while (lines.length > 1 && lines[lines.length - 1].trim() === "") lines.pop();
3229
+ return lines.map((l) => paint(indent + l)).join("\n");
3230
+ }