ring-cli 0.17.2__tar.gz → 0.17.4__tar.gz

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.
Files changed (69) hide show
  1. {ring_cli-0.17.2 → ring_cli-0.17.4}/PKG-INFO +1 -1
  2. {ring_cli-0.17.2 → ring_cli-0.17.4}/pyproject.toml +2 -2
  3. {ring_cli-0.17.2 → ring_cli-0.17.4}/pyproject.toml.orig +2 -2
  4. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/cli.py +5 -0
  5. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/hook.py +214 -74
  6. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/registry.py +83 -21
  7. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/__init__.py +17 -1
  8. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/tui.py +15 -5
  9. ring_cli-0.17.4/src/ring/waiting.py +104 -0
  10. {ring_cli-0.17.2 → ring_cli-0.17.4}/LICENSE +0 -0
  11. {ring_cli-0.17.2 → ring_cli-0.17.4}/README.en.md +0 -0
  12. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/__init__.py +0 -0
  13. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/__main__.py +0 -0
  14. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/agent_notify.py +0 -0
  15. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/__init__.py +0 -0
  16. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/_args.py +0 -0
  17. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/completion.py +0 -0
  18. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/digest.py +0 -0
  19. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/doctor.py +0 -0
  20. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/focus.py +0 -0
  21. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/gc.py +0 -0
  22. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/hook.py +0 -0
  23. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/quiet.py +0 -0
  24. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/commands/stats.py +0 -0
  25. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/config.py +0 -0
  26. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/__init__.py +0 -0
  27. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/applescript.py +0 -0
  28. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/base.py +0 -0
  29. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/iterm2.py +0 -0
  30. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/kitty.py +0 -0
  31. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/linux_wm.py +0 -0
  32. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/neovim.py +0 -0
  33. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/terminal.py +0 -0
  34. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/tmux.py +0 -0
  35. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/focus/trace.py +0 -0
  36. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/gc.py +0 -0
  37. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/hook_protocol.py +0 -0
  38. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/i18n.py +0 -0
  39. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/ipc.py +0 -0
  40. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/labels.py +0 -0
  41. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  42. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/locale/en/LC_MESSAGES/ring.po +0 -0
  43. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/locale/ring.pot +0 -0
  44. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/__init__.py +0 -0
  45. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/base.py +0 -0
  46. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/command.py +0 -0
  47. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/notify_send.py +0 -0
  48. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/ntfy.py +0 -0
  49. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/osascript_notifier.py +0 -0
  50. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/terminal_notifier.py +0 -0
  51. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify/webhook.py +0 -0
  52. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/notify_queue.py +0 -0
  53. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/osascript.py +0 -0
  54. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/pathutil.py +0 -0
  55. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/payload_log.py +0 -0
  56. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/permission.py +0 -0
  57. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/plugins.py +0 -0
  58. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/ps_parse.py +0 -0
  59. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/question_detect.py +0 -0
  60. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/base.py +0 -0
  61. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/claude_code.py +0 -0
  62. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/codex.py +0 -0
  63. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/hook_registry.py +0 -0
  64. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/sources/local_llm.py +0 -0
  65. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/stats.py +0 -0
  66. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/subproc.py +0 -0
  67. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/tmux_scan.py +0 -0
  68. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/transcript.py +0 -0
  69. {ring_cli-0.17.2 → ring_cli-0.17.4}/src/ring/watcher.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ring-cli
3
- Version: 0.17.2
3
+ Version: 0.17.4
4
4
  Summary: RiNG — Realtime Instance Notification Grid for active agent CLI sessions.
5
5
  Keywords: claude-code,codex,ollama,llama-cpp,tui,dashboard,session,monitor,rich
6
6
  Author: Wei Lee
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ring-cli"
3
- version = "0.17.2"
3
+ version = "0.17.4"
4
4
  description = "RiNG — Realtime Instance Notification Grid for active agent CLI sessions."
5
5
  readme = "README.en.md"
6
6
  requires-python = ">=3.13"
@@ -77,7 +77,7 @@ include-group = "test"
77
77
  include-group = "linters"
78
78
 
79
79
  [build-system]
80
- requires = ["uv_build >= 0.10.3, <0.12.0"]
80
+ requires = ["uv_build>=0.10.3,<0.13.0"]
81
81
  build-backend = "uv_build"
82
82
 
83
83
  [tool.uv.build-backend]
@@ -2,7 +2,7 @@
2
2
  # import 的 module(見 [tool.uv.build-backend] module-name)與 CLI 指令仍是 `ring`。
3
3
  [project]
4
4
  name = "ring-cli"
5
- version = "0.17.2"
5
+ version = "0.17.4"
6
6
  description = "RiNG — Realtime Instance Notification Grid for active agent CLI sessions."
7
7
  readme = "README.en.md"
8
8
  requires-python = ">=3.13"
@@ -62,7 +62,7 @@ linters = ["ruff>=0.15.1", "mypy>=1.19.1", "prek>=0.3.3", "commitizen>=4.13.9"]
62
62
  docs = ["mkdocs-material>=9,<10", "mkdocs-static-i18n>=1.3,<2"]
63
63
 
64
64
  [build-system]
65
- requires = ["uv_build >= 0.10.3, <0.12.0"]
65
+ requires = ["uv_build>=0.10.3,<0.13.0"]
66
66
  build-backend = "uv_build"
67
67
 
68
68
  [tool.uv.build-backend]
@@ -284,6 +284,11 @@ def render_json(sessions: list[Session]) -> str:
284
284
  "last_active": s.last_active,
285
285
  "last_action": s.last_action,
286
286
  "waiting_detail": s.waiting_detail,
287
+ "waiting_requests": [
288
+ {"id": request.request_id, "owner": request.owner, "kind": request.kind, "detail": request.detail}
289
+ for request in s.waiting_requests
290
+ if s.status is Status.WAITING
291
+ ],
287
292
  "todo": {"done": s.todo[0], "total": s.todo[1]} if s.todo else None,
288
293
  "source": s.source,
289
294
  }
@@ -26,13 +26,16 @@ Agent CLI 在各事件把一段 JSON 從 stdin 餵進來。我們據此 upsert
26
26
 
27
27
  from __future__ import annotations
28
28
 
29
+ import fcntl
29
30
  import json
30
31
  import os
31
32
  import shutil
32
33
  import subprocess
33
34
  import sys
34
35
  import time
35
- from dataclasses import dataclass, replace
36
+ from collections.abc import Iterator
37
+ from contextlib import contextmanager
38
+ from dataclasses import asdict, dataclass, replace
36
39
  from pathlib import Path
37
40
  from typing import Any
38
41
  from urllib.parse import quote
@@ -52,6 +55,16 @@ from ring.registry import (
52
55
  )
53
56
  from ring.stats import log_transition
54
57
  from ring.transcript import _extract_todo, _latest_action, _tail_records
58
+ from ring.waiting import (
59
+ FOREGROUND_OWNER,
60
+ UNKNOWN_OWNER,
61
+ WaitingRequest,
62
+ event_owner,
63
+ primary_wait,
64
+ read_waiting_requests,
65
+ renew_wait,
66
+ tool_request_id,
67
+ )
55
68
 
56
69
  _HOOK_EVENTS = list(HOOK_EVENTS)
57
70
 
@@ -120,25 +133,22 @@ def _ps_row(pid: int) -> tuple[int, str] | None:
120
133
  return None
121
134
 
122
135
 
123
- def _session_tty(process_names: tuple[str, ...]) -> str:
124
- """hook 是 agent CLI 的後代——往上找到 provider process,回它的控制終端 tty。
125
-
126
- 這是「session → 哪個終端」最精準的對應(不必靠 cwd 猜),給非-tmux 終端 focuser(iTerm2 等)跳轉用。
127
- """
136
+ def _session_pid(process_names: tuple[str, ...]) -> int | None:
137
+ """hook 是 agent CLI 的後代——往上找到真正的 provider process PID。"""
128
138
  if not process_names:
129
- return ""
139
+ return None
130
140
  pid = os.getppid()
131
141
  for _attempt in range(12):
132
142
  row = _ps_row(pid)
133
143
  if row is None:
134
- return ""
144
+ return None
135
145
  ppid, comm = row
136
146
  if Path(comm.strip()).name in process_names:
137
- return _pid_tty(pid)
147
+ return pid
138
148
  if ppid <= 1:
139
- return ""
149
+ return None
140
150
  pid = ppid
141
- return ""
151
+ return None
142
152
 
143
153
 
144
154
  def _controlling_tty() -> str:
@@ -188,33 +198,120 @@ def run_hook(provider: str = "claude-code") -> int:
188
198
  return _delegate_to_agent_hooks(raw, selected_provider)
189
199
 
190
200
 
201
+ @contextmanager
202
+ def _session_state_lock(path: Path) -> Iterator[None]:
203
+ """同 session 的 hook 序列化整段 read-modify-write,包含 SessionEnd。
204
+
205
+ lock 檔不隨 row 刪除,避免仍在排隊的 writer 鎖住舊 inode、另一個 writer 卻鎖住新 inode。
206
+ """
207
+ path.parent.mkdir(parents=True, exist_ok=True)
208
+ with path.with_suffix(".json.lock").open("a", encoding="utf-8") as handle:
209
+ fcntl.flock(handle, fcntl.LOCK_EX)
210
+ try:
211
+ yield
212
+ finally:
213
+ fcntl.flock(handle, fcntl.LOCK_UN)
214
+
215
+
191
216
  def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
192
- """把事件正規化後 upsert / 刪除 RiNG registry 檔(看板狀態)。失敗安靜吞,不回傳。"""
217
+ """正規化後序列化 registry 更新;I/O 失敗不影響 hook 後續委派。"""
193
218
  adapter = adapter_for(selected_provider)
194
219
  event = adapter.normalize(data)
195
220
  if event is None:
196
221
  return
197
222
  event = _maybe_flag_trailing_question(event, data)
198
223
 
199
- unhide_session(event.session_id)
200
224
  path = RING_REGISTRY / f"{quote(event.session_id, safe=':')}.json"
225
+ try:
226
+ with _session_state_lock(path):
227
+ notification = _update_session_state(path, event, data, adapter.process_names)
228
+ except OSError:
229
+ return
230
+ # 系統通知可能等待外部程序,不可持鎖阻擋後續解除等待的 hook。
231
+ if notification is not None:
232
+ _ring_waiting_now(*notification)
233
+
234
+
235
+ def _update_session_state(
236
+ path: Path, event: NormalizedHookEvent, data: dict[str, Any], process_names: tuple[str, ...]
237
+ ) -> tuple[NormalizedHookEvent, dict[str, Any], str] | None:
238
+ """持有 session lock 時合併並寫入;回傳需在鎖外發送的通知。"""
201
239
  prev_row = _previous_row(path)
202
240
  prev_status = str(prev_row["status"]) if "status" in prev_row else None
203
- # 一般 Notification 只能升 🔴、不能降 🟡——閒置提醒不是「使用者回應了」的證據。
204
- keep_waiting = _notification_keeps_waiting(event, prev_row)
205
- if keep_waiting:
206
- event = replace(
207
- event,
208
- status=Status.WAITING,
209
- waiting_for=str(prev_row.get("waiting_for", "")),
210
- waiting_kind=str(prev_row.get("waiting_kind", "")),
211
- detail=str(prev_row.get("waiting_detail", "")),
212
- )
241
+ owner = event_owner(data)
242
+ is_subagent_event = owner != FOREGROUND_OWNER
243
+ if is_subagent_event:
244
+ # Subagent SessionEnd 不是 host session 的結束。
245
+ if event.status is Status.ENDED:
246
+ raw_pending = prev_row.get("pending_permissions", [])
247
+ owns_pending = isinstance(raw_pending, list) and any(
248
+ isinstance(item, dict) and item.get("owner") == owner for item in raw_pending
249
+ )
250
+ if owner == UNKNOWN_OWNER or (owner not in read_waiting_requests(prev_row) and not owns_pending):
251
+ return None
252
+ # 只結束這個 agent 的待決事項;host 仍在工作,不能刪掉共用 registry。
253
+ event = replace(event, status=Status.WORKING)
254
+ if prev_row:
255
+ event = replace(
256
+ event,
257
+ cwd=str(prev_row.get("cwd", event.cwd)),
258
+ transcript_path=str(prev_row.get("source_path", "")),
259
+ )
260
+ unhide_session(event.session_id)
213
261
  if event.status is Status.ENDED:
214
262
  path.unlink(missing_ok=True) # 乾淨離場:直接消失
215
263
  if prev_status is not None and prev_status != Status.ENDED.value:
216
264
  log_transition(event.session_id, event.provider, event.cwd, Status.ENDED.value)
217
- return
265
+ return None
266
+
267
+ previous_pid = int(prev_row["agent_pid"]) if str(prev_row.get("agent_pid", "")).isdigit() else None
268
+ agent_pid = None if is_subagent_event else _session_pid(process_names)
269
+ same_binding = is_subagent_event or (
270
+ event.event != "SessionStart" and (agent_pid is None or agent_pid == previous_pid)
271
+ )
272
+ if same_binding and agent_pid is None:
273
+ # 查詢未知不是 session 換人;保留已取得的前景身分,成功的新 lookup 仍可重新綁定。
274
+ agent_pid = previous_pid
275
+
276
+ reset_waits = not is_subagent_event and (
277
+ event.event == "SessionStart" or (previous_pid is not None and agent_pid != previous_pid)
278
+ )
279
+ previous_state = {} if reset_waits else prev_row
280
+ requests = read_waiting_requests(previous_state)
281
+ keep_waiting = _notification_keeps_waiting(event, prev_row)
282
+ now = time.time()
283
+ pending, matched = _pending_permission_details(event, previous_state, data, owner, now)
284
+ request_id = tool_request_id(data)
285
+ if event.event == "Notification" and event.waiting_kind == "permission" and matched is not None:
286
+ # 無 agent ID 的 Notification 只有唯一候選時才可借用其來源與摘要。
287
+ owner = str(matched["owner"])
288
+ event = replace(event, detail=str(matched["detail"]))
289
+ request_id = str(matched["request_id"])
290
+ if event.status is Status.WAITING:
291
+ previous_wait = requests.get(owner)
292
+ if (
293
+ event.event == "Notification"
294
+ and event.waiting_kind == "permission"
295
+ and not request_id
296
+ and not pending
297
+ and previous_wait is not None
298
+ and previous_wait.kind == "permission"
299
+ and previous_wait.tool_use_id
300
+ ):
301
+ # 暫存摘要 TTL 過後的泛用提醒不是另一筆請求,也不該蓋掉已知的工具摘要。
302
+ request_id = previous_wait.tool_use_id
303
+ event = replace(event, detail=previous_wait.detail)
304
+ requests[owner] = renew_wait(
305
+ previous_wait,
306
+ WaitingRequest(owner, event.waiting_kind, event.detail, event.waiting_for, now, tool_use_id=request_id),
307
+ )
308
+ elif not keep_waiting and owner != UNKNOWN_OWNER:
309
+ requests.pop(owner, None)
310
+ if owner == FOREGROUND_OWNER:
311
+ # 沒有 agent ID 的舊/匿名等待只能由前景的明確回應解除。
312
+ requests.pop(UNKNOWN_OWNER, None)
313
+ selected = primary_wait(requests) if requests else None
314
+ status = Status.WAITING if selected is not None else event.status
218
315
 
219
316
  last_action, todo = event.last_action or "—", None
220
317
  tp = event.transcript_path
@@ -224,29 +321,37 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
224
321
  last_action = _latest_action(records)
225
322
  todo = _extract_todo(records)
226
323
 
227
- now = time.time()
228
324
  payload: dict[str, Any] = {
229
325
  "session_id": event.session_id,
230
326
  "provider": event.provider,
231
327
  "cwd": event.cwd,
232
- "origin_cwd": event.cwd,
233
- "status": event.status.value,
328
+ "origin_cwd": prev_row.get("origin_cwd", event.cwd) if is_subagent_event else event.cwd,
329
+ "status": status.value,
234
330
  # 最後一個 hook 事件名:讀取側據此做 codex 的核可等待判定(最後事件是
235
331
  # PermissionRequest 且靜默逾時 → 🔴),任何後續事件覆寫它就自然清紅。
236
332
  "last_event": event.event,
333
+ "last_event_owner": owner,
334
+ "last_tool_use_id": request_id,
237
335
  "last_active": now,
238
336
  "heartbeat_at": now,
239
337
  "last_action": last_action,
240
338
  "hook_pid": os.getpid(),
339
+ "waiting_requests": {key: asdict(request) for key, request in requests.items()},
340
+ "pending_permissions": pending,
241
341
  }
342
+ if agent_pid is not None:
343
+ payload["agent_pid"] = agent_pid
242
344
  if tp:
243
345
  payload["source_path"] = tp
244
- tmux_pane = os.environ.get("TMUX_PANE", "").strip()
346
+ previous_pane = str(prev_row.get("tmux_pane", "")) if same_binding else ""
347
+ tmux_pane = previous_pane if is_subagent_event else os.environ.get("TMUX_PANE", "").strip() or previous_pane
245
348
  if tmux_pane:
246
349
  payload["tmux_pane"] = tmux_pane
247
350
  if todo:
248
351
  payload["todo"] = list(todo)
249
- if event.waiting_for:
352
+ if selected is not None and selected.waiting_for:
353
+ payload["waiting_for"] = selected.waiting_for
354
+ elif selected is None and event.waiting_for:
250
355
  payload["waiting_for"] = event.waiting_for
251
356
 
252
357
  # 裸 PermissionRequest(→ WORKING)帶著最具體的 tool/指令摘要;真的停下來等人時,
@@ -255,48 +360,50 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
255
360
  # (還新鮮的話)拿它當 waiting_detail,看板與通知才看得到具體是哪條指令在等核可。
256
361
  # Codex 沒有 Notification:這份暫存改由讀取側的靜默逾時判定拿去當 waiting_detail
257
362
  # (見 registry._promote_codex_permission_wait)。
258
- pending_detail, pending_at = _pending_permission_detail(event, prev_row, now)
259
- if pending_detail:
260
- payload["pending_permission_detail"] = pending_detail
261
- payload["pending_permission_detail_at"] = pending_at
262
-
263
- if event.status is Status.WAITING and event.waiting_kind:
264
- payload["waiting_kind"] = event.waiting_kind
265
- if event.status is Status.WAITING:
266
- waiting_detail = event.detail
267
- if event.event == "Notification" and event.waiting_kind == "permission" and pending_detail:
268
- waiting_detail = pending_detail
269
- if waiting_detail:
270
- payload["waiting_detail"] = waiting_detail
271
- tty = event.tty or _controlling_tty() or _session_tty(adapter.process_names)
363
+ if matched is not None:
364
+ payload["pending_permission_detail"] = matched["detail"]
365
+ payload["pending_permission_detail_at"] = matched["at"]
366
+
367
+ if selected is not None:
368
+ if selected.kind:
369
+ payload["waiting_kind"] = selected.kind
370
+ if selected.owner.startswith("agent:"):
371
+ payload["waiting_agent_id"] = selected.owner.removeprefix("agent:")
372
+ if selected.detail:
373
+ payload["waiting_detail"] = selected.detail
374
+ previous_tty = str(prev_row.get("tty", "")) if same_binding else ""
375
+ if is_subagent_event:
376
+ tty = previous_tty or (_pid_tty(agent_pid) if agent_pid is not None else "")
377
+ else:
378
+ tty = event.tty or _controlling_tty() or (_pid_tty(agent_pid) if agent_pid is not None else "") or previous_tty
272
379
  if tty:
273
380
  payload["tty"] = tty
274
381
 
275
382
  # waiting 通知冷卻(防翻轉轟炸):hook 是短命 process,冷卻狀態持久化在 registry row
276
383
  # 的 waiting_notified_at(上次 waiting 通知的 epoch 時間戳)。離開 WAITING 也要把時間戳
277
384
  # 帶進新 row(payload 每次重建,不帶會遺失),快速翻回 WAITING 時才判得出「還在冷卻期」。
278
- # 舊 row 沒這欄位 = 從未通知過 → 照發。並發寫沿用既有 tmp+replace 的 last-write-wins。
279
- last_notified = _as_epoch(prev_row.get("waiting_notified_at"))
385
+ # 舊 row 沒這欄位 = 從未通知過 → 照發。讀取與預約通知時間同樣受 session lock 保護。
386
+ last_notified = _as_epoch(previous_state.get("waiting_notified_at"))
280
387
  if last_notified is not None:
281
388
  payload["waiting_notified_at"] = last_notified
282
389
  should_ring = False
283
- if event.status is Status.WAITING and not keep_waiting:
284
- # keep_waiting=只是沿用上一筆就已成立的 🔴,不是新的等待事件,不重發通知
285
- # (重複提醒由 TUI 的提醒排程器負責,見 tui._ring_on_waiting_alerts)。
390
+ if event.status is Status.WAITING:
391
+ # 只通知本事件提出的等待;沿用其他 owner 的 🔴 不算新的等待事件。
286
392
  should_ring = _waiting_ring_allowed(last_notified, now)
287
393
  if should_ring:
288
394
  payload["waiting_notified_at"] = now
289
395
 
290
- RING_REGISTRY.mkdir(parents=True, exist_ok=True)
291
396
  tmp = path.with_suffix(".json.tmp")
292
397
  tmp.write_text(json.dumps(payload))
293
398
  tmp.replace(path) # atomic
294
399
 
295
- if prev_status != event.status.value:
296
- log_transition(event.session_id, event.provider, event.cwd, event.status.value)
400
+ if prev_status != status.value:
401
+ log_transition(event.session_id, event.provider, event.cwd, status.value)
297
402
 
298
403
  if should_ring:
299
- _ring_waiting_now(event, payload, last_action)
404
+ # 看板可能仍選著另一個等待者;即時通知要描述這次事件本身。
405
+ return event, payload | {"waiting_kind": event.waiting_kind, "waiting_detail": event.detail}, last_action
406
+ return None
300
407
 
301
408
 
302
409
  def _notification_keeps_waiting(event: NormalizedHookEvent, prev_row: dict[str, Any]) -> bool:
@@ -311,8 +418,8 @@ def _notification_keeps_waiting(event: NormalizedHookEvent, prev_row: dict[str,
311
418
 
312
419
  只有真的證明使用者已經回應的事件(UserPromptSubmit / PreToolUse / PostToolUse /
313
420
  下一輪 Stop)才該清掉 WAITING;Notification 一律只能升 🔴、不能降 🟡。這裡回 True 時
314
- 由呼叫端沿用舊 row 的 waiting_for / waiting_kind / waiting_detail(payload 每次重建,
315
- 不帶就會遺失),並且不重發通知。
421
+ 由呼叫端保留 waiting_requests 的各來源內容(payload 每次重建,不帶就會遺失),
422
+ 再選出摘要欄位,並且不重發通知。
316
423
  """
317
424
  if event.event != "Notification" or event.status is not Status.IDLE:
318
425
  return False
@@ -354,29 +461,62 @@ def _as_epoch(v: Any) -> float | None:
354
461
 
355
462
 
356
463
  # 暫存的權限 detail 新鮮期(秒):permission_prompt Notification 通常在裸 PermissionRequest
357
- # 後 ~6 秒到;超過這個窗口的暫存視為過期(大概率屬於已解決的舊請求),不再拿來當 detail。
464
+ # 後 ~6 秒到;超過這個窗口的暫存視為過期(多半屬於已解決的舊請求),不再拿來當 detail。
358
465
  _PENDING_DETAIL_TTL = 120.0
359
466
 
360
467
  # 這些事件代表權限已放行(工具跑完)或回合已推進(新輸入 / 回合結束)→ 清掉暫存。
361
- _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop"}
362
-
363
-
364
- def _pending_permission_detail(event: NormalizedHookEvent, prev_row: dict[str, Any], now: float) -> tuple[str, float]:
365
- """決定這次要寫進 row 的「暫存權限 detail」:(detail, 暫存時間戳);不留就回 ("", 0.0)。
366
-
367
- - 裸 PermissionRequest(→ WORKING)帶 detail → 以這次的 detail 起新暫存
368
- - PostToolUse / UserPromptSubmit / Stop → 清掉(已放行或回合推進,舊暫存失效)
369
- - 其餘事件 → 沿用 prev_row 的暫存(row 每次重建,不帶會遺失),但過期就丟
370
- """
371
- if event.event == "PermissionRequest" and event.status is Status.WORKING and event.detail:
372
- return event.detail, now
373
- if event.event in _PENDING_DETAIL_CLEAR_EVENTS:
374
- return "", 0.0
375
- prev_detail = prev_row.get("pending_permission_detail")
376
- prev_at = _as_epoch(prev_row.get("pending_permission_detail_at"))
377
- if isinstance(prev_detail, str) and prev_detail and prev_at is not None and now - prev_at <= _PENDING_DETAIL_TTL:
378
- return prev_detail, prev_at
379
- return "", 0.0
468
+ _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop", "SessionEnd"}
469
+
470
+
471
+ def _pending_permission_details(
472
+ event: NormalizedHookEvent, prev_row: dict[str, Any], data: dict[str, Any], owner: str, now: float
473
+ ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
474
+ """依來源/tool use ID 保存候選;沒有唯一配對時不向通知提供摘要。"""
475
+ raw = prev_row.get("pending_permissions")
476
+ if not isinstance(raw, list):
477
+ raw = [
478
+ {
479
+ "owner": FOREGROUND_OWNER,
480
+ "request_id": "",
481
+ "detail": prev_row.get("pending_permission_detail"),
482
+ "at": prev_row.get("pending_permission_detail_at"),
483
+ }
484
+ ]
485
+ pending = [
486
+ item
487
+ for item in raw
488
+ if isinstance(item, dict)
489
+ and isinstance(item.get("owner"), str)
490
+ and isinstance(item.get("request_id"), str)
491
+ and isinstance(item.get("detail"), str)
492
+ and item["detail"]
493
+ and (at := _as_epoch(item.get("at"))) is not None
494
+ and 0 <= now - at <= _PENDING_DETAIL_TTL
495
+ ]
496
+ request_id = tool_request_id(data)
497
+ if owner != UNKNOWN_OWNER:
498
+ if event.event in _PENDING_DETAIL_CLEAR_EVENTS:
499
+ ambiguous_completion = (
500
+ event.event == "PostToolUse" and not request_id and sum(item["owner"] == owner for item in pending) > 1
501
+ )
502
+ pending = [
503
+ item
504
+ for item in pending
505
+ if ambiguous_completion
506
+ or item["owner"] != owner
507
+ or (event.event == "PostToolUse" and request_id and item["request_id"] != request_id)
508
+ ]
509
+ if event.event == "PermissionRequest" and event.status is Status.WORKING and event.detail:
510
+ pending = [item for item in pending if (item["owner"], item["request_id"]) != (owner, request_id)]
511
+ pending.append({"owner": owner, "request_id": request_id, "detail": event.detail, "at": now})
512
+ # 缺少來源的 Notification 可能來自背景請求;多個候選時不把最後一筆當答案。
513
+ unqualified = event.event == "Notification" and owner == FOREGROUND_OWNER
514
+ candidates = [
515
+ item
516
+ for item in pending
517
+ if (unqualified or item["owner"] == owner) and (not request_id or item["request_id"] == request_id)
518
+ ]
519
+ return pending, candidates[0] if len(candidates) == 1 else None
380
520
 
381
521
 
382
522
  def _waiting_ring_allowed(last_notified: float | None, now: float) -> bool:
@@ -55,6 +55,7 @@ from ring.transcript import (
55
55
  _recent_actions,
56
56
  _tail_records,
57
57
  )
58
+ from ring.waiting import FOREGROUND_OWNER, WaitingRequest, read_waiting_requests
58
59
 
59
60
  CLAUDE_PROJECTS = Path.home() / ".claude" / "projects"
60
61
  RING_REGISTRY = Path.home() / ".config" / "ring" / "sessions"
@@ -86,6 +87,7 @@ BARE_SESSION_START_GRACE_SECONDS = 120.0
86
87
  # 同義 provider 名先正規化(例如 "claude" → "claude-code")。
87
88
  _PROVIDER_ALIASES: dict[str, str] = {"claude": "claude-code"}
88
89
  _PROVIDER_PROCS: dict[str, Callable[[], list[tuple[str, str]] | None]] = {}
90
+ _PROVIDER_PIDS: dict[str, Callable[[], list[int] | None]] = {}
89
91
 
90
92
 
91
93
  def _canonical_provider(provider: str) -> str:
@@ -269,13 +271,25 @@ def prune_hidden_sessions(
269
271
  return stale
270
272
 
271
273
 
272
- def register_provider_procs(provider: str, detector: Callable[[], list[tuple[str, str]] | None]) -> None:
274
+ def register_provider_procs(
275
+ provider: str,
276
+ detector: Callable[[], list[tuple[str, str]] | None],
277
+ *,
278
+ pid_detector: Callable[[], list[int] | None] | None = None,
279
+ ) -> None:
273
280
  """註冊某 provider 的 live-process 偵測器(回傳 ``[(cwd, tty), …]``)。
274
281
 
275
282
  有偵測器的 provider 才會在 ``_hook_sessions`` 走 process-based 存活清理;沒註冊的
276
283
  provider 一律 fail-open(不靠 process 判離場,交給該工具自己的 SessionEnd hook)。
284
+ 有提供 ``pid_detector`` 時,新格式 hook row 會優先用精準 PID 驗活;未提供或舊格式
285
+ row 則繼續使用 cwd / tty 判定。
277
286
  """
278
- _PROVIDER_PROCS[_canonical_provider(provider)] = detector
287
+ canonical = _canonical_provider(provider)
288
+ _PROVIDER_PROCS[canonical] = detector
289
+ if pid_detector is None:
290
+ _PROVIDER_PIDS.pop(canonical, None)
291
+ else:
292
+ _PROVIDER_PIDS[canonical] = pid_detector
279
293
 
280
294
 
281
295
  def collect_provider_procs() -> dict[str, list[tuple[str, str]] | None]:
@@ -287,6 +301,20 @@ def collect_provider_procs() -> dict[str, list[tuple[str, str]] | None]:
287
301
  return {provider: detector() for provider, detector in _PROVIDER_PROCS.items()}
288
302
 
289
303
 
304
+ def collect_provider_pids(providers: set[str] | None = None) -> dict[str, list[int] | None]:
305
+ """取得 provider 的 live PID,供新格式 hook row 做精準存活比對。
306
+
307
+ ``providers`` 只限制要呼叫哪些偵測器;沒有 PID 偵測器的 provider 不會出現在
308
+ 結果中,讀取側會沿用 cwd / tty fallback。``None`` 仍代表這輪偵測失敗。
309
+ """
310
+ wanted = None if providers is None else {_canonical_provider(provider) for provider in providers}
311
+ result: dict[str, list[int] | None] = {}
312
+ for provider, detector in _PROVIDER_PIDS.items():
313
+ if wanted is None or provider in wanted:
314
+ result[provider] = detector()
315
+ return result
316
+
317
+
290
318
  class Status(StrEnum):
291
319
  """場館裡一個 session 的狀態。等你的排最上面。"""
292
320
 
@@ -316,6 +344,7 @@ class Session:
316
344
  tmux_pane: str | None = None # stable tmux pane id from hook, e.g. "%12"
317
345
  tty: str | None = None # e.g. "/dev/ttys003",給非-tmux 終端(iTerm2 等)聚焦用
318
346
  hook_pid: int | None = None
347
+ agent_pid: int | None = None # provider CLI 的長命 process;精準排除同 cwd 的舊 hook row
319
348
  heartbeat_at: float = 0.0
320
349
  source_path: str = ""
321
350
  hook_stale: bool = False
@@ -331,6 +360,7 @@ class Session:
331
360
  # 只是借一個「真實 session 的欄位」組出來的通知 payload,讓 notify_title / notify_message
332
361
  # 改用彙總句式。session_id 本身維持真實值(不覆寫成 sentinel),點擊通知才能正確 focus。
333
362
  is_summary: bool = field(default=False, repr=False, compare=False)
363
+ waiting_requests: tuple[WaitingRequest, ...] = ()
334
364
 
335
365
  @property
336
366
  def project(self) -> str:
@@ -786,8 +816,8 @@ def _codex_procs() -> list[tuple[str, str]] | None:
786
816
 
787
817
 
788
818
  # 內建 provider 的 live-process 偵測器。外部工具用 register_provider_procs() 加自己的。
789
- register_provider_procs("claude-code", _claude_procs)
790
- register_provider_procs("codex", _codex_procs)
819
+ register_provider_procs("claude-code", _claude_procs, pid_detector=running_foreground_claude_pids)
820
+ register_provider_procs("codex", _codex_procs, pid_detector=running_codex_pids)
791
821
 
792
822
 
793
823
  def _codex_tail_kind(records: list[dict[str, Any]]) -> str:
@@ -1069,6 +1099,7 @@ def _hook_sessions(
1069
1099
  procs: list[tuple[str, str]] | None = None,
1070
1100
  *,
1071
1101
  procs_by_provider: dict[str, list[tuple[str, str]] | None] | None = None,
1102
+ pids_by_provider: dict[str, list[int] | None] | None = None,
1072
1103
  purge_session_start_phantoms: bool = True,
1073
1104
  ) -> list[Session]:
1074
1105
  if not RING_REGISTRY.is_dir():
@@ -1098,12 +1129,14 @@ def _hook_sessions(
1098
1129
  tmux_pane=str(data.get("tmux_pane", "")) or None,
1099
1130
  tty=str(data.get("tty", "")) or None,
1100
1131
  hook_pid=int(data["hook_pid"]) if str(data.get("hook_pid", "")).isdigit() else None,
1132
+ agent_pid=int(data["agent_pid"]) if str(data.get("agent_pid", "")).isdigit() else None,
1101
1133
  heartbeat_at=float(data.get("heartbeat_at", data.get("last_active", 0.0))),
1102
1134
  source_path=str(data.get("source_path", "")),
1103
1135
  todo=tuple(todo) if isinstance(todo, list) and len(todo) == 2 else None,
1104
1136
  provider=provider,
1105
1137
  waiting_kind=str(data.get("waiting_kind", "")),
1106
1138
  waiting_detail=str(data.get("waiting_detail", "")),
1139
+ waiting_requests=tuple(read_waiting_requests(data).values()),
1107
1140
  origin_cwd=str(data.get("origin_cwd", "")),
1108
1141
  )
1109
1142
  if _promote_codex_permission_wait(
@@ -1121,6 +1154,15 @@ def _hook_sessions(
1121
1154
  # 「下一個事件來時還新不新鮮」;這裡 hook 靜默 = 同一筆請求還掛著,
1122
1155
  # 摘要必然還是它,直接沿用)。
1123
1156
  row.waiting_detail = pending_detail
1157
+ row.waiting_requests = (
1158
+ WaitingRequest(
1159
+ str(data.get("last_event_owner", FOREGROUND_OWNER)),
1160
+ "permission",
1161
+ row.waiting_detail,
1162
+ since=row.last_active,
1163
+ tool_use_id=str(data.get("last_tool_use_id", "")),
1164
+ ),
1165
+ )
1124
1166
  if _is_bare_session_start_row(
1125
1167
  row.tty or "",
1126
1168
  str(data.get("last_event", "")),
@@ -1135,16 +1177,25 @@ def _hook_sessions(
1135
1177
  for s in out:
1136
1178
  if s.source == "hook":
1137
1179
  s.hook_stale = _hook_heartbeat_stale(s.source_path, s.heartbeat_at, s.status)
1180
+ pid_providers = {
1181
+ _canonical_provider(s.provider)
1182
+ for s in out
1183
+ if s.agent_pid is not None and _canonical_provider(s.provider) in _PROVIDER_PIDS
1184
+ }
1185
+ if pids_by_provider is None and pid_providers:
1186
+ pids_by_provider = collect_provider_pids(pid_providers)
1138
1187
  # SessionEnd 沒觸發(crash)會留下幽靈檔。判定離場:
1139
- # 1. 該 cwd 完全沒有 live proc → 一定離場。
1140
- # 2. 該 cwd 的 hook row 數「多於一筆」時,用 tty 挑出 tty 對不上的那幾筆標離場——
1188
+ # 1. 新格式 row 有 provider CLI PID 時,直接用 PID 判斷,不讓同 cwd 的另一個新
1189
+ # session 替已離場的舊 WAITING row 證明存活。
1190
+ # 2. 舊格式 row 的 cwd 完全沒有 live proc → 一定離場。
1191
+ # 3. 該 cwd 的 hook row 數「多於一筆」時,用 tty 挑出 tty 對不上的那幾筆標離場——
1141
1192
  # 不論這筆數是否 <= live proc 數:計數只是巧合對上(例如同 cwd 剛好有跟 RiNG
1142
1193
  # hook 無關的 live process 佔掉名額),不代表每筆 row 都真的還活著;row 數 > 1
1143
1194
  # 時 tty 交叉比對才有意義去挑出誰是 stale 的。
1144
- # 3. 該 cwd 只有「單一」hook row 時,無論 tty 是否對得上都不靠 tty 殺——hook 寫進來
1195
+ # 4. 該 cwd 只有「單一」舊格式 hook row 時,無論 tty 是否對得上都不靠 tty 殺——hook 寫進來
1145
1196
  # 的 tty 不一定可靠(終端 tty 會被作業系統重配,甚至跨 session 錯置),拿它隱藏
1146
1197
  # 唯一活著的 session 會讓整列憑空消失。
1147
- # 4. 「這個 provider 這輪 ps/lsof 掃描失敗」(值為 ``None``)是「未知」,不是
1198
+ # 5. 「這個 provider 這輪 ps/lsof 掃描失敗」(值為 ``None``)是「未知」,不是
1148
1199
  # 「真的偵測到零個 live process」——未知時完全不動這個 provider 底下任何一筆
1149
1200
  # row 的狀態,保留既有狀態,避免單次系統瞬間卡頓(ps timeout)把整版 session
1150
1201
  # 誤判 ENDED(見 ring-vanishing-sessions 診斷)。
@@ -1181,18 +1232,33 @@ def _hook_sessions(
1181
1232
  # 這裡的 fallback 只是避免拿 None 做 in 運算炸掉。
1182
1233
  background_ids = background_agent_session_ids() or set()
1183
1234
  rows_by_key: dict[tuple[str, str], list[Session]] = {}
1235
+ pid_resolved: set[str] = set()
1236
+ claimed_pids: dict[tuple[str, str], set[int]] = {}
1184
1237
  for s in out:
1185
1238
  pk = _canonical_provider(s.provider)
1186
1239
  if pk not in _PROVIDER_PROCS:
1187
1240
  continue # 沒有 proc 偵測器 → 無法驗活性 → fail-open,交給 SessionEnd
1188
1241
  if pk == "claude-code" and s.session_id in background_ids:
1189
1242
  continue
1190
- rows_by_key.setdefault((pk, _real(s.cwd)), []).append(s)
1243
+ key = (pk, _real(s.cwd))
1244
+ rows_by_key.setdefault(key, []).append(s)
1245
+ if s.agent_pid is not None and pids_by_provider is not None and pk in pids_by_provider:
1246
+ live_pids = pids_by_provider[pk]
1247
+ if live_pids is not None:
1248
+ if s.agent_pid not in live_pids:
1249
+ s.status = Status.ENDED
1250
+ else:
1251
+ claimed_pids.setdefault(key, set()).add(s.agent_pid)
1252
+ # 保留完整分組基數與已認領的名額,但 fallback 不得覆寫精準 PID 結果。
1253
+ pid_resolved.add(s.session_id)
1191
1254
 
1192
1255
  for key, rows in rows_by_key.items():
1193
1256
  pk, row_cwd = key
1194
1257
  if pk in unknown_providers:
1195
1258
  continue # 這輪掃描失敗,未知不等於離場,保留既有狀態
1259
+ fallback_rows = [s for s in rows if s.session_id not in pid_resolved]
1260
+ if not fallback_rows:
1261
+ continue
1196
1262
  live_n = proc_counts.get(key, 0)
1197
1263
  if live_n == 0:
1198
1264
  if _has_ancestor_live_process(row_cwd, proc_cwds_by_provider.get(pk, [])):
@@ -1202,30 +1268,26 @@ def _hook_sessions(
1202
1268
  # cd 進子目錄的 session 誤判 ENDED(見
1203
1269
  # test_hook_sessions_keeps_live_session_when_cwd_moved_to_subdir)。
1204
1270
  continue
1205
- for s in rows:
1271
+ for s in fallback_rows:
1206
1272
  s.status = Status.ENDED
1207
1273
  continue
1208
1274
 
1209
- # 單筆 row:不靠 tty 殺,理由見上方註解 3——避免唯一活著的 session 因 tty
1275
+ # 單筆舊格式 row:不靠 tty 殺,理由見上方註解 4——避免唯一活著的 session 因 tty
1210
1276
  # 重配而憑空消失(test_hook_sessions_keeps_lone_live_session_with_wrong_tty)。
1211
1277
  if len(rows) == 1:
1212
1278
  continue
1213
1279
 
1214
1280
  live_ttys = proc_ttys.get(key, set())
1215
1281
  if live_ttys:
1216
- for s in rows:
1282
+ for s in fallback_rows:
1217
1283
  if s.tty and s.tty not in live_ttys:
1218
1284
  s.status = Status.ENDED
1219
1285
 
1220
- if len(rows) <= live_n:
1221
- # 沒有多餘列要修剪,但上面的 tty 交叉比對仍然有效——即使計數巧合對上,
1222
- # tty 對不上的那幾筆(例如已 crash 的舊 row)還是會被標離場,不會永遠
1223
- # 靠計數巧合躲過清理。
1224
- continue
1225
-
1226
- remaining = [s for s in rows if s.status is not Status.ENDED]
1227
- if len(remaining) > live_n:
1286
+ # 新舊格式不能共用同一個 process 名額;只修剪未經 PID 確認的列。
1287
+ available = max(0, live_n - len(claimed_pids.get(key, set())))
1288
+ remaining = [s for s in fallback_rows if s.status is not Status.ENDED]
1289
+ if len(remaining) > available:
1228
1290
  remaining.sort(key=lambda s: s.last_active, reverse=True)
1229
- for s in remaining[live_n:]:
1291
+ for s in remaining[available:]:
1230
1292
  s.status = Status.ENDED
1231
1293
  return out
@@ -7,6 +7,8 @@
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ from dataclasses import replace
11
+
10
12
  import ring.registry as registry
11
13
  import ring.tmux_scan as tmux_scan
12
14
  from ring.registry import Session, Status
@@ -16,6 +18,7 @@ from ring.sources.codex import source as _codex
16
18
  from ring.sources.hook_registry import source as _hook_registry
17
19
  from ring.sources.local_llm import llama_cpp_source as _llama_cpp
18
20
  from ring.sources.local_llm import ollama_source as _ollama
21
+ from ring.waiting import FOREGROUND_OWNER, primary_wait
19
22
 
20
23
  # 註冊表(順序=彙整順序)。hook registry 先於 zero-config source,精準事件優先。
21
24
  _SOURCES: list[SessionSource] = [_hook_registry, _claude_code, _codex, _ollama, _llama_cpp]
@@ -119,15 +122,28 @@ def _merge_duplicate_session(current: Session, candidate: Session) -> Session:
119
122
  「使用者回應了」。這種 row 只由真人 prompt(tail "working")或後續 hook 事件清掉,
120
123
  否則 Stop 之後任何一筆簿記寫入推進 mtime 都會讓紅色憑空消失。
121
124
  """
125
+ foreground_wait = next((r for r in current.waiting_requests if r.owner == FOREGROUND_OWNER), None)
126
+ # 背景 hook 會更新 row 的 last_active,但不能讓已解決的前景等待又蓋過 transcript 證據。
127
+ waiting_since = foreground_wait.since if foreground_wait is not None else current.last_active
122
128
  if (
123
129
  current.source == "hook"
124
130
  and current.status is Status.WAITING
125
131
  and candidate.provider == current.provider
126
132
  and candidate.status is not Status.WAITING
127
- and candidate.last_active > current.last_active
133
+ and candidate.last_active > waiting_since
128
134
  and candidate._tail_kind in {"working", "waiting"}
129
135
  and not (current.waiting_kind == "question" and candidate._tail_kind == "waiting")
130
136
  ):
137
+ # Host transcript 只能證明前景已回應,不能代替另一個 subagent 解除等待。
138
+ remaining = {r.owner: r for r in current.waiting_requests if r.owner != FOREGROUND_OWNER}
139
+ if remaining:
140
+ selected = primary_wait(remaining)
141
+ return replace(
142
+ current,
143
+ waiting_requests=tuple(remaining.values()),
144
+ waiting_kind=selected.kind,
145
+ waiting_detail=selected.detail,
146
+ )
131
147
  if not candidate.tty:
132
148
  candidate.tty = current.tty
133
149
  if not candidate.tmux_target:
@@ -477,7 +477,7 @@ class RingApp(App[None]):
477
477
  acknowledged_revision = self._permission_acks.get(s.session_id)
478
478
  if acknowledged_revision is None:
479
479
  continue
480
- if s.last_active > acknowledged_revision:
480
+ if s.last_active > acknowledged_revision or len(s.waiting_requests) > 1:
481
481
  # 新 hook event(可能是下一個權限請求)已到,重新採信 provider 狀態。
482
482
  del self._permission_acks[s.session_id]
483
483
  continue
@@ -486,6 +486,7 @@ class RingApp(App[None]):
486
486
  s.status = Status.WORKING
487
487
  s.waiting_kind = ""
488
488
  s.waiting_detail = ""
489
+ s.waiting_requests = ()
489
490
  else:
490
491
  # provider 已用同 revision 清掉 WAITING,不再需要本地 acknowledgment。
491
492
  del self._permission_acks[s.session_id]
@@ -663,20 +664,29 @@ class RingApp(App[None]):
663
664
  self._permission_replies_inflight.discard(s.session_id)
664
665
  option = next((f"{n}. {text}" for n, text in dialog.options if n == number), str(number))
665
666
  if outcome is permission.ReplyOutcome.OK:
666
- if s.session_id == self._focused_sid:
667
- self._focused_sid = None # 已就地回覆,解除通知標記
668
- self._permission_acks[s.session_id] = s.last_active
667
+ # 畫面只證實一個對話框消失,無法證明其他 agent 的等待也已解除。
668
+ can_ack = len(s.waiting_requests) <= 1
669
+ if can_ack:
670
+ if s.session_id == self._focused_sid:
671
+ self._focused_sid = None # 已就地回覆,解除通知標記
672
+ self._permission_acks[s.session_id] = s.last_active
669
673
  # 先直接更新現有資料,別為了一筆 acknowledgment 同步重掃所有 process。
670
674
  # 下一次既有輪詢仍會正常全量同步、重排表格。
671
675
  row = next(
672
676
  ((idx, current) for idx, current in enumerate(self._sessions) if current.session_id == s.session_id),
673
677
  None,
674
678
  )
675
- if row is not None and row[1].last_active <= s.last_active:
679
+ if (
680
+ can_ack
681
+ and row is not None
682
+ and row[1].last_active <= s.last_active
683
+ and len(row[1].waiting_requests) <= 1
684
+ ):
676
685
  idx, current = row
677
686
  current.status = Status.WORKING
678
687
  current.waiting_kind = ""
679
688
  current.waiting_detail = ""
689
+ current.waiting_requests = ()
680
690
  self.query_one(DataTable).update_cell_at(Coordinate(idx, 0), self._status_cell(current))
681
691
  self._toast(_("→ {project}:已回覆權限({option})", project=name, option=option), ok=True)
682
692
  self._update_detail()
@@ -0,0 +1,104 @@
1
+ """Hook 等待來源的持久化格式;writer 與讀取/合併路徑共用。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from dataclasses import dataclass, replace
9
+ from typing import Any
10
+ from uuid import uuid4
11
+
12
+ FOREGROUND_OWNER = "foreground"
13
+ UNKNOWN_OWNER = "unknown"
14
+
15
+
16
+ def event_owner(data: dict[str, Any]) -> str:
17
+ for key in ("agent_id", "agentId"):
18
+ if isinstance(value := data.get(key), str) and value:
19
+ return f"agent:{value}"
20
+ if any(isinstance(data.get(key), str) and data[key] for key in ("agent_type", "agentType")):
21
+ return UNKNOWN_OWNER
22
+ return FOREGROUND_OWNER
23
+
24
+
25
+ def tool_request_id(data: dict[str, Any]) -> str:
26
+ return next(
27
+ (value for key in ("tool_use_id", "toolUseId") if isinstance(value := data.get(key), str) and value), ""
28
+ )
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class WaitingRequest:
33
+ owner: str
34
+ kind: str = ""
35
+ detail: str = ""
36
+ waiting_for: str = ""
37
+ since: float = 0.0
38
+ revision: str = ""
39
+ tool_use_id: str = ""
40
+
41
+ @property
42
+ def request_id(self) -> str:
43
+ """跨輪詢穩定的不透明 ID;舊 row/讀取側升紅不可每次產生隨機值。"""
44
+ if self.revision:
45
+ return self.revision
46
+ identity = json.dumps([self.owner, self.since, self.tool_use_id])
47
+ return "legacy:" + hashlib.sha256(identity.encode()).hexdigest()
48
+
49
+
50
+ def renew_wait(previous: WaitingRequest | None, current: WaitingRequest) -> WaitingRequest:
51
+ """同一工具的重複事件/相同提醒保留識別;明確的新請求才換 ID。"""
52
+ if previous is not None and previous.owner == current.owner and previous.kind == current.kind:
53
+ if previous.tool_use_id and current.tool_use_id:
54
+ same_request = previous.tool_use_id == current.tool_use_id
55
+ else:
56
+ same_request = (previous.detail, previous.waiting_for) == (current.detail, current.waiting_for)
57
+ if same_request:
58
+ return replace(
59
+ current,
60
+ since=previous.since,
61
+ revision=previous.request_id,
62
+ tool_use_id=current.tool_use_id or previous.tool_use_id,
63
+ )
64
+ return replace(current, revision=uuid4().hex)
65
+
66
+
67
+ def read_waiting_requests(row: dict[str, Any]) -> dict[str, WaitingRequest]:
68
+ """舊單一 waiting row 視為一個來源;新格式的空集合不能復活舊欄位。"""
69
+ raw = row.get("waiting_requests")
70
+ if not isinstance(raw, dict):
71
+ if row.get("status") != "waiting":
72
+ return {}
73
+ owner = f"agent:{row['waiting_agent_id']}" if row.get("waiting_agent_id") else FOREGROUND_OWNER
74
+ raw = {
75
+ owner: {
76
+ "kind": row.get("waiting_kind", ""),
77
+ "detail": row.get("waiting_detail", ""),
78
+ "waiting_for": row.get("waiting_for", ""),
79
+ "since": row.get("last_active", 0.0),
80
+ }
81
+ }
82
+ requests = {}
83
+ for owner, value in raw.items():
84
+ if not isinstance(owner, str) or not isinstance(value, dict):
85
+ continue
86
+ if owner not in {FOREGROUND_OWNER, UNKNOWN_OWNER} and not owner.startswith("agent:"):
87
+ continue
88
+ since = value.get("since", 0.0)
89
+ if not isinstance(since, (int, float)) or isinstance(since, bool) or not math.isfinite(since):
90
+ since = 0.0
91
+ requests[owner] = WaitingRequest(
92
+ owner,
93
+ **{
94
+ key: value.get(key, "") if isinstance(value.get(key, ""), str) else ""
95
+ for key in ("kind", "detail", "waiting_for", "revision", "tool_use_id")
96
+ },
97
+ since=float(since),
98
+ )
99
+ return requests
100
+
101
+
102
+ def primary_wait(requests: dict[str, WaitingRequest]) -> WaitingRequest:
103
+ """優先顯示前景;其餘依加入順序,避免背景活動讓摘要一直換人。"""
104
+ return requests.get(FOREGROUND_OWNER) or next(iter(requests.values()))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes