@tiens.nguyen/gu-cli 1.0.931 → 1.0.935
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/autocompact.mjs +136 -0
- package/browser-bridge.mjs +8 -0
- package/browser-extension/README.md +4 -0
- package/browser-extension/actions.js +366 -5
- package/browser-extension/background.js +104 -14
- package/browser-extension/manifest.json +1 -1
- package/browser-extension/popup.html +83 -15
- package/browser-extension/popup.js +145 -35
- package/clear-state.mjs +12 -1
- package/cli-token.mjs +6 -3
- package/client-expert-api.mjs +109 -20
- package/client-expert-run.mjs +263 -120
- package/client-expert-setup.mjs +3 -2
- package/coding-provider-setup.mjs +27 -0
- package/free-model.mjs +33 -6
- package/gonext_agent_chat.py +748 -27
- package/gu-cli.mjs +90 -6
- package/gu-repl.mjs +545 -29
- package/gu_browser.py +83 -9
- package/gu_gif.py +101 -0
- package/gu_turn_notes.py +29 -2
- package/install-path.mjs +52 -20
- package/lsp-client.mjs +267 -0
- package/lsp-host.mjs +391 -0
- package/lsp-registry.mjs +568 -0
- package/model-doctor.mjs +34 -7
- package/model-prices.mjs +22 -0
- package/next-suggestion.mjs +137 -0
- package/package.json +10 -1
- package/powershell-alias.mjs +12 -1
- package/python-unix.mjs +120 -0
- package/setup-fixes.mjs +245 -0
- package/step-group.mjs +59 -18
- package/terminal-layout.mjs +82 -3
- package/turn-notes.mjs +65 -0
- package/win-shell.mjs +26 -0
package/autocompact.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AUTOCOMPACT (GH #538) — when the agent compacts a turn's older steps. Pure; gu-repl.mjs asks.
|
|
3
|
+
*
|
|
4
|
+
* The agent compacts at 2/3 of the model's context window (_compact_threshold in
|
|
5
|
+
* gonext_agent_chat.py). For a 1M-token model that is ~666k: every step of a long session resends
|
|
6
|
+
* hundreds of thousands of tokens — slow and costly, for no gain on most tasks. So gu asks once,
|
|
7
|
+
* like Claude Code's "Autocompact now defaults to 400k tokens": apply 400k to every model, to the
|
|
8
|
+
* current one only, or keep the old rule. NO ANSWER MEANS 400K FOR ALL MODELS.
|
|
9
|
+
*
|
|
10
|
+
* The choice is ~/.gonext/autocompact.json, read by the agent on this computer:
|
|
11
|
+
* { "all": 400000 | null, "models": { "<model id>": 400000 | null }, "answeredAt": "…" }
|
|
12
|
+
* A model's own entry wins over "all"; null means "keep" (the 2/3 rule alone). The agent only
|
|
13
|
+
* ever LOWERS its threshold to the cap: a model with a smaller window is unaffected.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
export const AUTOCOMPACT_DEFAULT = 400_000;
|
|
19
|
+
/** What /autocompact offers besides "keep". */
|
|
20
|
+
export const AUTOCOMPACT_SIZES = [200_000, 400_000, 600_000];
|
|
21
|
+
/** Below this a cap would leave the model too little room to work; the agent ignores it too. */
|
|
22
|
+
export const AUTOCOMPACT_MIN = 16_000;
|
|
23
|
+
/** The startup question answers itself after this long (no answer = 400k, all models). */
|
|
24
|
+
export const AUTOCOMPACT_ASK_MS = 30_000;
|
|
25
|
+
|
|
26
|
+
export const autocompactPath = (home) => join(home, ".gonext", "autocompact.json");
|
|
27
|
+
|
|
28
|
+
const modelKey = (model) => String(model ?? "").trim().toLowerCase();
|
|
29
|
+
const validCap = (v) => (v === null ? null : Number.isFinite(Number(v)) && Number(v) >= AUTOCOMPACT_MIN ? Math.round(Number(v)) : undefined);
|
|
30
|
+
|
|
31
|
+
/** The saved choice from the file's text; `answered` is false when there is none yet. */
|
|
32
|
+
export function readAutocompact(text) {
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = JSON.parse(String(text ?? ""));
|
|
36
|
+
} catch {
|
|
37
|
+
return { answered: false, all: null, models: {} };
|
|
38
|
+
}
|
|
39
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { answered: false, all: null, models: {} };
|
|
40
|
+
const models = {};
|
|
41
|
+
for (const [k, v] of Object.entries(raw.models && typeof raw.models === "object" ? raw.models : {})) {
|
|
42
|
+
const c = validCap(v);
|
|
43
|
+
if (c !== undefined && modelKey(k)) models[modelKey(k)] = c;
|
|
44
|
+
}
|
|
45
|
+
const all = validCap(raw.all);
|
|
46
|
+
return { answered: true, all: all === undefined ? null : all, models };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The file's text for a state. */
|
|
50
|
+
export const writeAutocompact = (state, now = new Date()) =>
|
|
51
|
+
JSON.stringify({ all: state.all ?? null, models: state.models ?? {}, answeredAt: now.toISOString() }, null, 2) + "\n";
|
|
52
|
+
|
|
53
|
+
/** The cap for a model (0 = none: the 2/3 rule alone). Mirrors _autocompact_cap in the agent. */
|
|
54
|
+
export function capFor(state, model) {
|
|
55
|
+
const k = modelKey(model);
|
|
56
|
+
const v = k && state?.models && k in state.models ? state.models[k] : state?.all;
|
|
57
|
+
return Number(v) >= AUTOCOMPACT_MIN ? Number(v) : 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** "400k", "1.5M" — how a threshold is said. */
|
|
61
|
+
export function tokensLabel(n) {
|
|
62
|
+
const v = Number(n) || 0;
|
|
63
|
+
if (v >= 1_000_000) return `${+(v / 1_000_000).toFixed(1)}M`;
|
|
64
|
+
return `${Math.round(v / 1000)}k`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The startup question's rows. The first is the default: highlighted, and what silence means. */
|
|
68
|
+
export function startupChoices(model) {
|
|
69
|
+
const name = String(model ?? "").trim();
|
|
70
|
+
return [
|
|
71
|
+
{ label: "Apply (all models)", apply: { scope: "all", cap: AUTOCOMPACT_DEFAULT } },
|
|
72
|
+
...(name ? [{ label: `Apply (${name} only)`, apply: { scope: "model", cap: AUTOCOMPACT_DEFAULT } }] : []),
|
|
73
|
+
{ label: "Keep (near the model's limit)", apply: { scope: "all", cap: null } },
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The startup question's words. */
|
|
78
|
+
export function startupText() {
|
|
79
|
+
return {
|
|
80
|
+
title: `Autocompact at ${tokensLabel(AUTOCOMPACT_DEFAULT)} tokens`,
|
|
81
|
+
body:
|
|
82
|
+
`gu will compact older steps near ${tokensLabel(AUTOCOMPACT_DEFAULT)} tokens instead of near the model's limit ` +
|
|
83
|
+
"(about 666k on a 1M model). Quality should stay the same for most tasks, at lower usage and cost — " +
|
|
84
|
+
"especially on long sessions. Change it any time with /autocompact.",
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A choice applied to the saved state → the new state.
|
|
90
|
+
* `scope: "all"` sets every model (and drops per-model entries); `"model"` sets one model only —
|
|
91
|
+
* the others keep what they had (on a first answer: no cap, the old rule).
|
|
92
|
+
*/
|
|
93
|
+
export function applyChoice(state, { scope, cap }, model) {
|
|
94
|
+
const base = { all: state?.answered ? state.all ?? null : null, models: { ...(state?.models ?? {}) } };
|
|
95
|
+
if (scope === "model" && modelKey(model)) {
|
|
96
|
+
base.models[modelKey(model)] = cap;
|
|
97
|
+
return { answered: true, ...base };
|
|
98
|
+
}
|
|
99
|
+
return { answered: true, all: cap, models: {} };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** /autocompact's rows for a model: each size and keep, for this model or all, with the current one marked. */
|
|
103
|
+
export function commandChoices(state, model) {
|
|
104
|
+
const name = String(model ?? "").trim();
|
|
105
|
+
const own = modelKey(model) && state?.models && modelKey(model) in state.models;
|
|
106
|
+
const want = { scope: own ? "model" : "all", cap: own ? state.models[modelKey(model)] : state?.all ?? null };
|
|
107
|
+
const rows = [];
|
|
108
|
+
for (const cap of AUTOCOMPACT_SIZES) {
|
|
109
|
+
rows.push({ label: `${tokensLabel(cap)} — all models`, apply: { scope: "all", cap } });
|
|
110
|
+
if (name) rows.push({ label: `${tokensLabel(cap)} — ${name} only`, apply: { scope: "model", cap } });
|
|
111
|
+
}
|
|
112
|
+
rows.push({ label: "Keep — near the model's limit (all models)", apply: { scope: "all", cap: null } });
|
|
113
|
+
if (name) rows.push({ label: `Keep — near the model's limit (${name} only)`, apply: { scope: "model", cap: null } });
|
|
114
|
+
const current = rows.findIndex((r) => r.apply.scope === want.scope && (r.apply.cap ?? null) === (want.cap ?? null));
|
|
115
|
+
return { rows, current: Math.max(0, current) };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** `/autocompact 400k`, `/autocompact 250000`, `/autocompact keep` → { cap } (all models), or null when not understood. */
|
|
119
|
+
export function parseAutocompactArg(arg) {
|
|
120
|
+
const a = String(arg ?? "").trim().toLowerCase();
|
|
121
|
+
if (!a) return null;
|
|
122
|
+
if (a === "keep" || a === "off") return { cap: null };
|
|
123
|
+
const m = /^(\d+(?:\.\d+)?)\s*(k|m)?$/.exec(a);
|
|
124
|
+
if (!m) return null;
|
|
125
|
+
const n = Number(m[1]) * (m[2] === "m" ? 1_000_000 : m[2] === "k" ? 1000 : 1);
|
|
126
|
+
return n >= AUTOCOMPACT_MIN ? { cap: Math.round(n) } : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One line saying what applies to a model now. */
|
|
130
|
+
export function describeAutocompact(state, model) {
|
|
131
|
+
const cap = capFor(state, model);
|
|
132
|
+
const who = String(model ?? "").trim() || "this model";
|
|
133
|
+
return cap
|
|
134
|
+
? `autocompact: ${who} compacts older steps near ${tokensLabel(cap)} tokens (or sooner, at 2/3 of a smaller window).`
|
|
135
|
+
: `autocompact: ${who} compacts older steps near its limit (2/3 of its context window).`;
|
|
136
|
+
}
|
package/browser-bridge.mjs
CHANGED
|
@@ -90,6 +90,9 @@ export function startBridge({ port = DEFAULT_PORT, token = randomBytes(24).toStr
|
|
|
90
90
|
let lastUse = Date.now();
|
|
91
91
|
const refused = new Map(); // extension id → when a second copy was turned away (#148)
|
|
92
92
|
const sockets = new Set(); // every upgraded socket, so close() can end them all
|
|
93
|
+
// GH #551: the Stop button in the extension. A counter, not a flag: the running agent remembers
|
|
94
|
+
// the value it started with and stops when it goes up, so an old press never stops a new turn.
|
|
95
|
+
let stops = 0;
|
|
93
96
|
|
|
94
97
|
const hostOk = (h) => /^(127\.0\.0\.1|localhost)(:\d+)?$/i.test(String(h || ""));
|
|
95
98
|
|
|
@@ -167,8 +170,10 @@ export function startBridge({ port = DEFAULT_PORT, token = randomBytes(24).toStr
|
|
|
167
170
|
ownChrome: Boolean(own?.running),
|
|
168
171
|
refused: [...refused].filter(([id, at]) => at > since && !(ext && id === extId(ext.origin))).map(([id, at]) => ({ id, at })),
|
|
169
172
|
pid: process.pid,
|
|
173
|
+
stops,
|
|
170
174
|
});
|
|
171
175
|
}
|
|
176
|
+
if (req.method === "GET" && url.pathname === "/stop") return json(200, { stops });
|
|
172
177
|
if (req.method === "POST" && url.pathname === "/cmd") {
|
|
173
178
|
let body = "";
|
|
174
179
|
for await (const c of req) body += c;
|
|
@@ -252,6 +257,9 @@ export function startBridge({ port = DEFAULT_PORT, token = randomBytes(24).toStr
|
|
|
252
257
|
ext.installType = msg.installType || null;
|
|
253
258
|
}
|
|
254
259
|
for (const w of [...waiters]) w(true);
|
|
260
|
+
} else if (msg.type === "stop" && ext?.socket === socket) {
|
|
261
|
+
stops += 1;
|
|
262
|
+
log(`the user pressed Stop in Chrome (${stops})`);
|
|
255
263
|
} else if (msg.id !== undefined && pending.has(msg.id)) {
|
|
256
264
|
const p = pending.get(msg.id);
|
|
257
265
|
pending.delete(msg.id);
|
|
@@ -36,6 +36,10 @@ browser-bridge.mjs 127.0.0.1:4127, started on demand, outlives the turn
|
|
|
36
36
|
- **`/browser allow` / `/browser forget`** stop or restart the question for this folder.
|
|
37
37
|
- **Share a tab** (extension only): click the gu icon on a tab, then **Let gu use this tab**. The tab joins the "gu" group and the agent can use it. **Stop sharing this tab** takes it back.
|
|
38
38
|
- **Turning it off:** `GU_BROWSER=0` in the worker's environment removes the tool.
|
|
39
|
+
- **The popup (GH #551):** click the gu icon in Chrome's toolbar (not the purple "gu" tab group label, which folds the group). It shows what gu is doing or did last and in which tab, gu's tabs (**Show**, **Close** / **Unshare**), and sharing for the current tab. Typed text is never shown.
|
|
40
|
+
- **Stop gu** (in the popup, while gu has a tab open) ends the turn like Ctrl+C: the extension tells the bridge, the running agent cancels its own job, and the terminal says "(cancelled — the agent was stopped)". Until that turn's cleanup, the extension refuses its commands.
|
|
41
|
+
- **A folded "gu" group:** Chrome stops drawing a folded group's tabs, and they take no mouse or key input. gu unfolds the group before such input, and any input that still gets no answer fails after 10 s with the reason.
|
|
42
|
+
- **Developer copies reload themselves:** `reload_self` (sent by gu) reloads an unpacked copy after its files change; the store copy is never touched.
|
|
39
43
|
|
|
40
44
|
### The extension, to use your own Chrome (optional)
|
|
41
45
|
|
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
// No chrome.* and no Node API in here: it runs in an extension service worker and in Node.
|
|
17
17
|
|
|
18
18
|
const consoleBuf = new Map(); // tabId → [{level, text}] since the last "console" read
|
|
19
|
+
const resized = new Map(); // tabId → the size gu set (GH #549), undone at the end of the turn
|
|
20
|
+
const choosers = new Map(); // tabId → backendNodeId of a file chooser the page just opened (GH #547)
|
|
21
|
+
const netBuf = new Map(); // tabId → Map(requestId → request) since the last "network" read (GH #546)
|
|
22
|
+
export const NET_KEEP = 300; // per tab: the oldest go first
|
|
23
|
+
export const NET_SHOW = 50; // rows in one answer
|
|
19
24
|
const dialogs = new Map(); // tabId → [text] of alerts/confirms gu accepted
|
|
20
25
|
const freshErrors = new Map(); // tabId → errors not yet reported after a command
|
|
21
26
|
|
|
@@ -26,20 +31,130 @@ export function sleep(ms) {
|
|
|
26
31
|
export function forgetTab(tabId) {
|
|
27
32
|
frameScripts.delete(tabId);
|
|
28
33
|
consoleBuf.delete(tabId);
|
|
34
|
+
netBuf.delete(tabId);
|
|
35
|
+
resized.delete(tabId);
|
|
29
36
|
freshErrors.delete(tabId);
|
|
30
37
|
dialogs.delete(tabId);
|
|
31
38
|
}
|
|
32
39
|
|
|
33
|
-
function pushConsole(tabId, level,
|
|
40
|
+
function pushConsole(tabId, level, message) {
|
|
41
|
+
const text = maskText(message); // before any cut, so a cut never leaves half a secret unmatched
|
|
34
42
|
const buf = consoleBuf.get(tabId) || [];
|
|
35
|
-
buf.push({ level, text:
|
|
43
|
+
buf.push({ level, text: text.slice(0, 500) });
|
|
36
44
|
if (buf.length > 100) buf.splice(0, buf.length - 100);
|
|
37
45
|
consoleBuf.set(tabId, buf);
|
|
38
|
-
if (level === "error") freshErrors.set(tabId, [...(freshErrors.get(tabId) || []),
|
|
46
|
+
if (level === "error") freshErrors.set(tabId, [...(freshErrors.get(tabId) || []), text.slice(0, 300)].slice(-5));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── network requests (GH #546) ─────────────────────────────────────────────────────────────
|
|
50
|
+
// What Claude Code's read_network_requests gives: which calls a page made and how they ended — the
|
|
51
|
+
// fastest answer to "the button does nothing" (a 500 from /api/login, a CORS refusal, a 404).
|
|
52
|
+
// Never headers, cookies or bodies (only one failed response's body, on request); secrets in URLs
|
|
53
|
+
// are masked.
|
|
54
|
+
const SECRET_PARAM = /^(access_?token|id_?token|refresh_?token|token|auth|authorization|api_?key|apikey|key|secret|client_?secret|password|passwd|pwd|sig|signature|code|session|sessionid|jwt)$/i;
|
|
55
|
+
|
|
56
|
+
/** A URL as the model sees it: secrets masked, data: cut, at most 160 characters. */
|
|
57
|
+
export function maskUrl(url) {
|
|
58
|
+
const raw = String(url ?? "");
|
|
59
|
+
if (/^data:/i.test(raw)) return raw.slice(0, 30) + "…";
|
|
60
|
+
let u;
|
|
61
|
+
try {
|
|
62
|
+
u = new URL(raw);
|
|
63
|
+
} catch {
|
|
64
|
+
return raw.slice(0, 160);
|
|
65
|
+
}
|
|
66
|
+
for (const k of [...u.searchParams.keys()]) if (SECRET_PARAM.test(k)) u.searchParams.set(k, "***");
|
|
67
|
+
if (u.username || u.password) {
|
|
68
|
+
u.username = "***";
|
|
69
|
+
u.password = "";
|
|
70
|
+
}
|
|
71
|
+
const out = u.href.replace(/%2A%2A%2A/g, "***");
|
|
72
|
+
return out.length > 160 ? out.slice(0, 159) + "…" : out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The same secrets, in URLs inside free text: a console message or an exception quotes the failing
|
|
77
|
+
* URL in full ("Failed to load resource … (http://…/login?token=abc)"), and it reaches the model
|
|
78
|
+
* just like a network row does. The rest of the text is left as it was.
|
|
79
|
+
*/
|
|
80
|
+
export function maskText(text) {
|
|
81
|
+
return String(text ?? "")
|
|
82
|
+
.replace(/([?&#])([A-Za-z0-9_.-]+)=([^&#\s"'<>]+)/g, (m, sep, name, value) => {
|
|
83
|
+
if (!SECRET_PARAM.test(name)) return m;
|
|
84
|
+
const tail = value.match(/\)+(?::\d+)*$|[,;]+$/)?.[0] ?? ""; // "(url?token=x)" keeps its bracket
|
|
85
|
+
return `${sep}${name}=***${tail}`;
|
|
86
|
+
})
|
|
87
|
+
.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s"'<>?#]+@/gi, "$1***@");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function netEntry(tabId, requestId) {
|
|
91
|
+
let m = netBuf.get(tabId);
|
|
92
|
+
if (!m) netBuf.set(tabId, (m = new Map()));
|
|
93
|
+
let e = m.get(requestId);
|
|
94
|
+
if (!e) {
|
|
95
|
+
e = { id: requestId };
|
|
96
|
+
m.set(requestId, e);
|
|
97
|
+
if (m.size > NET_KEEP) m.delete(m.keys().next().value);
|
|
98
|
+
}
|
|
99
|
+
return e;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function onNetworkEvent(tabId, method, p) {
|
|
103
|
+
if (method === "Network.requestWillBeSent") {
|
|
104
|
+
if (/^(data|blob|chrome-extension|devtools):/i.test(p.request?.url || "")) return;
|
|
105
|
+
const e = netEntry(tabId, p.requestId);
|
|
106
|
+
// A redirect re-uses the requestId: the earlier hop is finished, keep the latest.
|
|
107
|
+
Object.assign(e, { method: p.request?.method, url: p.request?.url, type: p.type, start: p.timestamp, status: undefined, failed: undefined });
|
|
108
|
+
} else if (method === "Network.responseReceived") {
|
|
109
|
+
const m = netBuf.get(tabId);
|
|
110
|
+
const e = m?.get(p.requestId);
|
|
111
|
+
if (!e) return;
|
|
112
|
+
Object.assign(e, { status: p.response?.status, statusText: p.response?.statusText, mime: p.response?.mimeType, type: p.type || e.type });
|
|
113
|
+
} else if (method === "Network.loadingFinished") {
|
|
114
|
+
const e = netBuf.get(tabId)?.get(p.requestId);
|
|
115
|
+
if (e) Object.assign(e, { end: p.timestamp, size: p.encodedDataLength });
|
|
116
|
+
} else if (method === "Network.loadingFailed") {
|
|
117
|
+
const e = netBuf.get(tabId)?.get(p.requestId);
|
|
118
|
+
if (!e) return;
|
|
119
|
+
const why = p.blockedReason ? `blocked (${p.blockedReason})` : p.corsErrorStatus?.corsError ? `CORS: ${p.corsErrorStatus.corsError}` : p.canceled ? "canceled" : p.errorText || "failed";
|
|
120
|
+
Object.assign(e, { end: p.timestamp, failed: why, type: p.type || e.type });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const isFailure = (e) => Boolean(e.failed && e.failed !== "canceled") || (e.status ?? 0) >= 400;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The requests as rows the model reads → { rows, total, more, failedIds }.
|
|
128
|
+
* `text`: only URLs containing it. `failed`: only requests that failed or answered ≥ 400.
|
|
129
|
+
* Pending ones say so — a request still running is often the bug.
|
|
130
|
+
*/
|
|
131
|
+
export function networkRows(entries, { text = "", failed = false } = {}) {
|
|
132
|
+
let list = [...(entries ?? [])].filter((e) => e.url);
|
|
133
|
+
if (text) list = list.filter((e) => String(e.url).toLowerCase().includes(String(text).toLowerCase()));
|
|
134
|
+
if (failed) list = list.filter(isFailure);
|
|
135
|
+
const total = list.length;
|
|
136
|
+
const shown = list.slice(-NET_SHOW);
|
|
137
|
+
const rows = shown.map((e) => {
|
|
138
|
+
const status = e.failed ? (e.failed === "canceled" ? "canceled" : "FAILED") : e.status ?? "pending";
|
|
139
|
+
const ms = e.end && e.start ? `${Math.round((e.end - e.start) * 1000)} ms` : e.status === undefined && !e.failed ? "still running" : "";
|
|
140
|
+
const kb = e.size ? `${e.size >= 1024 ? `${(e.size / 1024).toFixed(1)} KB` : `${e.size} B`}` : "";
|
|
141
|
+
const detail = [String(e.type || "").toLowerCase(), ms, kb].filter(Boolean).join(", ");
|
|
142
|
+
const why = e.failed && e.failed !== "canceled" ? ` — ${e.failed}` : (e.status ?? 0) >= 400 && e.statusText ? ` — ${e.statusText}` : "";
|
|
143
|
+
return `${e.method || "GET"} ${status} ${maskUrl(e.url)}${detail ? ` (${detail})` : ""}${why}`;
|
|
144
|
+
});
|
|
145
|
+
return { rows, total, more: Math.max(0, total - shown.length), failedIds: shown.filter(isFailure).map((e) => e.id) };
|
|
39
146
|
}
|
|
40
147
|
|
|
41
148
|
/** Every DevTools event of a tab goes through here (both hosts call it). */
|
|
42
149
|
export function onCdpEvent(tabId, method, params, cdp) {
|
|
150
|
+
if (method.startsWith("Network.")) {
|
|
151
|
+
onNetworkEvent(tabId, method, params || {});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (method === "Page.fileChooserOpened") {
|
|
155
|
+
choosers.set(tabId, params?.backendNodeId);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
43
158
|
if (method === "Runtime.consoleAPICalled") {
|
|
44
159
|
const text = (params.args || []).map((a) => (a.value !== undefined ? String(a.value) : a.description || a.type)).join(" ");
|
|
45
160
|
pushConsole(tabId, params.type === "warning" ? "warn" : params.type, text);
|
|
@@ -63,6 +178,9 @@ export async function enableDomains(cdp, tabId) {
|
|
|
63
178
|
await cdp(tabId, "Runtime.enable");
|
|
64
179
|
await cdp(tabId, "Page.enable");
|
|
65
180
|
await cdp(tabId, "Log.enable").catch(() => {});
|
|
181
|
+
// GH #546: the page's requests, for "network". Small post data and no extra info — gu reads
|
|
182
|
+
// method, URL, status and timing only.
|
|
183
|
+
await cdp(tabId, "Network.enable", { maxPostDataSize: 0 }).catch(() => {});
|
|
66
184
|
await showFrame(cdp, tabId);
|
|
67
185
|
}
|
|
68
186
|
|
|
@@ -86,6 +204,12 @@ function guFrame(mode) {
|
|
|
86
204
|
if (h) h.style.visibility = mode === "hide" ? "hidden" : "visible";
|
|
87
205
|
return true;
|
|
88
206
|
}
|
|
207
|
+
if (String(mode).startsWith("say:")) {
|
|
208
|
+
// GH #551: the label says gu's last step. Kept on the document, so a redrawn frame keeps it.
|
|
209
|
+
d.__guSay = String(mode).slice(4);
|
|
210
|
+
if (h && h.__guSay) h.__guSay(d.__guSay);
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
89
213
|
const put = () => {
|
|
90
214
|
if (d.getElementById(ID)) return;
|
|
91
215
|
h = d.createElement("div");
|
|
@@ -104,7 +228,13 @@ function guFrame(mode) {
|
|
|
104
228
|
mark.style.cssText = "background:#fff;color:#7c3aed;font:700 11px/1 -apple-system,system-ui,sans-serif;padding:3px 5px;border-radius:5px";
|
|
105
229
|
const text = d.createElement("span");
|
|
106
230
|
text.textContent = "is working here";
|
|
107
|
-
|
|
231
|
+
const step = d.createElement("span");
|
|
232
|
+
step.style.cssText = "font-weight:400;opacity:.85;max-width:46vw;overflow:hidden;text-overflow:ellipsis";
|
|
233
|
+
h.__guSay = (t) => {
|
|
234
|
+
step.textContent = t ? "· " + t : "";
|
|
235
|
+
};
|
|
236
|
+
if (d.__guSay) h.__guSay(d.__guSay);
|
|
237
|
+
pill.append(mark, text, step);
|
|
108
238
|
root.append(ring, pill);
|
|
109
239
|
(d.documentElement || d.body).appendChild(h);
|
|
110
240
|
};
|
|
@@ -261,6 +391,140 @@ async function point(host, tabId, cmd) {
|
|
|
261
391
|
throw new Error("say where: ref (a number from read) or x and y");
|
|
262
392
|
}
|
|
263
393
|
|
|
394
|
+
// ── resize: phone, tablet and desktop layouts (GH #549) ─────────────────────────────────────
|
|
395
|
+
// Only gu's tab is emulated (DevTools Emulation), never a window of the user's, and the size is
|
|
396
|
+
// undone at the end of the turn.
|
|
397
|
+
// One rule for presets and typed sizes (GH #550): touch + mobile viewport below 1024 px wide, and
|
|
398
|
+
// the pixel density of such a device — 3 for a phone, 2 for a tablet, 1 for a computer.
|
|
399
|
+
function device(width, height, mobile = width < 1024) {
|
|
400
|
+
return { width, height, mobile, scale: mobile ? (Math.min(width, height) < 600 ? 3 : 2) : 1 };
|
|
401
|
+
}
|
|
402
|
+
export const SIZES = {
|
|
403
|
+
small: device(360, 740), // a common Android phone
|
|
404
|
+
mobile: device(390, 844),
|
|
405
|
+
"mobile-landscape": device(844, 390),
|
|
406
|
+
tablet: device(820, 1180),
|
|
407
|
+
"tablet-landscape": device(1180, 820, true),
|
|
408
|
+
desktop: device(1280, 900),
|
|
409
|
+
wide: device(1440, 900),
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
/** a preset name | "reset" | "390x844" → a size, "reset", or an Error to say. */
|
|
413
|
+
export function parseSize(text) {
|
|
414
|
+
const t = String(text ?? "").trim().toLowerCase().replace(/[\s_]+/g, "-");
|
|
415
|
+
if (t === "reset" || t === "off" || t === "default") return "reset";
|
|
416
|
+
if (SIZES[t]) return { ...SIZES[t], name: t };
|
|
417
|
+
const m = /^(\d{2,4})-*[x×*,]-*(\d{2,4})$/.exec(t);
|
|
418
|
+
if (!m) return new Error(`resize needs text: ${Object.keys(SIZES).join(", ")}, reset, or a size like "375x667"`);
|
|
419
|
+
const width = Number(m[1]);
|
|
420
|
+
const height = Number(m[2]);
|
|
421
|
+
if (width < 200 || height < 200 || width > 4000 || height > 4000) return new Error("a size between 200 and 4000 px each way");
|
|
422
|
+
return { ...device(width, height), name: `${width}×${height}` };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// A tab in the background keeps its old layout until it draws a frame (seen in the user's own
|
|
426
|
+
// Chrome: reset left the page at 390 px; requestAnimationFrame and ResizeObserver never ran after
|
|
427
|
+
// a resize, so a layout built in JavaScript stayed stale). One throwaway capture draws a frame.
|
|
428
|
+
// Never waits long, never brings the tab forward.
|
|
429
|
+
async function drawFrame(host, tabId) {
|
|
430
|
+
await Promise.race([host.cdp(tabId, "Page.captureScreenshot", { format: "jpeg", quality: 1 }).catch(() => {}), sleep(4000)]);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function seenSize(host, tabId) {
|
|
434
|
+
const v = await evaluate(host, tabId, "innerWidth + '×' + innerHeight").catch(() => "");
|
|
435
|
+
return v ? String(v) : "";
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async function resizeTab(host, tabId, text) {
|
|
439
|
+
const size = parseSize(text);
|
|
440
|
+
if (size instanceof Error) throw size;
|
|
441
|
+
// Always from a clean state: an earlier phone size must not leave touch (no hover, a coarse
|
|
442
|
+
// pointer) on a desktop size set after it.
|
|
443
|
+
await host.cdp(tabId, "Emulation.clearDeviceMetricsOverride").catch(() => {});
|
|
444
|
+
await host.cdp(tabId, "Emulation.setTouchEmulationEnabled", { enabled: false }).catch(() => {});
|
|
445
|
+
if (size === "reset") {
|
|
446
|
+
await drawFrame(host, tabId);
|
|
447
|
+
resized.delete(tabId);
|
|
448
|
+
const seen = await seenSize(host, tabId);
|
|
449
|
+
return { resized: `the browser's own size again${seen ? ` (${seen})` : ""}`, viewport: seen };
|
|
450
|
+
}
|
|
451
|
+
const portrait = size.height > size.width;
|
|
452
|
+
await host.cdp(tabId, "Emulation.setDeviceMetricsOverride", {
|
|
453
|
+
width: size.width, height: size.height, deviceScaleFactor: size.scale, mobile: size.mobile,
|
|
454
|
+
screenOrientation: portrait ? { type: "portraitPrimary", angle: 0 } : { type: "landscapePrimary", angle: 90 },
|
|
455
|
+
});
|
|
456
|
+
if (size.mobile) await host.cdp(tabId, "Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 }).catch(() => {});
|
|
457
|
+
resized.set(tabId, size);
|
|
458
|
+
await drawFrame(host, tabId);
|
|
459
|
+
const seen = await seenSize(host, tabId);
|
|
460
|
+
const named = size.name.includes("×") ? size.name : `${size.name} (${size.width}×${size.height})`;
|
|
461
|
+
return { resized: `${named}${size.mobile ? ", touch" : ""}`, viewport: seen };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// ── upload a file (GH #547) ─────────────────────────────────────────────────────────────────
|
|
465
|
+
// Runs IN the page: the <input type=file> a ref means — the input itself, the label for it, an
|
|
466
|
+
// element holding one, the one in the same form — or the page's ONLY file input. Marks it and
|
|
467
|
+
// says what it is; null when there is none to find.
|
|
468
|
+
function markFileInput(ref) {
|
|
469
|
+
const isFile = (e) => e && e.tagName === "INPUT" && (e.type || "").toLowerCase() === "file";
|
|
470
|
+
const el = ref ? document.querySelector('[data-gu-ref="' + ref + '"]') : null;
|
|
471
|
+
let input = null;
|
|
472
|
+
if (el) {
|
|
473
|
+
if (isFile(el)) input = el;
|
|
474
|
+
else if (el.tagName === "LABEL" && isFile(el.control)) input = el.control;
|
|
475
|
+
else if (el.querySelector && isFile(el.querySelector("input[type=file]"))) input = el.querySelector("input[type=file]");
|
|
476
|
+
else {
|
|
477
|
+
const form = el.closest && el.closest("form, [role=dialog], section, div");
|
|
478
|
+
const near = form && form.querySelectorAll("input[type=file]");
|
|
479
|
+
if (near && near.length === 1) input = near[0];
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (!input) {
|
|
483
|
+
const all = document.querySelectorAll("input[type=file]");
|
|
484
|
+
if (all.length === 1) input = all[0];
|
|
485
|
+
}
|
|
486
|
+
if (!input) return null;
|
|
487
|
+
for (const e of document.querySelectorAll("[data-gu-upload]")) e.removeAttribute("data-gu-upload");
|
|
488
|
+
input.setAttribute("data-gu-upload", "1");
|
|
489
|
+
return { name: input.name || input.id || "", multiple: input.multiple, accept: input.accept || "" };
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Put a file into the page's file input. Through the input when one can be found (no dialog ever
|
|
494
|
+
* opens); otherwise click what was asked for with the file chooser intercepted, and answer the
|
|
495
|
+
* chooser the page opened. → { uploaded: name, into }.
|
|
496
|
+
*/
|
|
497
|
+
export async function uploadFile(host, tabId, cmd) {
|
|
498
|
+
const file = String(cmd.path || "");
|
|
499
|
+
if (!file) throw new Error("upload needs path — the file to upload");
|
|
500
|
+
const name = file.split(/[\\/]/).pop();
|
|
501
|
+
const hit = await evaluate(host, tabId, `(${markFileInput.toString()})(${hasRef(cmd) ? Number(cmd.ref) : 0})`);
|
|
502
|
+
if (hit) {
|
|
503
|
+
const doc = await host.cdp(tabId, "DOM.getDocument", { depth: 0 });
|
|
504
|
+
const q = await host.cdp(tabId, "DOM.querySelector", { nodeId: doc.root.nodeId, selector: "[data-gu-upload]" });
|
|
505
|
+
if (!q?.nodeId) throw new Error("the file input went away — read the page again");
|
|
506
|
+
await host.cdp(tabId, "DOM.setFileInputFiles", { files: [file], nodeId: q.nodeId });
|
|
507
|
+
return { uploaded: name, into: hit.name ? `file input "${hit.name}"` : "the file input" };
|
|
508
|
+
}
|
|
509
|
+
if (!hasRef(cmd) && !(Number.isFinite(cmd.x) && Number.isFinite(cmd.y))) {
|
|
510
|
+
throw new Error("no file input on this page — give ref (the upload button) so gu can click it and answer the file chooser");
|
|
511
|
+
}
|
|
512
|
+
choosers.delete(tabId);
|
|
513
|
+
await host.cdp(tabId, "Page.setInterceptFileChooserDialog", { enabled: true });
|
|
514
|
+
try {
|
|
515
|
+
const p = await point(host, tabId, cmd);
|
|
516
|
+
await mouse(host, tabId, p.x, p.y);
|
|
517
|
+
for (let i = 0; i < 30 && !choosers.has(tabId); i++) await sleep(100);
|
|
518
|
+
const node = choosers.get(tabId);
|
|
519
|
+
if (!node) throw new Error("clicking it opened no file chooser — read the page and pick the upload control");
|
|
520
|
+
await host.cdp(tabId, "DOM.setFileInputFiles", { files: [file], backendNodeId: node });
|
|
521
|
+
return { uploaded: name, into: "the file chooser it opened" };
|
|
522
|
+
} finally {
|
|
523
|
+
choosers.delete(tabId);
|
|
524
|
+
await host.cdp(tabId, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
264
528
|
// ── the visible gu cursor ───────────────────────────────────────────────────────────────────
|
|
265
529
|
// Runs IN the page. The DevTools input events move no real mouse pointer, so the user could not
|
|
266
530
|
// see where gu acts. This draws a purple "gu" arrow that glides to each point before gu clicks,
|
|
@@ -401,7 +665,70 @@ async function after(host, tabId, extra = {}) {
|
|
|
401
665
|
return { tab: tabId, url: t?.url || "", title: t?.title || "", errors: errs, dialogs: dl, notes, ...extra };
|
|
402
666
|
}
|
|
403
667
|
|
|
668
|
+
// ── what gu just did, in words a person reads (GH #551) ─────────────────────────────────────
|
|
669
|
+
// For the popup and the page label. NEVER what was typed (passwords), never a script.
|
|
670
|
+
const clip = (s, n = 48) => {
|
|
671
|
+
const t = String(s ?? "").replace(/\s+/g, " ").trim();
|
|
672
|
+
return t.length > n ? t.slice(0, n - 1) + "…" : t;
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
/** "clicked button “Call API”", "opened example.com"… or "" for commands that are not a step. */
|
|
676
|
+
export function stepText(cmd, res = {}) {
|
|
677
|
+
const a = String(cmd?.action || "").toLowerCase();
|
|
678
|
+
const host = (u) => {
|
|
679
|
+
try {
|
|
680
|
+
const x = new URL(String(u));
|
|
681
|
+
return x.protocol === "file:" ? x.pathname.split("/").pop() || "a file" : x.host;
|
|
682
|
+
} catch {
|
|
683
|
+
return "a page";
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const hit = String(res?.hit || "").replace(/"([^"]*)"/, "“$1”");
|
|
687
|
+
switch (a) {
|
|
688
|
+
case "open": return `opened ${host(cmd.url)}`;
|
|
689
|
+
case "read": return "read the page";
|
|
690
|
+
case "screenshot": return "took a screenshot";
|
|
691
|
+
case "click": return clip(`clicked ${hit || "the page"}`);
|
|
692
|
+
case "double_click": return clip(`double-clicked ${hit || "the page"}`);
|
|
693
|
+
case "right_click": return clip(`right-clicked ${hit || "the page"}`);
|
|
694
|
+
case "hover": return clip(`pointed at ${hit || "the page"}`);
|
|
695
|
+
case "type": return "typed text";
|
|
696
|
+
case "key": return clip(`pressed ${String(cmd.text || "a key").split(/\s+/).slice(0, 3).join(" ")}`, 32);
|
|
697
|
+
case "scroll": return `scrolled ${cmd.direction || "down"}`;
|
|
698
|
+
case "back": return "went back";
|
|
699
|
+
case "reload": return "reloaded the page";
|
|
700
|
+
case "wait": return "waited for the page";
|
|
701
|
+
case "console": return "read the console";
|
|
702
|
+
case "network": return "read the network requests";
|
|
703
|
+
case "resize": return clip(`resized to ${cmd.text || "?"}`, 32);
|
|
704
|
+
case "upload": return clip(`uploaded ${String(cmd.path || "a file").split(/[\\/]/).pop()}`);
|
|
705
|
+
case "js": return "ran a check in the page";
|
|
706
|
+
case "switch": return "switched tab";
|
|
707
|
+
default: return "";
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
let lastStep = null; // { text, tab, at } — the popup asks for it
|
|
712
|
+
export const getLastStep = () => lastStep;
|
|
713
|
+
|
|
714
|
+
/** The label on the page says the step. Only where gu drew its frame. Never fails. */
|
|
715
|
+
export async function sayOnPage(host, tabId, text) {
|
|
716
|
+
if (!frameScripts.has(tabId)) return;
|
|
717
|
+
await host.cdp(tabId, "Runtime.evaluate", { expression: `(${guFrame})(${JSON.stringify("say:" + text)})`, returnByValue: true }).catch(() => {});
|
|
718
|
+
}
|
|
719
|
+
|
|
404
720
|
export async function runAction(cmd, host) {
|
|
721
|
+
const res = await doAction(cmd, host);
|
|
722
|
+
const text = stepText(cmd, res);
|
|
723
|
+
if (text && res && res.tab != null) {
|
|
724
|
+
lastStep = { text, tab: res.tab, at: Date.now() };
|
|
725
|
+
await sayOnPage(host, res.tab, text);
|
|
726
|
+
}
|
|
727
|
+
if (String(cmd?.action || "").toLowerCase() === "cleanup") lastStep = null;
|
|
728
|
+
return res;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
async function doAction(cmd, host) {
|
|
405
732
|
const a = String(cmd.action || "").toLowerCase();
|
|
406
733
|
if (a === "open") {
|
|
407
734
|
const url = String(cmd.url || "");
|
|
@@ -413,7 +740,11 @@ export async function runAction(cmd, host) {
|
|
|
413
740
|
return after(host, id);
|
|
414
741
|
}
|
|
415
742
|
if (a === "tabs") return { tabs: await host.tabs() };
|
|
416
|
-
if (a === "cleanup")
|
|
743
|
+
if (a === "cleanup") {
|
|
744
|
+
// End of the turn (GH #428). A tab gu resized gets its own size back first (GH #549).
|
|
745
|
+
for (const tabId of [...resized.keys()]) await resizeTab(host, tabId, "reset").catch(() => {});
|
|
746
|
+
return host.cleanup ? host.cleanup() : { closed: [], released: [] };
|
|
747
|
+
}
|
|
417
748
|
if (a === "switch") {
|
|
418
749
|
const id = cmd.tab;
|
|
419
750
|
if (!(await host.switchTo(id))) throw new Error(`tab ${cmd.tab} is not one of gu's tabs — see action "tabs"`);
|
|
@@ -517,6 +848,36 @@ export async function runAction(cmd, host) {
|
|
|
517
848
|
consoleBuf.set(id, []);
|
|
518
849
|
return after(host, id, { console: all });
|
|
519
850
|
}
|
|
851
|
+
case "resize": {
|
|
852
|
+
const r = await resizeTab(host, id, cmd.text);
|
|
853
|
+
await settle(host, id);
|
|
854
|
+
return after(host, id, r);
|
|
855
|
+
}
|
|
856
|
+
case "upload": {
|
|
857
|
+
const r = await uploadFile(host, id, cmd);
|
|
858
|
+
await settle(host, id);
|
|
859
|
+
return after(host, id, r);
|
|
860
|
+
}
|
|
861
|
+
case "network": {
|
|
862
|
+
// GH #546: since the last "network" read, then cleared. body: the response body of the
|
|
863
|
+
// FIRST failed request shown (≤ 2 KB) — usually the server saying what went wrong.
|
|
864
|
+
const entries = [...(netBuf.get(id)?.values() ?? [])];
|
|
865
|
+
netBuf.set(id, new Map());
|
|
866
|
+
const net = networkRows(entries, { text: cmd.text || "", failed: Boolean(cmd.failed) });
|
|
867
|
+
if (cmd.body && net.failedIds.length) {
|
|
868
|
+
const rid = net.failedIds[0];
|
|
869
|
+
const e = entries.find((x) => x.id === rid);
|
|
870
|
+
try {
|
|
871
|
+
const r = await host.cdp(id, "Network.getResponseBody", { requestId: rid });
|
|
872
|
+
const text = r?.base64Encoded ? "(binary — not shown)" : String(r?.body ?? "");
|
|
873
|
+
net.body = { url: maskUrl(e?.url), status: e?.status ?? e?.failed, text: text.length > 2048 ? text.slice(0, 2048) + "…" : text };
|
|
874
|
+
} catch {
|
|
875
|
+
net.body = { url: maskUrl(e?.url), status: e?.status ?? e?.failed, text: "(Chrome no longer has this response's body)" };
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
delete net.failedIds;
|
|
879
|
+
return after(host, id, { network: net });
|
|
880
|
+
}
|
|
520
881
|
default:
|
|
521
882
|
throw new Error(`unknown action "${cmd.action}"`);
|
|
522
883
|
}
|