macOS 工作模式下把多个 AI Agent 的完成通知实时推到 Apple Watch
大家好,我是不会喷火的小火龙。
现在日常写代码,我经常同时开着好几个 AI Agent 并行干活,这边 Antigravity 在重构模块,那边 Codex 在跑测试修 Bug,终端里还挂着 dsh 或者 T3 Code 在处理另一条分支任务。
一旦切出编辑器看文档、或者离开工位倒杯水,最烦的就是两头踩空:要么任务早跑完了、或者卡在权限确认上干等十几分钟我却完全不知道;要么好不容易折腾通了推送,结果主 Agent 拉起几个子 Agent 并发干活时,手腕开始连续狂震刷屏。
而且我的 macOS 平时默认开着「工作」专注模式。macOS 的系统通知本来就不会转发到 iPhone 和 Apple Watch,再加上专注模式跨设备同步,普通通知在手表上要么根本收不到,要么静默折叠进通知中心。
今天我就把自己本机跑通的一整套方案拆成保姆级教程,带你从零实现 Antigravity、Codex、T3 Code(以及任意支持退出回调的终端工具)→ Bark → Apple Watch 的实时提醒闭环:
1)0 Token 消耗:不修改任何 App 底层,全靠宿主生命周期 Hook 与本地只读监听,不走大模型推理。
2)穿透工作专注模式:在工作模式下实现 Apple Watch 只震动不响铃,既不打扰身边人,也不会漏消息。
3)一轮任务只震一次:精准过滤 Antigravity 的 swarm / 子 Agent、未空闲中间态以及 Codex / T3 Code 的子线程,拒绝手腕刷屏。
友情提示:AI 编程工具版本迭代很快,不同小版本的配置文件字段可能略有差异。本文方案基于 macOS 26.6.2(arm64)、Antigravity 2.36.0、Codex CLI 0.172.0、T3 Code (Beta) 0.1.12 与 curl 8.7.1 实测验证;文中把校验命令和日志排查路径都完整留了出来,遇到差异时对照日志自检即可。
一、为什么自带开关不够用,整体架构怎么设计
很多同学打开 Antigravity 设置里的 Notifications → Enable notifications for agent 后,以为就能在手表上收到提醒了。
我实测下来,这里面有两道天然断层。第一道断层在苹果生态本身:根据 Apple 官方支持文档的说明,macOS 本地的通知中心弹窗(包括桌面 App 的原生通知和 osascript)不会镜像到 iPhone 或 Apple Watch。第二道断层在工具各自为政:Antigravity 目前的 Hook 仅支持本地 shell 命令而不支持直接填 HTTP Webhook;Codex 虽然有全局配置文件,但 notify 字段经常已经被其他桌面组件占用;而 T3 Code 内部更是把部分底层 Hook 特性禁用了。
为了省事,我把所有事件源都收敛到同一个本地分发脚本里,只在最外围做触发,不改动任何工具原有的核心逻辑。整体数据流向如下图所示。
这套架构分四层流转,且全程不需要改变原有工程结构:
1)事件触发层:Antigravity 和 Codex 各自在任务结束时拉起本地命令 Hook;T3 Code 由一个后台 launchd 守护进程以只读模式监听其本地 SQLite 状态库。
2)统一过滤与分发层:全部汇入 ~/.local/bin/notify-watch.sh,由它统一解析上下文摘要、剔除子 Agent 与用户主动取消事件,再通过后台子进程异步发出请求。
3)推送网关与专注模式层:请求发往 Bark(底层走苹果原生 APNs 通道,不在手机后台挂长连接),并携带 level=timeSensitive 参数穿透工作专注模式。
4)腕端触达层:当 iPhone 处于锁屏熄屏状态时,iOS 会将通知自动路由至佩戴在手腕上的 Apple Watch,配合手表静音模式实现纯触感震动。
在最终选定 Bark 之前,我也把常见的几种方案放在一起做了多维度对比,具体取舍如下表所示。
如果你的核心设备就是 Mac + iPhone + Apple Watch,Bark 是目前综合门槛最低、延迟可控且可自建的选择;只有当你希望在手表上脱离手机翻看更长的历史通知列表时,才需要考虑付费买断的 Pushover。
二、前置准备:3 分钟搞定 iPhone 与 Apple Watch「工作模式」
在写一行代码之前,先把手机和手表的系统链路打通。很多同学脚本明明返回了 200,手机屏幕也亮了,但手表死活不震动,九成都是卡在这一步。
1)获取你的 Bark 推送地址
在 iPhone 的 App Store 安装 Bark,打开 App 复制首页给出的测试 URL,形如 https://api.day.app/<你的BARK_KEY>/测试内容。后续所有命令和脚本里的 <你的BARK_KEY> 都替换成你自己的这一段 Key。
2)理解 Apple Watch 的互斥路由规则
根据 Apple 官方的《Apple Watch 上的通知》说明,同一条通知只会在 iPhone 或 Apple Watch 其中一端提醒,不会两边同时响。如果当前你的 iPhone 处于解锁亮屏状态,通知会停留在手机顶部,手表不会震动;只有当 iPhone 处于锁定或熄屏状态,且你的 Apple Watch 戴在手腕并已解锁时,通知才会顺着蓝牙/Wi-Fi 路由到手腕上。
3)把 Bark 放进「工作」专注模式白名单
打开 iPhone 的 设置 → 专注模式 → 工作 → App,这里最容易点错顶部开关:请务必确认上方选中了 「允许来自以下 App 的通知」(而不是「静音来自以下 App 的通知」),然后把 Bark 添加进列表,并打开页面下方的 「时效性通知」 开关。
4)打开手机侧「声音」开关,实现只震不响
这一步极其容易踩坑:打开 iPhone 的 设置 → 通知 → Bark,确保 「允许通知」、「即时通知」 和 「声音」 全部处于开启状态。原因在于,当 Apple Watch 设置为「从 iPhone 镜像提醒」时,一旦你在手机的系统通知里关掉了某款 App 的「声音」,iOS 会把它判定为静默通知,连带着把 Apple Watch 的震动马达也一起关掉。想要工作时只震动不响铃,正确做法是手机端保留声音权限,只在 Apple Watch 控制中心打开静音模式(铃铛图标)。
5)确认 Watch 镜像与触感强度
打开 iPhone 上的 Watch App → 通知,向下滑找到 Bark 并确认开关已打开;再进入 Watch App → 声音与触感,确认 「触感提醒」 开启,建议初次测试先调成 「显著」 方便感知。如果你希望 Mac 上开工作模式时干脆不要同步静音手表,也可以在 Mac 的 系统设置 → 专注模式 里关掉 「在设备间共享」。
三、核心步骤一:编写统一脚本 notify-watch.sh
先看一条最小可运行的 Bark 请求,这是理解后续脚本的基础。根据 Bark 官方文档,给基础地址拼接标题与正文路径即可发送:
▼bash复制代码curl -G "https://api.day.app/<你的BARK_KEY>/Agent通知/任务已完成" \ --data-urlencode "group=Antigravity" \ --data-urlencode "level=timeSensitive" \ --data-urlencode "ttl=600"
这里有三个核心参数分别负责不同边界:
1)group:在通知中心与 Bark 历史记录里按来源聚合,避免多个 Agent 同时完成时列表太乱。
2)level=timeSensitive:标记为时效性通知,配合前面开好的白名单穿透工作专注模式。
3)ttl=600:临时消息在历史记录中的有效存活时间(秒),10 分钟后自动清理,避免几天后翻出一堆过时的“任务已完成”。
实战中,任务摘要里经常带有斜杠、空格、换行和中文,直接拼路径很容易出错,而且 Antigravity 的 Stop Hook 有两个强制约束:脚本会同步阻塞执行,且必须向标准输出返回合法 JSON(如 {"decision":""})。
因此我们在 ~/.local/bin/notify-watch.sh 里把这件事一次封装到位:入口立即输出 {"decision":""}(仅对 Antigravity 的 Stop 事件),再用 Python 解析 stdin JSON 做摘要截断和 URL 编码,最后把 curl 放进重定向了标准输入输出的后台子进程中异步发出。
执行下面命令创建目录并写入脚本(记得把第 6 行的 <你的BARK_KEY> 换成真实 Key):
▼bash复制代码mkdir -p ~/.local/bin ~/.local/state cat <<'EOF' > ~/.local/bin/notify-watch.sh #!/usr/bin/env bash set -euo pipefail AGENT="${1:-Antigravity}" EVENT="${2:-Stop}" BARK_BASE="${BARK_BASE:-https://api.day.app/<你的BARK_KEY>}" LOG_PATH="${HOME}/.local/state/notify-watch.log" # 读取宿主通过 stdin 传入的事件上下文 PAYLOAD="$(cat || true)" # Antigravity Stop Hook 必须立刻向 stdout 返回合法 JSON,否则可能阻塞结束流程 if [ "$AGENT" = "Antigravity" ] && [ "$EVENT" = "Stop" ]; then printf '{"decision":""}\n' fi mkdir -p "${HOME}/.local/state" 2>/dev/null || true # 解析事件并过滤子 Agent / 中间暂停态 PY_OUT="$(AGENT="$AGENT" EVENT="$EVENT" PAYLOAD="$PAYLOAD" BARK_BASE="$BARK_BASE" python3 - <<'PY' import json import os import sqlite3 import sys import urllib.parse agent = os.environ.get("AGENT", "Antigravity") event = os.environ.get("EVENT", "Stop") base = os.environ.get("BARK_BASE", "").rstrip("/") raw = os.environ.get("PAYLOAD", "").strip() data = {} if raw: try: data = json.loads(raw) except Exception: data = {} def skip(reason_msg: str): print(f"SKIP:{reason_msg}") sys.exit(0) def is_antigravity_subagent(d: dict): conv_id = (d.get("conversationId") or "").strip() db_path = os.path.expanduser("~/.gemini/antigravity/conversation_summaries.db") if conv_id and os.path.exists(db_path): try: conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=1.5) cur = conn.cursor() cur.execute( "SELECT parent_conversation_id, nesting_depth, agent_name " "FROM conversation_summaries WHERE conversation_id = ?", (conv_id,), ) row = cur.fetchone() if row: parent_id, depth, ag_name = row if (parent_id or "") != "" or (depth or 0) > 0 or (ag_name or "") != "": conn.close() return f"subagent_db(parent={parent_id[:8] if parent_id else ''},depth={depth},name={ag_name})" cur.execute( "SELECT parent_id FROM conversation_parents WHERE conversation_id = ? LIMIT 1", (conv_id,), ) prow = cur.fetchone() conn.close() if prow and prow[0]: return f"subagent_parents(parent={prow[0][:8]})" except Exception: pass tpath = (d.get("transcriptPath") or "").strip() if tpath and os.path.exists(tpath): try: with open(tpath, "r", encoding="utf-8", errors="ignore") as f: first_line = f.readline().strip() if first_line: first = json.loads(first_line) if first.get("source") == "SYSTEM" and not (d.get("lastUserInput") or "").strip(): return "subagent_transcript(source=SYSTEM)" except Exception: pass return None def is_codex_subagent(d: dict): if d.get("agent_id") or d.get("parent_thread_id"): return "codex_subagent_field" sess_id = (d.get("session_id") or "").strip() db_path = os.path.expanduser("~/.codex/state_5.sqlite") if sess_id and os.path.exists(db_path): try: conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=1.5) cur = conn.cursor() cur.execute( "SELECT source, agent_nickname, agent_role, attached_thread_parent_id " "FROM threads WHERE id = ?", (sess_id,), ) row = cur.fetchone() conn.close() if row: src, nick, role, parent = row if (src or "").startswith("subagent") or (nick or "") != "" or (role or "") != "" or (parent or "") != "": return f"codex_subagent_db(src={src},role={role})" except Exception: pass return None reason = data.get("terminationReason", "") if reason == "USER_CANCELED": skip("user_canceled") if agent == "Antigravity" and event == "Stop": sub_reason = is_antigravity_subagent(data) if sub_reason: skip(sub_reason) if data.get("fullyIdle") is False: skip("not_fully_idle") elif agent == "Codex" and event in ("Stop", "SubagentStop"): if event == "SubagentStop": skip("codex_subagent_event") sub_reason = is_codex_subagent(data) if sub_reason: skip(sub_reason) cwd = data.get("cwd") or "" if not cwd: wp = data.get("workspacePaths") or [] if wp: cwd = wp[0] proj = os.path.basename(cwd.rstrip("/")) if cwd else "" title = f"{agent} · {proj}" if proj else agent summary = ( data.get("lastUserInput") or data.get("last_assistant_message") or data.get("prompt") or "" ).replace("\n", " ").strip() if len(summary) > 36: summary = summary[:35] + "…" if event == "PermissionRequest": tool_name = (data.get("tool_name") or "").strip() body = f"等待确认审批:{tool_name}" if tool_name else "等待你的确认审批" elif reason == "ERROR" or data.get("error"): err = str(data.get("error") or reason).replace("\n", " ").strip() body = f"任务异常结束: {err[:50]}" if err else "任务异常结束" elif reason == "MAX_INVOCATIONS": body = "已达到最大调用轮次并停止" else: body = f"任务已完成:{summary}" if summary else "任务已完成" enc_title = urllib.parse.quote(title, safe="") enc_body = urllib.parse.quote(body, safe="") query = urllib.parse.urlencode({ "group": agent, "level": "timeSensitive", "ttl": 600, }) print(f"URL:{base}/{enc_title}/{enc_body}?{query}") PY )" || exit 0 case "$PY_OUT" in SKIP:*) printf '%s skip agent=%s event=%s reason=%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$AGENT" "$EVENT" "${PY_OUT#SKIP:}" >> "$LOG_PATH" 2>/dev/null || true exit 0 ;; URL:*) BARK_REQ_URL="${PY_OUT#URL:}" ;; *) exit 0 ;; esac printf '%s agent=%s event=%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$AGENT" "$EVENT" >> "$LOG_PATH" 2>/dev/null || true send_bark() { local resp rc resp="$(curl -sS --max-time 10 --retry 3 --retry-delay 1 --retry-all-errors -w ' http=%{http_code}' "$BARK_REQ_URL" 2>&1)" rc=$? printf '%s result agent=%s event=%s rc=%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$AGENT" "$EVENT" "$rc" "$resp" >> "$LOG_PATH" 2>/dev/null || true printf '%s\n' "$resp" return $rc } if [ "${NOTIFY_WATCH_SYNC:-0}" = "1" ]; then send_bark printf '\n' else # 必须关闭或重定向标准流,避免宿主进程等待后台管道 EOF ( send_bark ) </dev/null >/dev/null 2>&1 & fi EOF chmod +x ~/.local/bin/notify-watch.sh
写完先锁定 iPhone 屏幕,用同步模式做一次最小校验,预期输出包含 {"decision":""} 以及 Bark 返回的 {"code":200,"message":"success"} http=200:
▼bash复制代码echo '{"terminationReason":"NO_TOOL_CALL","lastUserInput":"锁屏震动测试","cwd":"~/demo"}' \ | NOTIFY_WATCH_SYNC=1 ~/.local/bin/notify-watch.sh Antigravity Stop
如果此时你的 Apple Watch 已经震动,说明手机与通道侧全部通畅。
四、核心步骤二:无侵入接入 Antigravity 与 Codex
1. 接入 Antigravity(反重力)
打开全局配置文件 ~/.gemini/config/hooks.json。注意很多人本机已经有其他工具注册的 Hook(比如我本机就有一个 "orca-status"),Antigravity 会按顺序合并执行同一事件下的多个命名 Hook,因此不要覆盖原有条目,直接在顶层平级追加 "watch-notify" 即可:
▼json复制代码{ "orca-status": { "Stop": [ "...保留原有配置..." ] }, "watch-notify": { "Stop": [ { "type": "command", "command": "~/.local/bin/notify-watch.sh Antigravity Stop", "timeout": 5 } ] } }
这里顺带回答一个大家最关心的问题:加了这个 Hook 会不会浪费 Token?完全不会,消耗为 0 Token。 因为 Stop 是在模型执行循环已经结束之后,由 Antigravity 宿主进程直接拉起本地 shell 脚本;只要脚本返回 {"decision":""}(而不返回 "continue"),既不会再次请求大模型,也不会向上下文注入任何字符。
2. 接入 Codex CLI 与 Codex Desktop App
在 Codex 里配置通知时很容易踩一个坑:很多人网上一搜就去改 ~/.codex/config.toml 里的 notify = [...]。但在我的环境里,第 5 行其实已经被 SkyComputerUseClient 占用了,如果硬改 notify 会直接破坏原有功能。
更稳妥的做法是改 ~/.codex/hooks.json,直接在 Stop(任务完成)和 PermissionRequest(卡住等你人工审批)各自对象内部的 "hooks" 列表里追加一条命令(注意不要往 SubagentStop 里追加):
▼json复制代码{ "type": "command", "command": "/Users/<你的用户名>/.local/bin/notify-watch.sh Codex Stop", "timeout": 5, "statusMessage": "Sending Apple Watch notification" }
把上面这段对象放进 "PermissionRequest" 对象的 "hooks" 列表里,并把 "command" 参数末尾的 Codex Stop 改成 Codex PermissionRequest,以后 Codex 需要你点确认时手表也能立刻提醒。修改保存后,我用 codex exec --ephemeral --skip-git-repo-check -c model_reasoning_effort="low" "Reply OK" 跑了一次实测,从 notify-watch.log 中可以明确看到 agent=Codex event=Stop 自动触发。注意如果平时开着 Codex 桌面端,修改配置后需要重启一下 App 或新开线程才会重新加载。
如果你手里还有 dsh 或者其他支持退出回调的终端/脚本任务,只需在命令末尾串一句 && ~/.local/bin/notify-watch.sh dsh Stop < /dev/null(或把它包进自己的 shell 函数里),就能立刻复用同一条 Bark 链路。
五、核心步骤三:攻克 T3 Code(原生 Hook 失效后的只读监听方案)
接入完 Antigravity 和 Codex 后,我原本以为 T3 Code 也会顺带生效,因为我在 T3 Code 里主要跑的就是 codex 和 antigravity_2 两个驱动。结果实测发了一轮消息后,日志里纹丝不动。
排查了 /Applications/T3 Code (Beta).app/Contents/Resources/app.asar 与它的启动环境后,我才找到两个根本原因:
1)T3 Code 在 app.asar 中显式把 "hooks" 和 "codex_hooks" 列入了 EXEC_DISABLED_FEATURES,因此它拉起 codex app-server 时根本不会执行 ~/.codex/hooks.json。
2)T3 Code 驱动 antigravity_2 时,会创建一个 ~/.t3/userdata/providers/antigravity/<hash>/config/ 隔离配置目录,里面只软链了 skills,并没有软链 hooks.json。
同时,T3 Code 自身的桌面通知走的是 Electron 的 new Notification(...),不仅无法转发到 Apple Watch,窗口处于激活聚焦状态时还会被自动抑制。
既然不能靠底层 Hook,最好的办法就是只读监听 T3 Code 本地的状态数据库 ~/.t3/userdata/statev2.sqlite。T3 Code 每次运行结束都会更新 orchestration_v2_projection_runs 表,需要人工确认时会写入 orchestration_v2_projection_runtime_requests 表。
我们在 ~/.local/bin/t3-watch-daemon.py 写入如下守护脚本。为了把资源占用压到最低,脚本每 1.5 秒先对比数据库及 -wal 文件的修改时间与大小,文件没有变化时连 SQLite 连接都不打开;首次启动时把游标定位到最新记录,避免历史消息刷屏:
▼python复制代码#!/usr/bin/env python3 """只读监听 T3 Code 的 statev2.sqlite,并通过 notify-watch.sh 推送完成/审批提醒。""" import json import os import signal import sqlite3 import subprocess import sys import time DB_PATH = os.path.expanduser("~/.t3/userdata/statev2.sqlite") WAL_PATH = DB_PATH + "-wal" STATE_PATH = os.path.expanduser("~/.local/state/t3-watch-cursor.json") NOTIFY_SCRIPT = os.path.expanduser("~/.local/bin/notify-watch.sh") POLL_INTERVAL_SEC = 1.5 RUNNING = True def handle_signal(_signum, _frame): global RUNNING RUNNING = False signal.signal(signal.SIGTERM, handle_signal) signal.signal(signal.SIGINT, handle_signal) def stat_sig(path: str): try: st = os.stat(path) return (st.st_mtime_ns, st.st_size) except OSError: return None def open_ro_db(): return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True, timeout=2.0) def load_cursor(): try: with open(STATE_PATH, "r", encoding="utf-8") as f: data = json.load(f) return { "last_completed_at": data.get("last_completed_at") or "", "seen_runs": list(data.get("seen_runs") or []), "seen_requests": list(data.get("seen_requests") or []), } except Exception: return None def save_cursor(cursor): os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True) cursor["seen_runs"] = cursor["seen_runs"][-200:] cursor["seen_requests"] = cursor["seen_requests"][-200:] tmp = STATE_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cursor, f, ensure_ascii=False, indent=2) os.replace(tmp, STATE_PATH) def init_cursor(): last_completed_at = "" seen_runs, seen_requests = [], [] try: conn = open_ro_db() cur = conn.cursor() cur.execute( "SELECT run_id, completed_at FROM orchestration_v2_projection_runs " "WHERE completed_at IS NOT NULL ORDER BY completed_at DESC LIMIT 20" ) rows = cur.fetchall() if rows: last_completed_at = rows[0][1] or "" seen_runs = [r[0] for r in rows] cur.execute( "SELECT runtime_request_id FROM orchestration_v2_projection_runtime_requests " "ORDER BY created_at DESC LIMIT 20" ) seen_requests = [r[0] for r in cur.fetchall()] conn.close() except sqlite3.Error: pass cursor = { "last_completed_at": last_completed_at, "seen_runs": seen_runs, "seen_requests": seen_requests, } save_cursor(cursor) return cursor def provider_label(raw_provider: str) -> str: p = (raw_provider or "").lower() if p.startswith("codex"): return "Codex" if p.startswith("antigravity"): return "Antigravity" if p.startswith("claude"): return "Claude" return raw_provider or "Agent" def send_notify(event: str, payload: dict): try: subprocess.run( [NOTIFY_SCRIPT, "T3 Code", event], input=json.dumps(payload, ensure_ascii=False).encode("utf-8"), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, check=False, ) except Exception: pass def poll_once(cursor: dict) -> bool: changed = False conn = open_ro_db() try: cur = conn.cursor() cur.execute( """ SELECT r.run_id, r.provider, r.status, r.completed_at, t.title, t.payload_json FROM orchestration_v2_projection_runs r LEFT JOIN orchestration_v2_projection_threads t ON r.thread_id = t.thread_id WHERE r.completed_at IS NOT NULL AND r.completed_at >= ? AND r.status IN ('completed', 'failed', 'error') ORDER BY r.completed_at ASC """, (cursor["last_completed_at"],), ) seen_runs = set(cursor["seen_runs"]) for run_id, provider, status, completed_at, title, payload_json in cur.fetchall(): if run_id in seen_runs: continue seen_runs.add(run_id) cursor["seen_runs"].append(run_id) if completed_at > cursor["last_completed_at"]: cursor["last_completed_at"] = completed_at changed = True worktree = "" parent_thread_id = None if payload_json: try: tmeta = json.loads(payload_json) worktree = tmeta.get("worktreePath") or "" parent_thread_id = (tmeta.get("lineage") or {}).get("parentThreadId") except Exception: worktree = "" # 过滤子线程,避免派发子任务时重复提醒 if parent_thread_id: continue prov = provider_label(provider) thread_title = (title or "T3 会话").strip() send_notify( "Stop", { "cwd": worktree, "lastUserInput": f"{thread_title} ({prov})", "terminationReason": "ERROR" if status in ("failed", "error") else "NO_TOOL_CALL", }, ) cur.execute( """ SELECT req.runtime_request_id, req.kind, t.title, t.payload_json FROM orchestration_v2_projection_runtime_requests req LEFT JOIN orchestration_v2_projection_threads t ON req.thread_id = t.thread_id WHERE req.resolved_at IS NULL AND req.status != 'resolved' ORDER BY req.created_at ASC """ ) seen_reqs = set(cursor["seen_requests"]) for req_id, kind, title, payload_json in cur.fetchall(): if req_id in seen_reqs: continue seen_reqs.add(req_id) cursor["seen_requests"].append(req_id) changed = True worktree = "" parent_thread_id = None if payload_json: try: tmeta = json.loads(payload_json) worktree = tmeta.get("worktreePath") or "" parent_thread_id = (tmeta.get("lineage") or {}).get("parentThreadId") except Exception: worktree = "" if parent_thread_id: continue thread_title = (title or "T3 会话").strip() send_notify( "PermissionRequest", { "cwd": worktree, "tool_name": f"{thread_title} · {kind or '待确认'}", }, ) finally: conn.close() return changed def main(): if not os.path.exists(DB_PATH): sys.stderr.write(f"DB not found: {DB_PATH}\n") sys.exit(1) cursor = load_cursor() or init_cursor() last_sig = None while RUNNING: sig = (stat_sig(DB_PATH), stat_sig(WAL_PATH)) if sig != last_sig: last_sig = sig try: if poll_once(cursor): save_cursor(cursor) except sqlite3.Error: pass time.sleep(POLL_INTERVAL_SEC) if __name__ == "__main__": main()
接着用 macOS 原生 launchd 把它托管起来。写入 ~/Library/LaunchAgents/com.local.t3-watch-notify.plist(把 <你的用户名> 替换为实际用户名),然后用 launchctl bootstrap 加载:
▼xml复制代码<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.local.t3-watch-notify</string> <key>ProgramArguments</key> <array> <string>/opt/homebrew/bin/python3</string> <string>/Users/<你的用户名>/.local/bin/t3-watch-daemon.py</string> </array> <key>RunAtLoad</key><true/> <key>KeepAlive</key><true/> <key>StandardOutPath</key> <string>/Users/<你的用户名>/.local/state/t3-watch-daemon.log</string> <key>StandardErrorPath</key> <string>/Users/<你的用户名>/.local/state/t3-watch-daemon.log</string> <key>EnvironmentVariables</key> <dict> <key>HOME</key> <string>/Users/<你的用户名></string> <key>PATH</key> <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string> </dict> </dict> </plist>
注:如果使用的是 Intel 芯片 Mac,请先通过
which python3确认路径,将上面ProgramArguments中的/opt/homebrew/bin/python3替换为对应路径(如/usr/local/bin/python3)。
加载并检查进程是否处于运行状态:
▼bash复制代码chmod +x ~/.local/bin/t3-watch-daemon.py plutil -lint ~/Library/LaunchAgents/com.local.t3-watch-notify.plist launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.local.t3-watch-notify.plist launchctl print gui/$(id -u)/com.local.t3-watch-notify | grep -E 'state =|pid ='
看到 state = running 后,我在 T3 Code 里发了一句测试提示词,结束不到 2 秒手表就收到通知,notify-watch.log 也同步打印出了 agent=T3 Code event=Stop 与 http=200。
六、进阶必看:过滤子 Agent 与 Swarm 中间态,做到“一轮只震一次”
三端全通之后,我很快碰到了第二个真实痛点:当主 Agent 进入多步骤并发(比如 Antigravity 启动 swarm 或调用 research 子 Agent)时,手表开始频繁震动。
原因很简单,每一个子 Agent 或 swarm worker 在底层都是一个独立的对话循环,它们结束时一样会触发 hooks.json 的 Stop 事件;而主协调 Agent 在派发完后台任务暂停等待的那一刻,也会先触发一次中间态 Stop。
要实现“只有当我输入的这轮主任务全部收尾时才提醒一次”,三端各自有精准的拦截特征,判断流转如下图所示。
这些过滤逻辑其实都已经内嵌在上面那份 notify-watch.sh 和 t3-watch-daemon.py 里了,核心依据分别对应三端的数据结构:
1)Antigravity:先用 conversationId 只读查询 ~/.gemini/antigravity/conversation_summaries.db 与 conversation_parents,只要存在 parent_conversation_id、nesting_depth > 0 或 agent_name,直接判定为子 Agent 并跳过;若数据库刚创建尚未刷盘,则兜底读取 transcriptPath 首行是否 source == "SYSTEM"。最后再核对传入的 fullyIdle 字段,只要 fullyIdle 为 false(说明还有后台子任务在跑),一律跳过,等主会话最后一次汇总完且 fullyIdle: true 再推送。
2)Codex:在 hooks.json 里不配置 SubagentStop;同时在脚本中检查 agent_id、parent_thread_id 字段,并用 session_id 只读查询 ~/.codex/state_5.sqlite 的 threads 表,过滤掉 source 以 subagent 开头或带父线程指针的记录。
3)T3 Code:在守护进程里解析线程 payload_json 中的 lineage.parentThreadId,存在父线程的子线程直接忽略,仅对主线程的终态与未解决的 runtime_requests 发通知。
在改完过滤脚本后,我用本机真实的子 Agent ID、Swarm Worker ID 和主会话载荷跑了 5 组本地验证,日志输出完全符合预期:
▼text复制代码2026-12-01 21:02:26 skip agent=Antigravity event=Stop reason=subagent_db(parent=9fc95c41,depth=1,name=research) 2026-12-01 21:02:26 skip agent=Antigravity event=Stop reason=subagent_db(parent=2ceec0ec,depth=1,name=impl-code-schemas) 2026-12-01 21:02:26 skip agent=Antigravity event=Stop reason=not_fully_idle 2026-12-01 21:02:26 skip agent=Codex event=Stop reason=codex_subagent_field 2026-12-01 21:02:26 agent=Antigravity event=Stop 2026-12-01 21:02:27 result agent=Antigravity event=Stop rc=0 {"code":200,"message":"success","timestamp":1796130147} http=200
只有最后一条主会话 fullyIdle: true 真正发出了 Bark 请求,其余 4 条全部在本地毫秒级拦截。
七、常见踩坑排查与自测清单
实际折腾这套链路时,有四个坑出现频率最高,对应的修复方法都很明确:
1)本地代理下报 curl: (35) SSL_ERROR_SYSCALL 或 3 秒超时
如果你的 Mac 开着代理(如 127.0.0.1:7890 或 TUN Fake-IP),api.day.app:443 经过代理节点转发时可能延迟飙到 3~7 秒甚至偶发 TLS 握手重置。脚本里我已经加了 --max-time 10 --retry 3 --retry-delay 1 --retry-all-errors 做兜底重试;如果想把延迟稳定压回几百毫秒,建议直接在代理规则里给 DOMAIN,api.day.app 配上 DIRECT(直连)。
2)手机看得到推送,但工作模式下手表不震动
先关掉工作模式测一条,如果一关立刻就震,说明 Watch 硬件和镜像本身没问题,问题大概率出在 iPhone 设置 → 专注模式 → 工作 → App 没选成“允许列表”或者没开“时效性通知”;另外记得确认 设置 → 通知 → Bark → 声音 处于打开状态。
3)launchctl bootout 后紧接着 bootstrap 报错 Input/output error
macOS 卸载 LaunchAgent 是异步过程。修改完 .plist 或 Python 脚本需要重启守护进程时,不要把 bootout 和 bootstrap 写在同一行无缝连跑,直接用 launchctl kickstart -k gui/$(id -u)/com.local.t3-watch-notify 原地热重启,或者中间 sleep 1 再加载。
4)怀疑某轮任务漏推了怎么查?
直接执行 tail -n 30 ~/.local/state/notify-watch.log:如果是被规则拦截了,能看到清晰的 skip ... reason=...(顺便提醒,在 swarm 模式下如果特意保留了一个常驻 waiting 状态的监控 worker 没关,可能会导致主会话结束时 fullyIdle 仍为 false 而被跳过);如果是网络波动,能直接看到对应的 curl 返回码与 HTTP 状态。
八、写在最后
把多 Agent 任务流接到 Apple Watch 之后,同时开着 Antigravity、Codex、T3 Code 或终端里的 dsh 干活时,终于不用每隔两分钟切回来盯一眼进度条了。整套方案加起来也就四百多行脚本加几段 JSON/XML 配置,不碰任何软件底层、不额外花一分钱算力,算是我今年在多 Agent 协同上投入产出比最高的小改造。
如果你也是正在用 AI 搓工具、搭自动化工作流的开发者,欢迎关注我的公众号「小火龙AI 手记」。后续我会继续挖掘 GitHub 上真正好用的开源效率项目,也会把自己在独立开发、Agent 工程化落地过程中踩过的坑与填坑实录毫无保留地整理成可复现的教程分享给你。
参考资料
