session-trail 0.2.3__tar.gz → 0.3.1__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 (43) hide show
  1. {session_trail-0.2.3/src/session_trail.egg-info → session_trail-0.3.1}/PKG-INFO +14 -1
  2. {session_trail-0.2.3 → session_trail-0.3.1}/README.en.md +11 -0
  3. {session_trail-0.2.3 → session_trail-0.3.1}/README.md +11 -0
  4. {session_trail-0.2.3 → session_trail-0.3.1}/pyproject.toml +3 -1
  5. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/claude_code.py +6 -1
  6. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/codex.py +5 -1
  7. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/opencode.py +14 -0
  8. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/cli.py +4 -0
  9. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/launcher.py +18 -3
  10. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/models.py +12 -1
  11. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/tray/__init__.py +1 -1
  12. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/watcher.py +235 -41
  13. {session_trail-0.2.3 → session_trail-0.3.1/src/session_trail.egg-info}/PKG-INFO +14 -1
  14. {session_trail-0.2.3 → session_trail-0.3.1}/LICENSE +0 -0
  15. {session_trail-0.2.3 → session_trail-0.3.1}/MANIFEST.in +0 -0
  16. {session_trail-0.2.3 → session_trail-0.3.1}/setup.cfg +0 -0
  17. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/__init__.py +0 -0
  18. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/__main__.py +0 -0
  19. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/__init__.py +0 -0
  20. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/base.py +0 -0
  21. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/codebuddy.py +0 -0
  22. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/deepseek_harness.py +0 -0
  23. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/jsonl_utils.py +0 -0
  24. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/kimi_code.py +0 -0
  25. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/minimax_code.py +0 -0
  26. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/pi.py +0 -0
  27. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/sqlite_utils.py +0 -0
  28. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/adapters/zcode.py +0 -0
  29. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/scanner.py +0 -0
  30. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/server.py +0 -0
  31. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/static/app.js +0 -0
  32. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/static/i18n.js +0 -0
  33. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/static/index.html +0 -0
  34. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/static/styles.css +0 -0
  35. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/store.py +0 -0
  36. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/tray/app.py +0 -0
  37. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/tray/desktop.template +0 -0
  38. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/tray/icon.png +0 -0
  39. {session_trail-0.2.3 → session_trail-0.3.1}/src/agent_trail/tray/sni.py +0 -0
  40. {session_trail-0.2.3 → session_trail-0.3.1}/src/session_trail.egg-info/SOURCES.txt +0 -0
  41. {session_trail-0.2.3 → session_trail-0.3.1}/src/session_trail.egg-info/dependency_links.txt +0 -0
  42. {session_trail-0.2.3 → session_trail-0.3.1}/src/session_trail.egg-info/entry_points.txt +0 -0
  43. {session_trail-0.2.3 → session_trail-0.3.1}/src/session_trail.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: session-trail
3
- Version: 0.2.3
3
+ Version: 0.3.1
4
4
  Summary: Local cross-agent work timeline: discover, browse and resume coding-agent sessions on your machine
5
5
  Author: fwt11
6
6
  License-Expression: MIT
@@ -13,6 +13,8 @@ Classifier: Environment :: Web Environment
13
13
  Classifier: Environment :: X11 Applications
14
14
  Classifier: Intended Audience :: Developers
15
15
  Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
16
18
  Classifier: Programming Language :: Python :: 3
17
19
  Classifier: Programming Language :: Python :: 3.10
18
20
  Classifier: Programming Language :: Python :: 3.11
@@ -44,6 +46,17 @@ Dynamic: license-file
44
46
  - **隐私优先**:本地索引只存元数据(标题、目录、时间、统计),不存任何消息正文、代码、diff 或凭据;HTTP 服务只绑定 127.0.0.1,每次启动生成高熵访问令牌
45
47
  - **诚实降级**:没有原生标题就显示"未命名会话",恢复路径没验证过就不显示恢复按钮,绝不伪造
46
48
 
49
+ ## 平台支持
50
+
51
+ | 能力 | Linux | Windows | macOS |
52
+ | --- | --- | --- | --- |
53
+ | scan / list / serve 网页控制台 | ✅ | ✅ | ✅ |
54
+ | 实时变更监控 | inotify 秒级 | 轮询 ≈5s | 轮询 ≈5s |
55
+ | 系统托盘 + 内嵌窗口 | ✅(原生 SNI + WebKit2GTK) | 规划中 | 规划中 |
56
+ | 回到原会话(已验证工具) | ✅ | 取决于该 Agent 的 CLI 是否存在 | 同左 |
57
+
58
+ 数据目录路径:开源工具的 Windows/macOS 路径已按其源码/官方文档确认——Codex(`dirs::home_dir()/.codex`,全平台同布局)、Claude Code(`%USERPROFILE%/.claude`)、OpenCode(Windows = `%LOCALAPPDATA%/opencode`,macOS 同 Linux)、Pi(`~/.pi/agent` 全平台一致);三者并尊重各自的官方覆盖变量(`CODEX_HOME` / `CLAUDE_CONFIG_DIR` / `OPENCODE_DATA`)。闭源工具(Kimi/CodeBuddy/MiniMax/ZCode/DeepSeek)其他平台的目录未验证,未发现数据源的适配器会诚实显示"未发现"。
59
+
47
60
  ## 支持的 Agent
48
61
 
49
62
  | Agent | 时间线 | 回到原会话 | 说明 |
@@ -17,6 +17,17 @@ A local-first work memory for people who use multiple coding agents: it discover
17
17
  - **Honest degradation**: no native title → "Unnamed session"; unverified resume paths → no resume button. It never fakes capabilities
18
18
  - **i18n**: the console UI and tray menu ship in Simplified Chinese and English; the console follows your browser language (`?lang=en` / `?lang=zh-CN` to override), the tray follows `LANG` (`AGENT_TRAIL_LANG` overrides)
19
19
 
20
+ ## Platform support
21
+
22
+ | Capability | Linux | Windows | macOS |
23
+ | --- | --- | --- | --- |
24
+ | scan / list / serve web console | ✅ | ✅ | ✅ |
25
+ | Live change watching | inotify (seconds) | polling ≈5s | polling ≈5s |
26
+ | System tray + embedded window | ✅ (native SNI + WebKit2GTK) | planned | planned |
27
+ | Resume original session (verified tools) | ✅ | depends on each agent's CLI availability | same |
28
+
29
+ Data paths: Windows/macOS locations for the open-source CLIs are confirmed from their sources/docs — Codex (`dirs::home_dir()/.codex`, same layout everywhere), Claude Code (`%USERPROFILE%/.claude`), OpenCode (Windows = `%LOCALAPPDATA%/opencode`, macOS same as Linux), Pi (`~/.pi/agent` everywhere); the adapters also honor their official override vars (`CODEX_HOME` / `CLAUDE_CONFIG_DIR` / `OPENCODE_DATA`). Directories for the closed-source tools (Kimi/CodeBuddy/MiniMax/ZCode/DeepSeek) are unverified off Linux; adapters that find no data honestly report "Not found".
30
+
20
31
  ## Supported agents
21
32
 
22
33
  | Agent | Timeline | Resume | Notes |
@@ -18,6 +18,17 @@
18
18
  - **隐私优先**:本地索引只存元数据(标题、目录、时间、统计),不存任何消息正文、代码、diff 或凭据;HTTP 服务只绑定 127.0.0.1,每次启动生成高熵访问令牌
19
19
  - **诚实降级**:没有原生标题就显示"未命名会话",恢复路径没验证过就不显示恢复按钮,绝不伪造
20
20
 
21
+ ## 平台支持
22
+
23
+ | 能力 | Linux | Windows | macOS |
24
+ | --- | --- | --- | --- |
25
+ | scan / list / serve 网页控制台 | ✅ | ✅ | ✅ |
26
+ | 实时变更监控 | inotify 秒级 | 轮询 ≈5s | 轮询 ≈5s |
27
+ | 系统托盘 + 内嵌窗口 | ✅(原生 SNI + WebKit2GTK) | 规划中 | 规划中 |
28
+ | 回到原会话(已验证工具) | ✅ | 取决于该 Agent 的 CLI 是否存在 | 同左 |
29
+
30
+ 数据目录路径:开源工具的 Windows/macOS 路径已按其源码/官方文档确认——Codex(`dirs::home_dir()/.codex`,全平台同布局)、Claude Code(`%USERPROFILE%/.claude`)、OpenCode(Windows = `%LOCALAPPDATA%/opencode`,macOS 同 Linux)、Pi(`~/.pi/agent` 全平台一致);三者并尊重各自的官方覆盖变量(`CODEX_HOME` / `CLAUDE_CONFIG_DIR` / `OPENCODE_DATA`)。闭源工具(Kimi/CodeBuddy/MiniMax/ZCode/DeepSeek)其他平台的目录未验证,未发现数据源的适配器会诚实显示"未发现"。
31
+
21
32
  ## 支持的 Agent
22
33
 
23
34
  | Agent | 时间线 | 回到原会话 | 说明 |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "session-trail"
7
- version = "0.2.3"
7
+ version = "0.3.1"
8
8
  description = "Local cross-agent work timeline: discover, browse and resume coding-agent sessions on your machine"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -19,6 +19,8 @@ classifiers = [
19
19
  "Environment :: X11 Applications",
20
20
  "Intended Audience :: Developers",
21
21
  "Operating System :: POSIX :: Linux",
22
+ "Operating System :: MacOS",
23
+ "Operating System :: Microsoft :: Windows",
22
24
  "Programming Language :: Python :: 3",
23
25
  "Programming Language :: Python :: 3.10",
24
26
  "Programming Language :: Python :: 3.11",
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import os
3
4
  from datetime import datetime
4
5
  from pathlib import Path
5
6
 
@@ -14,7 +15,11 @@ class ClaudeCodeAdapter(BaseAdapter):
14
15
 
15
16
  @property
16
17
  def root(self) -> Path:
17
- return self.home / ".claude" / "projects"
18
+ # 官方行为:CLAUDE_CONFIG_DIR 重定向整个配置目录(含 projects/),
19
+ # Windows 默认 %USERPROFILE%/.claude —— Path.home() 全平台一致。
20
+ base = os.environ.get("CLAUDE_CONFIG_DIR")
21
+ root = Path(base) if base else self.home / ".claude"
22
+ return root / "projects"
18
23
 
19
24
  def discover(self) -> AdapterStatus:
20
25
  if not self.root.is_dir():
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import json
4
+ import os
4
5
  import sqlite3
5
6
  from contextlib import closing
6
7
  from datetime import datetime
@@ -18,7 +19,10 @@ class CodexAdapter(BaseAdapter):
18
19
 
19
20
  @property
20
21
  def root(self) -> Path:
21
- return self.home / ".codex"
22
+ # 官方行为(源码 codex-rs/utils/home-dir):CODEX_HOME 优先,否则
23
+ # dirs::home_dir()/.codex —— 全平台同布局(Windows = %USERPROFILE%/.codex)。
24
+ override = os.environ.get("CODEX_HOME")
25
+ return Path(override) if override else self.home / ".codex"
22
26
 
23
27
  @property
24
28
  def database_path(self) -> Path:
@@ -1,7 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import json
4
+ import os
4
5
  import sqlite3
6
+ import sys
5
7
  from contextlib import closing
6
8
  from datetime import datetime
7
9
  from pathlib import Path
@@ -19,6 +21,18 @@ class OpenCodeAdapter(BaseAdapter):
19
21
 
20
22
  @property
21
23
  def root(self) -> Path:
24
+ # 平台差异(调研依据见 README 平台矩阵):
25
+ # - Linux/macOS: ~/.local/share/opencode(官方 troubleshooting 文档确认
26
+ # macOS 同 Linux,不走 Library/Application Support)
27
+ # - Windows: %LOCALAPPDATA%/opencode(XDG data home 在 Windows 解析为
28
+ # %LOCALAPPDATA%)
29
+ # - 官方覆盖变量 OPENCODE_DATA 优先于以上全部
30
+ override = os.environ.get("OPENCODE_DATA")
31
+ if override:
32
+ return Path(override)
33
+ if sys.platform == "win32":
34
+ base = os.environ.get("LOCALAPPDATA") or self.home / "AppData" / "Local"
35
+ return Path(base) / "opencode"
22
36
  return self.home / ".local" / "share" / "opencode"
23
37
 
24
38
  @property
@@ -46,6 +46,10 @@ def main(argv: list[str] | None = None) -> int:
46
46
  if args.interval <= 0:
47
47
  parser.error("--interval must be positive")
48
48
  if args.command == "tray":
49
+ if sys.platform != "linux":
50
+ print("agent-trail tray is Linux-only for now "
51
+ "(Windows/macOS backends are planned).")
52
+ return 1
49
53
  # 托盘是独立子进程形态,不需要打开本地索引;当前解释器缺 GI
50
54
  # 绑定时由 tray.main 内部重执行到带 gi 的系统 Python。
51
55
  from .tray.app import main as tray_main
@@ -4,6 +4,7 @@ import json
4
4
  import os
5
5
  import shutil
6
6
  import subprocess
7
+ import sys
7
8
  from dataclasses import dataclass
8
9
  from pathlib import Path
9
10
 
@@ -21,6 +22,7 @@ class TerminalLauncher:
21
22
  _allowed_executables = frozenset(
22
23
  {"kimi", "codebuddy", "mcode", "dst", "pi", "opencode", "codex"}
23
24
  )
25
+ # Linux 检测列表;Windows/macOS 见 _terminals_for_platform()。
24
26
  _terminals = (
25
27
  ("x-terminal-emulator", ("-e",)),
26
28
  ("gnome-terminal", ("--",)),
@@ -32,6 +34,10 @@ class TerminalLauncher:
32
34
  ("foot", ("--",)),
33
35
  ("xterm", ("-e",)),
34
36
  )
37
+ _terminals_windows = (
38
+ ("wt.exe", ("-d", "{workdir}", "cmd", "/k", "{command}")),
39
+ ("cmd.exe", ("/c", "start", "/D", "{workdir}", "{command}")),
40
+ )
35
41
 
36
42
  def __init__(
37
43
  self,
@@ -74,6 +80,10 @@ class TerminalLauncher:
74
80
  ]
75
81
  if "{command}" not in template:
76
82
  arguments.extend(command)
83
+ popen_kwargs = {"close_fds": True}
84
+ if os.name == "posix":
85
+ # 新会话脱离当前终端;Windows 上该参数不存在(ValueError)。
86
+ popen_kwargs["start_new_session"] = True
77
87
  try:
78
88
  process = subprocess.Popen(
79
89
  [terminal, *arguments],
@@ -81,13 +91,18 @@ class TerminalLauncher:
81
91
  stdin=subprocess.DEVNULL,
82
92
  stdout=subprocess.DEVNULL,
83
93
  stderr=subprocess.DEVNULL,
84
- close_fds=True,
85
- start_new_session=True,
94
+ **popen_kwargs,
86
95
  )
87
96
  except OSError:
88
97
  return LaunchResult(False, "resume.launch_failed")
89
98
  return LaunchResult(True, "resume.launch_ok", process.pid)
90
99
 
100
+ @staticmethod
101
+ def _terminals_for_platform() -> tuple:
102
+ if sys.platform == "win32":
103
+ return TerminalLauncher._terminals_windows
104
+ return TerminalLauncher._terminals # POSIX(含 macOS 的回退路径)
105
+
91
106
  def _terminal_command(self) -> tuple[str | None, tuple[str, ...]]:
92
107
  terminal_name = self.terminal or os.environ.get("AGENT_TRAIL_TERMINAL")
93
108
  if terminal_name:
@@ -99,7 +114,7 @@ class TerminalLauncher:
99
114
  if template.count("{command}") > 1:
100
115
  raise ValueError("duplicate command placeholder")
101
116
  return shutil.which(terminal_name), template
102
- for name, arguments in self._terminals:
117
+ for name, arguments in self._terminals_for_platform():
103
118
  terminal = shutil.which(name)
104
119
  if terminal:
105
120
  return terminal, arguments
@@ -40,7 +40,7 @@ class ActivitySession:
40
40
  object.__setattr__(
41
41
  self,
42
42
  "workdir_normalized",
43
- os.path.normpath(os.path.expanduser(self.workdir)),
43
+ _normalize_path(self.workdir),
44
44
  )
45
45
 
46
46
 
@@ -84,3 +84,14 @@ class SessionFilter:
84
84
  query: str | None = None
85
85
  limit: int = 200
86
86
  offset: int = 0
87
+
88
+
89
+ def _normalize_path(value: str) -> str:
90
+ """规范化工作目录:POSIX 保持现状;Windows 追加大小写归一。
91
+
92
+ NTFS 大小写不敏感,同一目录的两种写法应匹配到同一条记录。
93
+ """
94
+ normalized = os.path.normpath(os.path.expanduser(value))
95
+ if os.name == "nt":
96
+ normalized = normalized.lower()
97
+ return normalized
@@ -1,4 +1,4 @@
1
- """Agent 足迹 系统托盘(Linux/GI)。
1
+ """Agent 足迹 系统托盘(仅 Linux;Windows/macOS 后端规划中)。
2
2
 
3
3
  app.py 是托盘主体(子进程管理 + GTK 窗口 + 菜单);sni.py 是原生
4
4
  StatusNotifierItem 实现。托盘不 import 包内其他模块,因此可以由
@@ -1,9 +1,15 @@
1
- """inotify-backed change notification for agent session sources.
2
-
3
- Uses ctypes against libc directly so the project stays on the standard
4
- library. The watcher never replaces the scan itself: it only replaces
5
- the timer that wakes :meth:`ScanService.scan_all`. Fingerprints remain
6
- the cheap dedup layer, so any spurious event degrades to a fast no-op.
1
+ """Change notification for agent session sources, with pluggable backends.
2
+
3
+ The watcher never replaces the scan itself: it only replaces the timer
4
+ that wakes :meth:`ScanService.scan_all`. Fingerprints remain the cheap
5
+ dedup layer, so any spurious trigger degrades to a fast no-op.
6
+
7
+ Backends:
8
+ - Linux: ``SourceWatcher`` — inotify(7) via ctypes against libc, seconds
9
+ level latency, directory-level watches with recursive growth.
10
+ - Windows/macOS (and Linux fallback): ``PollingWatcher`` — a background
11
+ thread polls a lightweight signature (paths + size + mtime) of the
12
+ watched roots every few seconds and feeds the same debounce window.
7
13
  """
8
14
 
9
15
  from __future__ import annotations
@@ -12,6 +18,7 @@ import ctypes
12
18
  import os
13
19
  import select
14
20
  import struct
21
+ import sys
15
22
  import threading
16
23
  from collections.abc import Callable
17
24
  from pathlib import Path
@@ -101,13 +108,18 @@ def parse_events(raw: bytes) -> list[tuple[int, int, str]]:
101
108
  return events
102
109
 
103
110
 
104
- class SourceWatcher:
105
- """Debounced, directory-level inotify watcher.
111
+ class BaseWatcher:
112
+ """Shared watcher interface + the debounce/minimum-spacing time window.
106
113
 
107
- ``on_change`` runs on the watch thread; the existing scan lock keeps it
108
- serialized against manual refreshes and the safety-net poll.
114
+ Backends detect change and call :meth:`_note_activity`; the shared
115
+ window coalesces bursts and :meth:`_maybe_trigger` invokes
116
+ ``on_change`` when the deadline passes. ``on_change`` runs on the
117
+ backend thread; the scan lock keeps it serialized against manual
118
+ refreshes and the safety-net poll.
109
119
  """
110
120
 
121
+ kind = "base"
122
+
111
123
  def __init__(
112
124
  self,
113
125
  roots: list[tuple[Path, bool]],
@@ -115,25 +127,92 @@ class SourceWatcher:
115
127
  *,
116
128
  debounce_seconds: float = 1.0,
117
129
  min_spacing_seconds: float = 5.0,
118
- max_watches: int = 2048,
119
130
  ) -> None:
120
131
  self._roots = [(Path(path), recursive) for path, recursive in roots]
121
132
  self._on_change = on_change
122
133
  self._debounce = debounce_seconds
123
134
  self._min_spacing = min_spacing_seconds
124
- self._max_watches = max_watches
125
- self._libc = libc_inotify()
126
- self._fd: int | None = None
127
135
  self._thread: threading.Thread | None = None
128
136
  self._stop = threading.Event()
129
- self._lock = threading.Lock()
130
- self._wds: dict[int, Path] = {}
131
- self._paths: set[Path] = set()
132
137
  self._pending = False
133
138
  self._deadline = 0.0
134
139
  self._first_pending = 0.0
135
140
  self._last_trigger = 0.0
136
141
  self.last_error: str | None = None
142
+
143
+ @property
144
+ def healthy(self) -> bool:
145
+ return self._thread is not None and self._thread.is_alive()
146
+
147
+ @property
148
+ def watch_count(self) -> int:
149
+ raise NotImplementedError
150
+
151
+ def start(self) -> bool:
152
+ raise NotImplementedError
153
+
154
+ def stop(self) -> None:
155
+ self._stop.set()
156
+ if self._thread is not None:
157
+ self._thread.join(timeout=5)
158
+
159
+ def resync(self) -> None:
160
+ """Re-arm the backend after safety-net scans (idempotent)."""
161
+ return None
162
+
163
+ # -- shared debounce window ----------------------------------------------
164
+
165
+ def _note_activity(self, now: float) -> None:
166
+ if not self._pending:
167
+ self._first_pending = now
168
+ self._pending = True
169
+ # Push the deadline out for new activity, but never starve a
170
+ # busy source: pending work fires at most min_spacing after the
171
+ # first event of the burst.
172
+ cap = self._first_pending + max(self._min_spacing, self._debounce)
173
+ self._deadline = min(now + self._debounce, cap)
174
+
175
+ def _maybe_trigger(self) -> None:
176
+ if not self._pending or monotonic() < self._deadline:
177
+ return
178
+ now = monotonic()
179
+ spacing = self._last_trigger + self._min_spacing - now
180
+ if spacing > 0:
181
+ self._deadline = now + spacing
182
+ return
183
+ self._pending = False
184
+ self._last_trigger = now
185
+ try:
186
+ self._on_change()
187
+ except Exception as error:
188
+ # Keep watching; the failure type carries no source content.
189
+ self.last_error = f"{type(error).__name__}: {error}"
190
+
191
+
192
+ class SourceWatcher(BaseWatcher):
193
+ """Debounced, directory-level inotify watcher (Linux)."""
194
+
195
+ kind = "inotify"
196
+
197
+ def __init__(
198
+ self,
199
+ roots: list[tuple[Path, bool]],
200
+ on_change: Callable[[], None],
201
+ *,
202
+ debounce_seconds: float = 1.0,
203
+ min_spacing_seconds: float = 5.0,
204
+ max_watches: int = 2048,
205
+ ) -> None:
206
+ super().__init__(
207
+ roots, on_change,
208
+ debounce_seconds=debounce_seconds, min_spacing_seconds=min_spacing_seconds,
209
+ )
210
+ self._max_watches = max_watches
211
+ self._libc = libc_inotify()
212
+ self._fd: int | None = None
213
+ self._lock = threading.Lock()
214
+ self._wds: dict[int, Path] = {}
215
+ self._paths: set[Path] = set()
137
216
  self.overflowed = False
138
217
 
139
218
  @property
@@ -167,9 +246,7 @@ class SourceWatcher:
167
246
  return True
168
247
 
169
248
  def stop(self) -> None:
170
- self._stop.set()
171
- if self._thread is not None:
172
- self._thread.join(timeout=5)
249
+ super().stop()
173
250
  fd, self._fd = self._fd, None
174
251
  if fd is not None:
175
252
  os.close(fd)
@@ -272,30 +349,147 @@ class SourceWatcher:
272
349
  parent = self._wds.get(wd)
273
350
  if parent is not None and name:
274
351
  self._add_tree_locked(parent / name, True)
275
- if not self._pending:
276
- self._first_pending = now
277
- self._pending = True
278
- # Push the deadline out for new activity, but never starve a
279
- # busy source: pending work fires at most min_spacing after the
280
- # first event of the burst.
281
- cap = self._first_pending + max(self._min_spacing, self._debounce)
282
- self._deadline = min(now + self._debounce, cap)
352
+ self._note_activity(now)
283
353
 
284
- def _maybe_trigger(self) -> None:
285
- if not self._pending or monotonic() < self._deadline:
286
- return
287
- now = monotonic()
288
- spacing = self._last_trigger + self._min_spacing - now
289
- if spacing > 0:
290
- self._deadline = now + spacing
291
- return
292
- self._pending = False
293
- self._last_trigger = now
354
+
355
+ class PollingWatcher(BaseWatcher):
356
+ """Portable backend: poll a lightweight signature of the watched roots.
357
+
358
+ Used on Windows/macOS where inotify does not exist. The signature is
359
+ existence + per-file (size, mtime_ns) over the root trees — enough to
360
+ notice session files appearing, growing or vanishing without parsing
361
+ any content. Resolution is therefore ``poll_seconds`` (default 5s)
362
+ rather than seconds-level like inotify; the fingerprint dedup layer
363
+ makes extra triggers cheap.
364
+ """
365
+
366
+ kind = "polling"
367
+
368
+ def __init__(
369
+ self,
370
+ roots: list[tuple[Path, bool]],
371
+ on_change: Callable[[], None],
372
+ *,
373
+ debounce_seconds: float = 1.0,
374
+ min_spacing_seconds: float = 5.0,
375
+ poll_seconds: float = 5.0,
376
+ ) -> None:
377
+ super().__init__(
378
+ roots, on_change,
379
+ debounce_seconds=debounce_seconds, min_spacing_seconds=min_spacing_seconds,
380
+ )
381
+ self._poll_seconds = poll_seconds
382
+ self._signature: tuple | None = None
383
+
384
+ @property
385
+ def watch_count(self) -> int:
386
+ return len(self._roots)
387
+
388
+ def start(self) -> bool:
294
389
  try:
295
- self._on_change()
390
+ self._signature = self._compute_signature()
296
391
  except Exception as error:
297
- # Keep watching; the failure type carries no source content.
298
- self.last_error = f"{type(error).__name__}: {error}"
392
+ self.last_error = f"signature scan failed: {type(error).__name__}"
393
+ return False
394
+ self._thread = threading.Thread(
395
+ target=self._run, name="agent-trail-watch", daemon=True
396
+ )
397
+ self._thread.start()
398
+ return True
399
+
400
+ # -- signature ------------------------------------------------------------
401
+
402
+ def _compute_signature(self) -> tuple:
403
+ parts: list = []
404
+ for path, recursive in self._roots:
405
+ if not path.is_dir():
406
+ # Missing root: watch the nearest existing ancestor so its
407
+ # creation is noticed (same semantics as the inotify backend).
408
+ ancestor = _nearest_existing_ancestor(path)
409
+ if ancestor is None:
410
+ parts.append((str(path), "missing"))
411
+ continue
412
+ parts.append((str(path), "missing", self._dir_signature(ancestor, False)))
413
+ elif recursive:
414
+ parts.append((str(path), True, self._tree_signature(path)))
415
+ else:
416
+ parts.append((str(path), False, self._dir_signature(path, True)))
417
+ return tuple(parts)
418
+
419
+ def _tree_signature(self, root: Path) -> tuple:
420
+ parts: list = []
421
+ for current, dirs, files in os.walk(root):
422
+ dirs.sort()
423
+ for name in sorted(files):
424
+ file_path = Path(current) / name
425
+ try:
426
+ stat = file_path.stat()
427
+ parts.append((str(file_path), stat.st_size, stat.st_mtime_ns))
428
+ except OSError:
429
+ parts.append((str(file_path), "unreadable"))
430
+ return tuple(parts)
431
+
432
+ def _dir_signature(self, directory: Path, entries: bool) -> tuple:
433
+ parts: list = [str(directory)]
434
+ try:
435
+ stat = directory.stat()
436
+ parts.append((stat.st_size, stat.st_mtime_ns))
437
+ except OSError:
438
+ parts.append("unreadable")
439
+ return tuple(parts)
440
+ if entries:
441
+ try:
442
+ for entry in sorted(directory.iterdir()):
443
+ try:
444
+ stat = entry.stat()
445
+ parts.append((entry.name, stat.st_size, stat.st_mtime_ns))
446
+ except OSError:
447
+ parts.append((entry.name, "unreadable"))
448
+ except OSError:
449
+ parts.append("unreadable-entries")
450
+ return tuple(parts)
451
+
452
+ # -- loop -----------------------------------------------------------------
453
+
454
+ def _run(self) -> None:
455
+ while not self._stop.wait(self._poll_seconds):
456
+ now = monotonic()
457
+ try:
458
+ signature = self._compute_signature()
459
+ except Exception as error:
460
+ self.last_error = f"signature scan failed: {type(error).__name__}"
461
+ continue
462
+ if signature != self._signature:
463
+ self._signature = signature
464
+ self._note_activity(now)
465
+ self._maybe_trigger()
466
+ # Drain a pending trigger on shutdown so the last change is not lost.
467
+ self._maybe_trigger()
468
+
469
+
470
+ def create_watcher(
471
+ roots: list[tuple[Path, bool]],
472
+ on_change: Callable[[], None],
473
+ *,
474
+ debounce_seconds: float = 1.0,
475
+ min_spacing_seconds: float = 5.0,
476
+ poll_seconds: float = 5.0,
477
+ **kwargs,
478
+ ) -> BaseWatcher:
479
+ """Pick the best backend for the current platform."""
480
+ if sys.platform.startswith("linux"):
481
+ return SourceWatcher(
482
+ roots, on_change,
483
+ debounce_seconds=debounce_seconds,
484
+ min_spacing_seconds=min_spacing_seconds,
485
+ **kwargs,
486
+ )
487
+ return PollingWatcher(
488
+ roots, on_change,
489
+ debounce_seconds=debounce_seconds,
490
+ min_spacing_seconds=min_spacing_seconds,
491
+ poll_seconds=poll_seconds,
492
+ )
299
493
 
300
494
 
301
495
  def _nearest_existing_ancestor(path: Path) -> Path | None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: session-trail
3
- Version: 0.2.3
3
+ Version: 0.3.1
4
4
  Summary: Local cross-agent work timeline: discover, browse and resume coding-agent sessions on your machine
5
5
  Author: fwt11
6
6
  License-Expression: MIT
@@ -13,6 +13,8 @@ Classifier: Environment :: Web Environment
13
13
  Classifier: Environment :: X11 Applications
14
14
  Classifier: Intended Audience :: Developers
15
15
  Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
16
18
  Classifier: Programming Language :: Python :: 3
17
19
  Classifier: Programming Language :: Python :: 3.10
18
20
  Classifier: Programming Language :: Python :: 3.11
@@ -44,6 +46,17 @@ Dynamic: license-file
44
46
  - **隐私优先**:本地索引只存元数据(标题、目录、时间、统计),不存任何消息正文、代码、diff 或凭据;HTTP 服务只绑定 127.0.0.1,每次启动生成高熵访问令牌
45
47
  - **诚实降级**:没有原生标题就显示"未命名会话",恢复路径没验证过就不显示恢复按钮,绝不伪造
46
48
 
49
+ ## 平台支持
50
+
51
+ | 能力 | Linux | Windows | macOS |
52
+ | --- | --- | --- | --- |
53
+ | scan / list / serve 网页控制台 | ✅ | ✅ | ✅ |
54
+ | 实时变更监控 | inotify 秒级 | 轮询 ≈5s | 轮询 ≈5s |
55
+ | 系统托盘 + 内嵌窗口 | ✅(原生 SNI + WebKit2GTK) | 规划中 | 规划中 |
56
+ | 回到原会话(已验证工具) | ✅ | 取决于该 Agent 的 CLI 是否存在 | 同左 |
57
+
58
+ 数据目录路径:开源工具的 Windows/macOS 路径已按其源码/官方文档确认——Codex(`dirs::home_dir()/.codex`,全平台同布局)、Claude Code(`%USERPROFILE%/.claude`)、OpenCode(Windows = `%LOCALAPPDATA%/opencode`,macOS 同 Linux)、Pi(`~/.pi/agent` 全平台一致);三者并尊重各自的官方覆盖变量(`CODEX_HOME` / `CLAUDE_CONFIG_DIR` / `OPENCODE_DATA`)。闭源工具(Kimi/CodeBuddy/MiniMax/ZCode/DeepSeek)其他平台的目录未验证,未发现数据源的适配器会诚实显示"未发现"。
59
+
47
60
  ## 支持的 Agent
48
61
 
49
62
  | Agent | 时间线 | 回到原会话 | 说明 |
File without changes
File without changes
File without changes