ring-cli 0.17.3__tar.gz → 0.17.5__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 (70) hide show
  1. {ring_cli-0.17.3 → ring_cli-0.17.5}/PKG-INFO +1 -1
  2. {ring_cli-0.17.3 → ring_cli-0.17.5}/pyproject.toml +1 -1
  3. {ring_cli-0.17.3 → ring_cli-0.17.5}/pyproject.toml.orig +1 -1
  4. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/cli.py +9 -4
  5. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/gc.py +22 -7
  6. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/hook.py +156 -77
  7. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/ipc.py +26 -23
  8. ring_cli-0.17.5/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  9. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/locale/en/LC_MESSAGES/ring.po +6 -0
  10. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/locale/ring.pot +111 -101
  11. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify_queue.py +88 -17
  12. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/registry.py +12 -0
  13. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/__init__.py +67 -2
  14. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/tui.py +88 -34
  15. ring_cli-0.17.5/src/ring/waiting.py +104 -0
  16. ring_cli-0.17.3/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  17. {ring_cli-0.17.3 → ring_cli-0.17.5}/LICENSE +0 -0
  18. {ring_cli-0.17.3 → ring_cli-0.17.5}/README.en.md +0 -0
  19. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/__init__.py +0 -0
  20. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/__main__.py +0 -0
  21. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/agent_notify.py +0 -0
  22. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/__init__.py +0 -0
  23. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/_args.py +0 -0
  24. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/completion.py +0 -0
  25. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/digest.py +0 -0
  26. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/doctor.py +0 -0
  27. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/focus.py +0 -0
  28. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/gc.py +0 -0
  29. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/hook.py +0 -0
  30. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/quiet.py +0 -0
  31. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/commands/stats.py +0 -0
  32. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/config.py +0 -0
  33. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/__init__.py +0 -0
  34. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/applescript.py +0 -0
  35. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/base.py +0 -0
  36. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/iterm2.py +0 -0
  37. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/kitty.py +0 -0
  38. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/linux_wm.py +0 -0
  39. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/neovim.py +0 -0
  40. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/terminal.py +0 -0
  41. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/tmux.py +0 -0
  42. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/focus/trace.py +0 -0
  43. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/hook_protocol.py +0 -0
  44. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/i18n.py +0 -0
  45. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/labels.py +0 -0
  46. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/__init__.py +0 -0
  47. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/base.py +0 -0
  48. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/command.py +0 -0
  49. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/notify_send.py +0 -0
  50. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/ntfy.py +0 -0
  51. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/osascript_notifier.py +0 -0
  52. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/terminal_notifier.py +0 -0
  53. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/notify/webhook.py +0 -0
  54. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/osascript.py +0 -0
  55. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/pathutil.py +0 -0
  56. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/payload_log.py +0 -0
  57. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/permission.py +0 -0
  58. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/plugins.py +0 -0
  59. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/ps_parse.py +0 -0
  60. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/question_detect.py +0 -0
  61. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/base.py +0 -0
  62. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/claude_code.py +0 -0
  63. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/codex.py +0 -0
  64. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/hook_registry.py +0 -0
  65. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/sources/local_llm.py +0 -0
  66. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/stats.py +0 -0
  67. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/subproc.py +0 -0
  68. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/tmux_scan.py +0 -0
  69. {ring_cli-0.17.3 → ring_cli-0.17.5}/src/ring/transcript.py +0 -0
  70. {ring_cli-0.17.3 → ring_cli-0.17.5}/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.3
3
+ Version: 0.17.5
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.3"
3
+ version = "0.17.5"
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"
@@ -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.3"
5
+ version = "0.17.5"
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"
@@ -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
  }
@@ -402,7 +407,7 @@ def run_config(args: list[str]) -> int:
402
407
  return 2
403
408
 
404
409
 
405
- def _watch_flush_if_due() -> None:
410
+ def _watch_flush_if_due(sessions: list[Session]) -> None:
406
411
  """headless watch 輪詢時的懶惰 flush 觸發點(同 hook.py / tui.py 既有呼叫慣例)。
407
412
 
408
413
  quiet active 或仍在 debounce 視窗內時,``flush_if_due`` 內部本來就會 skip(跟
@@ -410,7 +415,7 @@ def _watch_flush_if_due() -> None:
410
415
  失敗安靜吞掉,不影響看板本身。
411
416
  """
412
417
  with contextlib.suppress(Exception):
413
- flush_if_due()
418
+ flush_if_due(current_sessions=sessions)
414
419
 
415
420
 
416
421
  def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int:
@@ -425,9 +430,9 @@ def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int
425
430
  if not HAVE_RICH:
426
431
  try:
427
432
  while True:
428
- _watch_flush_if_due()
429
433
  sys.stdout.write("\033[2J\033[H")
430
434
  sessions = board(show_all)
435
+ _watch_flush_if_due(sessions)
431
436
  print(_render_plain(sessions, show_legend, show_tool_column(sessions)))
432
437
  print(f"\n{footer_text}")
433
438
  sys.stdout.flush()
@@ -442,8 +447,8 @@ def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int
442
447
  try:
443
448
  with Live(console=console, screen=True, auto_refresh=False) as live:
444
449
  while True:
445
- _watch_flush_if_due()
446
450
  sessions = board(show_all)
451
+ _watch_flush_if_due(sessions)
447
452
  body = _rich_renderable(sessions, show_legend, show_tool_column(sessions))
448
453
  live.update(Group(body, Text(f"\n{footer_text}", style=_MUTED)), refresh=True)
449
454
  frames += 1
@@ -11,7 +11,7 @@ import time
11
11
  from dataclasses import dataclass, field
12
12
  from pathlib import Path
13
13
 
14
- from ring.ipc import _FOCUS_REQUEST_PATH, _PRESENCE_PATH, _PRESENCE_TTL, _REQUEST_TTL
14
+ from ring.ipc import _FOCUS_REQUEST_PATH, _PRESENCE_PATH, _PRESENCE_TTL, _REQUEST_TTL, _focus_request_lock
15
15
  from ring.registry import (
16
16
  _SESSION_START_SOURCES,
17
17
  RING_REGISTRY,
@@ -81,7 +81,9 @@ def run_gc(
81
81
  # 隱藏清單本來就空時,不必為了「找不到就清」去掃全部 source(省掉一輪 process/檔案掃描)。
82
82
  known_ids = _known_session_ids() if hidden_now else set()
83
83
  hidden_stale_preview = {
84
- sid: hidden_at for sid, hidden_at in hidden_now.items() if sid not in known_ids or now - hidden_at >= older_than
84
+ sid: hidden_at
85
+ for sid, hidden_at in hidden_now.items()
86
+ if (known_ids is not None and sid not in known_ids) or now - hidden_at >= older_than
85
87
  }
86
88
 
87
89
  if dry_run:
@@ -98,8 +100,8 @@ def run_gc(
98
100
  errors: list[tuple[GcCandidate, str]] = []
99
101
  for candidate in candidates:
100
102
  try:
101
- candidate.path.unlink(missing_ok=True)
102
- deleted.append(candidate)
103
+ if _delete_candidate(candidate, now=now):
104
+ deleted.append(candidate)
103
105
  except OSError as e:
104
106
  errors.append((candidate, str(e)))
105
107
 
@@ -114,19 +116,32 @@ def run_gc(
114
116
  )
115
117
 
116
118
 
117
- def _known_session_ids() -> set[str]:
119
+ def _delete_candidate(candidate: GcCandidate, *, now: float) -> bool:
120
+ if candidate.path == _FOCUS_REQUEST_PATH:
121
+ # GC 也會刪 request:不能在盤點過期檔後,把 writer 剛送來的新 request 一起刪掉。
122
+ with _focus_request_lock(candidate.path):
123
+ if not _stale_json_file(candidate.path, ttl=_REQUEST_TTL, now=now, label="focus-request"):
124
+ return False
125
+ candidate.path.unlink(missing_ok=True)
126
+ return True
127
+ candidate.path.unlink(missing_ok=True)
128
+ return True
129
+
130
+
131
+ def _known_session_ids() -> set[str] | None:
118
132
  """目前任何已註冊來源(不管有沒有被手動隱藏)找得到的 session id。
119
133
 
120
134
  只用來判斷隱藏清單裡的條目是不是「哪裡都找不到了」;不碰、不引用
121
135
  ``discover_sessions()`` 的 merge / tmux 配對邏輯。
122
136
  """
137
+ from ring.sources import discover_source_sessions, source_errors
123
138
  from ring.sources import sources as _registered_sources
124
139
 
125
140
  ids: set[str] = set()
126
141
  for source in _registered_sources():
127
- for s in source.discover():
142
+ for s in discover_source_sessions(source):
128
143
  ids.add(s.session_id)
129
- return ids
144
+ return None if source_errors() else ids
130
145
 
131
146
 
132
147
  def _registry_candidates(*, older_than: float, all_ended: bool, now: float) -> list[GcCandidate]:
@@ -35,7 +35,7 @@ import sys
35
35
  import time
36
36
  from collections.abc import Iterator
37
37
  from contextlib import contextmanager
38
- from dataclasses import dataclass, replace
38
+ from dataclasses import asdict, dataclass, replace
39
39
  from pathlib import Path
40
40
  from typing import Any
41
41
  from urllib.parse import quote
@@ -55,6 +55,16 @@ from ring.registry import (
55
55
  )
56
56
  from ring.stats import log_transition
57
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
+ )
58
68
 
59
69
  _HOOK_EVENTS = list(HOOK_EVENTS)
60
70
 
@@ -158,17 +168,10 @@ def run_hook(provider: str = "claude-code") -> int:
158
168
  收按鈕、把決策寫到 stdout 回給 Claude(這條路下 ``_ring_waiting_now`` 自動短路、不重複發)。
159
169
  其餘情況 RiNG 記狀態 + 發通知後 exit 0(你在終端自己回答)。
160
170
 
161
- 每次執行開頭先嘗試懶惰 flush 合流 queue(見 ``notify_queue.flush_if_due``)——沒有常駐
171
+ 更新 registry 後嘗試懶惰 flush 合流 queue(見 ``notify_queue.flush_if_due``)——沒有常駐
162
172
  daemon,任何 hook 事件(不限於這次自己是不是 waiting 事件)都是「debounce 視窗過期」的
163
173
  天然觸發點,讓 headless(沒開 TUI)也能補發彙總通知。失敗安靜吞掉,不影響本次事件記錄。
164
174
  """
165
- try:
166
- from ring.notify_queue import flush_if_due
167
-
168
- flush_if_due()
169
- except Exception:
170
- pass
171
-
172
175
  try:
173
176
  raw = sys.stdin.read()
174
177
  except OSError:
@@ -217,6 +220,12 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
217
220
  notification = _update_session_state(path, event, data, adapter.process_names)
218
221
  except OSError:
219
222
  return
223
+ try:
224
+ from ring.notify_queue import flush_if_due
225
+
226
+ flush_if_due()
227
+ except Exception:
228
+ pass
220
229
  # 系統通知可能等待外部程序,不可持鎖阻擋後續解除等待的 hook。
221
230
  if notification is not None:
222
231
  _ring_waiting_now(*notification)
@@ -228,17 +237,19 @@ def _update_session_state(
228
237
  """持有 session lock 時合併並寫入;回傳需在鎖外發送的通知。"""
229
238
  prev_row = _previous_row(path)
230
239
  prev_status = str(prev_row["status"]) if "status" in prev_row else None
231
- agent_id = next((value for key in ("agent_id", "agentId") if isinstance(value := data.get(key), str) and value), "")
232
- is_subagent_event = bool(agent_id) or any(
233
- isinstance(data.get(key), str) and data[key] for key in ("agent_type", "agentType")
234
- )
240
+ owner = event_owner(data)
241
+ is_subagent_event = owner != FOREGROUND_OWNER
235
242
  if is_subagent_event:
236
- # 共用 host session_id 不代表能解除前景或另一個 agent 的等待。
237
- # 舊 row 沒有等待來源時視為前景;僅知道 agent_type 也不能證明是同一個等待者。
238
- if event.status is Status.ENDED or (
239
- prev_status == Status.WAITING.value and (not agent_id or prev_row.get("waiting_agent_id") != agent_id)
240
- ):
241
- return None
243
+ # Subagent SessionEnd 不是 host session 的結束。
244
+ if event.status is Status.ENDED:
245
+ raw_pending = prev_row.get("pending_permissions", [])
246
+ owns_pending = isinstance(raw_pending, list) and any(
247
+ isinstance(item, dict) and item.get("owner") == owner for item in raw_pending
248
+ )
249
+ if owner == UNKNOWN_OWNER or (owner not in read_waiting_requests(prev_row) and not owns_pending):
250
+ return None
251
+ # 只結束這個 agent 的待決事項;host 仍在工作,不能刪掉共用 registry。
252
+ event = replace(event, status=Status.WORKING)
242
253
  if prev_row:
243
254
  event = replace(
244
255
  event,
@@ -246,16 +257,6 @@ def _update_session_state(
246
257
  transcript_path=str(prev_row.get("source_path", "")),
247
258
  )
248
259
  unhide_session(event.session_id)
249
- # 一般 Notification 只能升 🔴、不能降 🟡——閒置提醒不是「使用者回應了」的證據。
250
- keep_waiting = _notification_keeps_waiting(event, prev_row)
251
- if keep_waiting:
252
- event = replace(
253
- event,
254
- status=Status.WAITING,
255
- waiting_for=str(prev_row.get("waiting_for", "")),
256
- waiting_kind=str(prev_row.get("waiting_kind", "")),
257
- detail=str(prev_row.get("waiting_detail", "")),
258
- )
259
260
  if event.status is Status.ENDED:
260
261
  path.unlink(missing_ok=True) # 乾淨離場:直接消失
261
262
  if prev_status is not None and prev_status != Status.ENDED.value:
@@ -271,6 +272,46 @@ def _update_session_state(
271
272
  # 查詢未知不是 session 換人;保留已取得的前景身分,成功的新 lookup 仍可重新綁定。
272
273
  agent_pid = previous_pid
273
274
 
275
+ reset_waits = not is_subagent_event and (
276
+ event.event == "SessionStart" or (previous_pid is not None and agent_pid != previous_pid)
277
+ )
278
+ previous_state = {} if reset_waits else prev_row
279
+ requests = read_waiting_requests(previous_state)
280
+ keep_waiting = _notification_keeps_waiting(event, prev_row)
281
+ now = time.time()
282
+ pending, matched = _pending_permission_details(event, previous_state, data, owner, now)
283
+ request_id = tool_request_id(data)
284
+ if event.event == "Notification" and event.waiting_kind == "permission" and matched is not None:
285
+ # 無 agent ID 的 Notification 只有唯一候選時才可借用其來源與摘要。
286
+ owner = str(matched["owner"])
287
+ event = replace(event, detail=str(matched["detail"]))
288
+ request_id = str(matched["request_id"])
289
+ if event.status is Status.WAITING:
290
+ previous_wait = requests.get(owner)
291
+ if (
292
+ event.event == "Notification"
293
+ and event.waiting_kind == "permission"
294
+ and not request_id
295
+ and not pending
296
+ and previous_wait is not None
297
+ and previous_wait.kind == "permission"
298
+ and previous_wait.tool_use_id
299
+ ):
300
+ # 暫存摘要 TTL 過後的泛用提醒不是另一筆請求,也不該蓋掉已知的工具摘要。
301
+ request_id = previous_wait.tool_use_id
302
+ event = replace(event, detail=previous_wait.detail)
303
+ requests[owner] = renew_wait(
304
+ previous_wait,
305
+ WaitingRequest(owner, event.waiting_kind, event.detail, event.waiting_for, now, tool_use_id=request_id),
306
+ )
307
+ elif not keep_waiting and owner != UNKNOWN_OWNER:
308
+ requests.pop(owner, None)
309
+ if owner == FOREGROUND_OWNER:
310
+ # 沒有 agent ID 的舊/匿名等待只能由前景的明確回應解除。
311
+ requests.pop(UNKNOWN_OWNER, None)
312
+ selected = primary_wait(requests) if requests else None
313
+ status = Status.WAITING if selected is not None else event.status
314
+
274
315
  last_action, todo = event.last_action or "—", None
275
316
  tp = event.transcript_path
276
317
  if tp:
@@ -279,20 +320,23 @@ def _update_session_state(
279
320
  last_action = _latest_action(records)
280
321
  todo = _extract_todo(records)
281
322
 
282
- now = time.time()
283
323
  payload: dict[str, Any] = {
284
324
  "session_id": event.session_id,
285
325
  "provider": event.provider,
286
326
  "cwd": event.cwd,
287
327
  "origin_cwd": prev_row.get("origin_cwd", event.cwd) if is_subagent_event else event.cwd,
288
- "status": event.status.value,
328
+ "status": status.value,
289
329
  # 最後一個 hook 事件名:讀取側據此做 codex 的核可等待判定(最後事件是
290
330
  # PermissionRequest 且靜默逾時 → 🔴),任何後續事件覆寫它就自然清紅。
291
331
  "last_event": event.event,
332
+ "last_event_owner": owner,
333
+ "last_tool_use_id": request_id,
292
334
  "last_active": now,
293
335
  "heartbeat_at": now,
294
336
  "last_action": last_action,
295
337
  "hook_pid": os.getpid(),
338
+ "waiting_requests": {key: asdict(request) for key, request in requests.items()},
339
+ "pending_permissions": pending,
296
340
  }
297
341
  if agent_pid is not None:
298
342
  payload["agent_pid"] = agent_pid
@@ -304,7 +348,9 @@ def _update_session_state(
304
348
  payload["tmux_pane"] = tmux_pane
305
349
  if todo:
306
350
  payload["todo"] = list(todo)
307
- if event.waiting_for:
351
+ if selected is not None and selected.waiting_for:
352
+ payload["waiting_for"] = selected.waiting_for
353
+ elif selected is None and event.waiting_for:
308
354
  payload["waiting_for"] = event.waiting_for
309
355
 
310
356
  # 裸 PermissionRequest(→ WORKING)帶著最具體的 tool/指令摘要;真的停下來等人時,
@@ -313,22 +359,17 @@ def _update_session_state(
313
359
  # (還新鮮的話)拿它當 waiting_detail,看板與通知才看得到具體是哪條指令在等核可。
314
360
  # Codex 沒有 Notification:這份暫存改由讀取側的靜默逾時判定拿去當 waiting_detail
315
361
  # (見 registry._promote_codex_permission_wait)。
316
- pending_detail, pending_at = _pending_permission_detail(event, prev_row, now)
317
- if pending_detail:
318
- payload["pending_permission_detail"] = pending_detail
319
- payload["pending_permission_detail_at"] = pending_at
320
-
321
- if event.status is Status.WAITING and event.waiting_kind:
322
- payload["waiting_kind"] = event.waiting_kind
323
- if event.status is Status.WAITING:
324
- waiting_agent_id = prev_row.get("waiting_agent_id", "") if keep_waiting else agent_id
325
- if waiting_agent_id:
326
- payload["waiting_agent_id"] = waiting_agent_id
327
- waiting_detail = event.detail
328
- if event.event == "Notification" and event.waiting_kind == "permission" and pending_detail:
329
- waiting_detail = pending_detail
330
- if waiting_detail:
331
- payload["waiting_detail"] = waiting_detail
362
+ if matched is not None:
363
+ payload["pending_permission_detail"] = matched["detail"]
364
+ payload["pending_permission_detail_at"] = matched["at"]
365
+
366
+ if selected is not None:
367
+ if selected.kind:
368
+ payload["waiting_kind"] = selected.kind
369
+ if selected.owner.startswith("agent:"):
370
+ payload["waiting_agent_id"] = selected.owner.removeprefix("agent:")
371
+ if selected.detail:
372
+ payload["waiting_detail"] = selected.detail
332
373
  previous_tty = str(prev_row.get("tty", "")) if same_binding else ""
333
374
  if is_subagent_event:
334
375
  tty = previous_tty or (_pid_tty(agent_pid) if agent_pid is not None else "")
@@ -341,13 +382,12 @@ def _update_session_state(
341
382
  # 的 waiting_notified_at(上次 waiting 通知的 epoch 時間戳)。離開 WAITING 也要把時間戳
342
383
  # 帶進新 row(payload 每次重建,不帶會遺失),快速翻回 WAITING 時才判得出「還在冷卻期」。
343
384
  # 舊 row 沒這欄位 = 從未通知過 → 照發。讀取與預約通知時間同樣受 session lock 保護。
344
- last_notified = _as_epoch(prev_row.get("waiting_notified_at"))
385
+ last_notified = _as_epoch(previous_state.get("waiting_notified_at"))
345
386
  if last_notified is not None:
346
387
  payload["waiting_notified_at"] = last_notified
347
388
  should_ring = False
348
- if event.status is Status.WAITING and not keep_waiting:
349
- # keep_waiting=只是沿用上一筆就已成立的 🔴,不是新的等待事件,不重發通知
350
- # (重複提醒由 TUI 的提醒排程器負責,見 tui._ring_on_waiting_alerts)。
389
+ if event.status is Status.WAITING:
390
+ # 只通知本事件提出的等待;沿用其他 owner 的 🔴 不算新的等待事件。
351
391
  should_ring = _waiting_ring_allowed(last_notified, now)
352
392
  if should_ring:
353
393
  payload["waiting_notified_at"] = now
@@ -356,11 +396,12 @@ def _update_session_state(
356
396
  tmp.write_text(json.dumps(payload))
357
397
  tmp.replace(path) # atomic
358
398
 
359
- if prev_status != event.status.value:
360
- log_transition(event.session_id, event.provider, event.cwd, event.status.value)
399
+ if prev_status != status.value:
400
+ log_transition(event.session_id, event.provider, event.cwd, status.value)
361
401
 
362
402
  if should_ring:
363
- return event, payload, last_action
403
+ # 看板可能仍選著另一個等待者;即時通知要描述這次事件本身。
404
+ return event, payload | {"waiting_kind": event.waiting_kind, "waiting_detail": event.detail}, last_action
364
405
  return None
365
406
 
366
407
 
@@ -376,8 +417,8 @@ def _notification_keeps_waiting(event: NormalizedHookEvent, prev_row: dict[str,
376
417
 
377
418
  只有真的證明使用者已經回應的事件(UserPromptSubmit / PreToolUse / PostToolUse /
378
419
  下一輪 Stop)才該清掉 WAITING;Notification 一律只能升 🔴、不能降 🟡。這裡回 True 時
379
- 由呼叫端沿用舊 row 的 waiting_for / waiting_kind / waiting_detail(payload 每次重建,
380
- 不帶就會遺失),並且不重發通知。
420
+ 由呼叫端保留 waiting_requests 的各來源內容(payload 每次重建,不帶就會遺失),
421
+ 再選出摘要欄位,並且不重發通知。
381
422
  """
382
423
  if event.event != "Notification" or event.status is not Status.IDLE:
383
424
  return False
@@ -419,29 +460,62 @@ def _as_epoch(v: Any) -> float | None:
419
460
 
420
461
 
421
462
  # 暫存的權限 detail 新鮮期(秒):permission_prompt Notification 通常在裸 PermissionRequest
422
- # 後 ~6 秒到;超過這個窗口的暫存視為過期(大概率屬於已解決的舊請求),不再拿來當 detail。
463
+ # 後 ~6 秒到;超過這個窗口的暫存視為過期(多半屬於已解決的舊請求),不再拿來當 detail。
423
464
  _PENDING_DETAIL_TTL = 120.0
424
465
 
425
466
  # 這些事件代表權限已放行(工具跑完)或回合已推進(新輸入 / 回合結束)→ 清掉暫存。
426
- _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop"}
427
-
428
-
429
- def _pending_permission_detail(event: NormalizedHookEvent, prev_row: dict[str, Any], now: float) -> tuple[str, float]:
430
- """決定這次要寫進 row 的「暫存權限 detail」:(detail, 暫存時間戳);不留就回 ("", 0.0)。
431
-
432
- - 裸 PermissionRequest(→ WORKING)帶 detail → 以這次的 detail 起新暫存
433
- - PostToolUse / UserPromptSubmit / Stop → 清掉(已放行或回合推進,舊暫存失效)
434
- - 其餘事件 → 沿用 prev_row 的暫存(row 每次重建,不帶會遺失),但過期就丟
435
- """
436
- if event.event == "PermissionRequest" and event.status is Status.WORKING and event.detail:
437
- return event.detail, now
438
- if event.event in _PENDING_DETAIL_CLEAR_EVENTS:
439
- return "", 0.0
440
- prev_detail = prev_row.get("pending_permission_detail")
441
- prev_at = _as_epoch(prev_row.get("pending_permission_detail_at"))
442
- if isinstance(prev_detail, str) and prev_detail and prev_at is not None and now - prev_at <= _PENDING_DETAIL_TTL:
443
- return prev_detail, prev_at
444
- return "", 0.0
467
+ _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop", "SessionEnd"}
468
+
469
+
470
+ def _pending_permission_details(
471
+ event: NormalizedHookEvent, prev_row: dict[str, Any], data: dict[str, Any], owner: str, now: float
472
+ ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
473
+ """依來源/tool use ID 保存候選;沒有唯一配對時不向通知提供摘要。"""
474
+ raw = prev_row.get("pending_permissions")
475
+ if not isinstance(raw, list):
476
+ raw = [
477
+ {
478
+ "owner": FOREGROUND_OWNER,
479
+ "request_id": "",
480
+ "detail": prev_row.get("pending_permission_detail"),
481
+ "at": prev_row.get("pending_permission_detail_at"),
482
+ }
483
+ ]
484
+ pending = [
485
+ item
486
+ for item in raw
487
+ if isinstance(item, dict)
488
+ and isinstance(item.get("owner"), str)
489
+ and isinstance(item.get("request_id"), str)
490
+ and isinstance(item.get("detail"), str)
491
+ and item["detail"]
492
+ and (at := _as_epoch(item.get("at"))) is not None
493
+ and 0 <= now - at <= _PENDING_DETAIL_TTL
494
+ ]
495
+ request_id = tool_request_id(data)
496
+ if owner != UNKNOWN_OWNER:
497
+ if event.event in _PENDING_DETAIL_CLEAR_EVENTS:
498
+ ambiguous_completion = (
499
+ event.event == "PostToolUse" and not request_id and sum(item["owner"] == owner for item in pending) > 1
500
+ )
501
+ pending = [
502
+ item
503
+ for item in pending
504
+ if ambiguous_completion
505
+ or item["owner"] != owner
506
+ or (event.event == "PostToolUse" and request_id and item["request_id"] != request_id)
507
+ ]
508
+ if event.event == "PermissionRequest" and event.status is Status.WORKING and event.detail:
509
+ pending = [item for item in pending if (item["owner"], item["request_id"]) != (owner, request_id)]
510
+ pending.append({"owner": owner, "request_id": request_id, "detail": event.detail, "at": now})
511
+ # 缺少來源的 Notification 可能來自背景請求;多個候選時不把最後一筆當答案。
512
+ unqualified = event.event == "Notification" and owner == FOREGROUND_OWNER
513
+ candidates = [
514
+ item
515
+ for item in pending
516
+ if (unqualified or item["owner"] == owner) and (not request_id or item["request_id"] == request_id)
517
+ ]
518
+ return pending, candidates[0] if len(candidates) == 1 else None
445
519
 
446
520
 
447
521
  def _waiting_ring_allowed(last_notified: float | None, now: float) -> bool:
@@ -484,6 +558,11 @@ def _ring_waiting_now(event: Any, payload: dict[str, Any], last_action: str) ->
484
558
  provider=event.provider,
485
559
  waiting_kind=str(payload.get("waiting_kind", "")),
486
560
  waiting_detail=str(payload.get("waiting_detail", "")),
561
+ waiting_requests=tuple(
562
+ request
563
+ for owner, request in read_waiting_requests(payload).items()
564
+ if owner == payload.get("last_event_owner", FOREGROUND_OWNER)
565
+ ),
487
566
  origin_cwd=event.cwd,
488
567
  )
489
568
  ]
@@ -16,10 +16,12 @@
16
16
  from __future__ import annotations
17
17
 
18
18
  import contextlib
19
+ import fcntl
19
20
  import json
20
21
  import os
21
22
  import sys
22
23
  import time
24
+ from collections.abc import Iterator
23
25
  from pathlib import Path
24
26
  from typing import TypedDict
25
27
 
@@ -53,6 +55,18 @@ class _TuiPresence(TypedDict):
53
55
  # --------------------------------------------------------------------------- focus-request 相關
54
56
 
55
57
 
58
+ @contextlib.contextmanager
59
+ def _focus_request_lock(path: Path) -> Iterator[None]:
60
+ path.parent.mkdir(parents=True, exist_ok=True)
61
+ # 鎖檔獨立於會被消費/替換的 request inode,reader 與 writer 才會鎖到同一把鎖。
62
+ with path.with_name(path.name + ".lock").open("a", encoding="utf-8") as handle:
63
+ fcntl.flock(handle, fcntl.LOCK_EX)
64
+ try:
65
+ yield
66
+ finally:
67
+ fcntl.flock(handle, fcntl.LOCK_UN)
68
+
69
+
56
70
  def write_focus_request(session_id: str, *, request_path: Path | None = None) -> None:
57
71
  """把 focus-request 寫入磁碟,供 TUI poll 讀取。
58
72
 
@@ -62,8 +76,10 @@ def write_focus_request(session_id: str, *, request_path: Path | None = None) ->
62
76
  path = request_path or _FOCUS_REQUEST_PATH
63
77
  payload: _FocusRequest = {"session_id": session_id, "ts": time.time()}
64
78
  try:
65
- path.parent.mkdir(parents=True, exist_ok=True)
66
- path.write_text(json.dumps(payload), encoding="utf-8")
79
+ with _focus_request_lock(path):
80
+ tmp = path.with_name(path.name + ".tmp")
81
+ tmp.write_text(json.dumps(payload), encoding="utf-8")
82
+ tmp.replace(path)
67
83
  except Exception:
68
84
  pass
69
85
 
@@ -86,29 +102,16 @@ def read_focus_request(
86
102
  """
87
103
  path = request_path or _FOCUS_REQUEST_PATH
88
104
  try:
89
- raw = path.read_text(encoding="utf-8")
90
- except Exception:
91
- return None
92
-
93
- try:
94
- data: _FocusRequest = json.loads(raw)
95
- session_id = str(data["session_id"])
96
- ts = float(data["ts"])
97
- except Exception:
98
- # 解析失敗:刪掉爛檔
99
- with contextlib.suppress(Exception):
105
+ with _focus_request_lock(path):
106
+ raw = path.read_text(encoding="utf-8")
107
+ # 讀取與消費在同一臨界區,後來的 writer 不會被這次 unlink 刪掉。
100
108
  path.unlink()
109
+ data: _FocusRequest = json.loads(raw)
110
+ session_id = str(data["session_id"])
111
+ ts = float(data["ts"])
112
+ except Exception:
101
113
  return None
102
-
103
- age = time.time() - ts
104
- # 不論有效或過期,都刪掉(消費即焚;過期的也不留)
105
- with contextlib.suppress(Exception):
106
- path.unlink()
107
-
108
- if age > ttl:
109
- return None
110
-
111
- return session_id
114
+ return session_id if time.time() - ts <= ttl else None
112
115
 
113
116
 
114
117
  # --------------------------------------------------------------------------- tui-presence 相關
@@ -845,3 +845,9 @@ msgstr "to keep only RiNG"
845
845
 
846
846
  msgid "把 preferredNotifChannel 設成 notifications_disabled"
847
847
  msgstr "set preferredNotifChannel to notifications_disabled"
848
+
849
+ msgid "⚠️ session 來源 '{name}' 讀取失敗,保留上次資料:{error}"
850
+ msgstr "⚠️ session source '{name}' failed; keeping the last snapshot: {error}"
851
+
852
+ msgid "看板刷新失敗,保留上次資料:{error}"
853
+ msgstr "Dashboard refresh failed; keeping the last snapshot: {error}"