ring-cli 0.17.4__tar.gz → 0.17.6__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.4 → ring_cli-0.17.6}/PKG-INFO +7 -1
  2. {ring_cli-0.17.4 → ring_cli-0.17.6}/README.en.md +6 -0
  3. {ring_cli-0.17.4 → ring_cli-0.17.6}/pyproject.toml +1 -1
  4. {ring_cli-0.17.4 → ring_cli-0.17.6}/pyproject.toml.orig +2 -2
  5. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/cli.py +8 -4
  6. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/trace.py +11 -6
  7. ring_cli-0.17.6/src/ring/fsutil.py +83 -0
  8. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/gc.py +22 -7
  9. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/hook.py +88 -40
  10. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/i18n.py +2 -2
  11. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/ipc.py +20 -23
  12. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/labels.py +12 -11
  13. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  14. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/locale/en/LC_MESSAGES/ring.po +22 -0
  15. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/locale/ring.pot +121 -101
  16. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify_queue.py +97 -42
  17. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/payload_log.py +11 -6
  18. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/registry.py +151 -98
  19. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/__init__.py +50 -1
  20. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/stats.py +15 -6
  21. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/transcript.py +99 -0
  22. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/tui.py +73 -29
  23. {ring_cli-0.17.4 → ring_cli-0.17.6}/LICENSE +0 -0
  24. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/__init__.py +0 -0
  25. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/__main__.py +0 -0
  26. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/agent_notify.py +0 -0
  27. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/__init__.py +0 -0
  28. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/_args.py +0 -0
  29. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/completion.py +0 -0
  30. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/digest.py +0 -0
  31. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/doctor.py +0 -0
  32. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/focus.py +0 -0
  33. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/gc.py +0 -0
  34. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/hook.py +0 -0
  35. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/quiet.py +0 -0
  36. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/commands/stats.py +0 -0
  37. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/config.py +0 -0
  38. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/__init__.py +0 -0
  39. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/applescript.py +0 -0
  40. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/base.py +0 -0
  41. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/iterm2.py +0 -0
  42. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/kitty.py +0 -0
  43. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/linux_wm.py +0 -0
  44. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/neovim.py +0 -0
  45. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/terminal.py +0 -0
  46. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/focus/tmux.py +0 -0
  47. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/hook_protocol.py +0 -0
  48. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/__init__.py +0 -0
  49. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/base.py +0 -0
  50. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/command.py +0 -0
  51. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/notify_send.py +0 -0
  52. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/ntfy.py +0 -0
  53. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/osascript_notifier.py +0 -0
  54. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/terminal_notifier.py +0 -0
  55. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/notify/webhook.py +0 -0
  56. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/osascript.py +0 -0
  57. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/pathutil.py +0 -0
  58. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/permission.py +0 -0
  59. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/plugins.py +0 -0
  60. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/ps_parse.py +0 -0
  61. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/question_detect.py +0 -0
  62. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/base.py +0 -0
  63. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/claude_code.py +0 -0
  64. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/codex.py +0 -0
  65. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/hook_registry.py +0 -0
  66. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/sources/local_llm.py +0 -0
  67. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/subproc.py +0 -0
  68. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/tmux_scan.py +0 -0
  69. {ring_cli-0.17.4 → ring_cli-0.17.6}/src/ring/waiting.py +0 -0
  70. {ring_cli-0.17.4 → ring_cli-0.17.6}/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.4
3
+ Version: 0.17.6
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
@@ -84,6 +84,12 @@ Use `pipx install 'ring-cli[tui]'` if you prefer pipx. Run `ring` for a one-shot
84
84
 
85
85
  Zero-config mode works without hooks. Precise 🔴 waiting states, pending details, and immediate notifications require hooks. Restart Claude Code or Codex sessions after installing or updating them.
86
86
 
87
+ ## Troubleshooting And Uninstall
88
+
89
+ - Hooks not taking effect: restart the agent session, then run `ring doctor`; hooks are writing only if `ls ~/.config/ring/sessions/` shows `<session_id>.json` files.
90
+ - Uninstall: `ring remove-hooks`, then `uv tool uninstall ring-cli`. State and config live in `~/.config/ring/`; delete that directory by hand to wipe everything (`ring gc` only removes stale state files of ended sessions).
91
+ - See "Troubleshooting And Uninstall" in the [full guide](https://lee-w.github.io/ring/guide/) for details.
92
+
87
93
  ## Learn More
88
94
 
89
95
  - [Full guide](https://lee-w.github.io/ring/guide/): commands, TUI controls, hooks, notifications, configuration, extensions, and privacy
@@ -58,6 +58,12 @@ Use `pipx install 'ring-cli[tui]'` if you prefer pipx. Run `ring` for a one-shot
58
58
 
59
59
  Zero-config mode works without hooks. Precise 🔴 waiting states, pending details, and immediate notifications require hooks. Restart Claude Code or Codex sessions after installing or updating them.
60
60
 
61
+ ## Troubleshooting And Uninstall
62
+
63
+ - Hooks not taking effect: restart the agent session, then run `ring doctor`; hooks are writing only if `ls ~/.config/ring/sessions/` shows `<session_id>.json` files.
64
+ - Uninstall: `ring remove-hooks`, then `uv tool uninstall ring-cli`. State and config live in `~/.config/ring/`; delete that directory by hand to wipe everything (`ring gc` only removes stale state files of ended sessions).
65
+ - See "Troubleshooting And Uninstall" in the [full guide](https://lee-w.github.io/ring/guide/) for details.
66
+
61
67
  ## Learn More
62
68
 
63
69
  - [Full guide](https://lee-w.github.io/ring/guide/): commands, TUI controls, hooks, notifications, configuration, extensions, and privacy
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ring-cli"
3
- version = "0.17.4"
3
+ version = "0.17.6"
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.4"
5
+ version = "0.17.6"
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"
@@ -96,7 +96,7 @@ select = [
96
96
  "TRY",
97
97
  ]
98
98
  ignore = [
99
- # 本專案刻意大量使用台灣漢語註解/字串,關掉「模糊 unicode 字元」誤報(全形標點等)。
99
+ # 本專案刻意大量使用台灣華語註解/字串,關掉「模糊 unicode 字元」誤報(全形標點等)。
100
100
  "RUF001",
101
101
  "RUF002",
102
102
  "RUF003",
@@ -407,7 +407,7 @@ def run_config(args: list[str]) -> int:
407
407
  return 2
408
408
 
409
409
 
410
- def _watch_flush_if_due() -> None:
410
+ def _watch_flush_if_due(sessions: list[Session]) -> None:
411
411
  """headless watch 輪詢時的懶惰 flush 觸發點(同 hook.py / tui.py 既有呼叫慣例)。
412
412
 
413
413
  quiet active 或仍在 debounce 視窗內時,``flush_if_due`` 內部本來就會 skip(跟
@@ -415,7 +415,7 @@ def _watch_flush_if_due() -> None:
415
415
  失敗安靜吞掉,不影響看板本身。
416
416
  """
417
417
  with contextlib.suppress(Exception):
418
- flush_if_due()
418
+ flush_if_due(current_sessions=sessions)
419
419
 
420
420
 
421
421
  def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int:
@@ -430,9 +430,9 @@ def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int
430
430
  if not HAVE_RICH:
431
431
  try:
432
432
  while True:
433
- _watch_flush_if_due()
434
433
  sys.stdout.write("\033[2J\033[H")
435
434
  sessions = board(show_all)
435
+ _watch_flush_if_due(sessions)
436
436
  print(_render_plain(sessions, show_legend, show_tool_column(sessions)))
437
437
  print(f"\n{footer_text}")
438
438
  sys.stdout.flush()
@@ -447,8 +447,8 @@ def watch(interval: float, count: int, show_all: bool, show_legend: bool) -> int
447
447
  try:
448
448
  with Live(console=console, screen=True, auto_refresh=False) as live:
449
449
  while True:
450
- _watch_flush_if_due()
451
450
  sessions = board(show_all)
451
+ _watch_flush_if_due(sessions)
452
452
  body = _rich_renderable(sessions, show_legend, show_tool_column(sessions))
453
453
  live.update(Group(body, Text(f"\n{footer_text}", style=_MUTED)), refresh=True)
454
454
  frames += 1
@@ -506,6 +506,10 @@ def _subcommand_help(name: str) -> str:
506
506
  """usage: ring install-hooks [--dry-run]
507
507
 
508
508
  安裝 Claude Code / Codex hooks。
509
+
510
+ 可重複執行:已裝過會回報沒有變更;只動 RiNG 的條目,不覆蓋既有 hooks。
511
+ 指令走 PATH 解析,多數升級不必重跑;新版本改了 hook(新事件或 timeout)時重跑一次即可。
512
+ Codex 只在 ~/.codex 存在時才會安裝。
509
513
  """
510
514
  ),
511
515
  "remove-hooks": _(
@@ -19,6 +19,8 @@ import json
19
19
  import time
20
20
  from pathlib import Path
21
21
 
22
+ from ring.fsutil import atomic_write_text, file_lock
23
+
22
24
  FOCUS_LOG_PATH = Path.home() / ".config" / "ring" / "focus.jsonl"
23
25
 
24
26
  # 一行約 200 bytes,1MB ≈ 5000 次跳轉。超過就砍半保新。
@@ -66,14 +68,17 @@ def log_jump(
66
68
 
67
69
 
68
70
  def _trim_if_oversized(p: Path) -> None:
69
- """log 超過 ``_MAX_BYTES`` 時砍半保新,避免無上限成長。失敗安靜放棄(不擋 append)。"""
71
+ """log 超過 ``_MAX_BYTES`` 時砍半保新,避免無上限成長。
72
+
73
+ 鎖只序列化 trimmer;append 不持鎖,trim 瞬間可能丟少量 log 行,可接受。失敗安靜放棄(不擋 append)。"""
70
74
  try:
71
75
  if p.stat().st_size <= _MAX_BYTES:
72
76
  return
73
- lines = p.read_text(encoding="utf-8").splitlines()
74
- keep = lines[len(lines) // 2 :]
75
- tmp = p.with_suffix(".jsonl.tmp")
76
- tmp.write_text("\n".join(keep) + "\n", encoding="utf-8")
77
- tmp.replace(p) # atomic
77
+ with file_lock(p):
78
+ if p.stat().st_size <= _MAX_BYTES: # 持鎖重驗:別的 process 可能已砍過
79
+ return
80
+ lines = p.read_text(encoding="utf-8").splitlines()
81
+ keep = lines[len(lines) // 2 :]
82
+ atomic_write_text(p, "\n".join(keep) + "\n")
78
83
  except Exception:
79
84
  pass
@@ -0,0 +1,83 @@
1
+ """檔案系統小工具——跨 process 的鎖與原子寫入,集中在這裡避免各模組各抄一份而分岔。
2
+
3
+ - ``file_lock(path)``:以 ``<path>.lock`` 旁檔做 ``fcntl.flock`` 獨占。鎖檔獨立於資料檔,
4
+ 資料檔被 ``os.replace`` 換掉 inode 後,等候中的 writer 仍會鎖到同一把鎖;鎖檔不隨資料刪除。
5
+ - ``atomic_write_text(path, text)``:同目錄唯一名 tmp + fsync + ``os.replace``,
6
+ 讀者要嘛看到舊內容、要嘛看到完整新內容。
7
+ - ``quarantine_file(path, stamp=...)``:壞檔改名保留,而不是被下一次寫入無聲蓋掉。
8
+ - ``backup_file(path)``:寫入前保留一份 ``<name>.bak``(覆寫舊 bak,不累積)。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import fcntl
15
+ import os
16
+ import shutil
17
+ import tempfile
18
+ from collections.abc import Iterator
19
+ from pathlib import Path
20
+
21
+ _NEW_FILE_MODE = 0o644
22
+
23
+
24
+ @contextlib.contextmanager
25
+ def file_lock(path: Path) -> Iterator[None]:
26
+ """跨 process 的 read-modify-write 臨界區;鎖的是 ``<path>.lock`` 旁檔。"""
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ with path.with_name(path.name + ".lock").open("a", encoding="utf-8") as handle:
29
+ fcntl.flock(handle, fcntl.LOCK_EX)
30
+ try:
31
+ yield
32
+ finally:
33
+ fcntl.flock(handle, fcntl.LOCK_UN)
34
+
35
+
36
+ def atomic_write_text(path: Path, text: str) -> None:
37
+ """原子寫入:tmp 在同目錄且名稱唯一,fsync 後 ``os.replace``;失敗會清掉 tmp 並往上拋。
38
+
39
+ 沿用既有檔的權限(沒有就用 0644),不讓 ``mkstemp`` 的 0600 悄悄改掉使用者檔案的權限。
40
+ """
41
+ path = Path(os.path.realpath(path)) # 跟進 symlink(dotfiles 管理的設定檔),不把連結換成一般檔
42
+ path.parent.mkdir(parents=True, exist_ok=True)
43
+ try:
44
+ mode = path.stat().st_mode & 0o7777
45
+ except OSError:
46
+ mode = _NEW_FILE_MODE
47
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
48
+ tmp = Path(tmp_name)
49
+ try:
50
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
51
+ fh.write(text)
52
+ fh.flush()
53
+ os.fsync(fh.fileno())
54
+ tmp.chmod(mode)
55
+ tmp.replace(path)
56
+ except BaseException:
57
+ with contextlib.suppress(OSError):
58
+ tmp.unlink()
59
+ raise
60
+
61
+
62
+ def backup_file(path: Path) -> Path | None:
63
+ """原檔存在才備份成 ``<name>.bak``;回傳 bak 路徑,原檔不存在回 None。
64
+
65
+ 每次都覆寫舊 bak:它是「上一次寫入前的前像」,不是歷史。對 symlink 備份真實檔;
66
+ 複製失敗會拋 ``OSError``,由呼叫端決定如何中止(不要在備份失敗時照樣覆寫原檔)。
67
+ """
68
+ real = Path(os.path.realpath(path))
69
+ if not real.exists():
70
+ return None
71
+ bak = real.with_name(real.name + ".bak")
72
+ shutil.copy2(real, bak)
73
+ return bak
74
+
75
+
76
+ def quarantine_file(path: Path, *, stamp: str) -> Path | None:
77
+ """把壞檔改名成 ``<name>.corrupt-<stamp>`` 保留下來;成功回新路徑,失敗回 None。"""
78
+ target = path.with_name(f"{path.name}.corrupt-{stamp}")
79
+ try:
80
+ path.replace(target)
81
+ except OSError:
82
+ return None
83
+ return target
@@ -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]:
@@ -26,21 +26,20 @@ Agent CLI 在各事件把一段 JSON 從 stdin 餵進來。我們據此 upsert
26
26
 
27
27
  from __future__ import annotations
28
28
 
29
- import fcntl
30
29
  import json
31
30
  import os
32
31
  import shutil
33
32
  import subprocess
34
33
  import sys
35
34
  import time
36
- from collections.abc import Iterator
37
- from contextlib import contextmanager
35
+ from contextlib import AbstractContextManager
38
36
  from dataclasses import asdict, dataclass, replace
39
37
  from pathlib import Path
40
38
  from typing import Any
41
39
  from urllib.parse import quote
42
40
 
43
41
  from ring.config import get_config
42
+ from ring.fsutil import atomic_write_text, backup_file, file_lock
44
43
  from ring.hook_protocol import HOOK_EVENTS, NormalizedHookEvent, adapter_for, provider_from_payload
45
44
  from ring.i18n import gettext as _
46
45
  from ring.i18n import set_lang
@@ -116,30 +115,47 @@ def _hook_targets() -> list[_HookTarget]:
116
115
  return targets
117
116
 
118
117
 
119
- def _ps_row(pid: int) -> tuple[int, str] | None:
120
- """回傳給定 pid 的 (ppid, comm);失敗回 None。"""
118
+ def _ps_comm(pid: int) -> str | None:
119
+ """單次 ``ps -o comm= -p <pid>``:pid 還活著回 comm,已不存在或失敗回 None。"""
121
120
  try:
122
- out = subprocess.run(
123
- ["ps", "-o", "ppid=,comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2
124
- ).stdout.strip()
121
+ out = subprocess.run(["ps", "-o", "comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2).stdout
125
122
  except (OSError, subprocess.SubprocessError):
126
123
  return None
127
- parts = out.split(None, 1)
128
- if len(parts) < 2:
129
- return None
124
+ return out.strip() or None
125
+
126
+
127
+ def _ps_table() -> dict[int, tuple[int, str]] | None:
128
+ """單次 ``ps -Ao pid=,ppid=,comm=`` 拿整張行程表:``{pid: (ppid, comm)}``;失敗回 None。
129
+
130
+ hook 在每個 PreToolUse/PostToolUse 都要找 agent pid;逐層 spawn ``ps`` 最多 12 次,
131
+ 改成一次拿全表、在行程內走祖先鏈。
132
+ """
130
133
  try:
131
- return int(parts[0]), parts[1]
132
- except ValueError:
134
+ out = subprocess.run(["ps", "-Ao", "pid=,ppid=,comm="], capture_output=True, text=True, timeout=2).stdout
135
+ except (OSError, subprocess.SubprocessError):
133
136
  return None
137
+ table: dict[int, tuple[int, str]] = {}
138
+ for line in out.splitlines():
139
+ parts = line.split(None, 2)
140
+ if len(parts) < 3:
141
+ continue
142
+ try:
143
+ table[int(parts[0])] = (int(parts[1]), parts[2])
144
+ except ValueError:
145
+ continue
146
+ return table or None
134
147
 
135
148
 
136
149
  def _session_pid(process_names: tuple[str, ...]) -> int | None:
137
- """hook 是 agent CLI 的後代——往上找到真正的 provider process PID。"""
150
+ """hook 是 agent CLI 的後代——往上找到真正的 provider process PID(一次 ``ps``,行程內走鏈)。"""
138
151
  if not process_names:
139
152
  return None
153
+ table = _ps_table()
154
+ if table is None:
155
+ return None
140
156
  pid = os.getppid()
141
157
  for _attempt in range(12):
142
- row = _ps_row(pid)
158
+ row = table.get(pid)
143
159
  if row is None:
144
160
  return None
145
161
  ppid, comm = row
@@ -151,6 +167,12 @@ def _session_pid(process_names: tuple[str, ...]) -> int | None:
151
167
  return None
152
168
 
153
169
 
170
+ def _confirm_previous_pid(previous_pid: int, process_names: tuple[str, ...]) -> bool:
171
+ """registry 已記錄的 agent pid 是否仍活著、且仍是同一種 agent(單次 ``ps``,免祖先爬)。"""
172
+ comm = _ps_comm(previous_pid)
173
+ return comm is not None and Path(comm).name in process_names
174
+
175
+
154
176
  def _controlling_tty() -> str:
155
177
  """hook process 自己的 controlling tty。非互動環境取不到時回空字串。"""
156
178
  try:
@@ -168,17 +190,10 @@ def run_hook(provider: str = "claude-code") -> int:
168
190
  收按鈕、把決策寫到 stdout 回給 Claude(這條路下 ``_ring_waiting_now`` 自動短路、不重複發)。
169
191
  其餘情況 RiNG 記狀態 + 發通知後 exit 0(你在終端自己回答)。
170
192
 
171
- 每次執行開頭先嘗試懶惰 flush 合流 queue(見 ``notify_queue.flush_if_due``)——沒有常駐
193
+ 更新 registry 後嘗試懶惰 flush 合流 queue(見 ``notify_queue.flush_if_due``)——沒有常駐
172
194
  daemon,任何 hook 事件(不限於這次自己是不是 waiting 事件)都是「debounce 視窗過期」的
173
195
  天然觸發點,讓 headless(沒開 TUI)也能補發彙總通知。失敗安靜吞掉,不影響本次事件記錄。
174
196
  """
175
- try:
176
- from ring.notify_queue import flush_if_due
177
-
178
- flush_if_due()
179
- except Exception:
180
- pass
181
-
182
197
  try:
183
198
  raw = sys.stdin.read()
184
199
  except OSError:
@@ -198,19 +213,12 @@ def run_hook(provider: str = "claude-code") -> int:
198
213
  return _delegate_to_agent_hooks(raw, selected_provider)
199
214
 
200
215
 
201
- @contextmanager
202
- def _session_state_lock(path: Path) -> Iterator[None]:
216
+ def _session_state_lock(path: Path) -> AbstractContextManager[None]:
203
217
  """同 session 的 hook 序列化整段 read-modify-write,包含 SessionEnd。
204
218
 
205
219
  lock 檔不隨 row 刪除,避免仍在排隊的 writer 鎖住舊 inode、另一個 writer 卻鎖住新 inode。
206
220
  """
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)
221
+ return file_lock(path)
214
222
 
215
223
 
216
224
  def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
@@ -227,6 +235,12 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
227
235
  notification = _update_session_state(path, event, data, adapter.process_names)
228
236
  except OSError:
229
237
  return
238
+ try:
239
+ from ring.notify_queue import flush_if_due
240
+
241
+ flush_if_due()
242
+ except Exception:
243
+ pass
230
244
  # 系統通知可能等待外部程序,不可持鎖阻擋後續解除等待的 hook。
231
245
  if notification is not None:
232
246
  _ring_waiting_now(*notification)
@@ -265,7 +279,19 @@ def _update_session_state(
265
279
  return None
266
280
 
267
281
  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)
282
+ agent_pid: int | None = None
283
+ if not is_subagent_event:
284
+ # 熱路徑:已綁定的 pid 還活著且 comm 吻合就直接沿用(1 次 ps);SessionStart 是重新綁定
285
+ # 的時機,一律走完整查詢。pid 失效或換人才付一次 ps -Ao 的全表代價。
286
+ if (
287
+ previous_pid is not None
288
+ and event.event != "SessionStart"
289
+ and process_names
290
+ and _confirm_previous_pid(previous_pid, process_names)
291
+ ):
292
+ agent_pid = previous_pid
293
+ else:
294
+ agent_pid = _session_pid(process_names)
269
295
  same_binding = is_subagent_event or (
270
296
  event.event != "SessionStart" and (agent_pid is None or agent_pid == previous_pid)
271
297
  )
@@ -393,9 +419,7 @@ def _update_session_state(
393
419
  if should_ring:
394
420
  payload["waiting_notified_at"] = now
395
421
 
396
- tmp = path.with_suffix(".json.tmp")
397
- tmp.write_text(json.dumps(payload))
398
- tmp.replace(path) # atomic
422
+ atomic_write_text(path, json.dumps(payload))
399
423
 
400
424
  if prev_status != status.value:
401
425
  log_transition(event.session_id, event.provider, event.cwd, status.value)
@@ -559,6 +583,11 @@ def _ring_waiting_now(event: Any, payload: dict[str, Any], last_action: str) ->
559
583
  provider=event.provider,
560
584
  waiting_kind=str(payload.get("waiting_kind", "")),
561
585
  waiting_detail=str(payload.get("waiting_detail", "")),
586
+ waiting_requests=tuple(
587
+ request
588
+ for owner, request in read_waiting_requests(payload).items()
589
+ if owner == payload.get("last_event_owner", FOREGROUND_OWNER)
590
+ ),
562
591
  origin_cwd=event.cwd,
563
592
  )
564
593
  ]
@@ -743,6 +772,16 @@ def install_hooks(dry_run: bool = False) -> int:
743
772
  return rc
744
773
 
745
774
 
775
+ def _backup_or_report(settings: Path) -> bool:
776
+ """寫入前備份設定檔;失敗就印一行錯誤並回 False(呼叫端須中止,不可照樣覆寫)。"""
777
+ try:
778
+ backup_file(settings)
779
+ except OSError as exc:
780
+ print(_("⚠️ 無法備份 {path}({error}),為避免弄壞設定檔,未寫入。", path=settings, error=exc))
781
+ return False
782
+ return True
783
+
784
+
746
785
  def _install_target(target: _HookTarget, dry_run: bool) -> int:
747
786
  """把 RiNG hook 合併進單一 target 的 settings 檔。"""
748
787
  settings = target.path
@@ -754,6 +793,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
754
793
  except json.JSONDecodeError:
755
794
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
756
795
  return 1
796
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
797
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
798
+ return 1
757
799
 
758
800
  hooks = data.setdefault("hooks", {})
759
801
 
@@ -801,8 +843,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
801
843
  cleaned.append({"hooks": [{"type": "command", "command": cmd, "timeout": _HOOK_TIMEOUT}]})
802
844
  hooks[event] = cleaned
803
845
 
804
- settings.parent.mkdir(parents=True, exist_ok=True)
805
- settings.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
846
+ if not _backup_or_report(settings): # 這是使用者自己的 Claude/Codex 設定檔:先留一份原樣
847
+ return 1
848
+ atomic_write_text(settings, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
806
849
  print(_("✅ 已註冊 RiNG hooks({events})到 {path}", events=", ".join(events_need_change), path=settings))
807
850
  print(" " + target.restart_hint)
808
851
  _print_conflict_warning(hooks)
@@ -826,10 +869,13 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
826
869
  return 0
827
870
 
828
871
  try:
829
- data: dict[str, Any] = json.loads(settings.read_text() or "{}")
872
+ data: Any = json.loads(settings.read_text() or "{}")
830
873
  except json.JSONDecodeError:
831
874
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
832
875
  return 1
876
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
877
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
878
+ return 1
833
879
 
834
880
  hooks = data.get("hooks", {})
835
881
  removed: list[str] = []
@@ -852,6 +898,8 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
852
898
  print(_("ℹ️ 沒有找到 RiNG hook 條目,無需移除。({path})", path=settings))
853
899
  return 0
854
900
 
855
- settings.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
901
+ if not _backup_or_report(settings):
902
+ return 1
903
+ atomic_write_text(settings, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
856
904
  print(_("✅ 已移除 RiNG hooks({events})從 {path}", events=", ".join(removed), path=settings))
857
905
  return 0
@@ -1,7 +1,7 @@
1
1
  """RiNG i18n — gettext。
2
2
 
3
- msgid 用**台灣漢語**:原始碼即預設語言,所以 zh-Hant 不需要任何 ``.mo``。
4
- 其他語言放 ``locale/<lang>/LC_MESSAGES/ring.mo``(由 ``.po`` 編譯,見 README / ``poe i18n-compile``)。
3
+ msgid 用**台灣華語**:原始碼即預設語言,所以 zh-Hant 不需要任何 ``.mo``。
4
+ 其他語言放 ``locale/<lang>/LC_MESSAGES/ring.mo``(由 ``.po`` 編譯,見 README / ``poe i18n:compile``)。
5
5
 
6
6
  切語言:process 啟動時 ``set_lang()`` 裝上對應 translation;之後 ``_()`` / ``ngettext()`` 就用它。
7
7
  在 ``import ring.tui`` 之前先 set_lang,class-level 的 Footer 按鍵說明也會跟著走。
@@ -20,9 +20,12 @@ import json
20
20
  import os
21
21
  import sys
22
22
  import time
23
+ from collections.abc import Iterator
23
24
  from pathlib import Path
24
25
  from typing import TypedDict
25
26
 
27
+ from ring.fsutil import atomic_write_text, file_lock
28
+
26
29
  # --------------------------------------------------------------------------- 路徑常數(可在測試中覆寫)
27
30
 
28
31
  _CONFIG_DIR: Path = Path.home() / ".config" / "ring"
@@ -53,6 +56,13 @@ class _TuiPresence(TypedDict):
53
56
  # --------------------------------------------------------------------------- focus-request 相關
54
57
 
55
58
 
59
+ @contextlib.contextmanager
60
+ def _focus_request_lock(path: Path) -> Iterator[None]:
61
+ # 鎖檔獨立於會被消費/替換的 request inode,reader 與 writer 才會鎖到同一把鎖。
62
+ with file_lock(path):
63
+ yield
64
+
65
+
56
66
  def write_focus_request(session_id: str, *, request_path: Path | None = None) -> None:
57
67
  """把 focus-request 寫入磁碟,供 TUI poll 讀取。
58
68
 
@@ -62,8 +72,8 @@ def write_focus_request(session_id: str, *, request_path: Path | None = None) ->
62
72
  path = request_path or _FOCUS_REQUEST_PATH
63
73
  payload: _FocusRequest = {"session_id": session_id, "ts": time.time()}
64
74
  try:
65
- path.parent.mkdir(parents=True, exist_ok=True)
66
- path.write_text(json.dumps(payload), encoding="utf-8")
75
+ with _focus_request_lock(path):
76
+ atomic_write_text(path, json.dumps(payload))
67
77
  except Exception:
68
78
  pass
69
79
 
@@ -86,29 +96,16 @@ def read_focus_request(
86
96
  """
87
97
  path = request_path or _FOCUS_REQUEST_PATH
88
98
  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):
99
+ with _focus_request_lock(path):
100
+ raw = path.read_text(encoding="utf-8")
101
+ # 讀取與消費在同一臨界區,後來的 writer 不會被這次 unlink 刪掉。
100
102
  path.unlink()
103
+ data: _FocusRequest = json.loads(raw)
104
+ session_id = str(data["session_id"])
105
+ ts = float(data["ts"])
106
+ except Exception:
101
107
  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
108
+ return session_id if time.time() - ts <= ttl else None
112
109
 
113
110
 
114
111
  # --------------------------------------------------------------------------- tui-presence 相關