ring-cli 0.17.5__tar.gz → 0.17.7__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.7}/PKG-INFO +7 -1
  2. {ring_cli-0.17.5 → ring_cli-0.17.7}/README.en.md +6 -0
  3. {ring_cli-0.17.5 → ring_cli-0.17.7}/pyproject.toml +1 -1
  4. {ring_cli-0.17.5 → ring_cli-0.17.7}/pyproject.toml.orig +2 -2
  5. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/cli.py +4 -0
  6. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/trace.py +11 -6
  7. ring_cli-0.17.7/src/ring/fsutil.py +83 -0
  8. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/hook.py +148 -33
  9. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/hook_protocol.py +4 -1
  10. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/i18n.py +2 -2
  11. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/ipc.py +5 -11
  12. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/labels.py +12 -11
  13. ring_cli-0.17.7/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  14. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/locale/en/LC_MESSAGES/ring.po +16 -0
  15. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/locale/ring.pot +42 -32
  16. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify_queue.py +9 -25
  17. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/payload_log.py +11 -6
  18. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/registry.py +152 -99
  19. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/stats.py +15 -6
  20. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/transcript.py +99 -0
  21. ring_cli-0.17.5/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  22. {ring_cli-0.17.5 → ring_cli-0.17.7}/LICENSE +0 -0
  23. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/__init__.py +0 -0
  24. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/__main__.py +0 -0
  25. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/agent_notify.py +0 -0
  26. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/__init__.py +0 -0
  27. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/_args.py +0 -0
  28. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/completion.py +0 -0
  29. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/digest.py +0 -0
  30. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/doctor.py +0 -0
  31. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/focus.py +0 -0
  32. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/gc.py +0 -0
  33. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/hook.py +0 -0
  34. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/quiet.py +0 -0
  35. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/commands/stats.py +0 -0
  36. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/config.py +0 -0
  37. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/__init__.py +0 -0
  38. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/applescript.py +0 -0
  39. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/base.py +0 -0
  40. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/iterm2.py +0 -0
  41. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/kitty.py +0 -0
  42. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/linux_wm.py +0 -0
  43. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/neovim.py +0 -0
  44. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/terminal.py +0 -0
  45. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/focus/tmux.py +0 -0
  46. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/gc.py +0 -0
  47. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/__init__.py +0 -0
  48. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/base.py +0 -0
  49. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/command.py +0 -0
  50. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/notify_send.py +0 -0
  51. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/ntfy.py +0 -0
  52. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/osascript_notifier.py +0 -0
  53. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/terminal_notifier.py +0 -0
  54. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/notify/webhook.py +0 -0
  55. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/osascript.py +0 -0
  56. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/pathutil.py +0 -0
  57. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/permission.py +0 -0
  58. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/plugins.py +0 -0
  59. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/ps_parse.py +0 -0
  60. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/question_detect.py +0 -0
  61. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/__init__.py +0 -0
  62. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/base.py +0 -0
  63. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/claude_code.py +0 -0
  64. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/codex.py +0 -0
  65. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/hook_registry.py +0 -0
  66. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/sources/local_llm.py +0 -0
  67. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/subproc.py +0 -0
  68. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/tmux_scan.py +0 -0
  69. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/tui.py +0 -0
  70. {ring_cli-0.17.5 → ring_cli-0.17.7}/src/ring/waiting.py +0 -0
  71. {ring_cli-0.17.5 → ring_cli-0.17.7}/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.7
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.7"
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.7"
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
@@ -21,26 +21,26 @@ Agent CLI 在各事件把一段 JSON 從 stdin 餵進來。我們據此 upsert
21
21
  一般 Notification → 🟡 跑完停著;但既有狀態已是 🔴 時保住 🔴——Claude Code
22
22
  閒置滿 60 秒送的 idle_prompt 不是「使用者回應了」的證據
23
23
  (見 _notification_keeps_waiting)
24
+ SubagentStop → 只清該 subagent 名下的等待與暫存摘要(需帶 agent_id)
24
25
  SessionEnd → 刪檔(乾淨離場)
25
26
  """
26
27
 
27
28
  from __future__ import annotations
28
29
 
29
- import fcntl
30
30
  import json
31
31
  import os
32
32
  import shutil
33
33
  import subprocess
34
34
  import sys
35
35
  import time
36
- from collections.abc import Iterator
37
- from contextlib import contextmanager
36
+ from contextlib import AbstractContextManager
38
37
  from dataclasses import asdict, dataclass, replace
39
38
  from pathlib import Path
40
39
  from typing import Any
41
40
  from urllib.parse import quote
42
41
 
43
42
  from ring.config import get_config
43
+ from ring.fsutil import atomic_write_text, backup_file, file_lock
44
44
  from ring.hook_protocol import HOOK_EVENTS, NormalizedHookEvent, adapter_for, provider_from_payload
45
45
  from ring.i18n import gettext as _
46
46
  from ring.i18n import set_lang
@@ -116,30 +116,47 @@ def _hook_targets() -> list[_HookTarget]:
116
116
  return targets
117
117
 
118
118
 
119
- def _ps_row(pid: int) -> tuple[int, str] | None:
120
- """回傳給定 pid 的 (ppid, comm);失敗回 None。"""
119
+ def _ps_comm(pid: int) -> str | None:
120
+ """單次 ``ps -o comm= -p <pid>``:pid 還活著回 comm,已不存在或失敗回 None。"""
121
121
  try:
122
- out = subprocess.run(
123
- ["ps", "-o", "ppid=,comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2
124
- ).stdout.strip()
122
+ out = subprocess.run(["ps", "-o", "comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2).stdout
125
123
  except (OSError, subprocess.SubprocessError):
126
124
  return None
127
- parts = out.split(None, 1)
128
- if len(parts) < 2:
129
- return None
125
+ return out.strip() or None
126
+
127
+
128
+ def _ps_table() -> dict[int, tuple[int, str]] | None:
129
+ """單次 ``ps -Ao pid=,ppid=,comm=`` 拿整張行程表:``{pid: (ppid, comm)}``;失敗回 None。
130
+
131
+ hook 在每個 PreToolUse/PostToolUse 都要找 agent pid;逐層 spawn ``ps`` 最多 12 次,
132
+ 改成一次拿全表、在行程內走祖先鏈。
133
+ """
130
134
  try:
131
- return int(parts[0]), parts[1]
132
- except ValueError:
135
+ out = subprocess.run(["ps", "-Ao", "pid=,ppid=,comm="], capture_output=True, text=True, timeout=2).stdout
136
+ except (OSError, subprocess.SubprocessError):
133
137
  return None
138
+ table: dict[int, tuple[int, str]] = {}
139
+ for line in out.splitlines():
140
+ parts = line.split(None, 2)
141
+ if len(parts) < 3:
142
+ continue
143
+ try:
144
+ table[int(parts[0])] = (int(parts[1]), parts[2])
145
+ except ValueError:
146
+ continue
147
+ return table or None
134
148
 
135
149
 
136
150
  def _session_pid(process_names: tuple[str, ...]) -> int | None:
137
- """hook 是 agent CLI 的後代——往上找到真正的 provider process PID。"""
151
+ """hook 是 agent CLI 的後代——往上找到真正的 provider process PID(一次 ``ps``,行程內走鏈)。"""
138
152
  if not process_names:
139
153
  return None
154
+ table = _ps_table()
155
+ if table is None:
156
+ return None
140
157
  pid = os.getppid()
141
158
  for _attempt in range(12):
142
- row = _ps_row(pid)
159
+ row = table.get(pid)
143
160
  if row is None:
144
161
  return None
145
162
  ppid, comm = row
@@ -151,6 +168,12 @@ def _session_pid(process_names: tuple[str, ...]) -> int | None:
151
168
  return None
152
169
 
153
170
 
171
+ def _confirm_previous_pid(previous_pid: int, process_names: tuple[str, ...]) -> bool:
172
+ """registry 已記錄的 agent pid 是否仍活著、且仍是同一種 agent(單次 ``ps``,免祖先爬)。"""
173
+ comm = _ps_comm(previous_pid)
174
+ return comm is not None and Path(comm).name in process_names
175
+
176
+
154
177
  def _controlling_tty() -> str:
155
178
  """hook process 自己的 controlling tty。非互動環境取不到時回空字串。"""
156
179
  try:
@@ -191,19 +214,12 @@ def run_hook(provider: str = "claude-code") -> int:
191
214
  return _delegate_to_agent_hooks(raw, selected_provider)
192
215
 
193
216
 
194
- @contextmanager
195
- def _session_state_lock(path: Path) -> Iterator[None]:
217
+ def _session_state_lock(path: Path) -> AbstractContextManager[None]:
196
218
  """同 session 的 hook 序列化整段 read-modify-write,包含 SessionEnd。
197
219
 
198
220
  lock 檔不隨 row 刪除,避免仍在排隊的 writer 鎖住舊 inode、另一個 writer 卻鎖住新 inode。
199
221
  """
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)
222
+ return file_lock(path)
207
223
 
208
224
 
209
225
  def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
@@ -231,6 +247,74 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
231
247
  _ring_waiting_now(*notification)
232
248
 
233
249
 
250
+ def _apply_subagent_stop(
251
+ path: Path, event: NormalizedHookEvent, prev_row: dict[str, Any], owner: str
252
+ ) -> tuple[NormalizedHookEvent, dict[str, Any], str] | None:
253
+ """SubagentStop 只做一件事:移除已收工 subagent 名下殘留的等待與暫存摘要。
254
+
255
+ 沒有既有 row、沒有 agent ID(Claude Code 內部 agent 無法對應 owner)、或該 owner 名下
256
+ 沒有東西可清時,一律不寫檔——不建列、不復活已離場 session、不刷新活動欄位。
257
+ 有東西可清時只改 waiting_requests/pending_permissions 與因此變動的 status 及其衍生欄位;
258
+ last_event、last_event_owner、last_action、last_active、heartbeat 維持原值。
259
+ """
260
+ if not prev_row or owner in (FOREGROUND_OWNER, UNKNOWN_OWNER):
261
+ return None
262
+ requests = read_waiting_requests(prev_row)
263
+ raw_pending = prev_row.get("pending_permissions")
264
+ pending_list = raw_pending if isinstance(raw_pending, list) else []
265
+ owns_pending = any(isinstance(item, dict) and item.get("owner") == owner for item in pending_list)
266
+ if owner not in requests and not owns_pending:
267
+ return None
268
+ requests.pop(owner, None)
269
+ row = dict(prev_row)
270
+ if isinstance(raw_pending, list):
271
+ row["pending_permissions"] = [
272
+ item for item in pending_list if not (isinstance(item, dict) and item.get("owner") == owner)
273
+ ]
274
+ row["waiting_requests"] = {key: asdict(request) for key, request in requests.items()}
275
+ prev_status = str(prev_row.get("status", ""))
276
+ status_value = prev_status
277
+ if prev_status == Status.WAITING.value:
278
+ for key in ("waiting_kind", "waiting_agent_id", "waiting_detail", "waiting_for"):
279
+ row.pop(key, None)
280
+ if requests:
281
+ selected = primary_wait(requests)
282
+ if selected.kind:
283
+ row["waiting_kind"] = selected.kind
284
+ if selected.owner.startswith("agent:"):
285
+ row["waiting_agent_id"] = selected.owner.removeprefix("agent:")
286
+ if selected.detail:
287
+ row["waiting_detail"] = selected.detail
288
+ if selected.waiting_for:
289
+ row["waiting_for"] = selected.waiting_for
290
+ else:
291
+ status_value = _status_without_waits(prev_row, event.provider).value
292
+ row["status"] = status_value
293
+ try:
294
+ atomic_write_text(path, json.dumps(row))
295
+ except OSError:
296
+ return None
297
+ if prev_status != status_value:
298
+ log_transition(event.session_id, event.provider, event.cwd, status_value)
299
+ return None
300
+
301
+
302
+ def _status_without_waits(prev_row: dict[str, Any], provider: str) -> Status:
303
+ """還原「主 session 在等待之外本來的狀態」:前景最後一筆事件經既有正規化得出;
304
+ 最後事件明確來自 subagent 或無法判定時取 WORKING;升級前的舊 row 沒有 last_event_owner
305
+ 欄位,當時的 last_event 都是前景事件,視同前景。"""
306
+ last_event = prev_row.get("last_event")
307
+ if (
308
+ prev_row.get("last_event_owner", FOREGROUND_OWNER) == FOREGROUND_OWNER
309
+ and isinstance(last_event, str)
310
+ and last_event
311
+ ):
312
+ normalized = adapter_for(provider).normalize({"hook_event_name": last_event, "session_id": "-"})
313
+ if normalized is not None and normalized.status in (Status.IDLE, Status.WORKING):
314
+ return normalized.status
315
+ return Status.WORKING
316
+
317
+
234
318
  def _update_session_state(
235
319
  path: Path, event: NormalizedHookEvent, data: dict[str, Any], process_names: tuple[str, ...]
236
320
  ) -> tuple[NormalizedHookEvent, dict[str, Any], str] | None:
@@ -239,6 +323,8 @@ def _update_session_state(
239
323
  prev_status = str(prev_row["status"]) if "status" in prev_row else None
240
324
  owner = event_owner(data)
241
325
  is_subagent_event = owner != FOREGROUND_OWNER
326
+ if event.event == "SubagentStop":
327
+ return _apply_subagent_stop(path, event, prev_row, owner)
242
328
  if is_subagent_event:
243
329
  # Subagent SessionEnd 不是 host session 的結束。
244
330
  if event.status is Status.ENDED:
@@ -264,7 +350,19 @@ def _update_session_state(
264
350
  return None
265
351
 
266
352
  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)
353
+ agent_pid: int | None = None
354
+ if not is_subagent_event:
355
+ # 熱路徑:已綁定的 pid 還活著且 comm 吻合就直接沿用(1 次 ps);SessionStart 是重新綁定
356
+ # 的時機,一律走完整查詢。pid 失效或換人才付一次 ps -Ao 的全表代價。
357
+ if (
358
+ previous_pid is not None
359
+ and event.event != "SessionStart"
360
+ and process_names
361
+ and _confirm_previous_pid(previous_pid, process_names)
362
+ ):
363
+ agent_pid = previous_pid
364
+ else:
365
+ agent_pid = _session_pid(process_names)
268
366
  same_binding = is_subagent_event or (
269
367
  event.event != "SessionStart" and (agent_pid is None or agent_pid == previous_pid)
270
368
  )
@@ -392,9 +490,7 @@ def _update_session_state(
392
490
  if should_ring:
393
491
  payload["waiting_notified_at"] = now
394
492
 
395
- tmp = path.with_suffix(".json.tmp")
396
- tmp.write_text(json.dumps(payload))
397
- tmp.replace(path) # atomic
493
+ atomic_write_text(path, json.dumps(payload))
398
494
 
399
495
  if prev_status != status.value:
400
496
  log_transition(event.session_id, event.provider, event.cwd, status.value)
@@ -464,7 +560,7 @@ def _as_epoch(v: Any) -> float | None:
464
560
  _PENDING_DETAIL_TTL = 120.0
465
561
 
466
562
  # 這些事件代表權限已放行(工具跑完)或回合已推進(新輸入 / 回合結束)→ 清掉暫存。
467
- _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop", "SessionEnd"}
563
+ _PENDING_DETAIL_CLEAR_EVENTS = {"PostToolUse", "UserPromptSubmit", "Stop", "SubagentStop", "SessionEnd"}
468
564
 
469
565
 
470
566
  def _pending_permission_details(
@@ -747,6 +843,16 @@ def install_hooks(dry_run: bool = False) -> int:
747
843
  return rc
748
844
 
749
845
 
846
+ def _backup_or_report(settings: Path) -> bool:
847
+ """寫入前備份設定檔;失敗就印一行錯誤並回 False(呼叫端須中止,不可照樣覆寫)。"""
848
+ try:
849
+ backup_file(settings)
850
+ except OSError as exc:
851
+ print(_("⚠️ 無法備份 {path}({error}),為避免弄壞設定檔,未寫入。", path=settings, error=exc))
852
+ return False
853
+ return True
854
+
855
+
750
856
  def _install_target(target: _HookTarget, dry_run: bool) -> int:
751
857
  """把 RiNG hook 合併進單一 target 的 settings 檔。"""
752
858
  settings = target.path
@@ -758,6 +864,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
758
864
  except json.JSONDecodeError:
759
865
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
760
866
  return 1
867
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
868
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
869
+ return 1
761
870
 
762
871
  hooks = data.setdefault("hooks", {})
763
872
 
@@ -805,8 +914,9 @@ def _install_target(target: _HookTarget, dry_run: bool) -> int:
805
914
  cleaned.append({"hooks": [{"type": "command", "command": cmd, "timeout": _HOOK_TIMEOUT}]})
806
915
  hooks[event] = cleaned
807
916
 
808
- settings.parent.mkdir(parents=True, exist_ok=True)
809
- settings.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
917
+ if not _backup_or_report(settings): # 這是使用者自己的 Claude/Codex 設定檔:先留一份原樣
918
+ return 1
919
+ atomic_write_text(settings, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
810
920
  print(_("✅ 已註冊 RiNG hooks({events})到 {path}", events=", ".join(events_need_change), path=settings))
811
921
  print(" " + target.restart_hint)
812
922
  _print_conflict_warning(hooks)
@@ -830,10 +940,13 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
830
940
  return 0
831
941
 
832
942
  try:
833
- data: dict[str, Any] = json.loads(settings.read_text() or "{}")
943
+ data: Any = json.loads(settings.read_text() or "{}")
834
944
  except json.JSONDecodeError:
835
945
  print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
836
946
  return 1
947
+ if not isinstance(data, dict): # 頂層是 list 等:同樣當作不是有效設定檔
948
+ print(_("⚠️ {path} 不是合法 JSON,先處理它再來。", path=settings))
949
+ return 1
837
950
 
838
951
  hooks = data.get("hooks", {})
839
952
  removed: list[str] = []
@@ -856,6 +969,8 @@ def _uninstall_target(target: _HookTarget, dry_run: bool) -> int:
856
969
  print(_("ℹ️ 沒有找到 RiNG hook 條目,無需移除。({path})", path=settings))
857
970
  return 0
858
971
 
859
- settings.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
972
+ if not _backup_or_report(settings):
973
+ return 1
974
+ atomic_write_text(settings, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
860
975
  print(_("✅ 已移除 RiNG hooks({events})從 {path}", events=", ".join(removed), path=settings))
861
976
  return 0
@@ -101,7 +101,9 @@ class CommonHookAdapter:
101
101
  explicit_requires_action = _explicit_requires_action(data)
102
102
  if event == "SessionEnd":
103
103
  status = Status.ENDED
104
- elif event in {"SessionStart", "UserPromptSubmit"}:
104
+ elif event in {"SessionStart", "UserPromptSubmit", "SubagentStop"}:
105
+ # SubagentStop 由 hook 端的 _apply_subagent_stop 短路處理(只清該 subagent 的等待),
106
+ # 不會依這裡的 WORKING 寫入 row;此值僅讓事件通過正規化。
105
107
  status = Status.WORKING
106
108
  elif explicit_requires_action is not None:
107
109
  status = Status.WAITING if explicit_requires_action else Status.IDLE
@@ -361,5 +363,6 @@ HOOK_EVENTS = (
361
363
  "PreToolUse",
362
364
  "PostToolUse",
363
365
  "Stop",
366
+ "SubagentStop",
364
367
  "SessionEnd",
365
368
  )
@@ -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"