幫 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 即可。

系列導覽