给 agy 配齐全局 MCP 之后,很快会碰到两个很现实的副作用:

  1. 会话一开,后台资源就跟着起飞:默认在 mcp_config.json 里直接挂 chrome-devtools-mcp 或 docker run ... mcp-atlassian,哪怕你只是进来改两行 Go 单测、压根不碰浏览器也不查 Jira,每次启动 agy 都会在后台弹出调试版 Chrome、或者拉起一个 Docker 容器。同时开四五个终端分屏,内存和容器列表瞬间爆炸。
  2. 多会话共用一个调试 Chrome,标签栏全乱成一锅粥:好不容易把 Chrome 改成单实例复用,结果三个并发会话一起往同一个窗口里 new_page,十几个 localhost、Swagger、报错页混在一起,根本分不清哪个标签属于哪个会话,关都不敢乱关。

这篇记录我本机实际在跑的整套解法:用两段零第三方依赖的 Python stdio 代理彻底干掉冷启动开销,再用一段 70 行的 RPC 脚本 + 一个极简 Chrome MV3 扩展,让每个 AGY 会话打开的标签自动落进以会话标题命名的标签组。

MCP 懒加载 stdio 代理与 Chrome 会话标签组联动方案


一、先分清两类重型 MCP 的懒加载策略

先澄清一个容易混淆的点:基础系列第 8 篇 讲的 Antigravity 内置 Lazy Loading 属于 Schema 懒加载(省的是 Prompt Token,进程本身还是会随会话启动);而本文做的代理属于 进程 / 容器级懒加载(省的是内存、调试 Chrome 实例与 Docker 容器冷启动开销)。

全局 ~/.gemini/config/mcp_config.json 里我挂了四个常用服务,其中 context7 和 memory 本身是极轻的本地 Node 进程,直接启动即可;真正吃资源的是 chrome-devtools 和 jira-internal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"mcpServers": {
"chrome-devtools": {
"command": "/home/user/.gemini/bin/chrome-devtools-mcp.sh"
},
"context7": {
"command": "/home/user/.gemini/mcp-servers/context7/node_modules/.bin/context7-mcp"
},
"jira-internal": {
"command": "/home/user/.gemini/bin/jira-mcp.sh"
},
"memory": {
"command": "/home/user/.gemini/mcp-servers/memory/node_modules/.bin/mcp-server-memory",
"env": {
"MEMORY_FILE_PATH": "/home/user/.gemini/memory/knowledge-graph.jsonl"
}
}
}
}

同样是懒加载,这两者的瓶颈不一样,所以我用了两种不同的代理模式:

服务 真正耗资源的环节 代理策略
chrome-devtools chrome-devtools-mcp 自身很轻,重的是它连的 Chrome 实例 透明透传型代理:先启动 chrome-devtools-mcp --browserUrl=...,握手与 tools/list 原样透传;仅在拦到 tools/call 时才检查并按需拉起独立调试 Chrome
jira-internal 整个服务跑在 Docker 容器里,哪怕只答一次 tools/list 也要 docker run 本地握手型代理:代理脚本自己用纯 Python 应答 initialize、ping、tools/list 和 notifications/*;直到第一次收到 tools/call 才启动容器,并透明重放一次握手

两种模式的请求路径对比:


二、Chrome DevTools 懒加载代理(chrome-devtools-mcp-lazy.py)

先套一层极薄的 Shell 入口 ~/.gemini/bin/chrome-devtools-mcp.sh(方便固定路径和透传参数):

1
2
3
#!/usr/bin/env bash
set -euo pipefail
exec python3 /home/user/.gemini/bin/chrome-devtools-mcp-lazy.py "$@"

核心逻辑在 ~/.gemini/bin/chrome-devtools-mcp-lazy.py。写这 170 行代码时,踩过四个很典型的坑,都在代码里做了防御:

  1. 探测本地端口一定要绕开代理环境变量:开发机通常挂着 HTTP_PROXY / ALL_PROXY。如果用 urllib.request 去探 http://127.0.0.1:9223/json/version,很容易被误转发到代理里报 502,代理脚本以为 Chrome 没起就疯狂重复拉起。这里直接用底层的 http.client.HTTPConnection("127.0.0.1", 9223),完全无视环境变量。
  2. 文件锁防并发双开:两个会话同时发起浏览器操作时,不加锁就会同时拉起两个 Chrome 抢同一个 --user-data-dir 导致其中一个崩溃。用 fcntl.flock 锁住 <PROFILE_DIR>/.launch.lock(15 秒超时),拿到锁后再 is_ready() 双检一次。
  3. 用 systemd-run --user --collect 脱离 CLI 生命周期:如果直接把 Chrome 当作代理的子进程启动,关闭某个终端窗口时整个进程组可能一起被 SIGHUP 带走,害正在调试的其他会话断连。优先用 systemd-run --user --unit=agy-debug-chrome --collect 交给用户态 systemd 托管,没有 systemd 时才退回 start_new_session=True。
  4. **必须配独立 --user-data-dir**:不要去蹭日常浏览器的默认 Profile,否则 Chrome 检测到已有实例运行会直接忽略 --remote-debugging-port。

完整实现如下(已脱敏路径):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/env python3
"""Lazy-launch stdio proxy for chrome-devtools-mcp."""
import errno, fcntl, http.client, json, os, shutil, signal, subprocess, sys, time

HOST = "127.0.0.1"
PORT = int(os.environ.get("AGY_CHROME_DEBUG_PORT", "9223"))
URL = f"http://{HOST}:{PORT}"
PROFILE_DIR = os.environ.get(
"AGY_CHROME_PROFILE_DIR",
os.path.join(os.path.expanduser("~"), ".local", "share", "chrome-mcp-profile"),
)
LOCK_FILE = os.path.join(PROFILE_DIR, ".launch.lock")
CHROME_BIN = os.environ.get("AGY_CHROME_BIN", "/usr/bin/google-chrome")
MCP_BIN = os.environ.get(
"AGY_CHROME_MCP_BIN",
os.path.expanduser("~/.gemini/mcp-servers/chrome-devtools/node_modules/.bin/chrome-devtools-mcp"),
)


def is_ready() -> bool:
"""Directly probe local CDP endpoint, bypassing any proxy env vars."""
conn = None
try:
conn = http.client.HTTPConnection(HOST, PORT, timeout=1.0)
conn.request("GET", "/json/version")
resp = conn.getresponse()
resp.read()
return resp.status == 200
except OSError:
return False
finally:
if conn is not None:
conn.close()


def acquire_lock(fd: int, timeout_s: float = 15.0) -> bool:
deadline = time.monotonic() + timeout_s
while True:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EAGAIN) or time.monotonic() >= deadline:
return False
time.sleep(0.1)


def launch_chrome() -> None:
chrome_args = [
CHROME_BIN,
f"--remote-debugging-address={HOST}",
f"--remote-debugging-port={PORT}",
f"--user-data-dir={PROFILE_DIR}",
"--no-first-run",
"--no-default-browser-check",
]
launched = False
if shutil.which("systemd-run") and (
os.environ.get("DBUS_SESSION_BUS_ADDRESS") or os.environ.get("XDG_RUNTIME_DIR")
):
res = subprocess.run(
["systemd-run", "--user", "--unit=agy-debug-chrome", "--collect", *chrome_args],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
close_fds=True, check=False,
)
launched = res.returncode == 0
if not launched:
subprocess.Popen(
chrome_args,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True,
)


def ensure_chrome() -> None:
if os.environ.get("AGY_NO_AUTO_CHROME", "0") == "1" or is_ready():
return
os.makedirs(PROFILE_DIR, exist_ok=True)
lock_fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR, 0o600)
try:
if not acquire_lock(lock_fd, timeout_s=15.0):
return
if not is_ready():
launch_chrome()
for _ in range(40):
if is_ready():
break
time.sleep(0.25)
finally:
try:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
except OSError:
pass
os.close(lock_fd)


def needs_browser(raw_line: bytes) -> bool:
if b"tools/call" not in raw_line:
return False
try:
msg = json.loads(raw_line)
except (ValueError, UnicodeDecodeError):
return False
if isinstance(msg, dict):
return msg.get("method") == "tools/call"
if isinstance(msg, list):
return any(isinstance(item, dict) and item.get("method") == "tools/call" for item in msg)
return False


def main() -> int:
cmd = [
MCP_BIN,
f"--browserUrl={URL}",
"--categoryExtensions",
"--backgroundNewPages",
"--no-usage-statistics",
"--no-performance-crux",
*sys.argv[1:],
]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)

def forward_signal(signum: int, _frame: object) -> None:
if proc.poll() is None:
try:
proc.send_signal(signum)
except ProcessLookupError:
pass
raise SystemExit(128 + signum)

for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(sig, forward_signal)

assert proc.stdin is not None
try:
while True:
line = sys.stdin.buffer.readline()
if not line:
break
if needs_browser(line):
ensure_chrome()
try:
proc.stdin.write(line)
proc.stdin.flush()
except BrokenPipeError:
break
finally:
try:
proc.stdin.close()
except OSError:
pass
return proc.wait()


if __name__ == "__main__":
raise SystemExit(main())

演进提示:上面的信号处理已补齐 raise SystemExit(128 + signum),避免收到 SIGTERM 后仍卡死在阻塞的 sys.stdin.buffer.readline() 上。如果你在多终端并发共用同一个调试 Chrome,建议继续阅读 #5 多会话 Chrome 护栏与橙色 UI 状态,了解这套代理如何进一步升级为基于 CDP targetId 的双向防误触护栏。

顺便提一下启动参数里的两个好用开关:

  • --backgroundNewPages:Agent 后台开新页时不会每次把你的桌面焦点强行切走;
  • --categoryExtensions:放开扩展管理类工具,方便平时在调试 Chrome 里重载自己写的本地扩展。

三、Jira Docker MCP 全本地握手代理(jira-mcp-lazy.py)

Jira MCP 我跑的是 ghcr.io/sooperset/mcp-atlassian 镜像(锁死 @sha256 摘要,加 READ_ONLY_MODE=true 和 ENABLED_TOOLS=jira_get_issue,jira_search 两个硬边界,确保 Agent 绝对改不了线上工单)。

问题在于只要把它放进 mcp_config.json,agy 启动瞬间就会做 MCP 发现(initialize → notifications/initialized → tools/list),直接把容器拉起来常驻到会话结束。

解法是把发现阶段的协议全在 Python 代理里本地消化掉:

  • 代理记住客户端发来的 initialize.params(包括 protocolVersion 和 capabilities),立刻返回本地构造的 initialize 结果;
  • tools/list 直接返回预录好的 jira_get_issue 与 jira_search JSON Schema;resources/list、prompts/list 返回空数组;
  • 一旦收到任何业务调用(如 tools/call),才调用 ensure_backend() 启动 Docker 容器,并替客户端把之前保存的 initialize 用内部 ID __agy_jira_lazy_init__ 重放一遍,等容器回包再发 notifications/initialized;
  • 握手补齐后,拉起一条守护线程 _pump_stdout 把容器输出持续刷回给 agy,主循环从此直接字节级透传,不再反复 json.loads;
  • 退出时关闭容器 stdin、wait(5) → terminate() → kill(),配合 docker run --rm 干净回收容器,不留僵尸。

核心代码节选(省略了长达百行的 TOOLS 静态 schema 定义,实际使用时直接从容器跑一次 tools/list 抄下来即可):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""Lazy-launch stdio MCP proxy for jira-internal (mcp-atlassian Docker container)."""
import json, os, shlex, signal, subprocess, sys, threading

JIRA_ENV_PATH = os.environ.get(
"AGY_JIRA_ENV_FILE",
os.path.join(os.path.expanduser("~"), ".gemini", "secrets", "jira.env"),
)
JIRA_IMAGE = os.environ.get(
"AGY_JIRA_IMAGE",
"ghcr.io/sooperset/mcp-atlassian@sha256:5b7c9b64d4eb3210cab74be8bf3e6aeea9ed14f3042dc59ba5c5287bd4dbe466",
)
DOCKER_BIN = os.environ.get("AGY_DOCKER_BIN", "/usr/bin/docker")
INIT_INTERNAL_ID = "__agy_jira_lazy_init__"

# 预录只读工具 Schema(jira_get_issue / jira_search),避免冷启动容器
TOOLS = [
{"name": "jira_get_issue", "description": "Get details of a specific Jira issue.", "inputSchema": {"type": "object", "required": ["issue_key"], "properties": {"issue_key": {"type": "string"}}}},
{"name": "jira_search", "description": "Search Jira issues using JQL.", "inputSchema": {"type": "object", "required": ["jql"], "properties": {"jql": {"type": "string"}}}},
]

WRITE_LOCK = threading.Lock()


def write_client(raw_line: bytes) -> None:
with WRITE_LOCK:
sys.stdout.buffer.write(raw_line)
sys.stdout.buffer.flush()


def send_json(obj: dict) -> None:
write_client((json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8"))


def backend_command() -> list[str]:
if not os.access(JIRA_ENV_PATH, os.R_OK):
raise RuntimeError(f"Jira credentials file is missing or unreadable: {JIRA_ENV_PATH}")
return [
DOCKER_BIN, "run", "--rm", "-i",
"--env-file", JIRA_ENV_PATH,
"-e", "READ_ONLY_MODE=true",
"-e", "ENABLED_TOOLS=jira_get_issue,jira_search",
JIRA_IMAGE,
]


class LazyJiraProxy:
def __init__(self) -> None:
self.proc: subprocess.Popen[bytes] | None = None
self.reader_thread: threading.Thread | None = None
self.init_params: dict = {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "antigravity-lazy-proxy", "version": "1.0.0"},
}

def handle_local(self, msg: dict) -> bool:
method, req_id = msg.get("method"), msg.get("id")
if method == "initialize":
if isinstance(msg.get("params"), dict):
self.init_params = msg["params"]
proto = self.init_params.get("protocolVersion") or "2024-11-05"
if req_id is not None:
send_json({
"jsonrpc": "2.0", "id": req_id,
"result": {
"protocolVersion": proto,
"capabilities": {"tools": {}},
"serverInfo": {"name": "jira-internal-lazy", "version": "1.0.0"},
},
})
return True
if method == "ping":
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {}})
return True
if method == "tools/list":
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}})
return True
if method in ("resources/list", "resources/templates/list", "prompts/list"):
key = {"resources/list": "resources", "resources/templates/list": "resourceTemplates", "prompts/list": "prompts"}[method]
if req_id is not None:
send_json({"jsonrpc": "2.0", "id": req_id, "result": {key: []}})
return True
return isinstance(method, str) and method.startswith("notifications/") and req_id is None

def ensure_backend(self) -> None:
if self.proc is not None and self.proc.poll() is None:
return
proc = subprocess.Popen(backend_command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
assert proc.stdin is not None and proc.stdout is not None

# 用内部 ID 重放 initialize,吞掉容器回包后再发 notifications/initialized
init_req = {"jsonrpc": "2.0", "id": INIT_INTERNAL_ID, "method": "initialize", "params": self.init_params}
proc.stdin.write((json.dumps(init_req, separators=(",", ":")) + "\n").encode("utf-8"))
proc.stdin.flush()

while True:
line = proc.stdout.readline()
if not line:
raise RuntimeError(f"jira-internal backend exited during initialize (rc={proc.wait()})")
try:
resp = json.loads(line)
except (ValueError, UnicodeDecodeError):
continue
if isinstance(resp, dict) and resp.get("id") == INIT_INTERNAL_ID:
if "error" in resp:
raise RuntimeError(f"jira-internal initialize failed: {resp['error']}")
break

inited = {"jsonrpc": "2.0", "method": "notifications/initialized"}
proc.stdin.write((json.dumps(inited, separators=(",", ":")) + "\n").encode("utf-8"))
proc.stdin.flush()

self.proc = proc
self.reader_thread = threading.Thread(target=self._pump_stdout, args=(proc,), daemon=True)
self.reader_thread.start()

@staticmethod
def _pump_stdout(proc: subprocess.Popen[bytes]) -> None:
assert proc.stdout is not None
try:
for line in iter(proc.stdout.readline, b""):
write_client(line)
except OSError:
pass

加上这个代理之后,开 10 个只写代码的 agy 会话,宿主机 docker ps 里一个 Jira 容器都看不到;需要查单号时,第一次 jira_get_issue 延迟大概 1.5 秒拉起容器,后续同会话里的查询就全部走长连接瞬时返回了。

如果你的 MCP 镜像升级后调整了工具参数,记得同步更新代理脚本里的 TOOLS 列表;不过对于只暴露两个只读查询工具的 Jira 服务,Schema 几个月都不会变一次,维护成本几乎为零。


四、多会话共享 Chrome:按 AGY 会话标题自动归组标签页

把 Chrome 收拢成 9223 端口的单实例后,立刻要解决“多会话标签打架”的问题。

Chrome 原生的 chrome.tabGroups API 只能由浏览器扩展调用,CDP 协议本身并不能直接给标签建组。顺着这个思路,拆成三块拼起来反而特别干净:

  1. 取当前 AGY 会话标题(session-tab-url.py)
  2. 在调试 Chrome 里装一个 50 行 JS 的 MV3 扩展(~/.gemini/chrome-tab-group-ext/)
  3. 写一个全局 Skill 约束 Agent 开标签前必须走一遍包装脚本(~/.gemini/config/skills/browser-tab-group/SKILL.md)

完整交互时序:

1. 读取当前会话标题并拼装中转 URL(session-tab-url.py)

agy 在执行命令时会注入 ANTIGRAVITY_LS_ADDRESS、ANTIGRAVITY_CSRF_TOKEN 和 ANTIGRAVITY_CONVERSATION_ID 三个环境变量。直接调本机 Connect-RPC 接口 ConversationService/GetConversation,优先拿 annotations.title,拿不到再回退 state.summary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
"""Print the current Antigravity conversation title (or a tab-grouper redirect URL)."""
import json, os, sys, urllib.parse, urllib.request


def get_session_title():
addr = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip()
csrf = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip()
conv_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip()
if not (addr and csrf and conv_id):
raise RuntimeError(
"Missing Antigravity conversation env vars "
"(ANTIGRAVITY_LS_ADDRESS / ANTIGRAVITY_CSRF_TOKEN / ANTIGRAVITY_CONVERSATION_ID)."
)
req = urllib.request.Request(
f"http://{addr}/product.v1.ConversationService/GetConversation",
data=json.dumps({"conversationId": conv_id}).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Connect-Protocol-Version": "1",
"x-antigravity-csrf-token": csrf,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=3) as resp:
data = json.loads(resp.read().decode("utf-8"))
except Exception as exc:
raise RuntimeError(
f"Failed to resolve conversation title via GetConversation ({exc}). "
"If blocked by sandbox (e.g., HTTP 403 / connection refused), "
"rerun this command outside the sandbox."
) from exc
title = (data.get("annotations") or {}).get("title") or ""
summary = (data.get("state") or {}).get("summary") or ""
picked = title.strip() or summary.strip()
if not picked:
raise RuntimeError(f"Conversation {conv_id} has neither annotations.title nor state.summary.")
return picked


def main():
try:
title = get_session_title()
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
if len(sys.argv) >= 3 and sys.argv[1] == "--url":
ext_id = os.environ.get("AGY_TAB_GROUP_EXT_ID", "").strip()
if not ext_id:
cfg = os.path.expanduser("~/.gemini/chrome-tab-group-ext/extension_id")
if os.path.isfile(cfg):
with open(cfg, encoding="utf-8") as f:
ext_id = f.read().strip()
if not ext_id:
print("Missing extension_id", file=sys.stderr)
return 1
query = urllib.parse.urlencode({"group": title, "url": sys.argv[2]})
print(f"chrome-extension://{ext_id}/group.html?{query}")
return 0
print(title)
return 0


if __name__ == "__main__":
raise SystemExit(main())

2. 极简 MV3 扩展(manifest.json + group.html + group.js)

扩展放在 ~/.gemini/chrome-tab-group-ext/,在调试 Chrome 的 chrome://extensions 里打开开发者模式加载一次,把生成的扩展 ID 写进同目录的 extension_id 文件即可。

如果你希望同一份未打包扩展在多台电脑上保持完全相同的扩展 ID(避免每台机器重新抄 extension_id),可以在 manifest.json 中固定 "key" 字段,具体生成方法见 #4 跨平台备份与一键还原。

manifest.json 只需要两个最小权限:

1
2
3
4
5
6
7
{
"manifest_version": 3,
"name": "Antigravity Session Tab Grouper",
"version": "1.0.0",
"description": "Group tabs opened by Antigravity CLI sessions using the current conversation title.",
"permissions": ["tabs", "tabGroups"]
}

group.html 作为中转承接页,只放一个状态节点并加载 group.js(MV3 禁止内联脚本):

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Grouping Tab...</title>
</head>
<body>
<p id="status">Grouping tab...</p>
<script src="group.js"></script>
</body>
</html>

group.js 干四件事:按标题做确定性哈希选色 → 查当前窗口里有没有同名标签组 → 有就并入、没有就新建 → 只允许跳转 ^https?://(防止被构造 javascript: 或 file:// 跳转):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const COLORS = ["blue", "cyan", "green", "yellow", "orange", "pink", "purple", "red", "grey"];

function pickColor(name, explicit) {
if (explicit && COLORS.includes(explicit)) return explicit;
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
}
return COLORS[hash % COLORS.length];
}

async function run() {
const statusEl = document.getElementById("status");
const params = new URLSearchParams(window.location.search);
const groupName = (params.get("group") || "Antigravity").trim().slice(0, 80);
const targetUrl = (params.get("url") || "").trim();
const color = pickColor(groupName, (params.get("color") || "").trim());

const tab = await chrome.tabs.getCurrent();
if (!tab || typeof tab.id !== "number") throw new Error("Cannot resolve current tab.");

const existing = await chrome.tabGroups.query({ windowId: tab.windowId, title: groupName });
if (existing.length > 0) {
await chrome.tabs.group({ groupId: existing[0].id, tabIds: [tab.id] });
} else {
const groupId = await chrome.tabs.group({ tabIds: [tab.id] });
await chrome.tabGroups.update(groupId, { title: groupName, color });
}

if (/^https?:\/\//i.test(targetUrl)) {
statusEl.textContent = `Grouped into "${groupName}", redirecting...`;
await chrome.tabs.update(tab.id, { url: targetUrl });
} else {
statusEl.textContent = `Grouped into "${groupName}".`;
}
}

run().catch((err) => {
const statusEl = document.getElementById("status");
if (statusEl) statusEl.textContent = `Tab group error: ${err?.message || err}`;
});

3. 用全局 Skill 兜住行为与边界踩坑(SKILL.md)

光有脚本和扩展,Agent 不会自己记得去调,必须放一个全局 Skill ~/.gemini/config/skills/browser-tab-group/SKILL.md,并且把几个实战踩过的边界全写死在规则里:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
---
name: browser-tab-group
description: >-
Use this skill whenever opening a new browser tab with the chrome-devtools
MCP (new_page) or starting browser automation/debugging in Chrome. Ensures
every tab opened by this Antigravity session is placed into a single Chrome
tab group named after the current Antigravity conversation title.
---

# Browser Session Tab Grouping

1. **Always wrap `new_page` URLs through the local tab-grouper helper**:
python3 ~/.gemini/config/skills/browser-tab-group/scripts/session-tab-url.py --url "<target-url>"
- If the terminal sandbox blocks `GetConversation`, rerun **only** that helper command outside the sandbox.
- Never fall back to the workspace directory name or pass `<target-url>` directly to `new_page`.

2. **One tab group per conversation**:
- First tab creates and names the group; subsequent tabs join the same group automatically.
- Reuse an existing tab in this session's group via `navigate_page` when a new tab is unnecessary.

3. **Wait for redirect before interacting**:
- Verify via `list_pages` or `take_snapshot` that the tab has left `group.html` before clicking or filling.

4. **Edge cases**:
- Do not combine `chrome-extension://` URLs with `isolatedContext`; isolated browser contexts cannot run the local extension.

这里有三个真实踩过的坑值得单独拎出来:

  • 沙盒拦截本机回环:开启终端沙盒时,默认禁止访问本机端口,session-tab-url.py 请求 GetConversation 会被拒。一定在脚本报错提示里写明“只对这一条辅助命令放开沙盒”,绝对不要让 Agent 偷懒回退成工作区目录名——否则同一仓库开三个会话,标签又全挤进同一个组里了。
  • 跳转竞态:new_page 返回时页面可能还停在 group.html 正在执行 chrome.tabs.update,紧接着就 click 或 take_snapshot 会扑空,所以在 Skill 第 3 条明确要求先确认 URL 已跳到目标页。
  • isolatedContext 不兼容扩展页:无痕/隔离上下文里跑不了 chrome-extension://,碰到明确要求无登录态验证的场景直接传目标 URL 即可。

系列导航