ring-cli 0.17.5__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 (71) hide show
  1. {ring_cli-0.17.5 → ring_cli-0.17.6}/PKG-INFO +7 -1
  2. {ring_cli-0.17.5 → ring_cli-0.17.6}/README.en.md +6 -0
  3. {ring_cli-0.17.5 → ring_cli-0.17.6}/pyproject.toml +1 -1
  4. {ring_cli-0.17.5 → ring_cli-0.17.6}/pyproject.toml.orig +2 -2
  5. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/cli.py +4 -0
  6. {ring_cli-0.17.5 → 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.5 → ring_cli-0.17.6}/src/ring/hook.py +76 -32
  9. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/i18n.py +2 -2
  10. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/ipc.py +5 -11
  11. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/labels.py +12 -11
  12. ring_cli-0.17.6/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  13. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/locale/en/LC_MESSAGES/ring.po +16 -0
  14. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/locale/ring.pot +42 -32
  15. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify_queue.py +9 -25
  16. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/payload_log.py +11 -6
  17. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/registry.py +151 -98
  18. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/stats.py +15 -6
  19. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/transcript.py +99 -0
  20. ring_cli-0.17.5/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  21. {ring_cli-0.17.5 → ring_cli-0.17.6}/LICENSE +0 -0
  22. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/__init__.py +0 -0
  23. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/__main__.py +0 -0
  24. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/agent_notify.py +0 -0
  25. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/__init__.py +0 -0
  26. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/_args.py +0 -0
  27. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/completion.py +0 -0
  28. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/digest.py +0 -0
  29. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/doctor.py +0 -0
  30. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/focus.py +0 -0
  31. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/gc.py +0 -0
  32. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/hook.py +0 -0
  33. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/quiet.py +0 -0
  34. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/commands/stats.py +0 -0
  35. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/config.py +0 -0
  36. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/__init__.py +0 -0
  37. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/applescript.py +0 -0
  38. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/base.py +0 -0
  39. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/iterm2.py +0 -0
  40. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/kitty.py +0 -0
  41. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/linux_wm.py +0 -0
  42. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/neovim.py +0 -0
  43. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/terminal.py +0 -0
  44. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/focus/tmux.py +0 -0
  45. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/gc.py +0 -0
  46. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/hook_protocol.py +0 -0
  47. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/__init__.py +0 -0
  48. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/base.py +0 -0
  49. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/command.py +0 -0
  50. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/notify_send.py +0 -0
  51. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/ntfy.py +0 -0
  52. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/osascript_notifier.py +0 -0
  53. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/terminal_notifier.py +0 -0
  54. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/notify/webhook.py +0 -0
  55. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/osascript.py +0 -0
  56. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/pathutil.py +0 -0
  57. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/permission.py +0 -0
  58. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/plugins.py +0 -0
  59. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/ps_parse.py +0 -0
  60. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/question_detect.py +0 -0
  61. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/__init__.py +0 -0
  62. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/base.py +0 -0
  63. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/claude_code.py +0 -0
  64. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/codex.py +0 -0
  65. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/hook_registry.py +0 -0
  66. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/sources/local_llm.py +0 -0
  67. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/subproc.py +0 -0
  68. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/tmux_scan.py +0 -0
  69. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/tui.py +0 -0
  70. {ring_cli-0.17.5 → ring_cli-0.17.6}/src/ring/waiting.py +0 -0
  71. {ring_cli-0.17.5 → 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.5
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.5"
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.5"
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",
@@ -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
@@ -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:
@@ -191,19 +213,12 @@ def run_hook(provider: str = "claude-code") -> int:
191
213
  return _delegate_to_agent_hooks(raw, selected_provider)
192
214
 
193
215
 
194
- @contextmanager
195
- def _session_state_lock(path: Path) -> Iterator[None]:
216
+ def _session_state_lock(path: Path) -> AbstractContextManager[None]:
196
217
  """同 session 的 hook 序列化整段 read-modify-write,包含 SessionEnd。
197
218
 
198
219
  lock 檔不隨 row 刪除,避免仍在排隊的 writer 鎖住舊 inode、另一個 writer 卻鎖住新 inode。
199
220
  """
200
- path.parent.mkdir(parents=True, exist_ok=True)
201
- with path.with_suffix(".json.lock").open("a", encoding="utf-8") as handle:
202
- fcntl.flock(handle, fcntl.LOCK_EX)
203
- try:
204
- yield
205
- finally:
206
- fcntl.flock(handle, fcntl.LOCK_UN)
221
+ return file_lock(path)
207
222
 
208
223
 
209
224
  def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
@@ -264,7 +279,19 @@ def _update_session_state(
264
279
  return None
265
280
 
266
281
  previous_pid = int(prev_row["agent_pid"]) if str(prev_row.get("agent_pid", "")).isdigit() else None
267
- 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)
268
295
  same_binding = is_subagent_event or (
269
296
  event.event != "SessionStart" and (agent_pid is None or agent_pid == previous_pid)
270
297
  )
@@ -392,9 +419,7 @@ def _update_session_state(
392
419
  if should_ring:
393
420
  payload["waiting_notified_at"] = now
394
421
 
395
- tmp = path.with_suffix(".json.tmp")
396
- tmp.write_text(json.dumps(payload))
397
- tmp.replace(path) # atomic
422
+ atomic_write_text(path, json.dumps(payload))
398
423
 
399
424
  if prev_status != status.value:
400
425
  log_transition(event.session_id, event.provider, event.cwd, status.value)
@@ -747,6 +772,16 @@ def install_hooks(dry_run: bool = False) -> int:
747
772
  return rc
748
773
 
749
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
+
750
785
  def _install_target(target: _HookTarget, dry_run: bool) -> int:
751
786
  """把 RiNG hook 合併進單一 target 的 settings 檔。"""
752
787
  settings = target.path
@@ -758,6 +793,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
758
793
  except json.JSONDecodeError:
759
794
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
760
795
  return 1
796
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
797
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
798
+ return 1
761
799
 
762
800
  hooks = data.setdefault("hooks", {})
763
801
 
@@ -805,8 +843,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
805
843
  cleaned.append({"hooks": [{"type": "command", "command": cmd, "timeout": _HOOK_TIMEOUT}]})
806
844
  hooks[event] = cleaned
807
845
 
808
- settings.parent.mkdir(parents=True, exist_ok=True)
809
- 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")
810
849
  print(_("✅ 已註冊 RiNG hooks({events})到 {path}", events=", ".join(events_need_change), path=settings))
811
850
  print(" " + target.restart_hint)
812
851
  _print_conflict_warning(hooks)
@@ -830,10 +869,13 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
830
869
  return 0
831
870
 
832
871
  try:
833
- data: dict[str, Any] = json.loads(settings.read_text() or "{}")
872
+ data: Any = json.loads(settings.read_text() or "{}")
834
873
  except json.JSONDecodeError:
835
874
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
836
875
  return 1
876
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
877
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
878
+ return 1
837
879
 
838
880
  hooks = data.get("hooks", {})
839
881
  removed: list[str] = []
@@ -856,6 +898,8 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
856
898
  print(_("ℹ️ 沒有找到 RiNG hook 條目,無需移除。({path})", path=settings))
857
899
  return 0
858
900
 
859
- 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")
860
904
  print(_("✅ 已移除 RiNG hooks({events})從 {path}", events=", ".join(removed), path=settings))
861
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 按鍵說明也會跟著走。
@@ -16,7 +16,6 @@
16
16
  from __future__ import annotations
17
17
 
18
18
  import contextlib
19
- import fcntl
20
19
  import json
21
20
  import os
22
21
  import sys
@@ -25,6 +24,8 @@ from collections.abc import Iterator
25
24
  from pathlib import Path
26
25
  from typing import TypedDict
27
26
 
27
+ from ring.fsutil import atomic_write_text, file_lock
28
+
28
29
  # --------------------------------------------------------------------------- 路徑常數(可在測試中覆寫)
29
30
 
30
31
  _CONFIG_DIR: Path = Path.home() / ".config" / "ring"
@@ -57,14 +58,9 @@ class _TuiPresence(TypedDict):
57
58
 
58
59
  @contextlib.contextmanager
59
60
  def _focus_request_lock(path: Path) -> Iterator[None]:
60
- path.parent.mkdir(parents=True, exist_ok=True)
61
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)
62
+ with file_lock(path):
63
+ yield
68
64
 
69
65
 
70
66
  def write_focus_request(session_id: str, *, request_path: Path | None = None) -> None:
@@ -77,9 +73,7 @@ def write_focus_request(session_id: str, *, request_path: Path | None = None) ->
77
73
  payload: _FocusRequest = {"session_id": session_id, "ts": time.time()}
78
74
  try:
79
75
  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)
76
+ atomic_write_text(path, json.dumps(payload))
83
77
  except Exception:
84
78
  pass
85
79
 
@@ -10,6 +10,8 @@ from __future__ import annotations
10
10
  import json
11
11
  from pathlib import Path
12
12
 
13
+ from ring.fsutil import atomic_write_text, file_lock
14
+
13
15
  _LABELS_PATH: Path = Path.home() / ".config" / "ring" / "labels.json"
14
16
 
15
17
 
@@ -33,18 +35,17 @@ def get_label(session_id: str, *, path: Path | None = None) -> str:
33
35
  def set_label(session_id: str, label: str, *, path: Path | None = None) -> None:
34
36
  """設定 / 更新某 session 的標籤;傳空字串(或全空白)則移除該標籤。"""
35
37
  p = path or _LABELS_PATH
36
- labels = load_labels(path=path)
37
38
  label = label.strip()
38
- if label:
39
- labels[session_id] = label
40
- elif session_id not in labels:
41
- return # 本來就沒有,且要清空 → 不必寫檔
42
- else:
43
- labels.pop(session_id, None)
44
39
  try:
45
- p.parent.mkdir(parents=True, exist_ok=True)
46
- tmp = p.with_suffix(".json.tmp")
47
- tmp.write_text(json.dumps(labels, ensure_ascii=False), encoding="utf-8")
48
- tmp.replace(p) # atomic
40
+ # 整段 read-modify-write 持鎖:兩個 TUI 同時改不同 session 的標籤不會互相蓋掉。
41
+ with file_lock(p):
42
+ labels = load_labels(path=p)
43
+ if label:
44
+ labels[session_id] = label
45
+ elif session_id not in labels:
46
+ return # 本來就沒有,且要清空 → 不必寫檔
47
+ else:
48
+ labels.pop(session_id, None)
49
+ atomic_write_text(p, json.dumps(labels, ensure_ascii=False))
49
50
  except Exception:
50
51
  pass
@@ -169,10 +169,17 @@ msgstr "no focuser handled it (run `ring doctor` to see which focusers are avail
169
169
  msgid "背景 agent,沒有終端可跳;用 `claude --resume {session_id}` 接回"
170
170
  msgstr "background agent, no terminal to jump to; reconnect with `claude --resume {session_id}`"
171
171
 
172
+ # ── TUI:就地回覆權限 ──
173
+ msgid "… {project}:正在回覆權限"
174
+ msgstr "… {project}: replying to permission request"
175
+
172
176
  # ── install-hooks ──
173
177
  msgid "⚠️ {path} 不是合法 JSON,先處理它再來。"
174
178
  msgstr "⚠️ {path} is not valid JSON; fix it first."
175
179
 
180
+ msgid "⚠️ 無法備份 {path}({error}),為避免弄壞設定檔,未寫入。"
181
+ msgstr "⚠️ Could not back up {path} ({error}); nothing was written, to avoid damaging the settings file."
182
+
176
183
  msgid "✅ RiNG hooks 已經裝過了,沒有變更。({path})"
177
184
  msgstr "✅ RiNG hooks already installed; no change. ({path})"
178
185
 
@@ -318,10 +325,19 @@ msgid ""
318
325
  "usage: ring install-hooks [--dry-run]\n"
319
326
  "\n"
320
327
  "安裝 Claude Code / Codex hooks。\n"
328
+ "\n"
329
+ "可重複執行:已裝過會回報沒有變更;只動 RiNG 的條目,不覆蓋既有 hooks。\n"
330
+ "指令走 PATH 解析,多數升級不必重跑;新版本改了 hook(新事件或 timeout)時重跑一次即可。\n"
331
+ "Codex 只在 ~/.codex 存在時才會安裝。\n"
321
332
  msgstr ""
322
333
  "usage: ring install-hooks [--dry-run]\n"
323
334
  "\n"
324
335
  "Install Claude Code / Codex hooks.\n"
336
+ "\n"
337
+ "Safe to run repeatedly: reports no change when already installed; only touches RiNG's entries and\n"
338
+ "never overwrites existing hooks. The command resolves via PATH, so most upgrades need no re-run;\n"
339
+ "re-run once if a new version changes the hooks (new events or timeout). Codex hooks are only\n"
340
+ "installed when ~/.codex exists.\n"
325
341
 
326
342
  msgid ""
327
343
  "usage: ring remove-hooks [--dry-run]\n"