sessionpulse 0.2.0__tar.gz → 0.2.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 (36) hide show
  1. {sessionpulse-0.2.0/src/sessionpulse.egg-info → sessionpulse-0.2.1}/PKG-INFO +1 -1
  2. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/pyproject.toml +1 -1
  3. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/followups.py +115 -14
  4. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/hook.py +22 -0
  5. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/reader.py +48 -22
  6. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/server.py +2 -0
  7. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/dashboard.html +59 -12
  8. {sessionpulse-0.2.0 → sessionpulse-0.2.1/src/sessionpulse.egg-info}/PKG-INFO +1 -1
  9. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/tests/test_sessionpulse.py +51 -2
  10. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/LICENSE +0 -0
  11. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/README.md +0 -0
  12. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/setup.cfg +0 -0
  13. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/__init__.py +0 -0
  14. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/__main__.py +0 -0
  15. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/cli.py +0 -0
  16. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/config.py +0 -0
  17. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/icons/sessionpulse-busy.svg +0 -0
  18. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/icons/sessionpulse-idle.svg +0 -0
  19. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/icons/sessionpulse-none.svg +0 -0
  20. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/install.py +0 -0
  21. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/learn.py +0 -0
  22. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/favicon.svg +0 -0
  23. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-idle-animated.svg +0 -0
  24. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-idle-static.svg +0 -0
  25. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-none-animated.svg +0 -0
  26. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-none-static.svg +0 -0
  27. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-working-animated.svg +0 -0
  28. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/static/brand/session-pulse-working-static.svg +0 -0
  29. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/status.py +0 -0
  30. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/todos.py +0 -0
  31. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse/tray.py +0 -0
  32. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse.egg-info/SOURCES.txt +0 -0
  33. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse.egg-info/dependency_links.txt +0 -0
  34. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse.egg-info/entry_points.txt +0 -0
  35. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse.egg-info/requires.txt +0 -0
  36. {sessionpulse-0.2.0 → sessionpulse-0.2.1}/src/sessionpulse.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessionpulse
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A quiet instrument panel for Claude Code: live sessions, usage, and a to-do board that fills itself from your sessions. Local only.
5
5
  Author: Vijay Shukla
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sessionpulse"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "A quiet instrument panel for Claude Code: live sessions, usage, and a to-do board that fills itself from your sessions. Local only."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -33,6 +33,8 @@ MAX_ITEMS = 12
33
33
  MAX_OPEN = 150 # open to-dos shown to the model per project
34
34
  MAX_RELATED = 60 # and from the projects linked to it
35
35
  NOT_USEFUL = 10 # recent "not useful" dismissals shown as examples of noise
36
+ MAX_WINDOWS = 4 # a long first read is split into windows of DIGEST_CHARS; beyond this many, the middle is left out
37
+ BRIEF_ITEMS = 5 # points per list in a session brief
36
38
  QUOTE_CHARS = 160
37
39
  EXCERPT_CHARS = 4000 # per turn, in the dashboard's transcript excerpt
38
40
  TIMEOUT = 180
@@ -73,6 +75,11 @@ in different words: if an open to-do already covers the work, leave it out. Do n
73
75
  under "dismissed". Items listed under "not useful" were dismissed by the user as noise: \
74
76
  don't add items of that sort.
75
77
 
78
+ Also return `brief`, a short summary of the whole session so far for someone coming back to it: `goal` (one \
79
+ sentence), `done` and `open` (up to 5 short points each), `blocked` (what it is waiting on, or empty) and `next` (the \
80
+ next step, or empty). When you are given the earlier summary and only the newer turns, update that summary with \
81
+ them, and list only follow-ups that the newer turns show.
82
+
76
83
  Turns are numbered (### #12 USER ...). For every item, set `quote` to a short passage copied exactly, word for \
77
84
  word, from one turn (max 160 characters) that shows the item is still open, preferring the user's own words, and \
78
85
  `ref` to that turn's number. Give each `resolved` to-do the same way: its id, and a `quote` and `ref` showing it \
@@ -91,8 +98,14 @@ SCHEMA = {
91
98
  "type": "object",
92
99
  "properties": {"id": {"type": "string"}, "quote": {"type": "string"}, "ref": {"type": "integer"}},
93
100
  "required": ["id"]}},
101
+ "brief": {"type": "object", "properties": {
102
+ "goal": {"type": "string"},
103
+ "done": {"type": "array", "maxItems": BRIEF_ITEMS, "items": {"type": "string"}},
104
+ "open": {"type": "array", "maxItems": BRIEF_ITEMS, "items": {"type": "string"}},
105
+ "blocked": {"type": "string"}, "next": {"type": "string"}},
106
+ "required": ["goal", "done", "open", "blocked", "next"]},
94
107
  },
95
- "required": ["items", "resolved"],
108
+ "required": ["items", "resolved", "brief"],
96
109
  }
97
110
 
98
111
  _state_lock = threading.Lock()
@@ -126,16 +139,22 @@ def conversation(path):
126
139
  return out
127
140
 
128
141
 
142
+ def _render(n, t):
143
+ """One turn as the model reads it: numbered, long ones cut in the middle. Returns (text, body)."""
144
+ body, cap = t["text"], USER_CHARS if t["role"] == "user" else CLAUDE_CHARS
145
+ if len(body) > cap:
146
+ body = body[:cap // 2] + "\n[…]\n" + body[-cap // 2:]
147
+ when = str(t["at"] or "")[:16].replace("T", " ")
148
+ return f"### #{n} {'USER' if t['role'] == 'user' else 'CLAUDE'} {when}\n{body}", body
149
+
150
+
129
151
  def digest(path, project="", limit=DIGEST_CHARS, turns=None):
130
152
  """The conversation as the model reads it, turns numbered #1.., trimmed to fit.
131
153
  If `turns` is a list, each numbered turn is added to it (with the text the model saw)."""
132
154
  parts = []
133
155
  for n, t in enumerate(conversation(path), 1):
134
- body, cap = t["text"], USER_CHARS if t["role"] == "user" else CLAUDE_CHARS
135
- if len(body) > cap:
136
- body = body[:cap // 2] + "\n[…]\n" + body[-cap // 2:]
137
- when = str(t["at"] or "")[:16].replace("T", " ")
138
- parts.append(f"### #{n} {'USER' if t['role'] == 'user' else 'CLAUDE'} {when}\n{body}")
156
+ part, body = _render(n, t)
157
+ parts.append(part)
139
158
  if turns is not None:
140
159
  turns.append({**t, "n": n, "text": body})
141
160
  text = "\n\n".join(parts)
@@ -145,6 +164,59 @@ def digest(path, project="", limit=DIGEST_CHARS, turns=None):
145
164
  return f"Project: {project}\n\n{text}"
146
165
 
147
166
 
167
+ def windows(conv, start=0, limit=DIGEST_CHARS, most=MAX_WINDOWS):
168
+ """The turns from `start` on, numbered, in windows that each fit `limit`:
169
+ [[{**turn, "n", "text", "part"}]]. With more than `most`, the first and the newest are kept."""
170
+ out, size = [[]], 0
171
+ for n, t in enumerate(conv[start:], start + 1):
172
+ part, body = _render(n, t)
173
+ if out[-1] and size + len(part) > limit:
174
+ out.append([])
175
+ size = 0
176
+ out[-1].append({**t, "n": n, "text": body, "part": part})
177
+ size += len(part) + 2
178
+ out = [w for w in out if w]
179
+ if len(out) <= most:
180
+ return out
181
+ return [out[-1]] if most == 1 else [out[0]] + out[-(most - 1):]
182
+
183
+
184
+ # ---------- session briefs ----------
185
+ def _briefs_path(cfg):
186
+ return cfg.data / "briefs.json"
187
+
188
+
189
+ def load_briefs(cfg):
190
+ """Per session: {"brief": {...}, "turns": how many were read, "at", "model", "project"}."""
191
+ try:
192
+ b = json.loads(_briefs_path(cfg).read_text())
193
+ return b if isinstance(b, dict) else {}
194
+ except (OSError, ValueError):
195
+ return {}
196
+
197
+
198
+ def _clean_brief(b):
199
+ if not isinstance(b, dict):
200
+ return None
201
+ text = lambda v, n=300: todos.redact(" ".join(str(v or "").split()))[:n] # noqa: E731
202
+ points = lambda v: [text(x, 200) for x in v if isinstance(x, str) and x.strip()][:BRIEF_ITEMS] \
203
+ if isinstance(v, list) else [] # noqa: E731
204
+ out = {"goal": text(b.get("goal")), "done": points(b.get("done")), "open": points(b.get("open")),
205
+ "blocked": text(b.get("blocked")), "next": text(b.get("next"))}
206
+ return out if any(out.values()) else None
207
+
208
+
209
+ def _save_brief(cfg, sess, brief, turns):
210
+ with _state_lock:
211
+ b = load_briefs(cfg)
212
+ b[sess["id"]] = {"brief": brief, "turns": turns, "project": sess.get("project"), "model": cfg.followups_model,
213
+ "at": datetime.now().astimezone().isoformat(timespec="seconds")}
214
+ cfg.data.mkdir(parents=True, exist_ok=True)
215
+ tmp = _briefs_path(cfg).with_suffix(".tmp")
216
+ tmp.write_text(json.dumps(b, indent=1))
217
+ os.replace(tmp, _briefs_path(cfg))
218
+
219
+
148
220
  def _plain(text):
149
221
  """Text reduced for quote matching: lower case, straight quotes, single spaces."""
150
222
  text = str(text or "").lower().translate(str.maketrans("‘’“”–—", "''\"\"--"))
@@ -352,8 +424,27 @@ def checked(out, shown):
352
424
  return items[:MAX_ITEMS], resolved
353
425
 
354
426
 
355
- def process(cfg, sess, path, usage=None):
356
- """Extract follow-ups from one session and merge them into the to-do list."""
427
+ def process(cfg, sess, path, usage=None, fresh=False):
428
+ """Extract follow-ups from one session and merge them into the to-do list. Returns (added, closed).
429
+
430
+ Only the turns since the last read are sent, with the brief written then; a session read
431
+ for the first time (or with `fresh`) is read from the start, in windows if it is long."""
432
+ conv = conversation(path)
433
+ prev = {} if fresh else load_briefs(cfg).get(sess["id"]) or {}
434
+ start = prev.get("turns") if isinstance(prev.get("turns"), int) and 0 < prev["turns"] <= len(conv) else 0
435
+ brief = prev.get("brief") if start else None
436
+ added = closed = 0
437
+ parts = windows(conv, start)
438
+ for n, window in enumerate(parts, 1):
439
+ a, c, brief = _read(cfg, sess, window, brief, usage, more=n < len(parts))
440
+ added += a
441
+ closed += c
442
+ _save_brief(cfg, sess, brief, window[-1]["n"])
443
+ return added, closed
444
+
445
+
446
+ def _read(cfg, sess, window, brief, usage, more=False):
447
+ """One model call on a window of turns (`more`: later turns follow). Returns (added, closed, brief)."""
357
448
  items = todos.load(cfg)
358
449
  project = sess.get("project") or ""
359
450
  linked = todos.related(cfg, project)
@@ -367,8 +458,17 @@ def process(cfg, sess, path, usage=None):
367
458
  gone = [d for d in todos.dismissed(cfg) if d.get("project") == project]
368
459
  dismissed = gone[-40:]
369
460
  noise = [d for d in gone if d.get("reason") == "not_useful"][-NOT_USEFUL:]
370
- turns = []
371
- prompt = digest(path, project, turns=turns)
461
+ prompt = f"Project: {project}\n\n"
462
+ if brief:
463
+ prompt += ("## Earlier in this session (your summary from then; the turns before "
464
+ f"#{window[0]['n']} are not repeated)\n{json.dumps(brief, ensure_ascii=False)}\n\n"
465
+ f"## Newer turns\n\n")
466
+ elif window[0]["n"] > 1:
467
+ prompt += f"[… turns #1 to #{window[0]['n'] - 1} left out …]\n\n"
468
+ prompt += "\n\n".join(t["part"] for t in window)
469
+ if more:
470
+ prompt += ("\n\n[… the session goes on after this; you will see the rest next. Don't list the work that is "
471
+ "simply in progress here, only what is clearly left for later …]")
372
472
  prompt += "\n\n## Open to-dos for this project\n" + (
373
473
  "\n".join(f"- [{i['id']}] {i['text']}" for i in open_) or "(none)")
374
474
  if others:
@@ -378,10 +478,11 @@ def process(cfg, sess, path, usage=None):
378
478
  "\n".join(f"- {d['text']}" for d in dismissed) or "(none)")
379
479
  if noise:
380
480
  prompt += "\n\n## Not useful (don't add things like these)\n" + "\n".join(f"- {d['text']}" for d in noise)
381
- found, resolved = checked(ask_claude(cfg, prompt, usage=usage), {i["id"] for i in open_ + others})
481
+ out = ask_claude(cfg, prompt, usage=usage)
482
+ found, resolved = checked(out, {i["id"] for i in open_ + others})
382
483
  for r in found + resolved:
383
- r["evidence"] = evidence(r, turns)
384
- return todos.merge_followups(cfg, sess, found, resolved)
484
+ r["evidence"] = evidence(r, window)
485
+ return (*todos.merge_followups(cfg, sess, found, resolved), _clean_brief(out.get("brief")) or brief)
385
486
 
386
487
 
387
488
  # ---------- one-off cleanup ----------
@@ -532,7 +633,7 @@ def _scan(cfg, limit, days, idle_minutes, session, force, log):
532
633
  return 0, 0
533
634
  use = {}
534
635
  try:
535
- a, c = process(cfg, s, s["transcript"], use)
636
+ a, c = process(cfg, s, s["transcript"], use, fresh=force)
536
637
  except NotReady as exc: # a usage limit or outage: stop the round, blame no session
537
638
  halt.set()
538
639
  errors.append(str(exc))
@@ -8,10 +8,31 @@ import os
8
8
  import socket
9
9
  import sys
10
10
  from datetime import datetime, timezone
11
+ from pathlib import Path
11
12
 
12
13
  from . import config
13
14
 
14
15
 
16
+ def _find_claude_pid():
17
+ """Walk up the process tree to find the ancestor 'claude' (node) process."""
18
+ try:
19
+ pid = os.getppid()
20
+ for _ in range(10): # at most 10 levels up
21
+ stat = Path(f"/proc/{pid}/stat").read_text()
22
+ comm = stat.split(")")[0].split("(")[-1]
23
+ if comm in ("claude", "node"):
24
+ return pid
25
+ # read ppid (field 4, 0-indexed after splitting on ") ")
26
+ fields = stat.split(") ", 1)[1].split()
27
+ ppid = int(fields[1]) # ppid is field index 1 after comm
28
+ if ppid <= 1:
29
+ break
30
+ pid = ppid
31
+ except (OSError, ValueError, IndexError):
32
+ pass
33
+ return None
34
+
35
+
15
36
  def run(stdin=sys.stdin):
16
37
  cfg = config.load()
17
38
  try:
@@ -25,6 +46,7 @@ def run(stdin=sys.stdin):
25
46
  # SessionEnd sends "reason" (clear, logout, prompt_input_exit, other);
26
47
  # SessionStart sends "source" (startup, resume, clear, compact).
27
48
  "reason": hook.get("reason") or hook.get("source"),
49
+ "pid": _find_claude_pid(),
28
50
  }
29
51
  cfg.data.mkdir(parents=True, exist_ok=True)
30
52
  with open(cfg.events_file, "a") as f:
@@ -178,29 +178,55 @@ def pid_alive(pid):
178
178
  return False
179
179
 
180
180
 
181
- def read_live(claude: Path, health):
181
+ def read_live(claude: Path, health, events=None):
182
182
  live = {}
183
183
  d = claude / "sessions"
184
- if not d.is_dir():
185
- health["warnings"].append(f"{d} not found: live sessions can't be shown "
186
- "(older Claude Code, or a changed layout).")
187
- return live
188
- for p in d.glob("*.json"):
189
- try:
190
- j = json.loads(p.read_text())
191
- except (OSError, ValueError):
192
- continue
193
- if not isinstance(j, dict) or any(k not in j for k in LIVE_KEYS):
194
- health["live_unrecognised"] += 1
195
- continue
196
- if not pid_alive(j.get("pid")):
197
- continue
198
- live[j["sessionId"]] = {
199
- "pid": j.get("pid"), "status": j.get("status"), "name": j.get("name"),
200
- "kind": j.get("kind"), "entrypoint": j.get("entrypoint"),
201
- "startedAt": j.get("startedAt"),
202
- "updatedAt": j.get("statusUpdatedAt") or j.get("updatedAt"),
203
- }
184
+ if d.is_dir():
185
+ for p in d.glob("*.json"):
186
+ try:
187
+ j = json.loads(p.read_text())
188
+ except (OSError, ValueError):
189
+ continue
190
+ if not isinstance(j, dict) or any(k not in j for k in LIVE_KEYS):
191
+ health["live_unrecognised"] += 1
192
+ continue
193
+ if not pid_alive(j.get("pid")):
194
+ continue
195
+ live[j["sessionId"]] = {
196
+ "pid": j.get("pid"), "status": j.get("status"), "name": j.get("name"),
197
+ "kind": j.get("kind"), "entrypoint": j.get("entrypoint"),
198
+ "startedAt": j.get("startedAt"),
199
+ "updatedAt": j.get("statusUpdatedAt") or j.get("updatedAt"),
200
+ }
201
+ # Fallback: if sessions/ yielded nothing, infer live sessions from events.
202
+ # A session is live if its most recent event is a SessionStart (not an End)
203
+ # and the captured pid is still running.
204
+ if not live and events:
205
+ latest = {} # sid -> most recent event
206
+ for e in events:
207
+ sid = e.get("session")
208
+ ev = e.get("event")
209
+ if sid and ev in ("SessionStart", "SessionEnd"):
210
+ latest[sid] = e
211
+ for sid, e in latest.items():
212
+ if e.get("event") != "SessionStart":
213
+ continue
214
+ pid = e.get("pid")
215
+ if pid and pid_alive(pid):
216
+ # Convert ISO timestamp to epoch (float) to match sessions/*.json format
217
+ ts = e.get("ts")
218
+ epoch = None
219
+ if ts:
220
+ try:
221
+ epoch = datetime.fromisoformat(ts).timestamp()
222
+ except (ValueError, OSError):
223
+ pass
224
+ live[sid] = {
225
+ "pid": pid, "status": "running", "name": None,
226
+ "kind": None, "entrypoint": None,
227
+ "startedAt": epoch,
228
+ "updatedAt": epoch,
229
+ }
204
230
  return live
205
231
 
206
232
 
@@ -306,8 +332,8 @@ def snapshot(cfg: Config):
306
332
  f"was tested with ({'.'.join(map(str, TESTED_CLI))}). "
307
333
  "Check the numbers look right.")
308
334
 
309
- live = read_live(claude, health)
310
335
  events = read_events(cfg.events_file)
336
+ live = read_live(claude, health, events)
311
337
  exits = {e.get("session"): e for e in events if e.get("event") == "SessionEnd"}
312
338
  for sid, s in sessions.items():
313
339
  if sid in live:
@@ -85,6 +85,8 @@ def make_handler(cfg: config.Config, tok: str):
85
85
  data = reader.snapshot(cfg)
86
86
  data["followups"] = {"enabled": cfg.followups, **followups.status,
87
87
  "week": followups.usage_totals(cfg, 7), "failing": len(followups.failing(cfg))}
88
+ ids = {s["id"] for s in data["sessions"]}
89
+ data["briefs"] = {k: v for k, v in followups.load_briefs(cfg).items() if k in ids}
88
90
  return self.send(200, json.dumps(data).encode(), "application/json")
89
91
  if url.path == "/api/excerpt":
90
92
  return self.excerpt(parse_qs(url.query))
@@ -74,6 +74,9 @@ h2 { font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacin
74
74
  .live .meta b { font-weight: 500; color: var(--text-muted); }
75
75
  .live .prompt { margin-top: 8px; font-size: 12px; color: var(--text-secondary); display: -webkit-box;
76
76
  -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
77
+ .live .next { margin-top: 8px; font-size: 12px; display: -webkit-box; -webkit-line-clamp: 3;
78
+ -webkit-box-orient: vertical; overflow: hidden; }
79
+ .live .next b { font-weight: 500; color: var(--text-muted); margin-right: 4px; }
77
80
  .pill { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 600;
78
81
  padding: 2px 8px; border-radius: 999px; white-space: nowrap; }
79
82
  .pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
@@ -112,6 +115,14 @@ td.proj { white-space: nowrap; max-width: 220px; overflow: hidden; text-overflow
112
115
  .detail dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 4px 0; }
113
116
  .detail dt { color: var(--text-muted); }
114
117
  .detail dd { margin: 0; word-break: break-word; }
118
+ .detail dl { position: sticky; left: 8px; max-width: min(100%, calc(100vw - 100px)); }
119
+ .detail dt.sep { grid-column: 1 / -1; border-top: 1px solid var(--border); margin: 6px 0 2px; }
120
+ @media (max-width: 640px) {
121
+ #history tr > :nth-child(3), #history tr > :nth-child(7), #history tr > :nth-child(8), #history tr > :nth-child(9) { display: none; }
122
+ }
123
+ .detail dd ul { margin: 0; padding-left: 16px; }
124
+ .detail .fu li { list-style: none; margin-left: -16px; }
125
+ .detail .fu .st { color: var(--text-muted); margin-left: 6px; }
115
126
  code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--surface-2);
116
127
  padding: 1px 5px; border-radius: 4px; border: 1px solid var(--border); }
117
128
  .copy, .why-btn { font: inherit; font-size: 11px; border: 1px solid var(--border); background: var(--surface-1);
@@ -142,7 +153,7 @@ input[type=search] { flex: 1; min-width: 200px; }
142
153
  .pgroup > summary::before { content: "▸"; color: var(--text-muted); font-size: 11px; width: 10px; }
143
154
  .pgroup[open] > summary::before { content: "▾"; }
144
155
  .pgroup > summary .n { font-weight: 400; color: var(--text-muted); font-size: 12px; }
145
- .pgroup > summary .kinds { display: flex; gap: 4px; margin-left: 4px; }
156
+ .pgroup > summary .kinds { display: flex; flex-wrap: wrap; gap: 4px; margin-left: 4px; }
146
157
  .pgroup > summary .kinds .kindtag { margin: 0; }
147
158
  .pgroup > ul { list-style: none; margin: 0 0 6px; padding: 0 0 0 16px; }
148
159
  .dismiss-all { margin-left: auto; font: inherit; font-size: 11px; font-weight: 400; border: 1px solid var(--border);
@@ -178,7 +189,7 @@ input[type=search] { flex: 1; min-width: 200px; }
178
189
  border-radius: 5px; padding: 1px 6px; margin-right: 6px; vertical-align: 1px; white-space: nowrap; }
179
190
  /* One color per category, shared by tags, dots, board columns and card stripes. */
180
191
  .k-decision { --c: var(--crit); } .k-external { --c: var(--busy); } .k-waiting { --c: var(--series-7); }
181
- .k-checklist { --c: var(--accent); } .k-task { --c: var(--series-5); } .k-mine, .k-todo { --c: var(--other); }
192
+ .k-checklist { --c: var(--accent); } .k-task { --c: var(--series-3); } .k-mine, .k-todo { --c: var(--other); }
182
193
  .k-doing { --c: var(--accent); } .k-done { --c: var(--good); }
183
194
  .k-hold { --c: var(--series-4); } .k-archived { --c: var(--other); }
184
195
  .kindtag { color: color-mix(in srgb, var(--c) 78%, var(--text-primary));
@@ -249,6 +260,10 @@ a:hover { text-decoration: underline; }
249
260
  .card2 .copy, .card2 .why-btn, .card2 select { white-space: nowrap; margin-left: 0; }
250
261
  .card2 select { font: inherit; font-size: 11px; padding: 1px 4px; border-radius: 5px; border: 1px solid var(--border);
251
262
  background: var(--surface-1); color: var(--text-secondary); }
263
+ .card2 { position: relative; }
264
+ .card2 > .x { position: absolute; top: 8px; right: 6px; }
265
+ .card2 > .t { padding-right: 16px; }
266
+ .card2 > .dismiss-why { margin-top: 7px; }
252
267
  .card2 .x { border: 0; background: none; color: var(--text-muted); cursor: pointer; font-size: 15px; line-height: 1; padding: 0 2px; }
253
268
  .card2 .x:hover { color: var(--crit); }
254
269
  .col-empty { font-size: 12px; color: var(--text-muted); padding: 10px 4px; text-align: center; }
@@ -257,7 +272,8 @@ a:hover { text-decoration: underline; }
257
272
  .why-box { background: var(--surface-1); color: var(--text-primary); width: min(560px, 100%); height: 100%; overflow-y: auto;
258
273
  padding: 18px 20px 28px; border-left: 1px solid var(--border); box-shadow: -8px 0 24px rgb(0 0 0 / .15); }
259
274
  .why-head { display: flex; gap: 10px; align-items: flex-start; }
260
- .why-head h2 { font-size: 16px; margin: 0; flex: 1; overflow-wrap: anywhere; }
275
+ .why-head h2 { font-size: 16px; margin: 0; flex: 1; overflow-wrap: anywhere; text-transform: none; letter-spacing: 0; line-height: 1.35; }
276
+ .why code, .detail code { word-break: break-all; }
261
277
  .why-close { border: 0; background: none; font-size: 22px; cursor: pointer; color: var(--text-muted); line-height: 1; padding: 0 2px; }
262
278
  .why h3 { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--text-muted); margin: 18px 0 6px; }
263
279
  .why p { margin: 6px 0; font-size: 13px; overflow-wrap: anywhere; }
@@ -268,6 +284,7 @@ a:hover { text-decoration: underline; }
268
284
  .why-quote { margin: 8px 0; padding: 8px 12px; border-left: 3px solid var(--accent); background: var(--surface-2); border-radius: 0 6px 6px 0; }
269
285
  .why-quote blockquote { margin: 0; font-size: 14px; overflow-wrap: anywhere; }
270
286
  .why-quote figcaption { font-size: 11px; color: var(--text-muted); margin-top: 4px; }
287
+ .todo .dismiss-why { grid-column: 2 / -1; }
271
288
  .dismiss-why { display: inline-flex; flex-wrap: wrap; gap: 4px; align-items: center; font-size: 11px; color: var(--text-muted); }
272
289
  .dismiss-why button { font: inherit; font-size: 11px; border: 1px solid var(--border); background: var(--surface-1);
273
290
  color: var(--text-secondary); border-radius: 5px; padding: 1px 6px; cursor: pointer; }
@@ -511,7 +528,7 @@ function renderLive() {
511
528
  <b>Usage</b><span>${fmtN(s.usage.output||0)} out · ${fmtN(tokTotal(s.usage))} total · ${s.prompts} prompts</span>
512
529
  <b>Model</b><span>${esc(shortModel(s.model))} · pid ${L.pid}${L.entrypoint ? " · "+esc(L.entrypoint) : ""}</span>
513
530
  </div>
514
- ${s.last_prompt ? `<div class="prompt">“${esc(s.last_prompt)}”</div>` : ""}
531
+ ${s.last_prompt ? `<div class="prompt">“${esc(s.last_prompt)}”</div>` : ""}${liveBrief(s)}
515
532
  </div>`;
516
533
  }).join("");
517
534
  }
@@ -636,6 +653,35 @@ function renderEvents() {
636
653
  }).join("");
637
654
  }
638
655
 
656
+ // ---------- session briefs ----------
657
+ // What a session is about, as of its last follow-up read, and the follow-ups it left or closed.
658
+ const briefOf = s => DATA.briefs?.[s.id];
659
+ const leftBy = s => (DATA.todos || []).filter(i => i.session === s.id && i.status !== "archived");
660
+ function liveBrief(s) {
661
+ const B = briefOf(s), b = B?.brief, n = leftBy(s).filter(isOpen).length;
662
+ if (!b?.next && !n) return "";
663
+ const as = B?.at ? ` title="As of ${esc(fmtD(B.at))}"` : "";
664
+ return `<div class="next"${as}>${b?.next ? `<b>Next</b>${esc(b.next)}` : ""}${n ? `${b?.next ? " · " : ""}<b>${n} follow-up${n > 1 ? "s" : ""} open</b>` : ""}</div>`;
665
+ }
666
+ function briefRows(s) {
667
+ const B = briefOf(s), b = B?.brief || {};
668
+ const list = xs => `<ul>${xs.map(x => `<li>${esc(x)}</li>`).join("")}</ul>`;
669
+ const state = i => i.done_at ? (i.closed_by === s.id ? "closed here" : "done") : i.status === "hold" ? "on hold" : i.doing ? "doing" : "";
670
+ const fu = (i, tag = state(i)) => `<li>${i.kind ? `<span class="kindtag k-${esc(i.kind)}">${esc(KIND[i.kind] || i.kind)}</span>` : ""}${esc(i.text)}${tag ? `<span class="st">${tag}</span>` : ""}<button class="why-btn" data-why="${esc(i.id)}" title="${i.closed_by && i.done_at ? "What closed it" : "Where this came from"}">Why?</button></li>`;
671
+ const left = leftBy(s).sort((x, y) => isOpen(y) - isOpen(x));
672
+ const closed = (DATA.todos || []).filter(i => i.closed_by === s.id && i.done_at && i.session !== s.id);
673
+ let h = "";
674
+ if (b.goal) h += `<dt>Goal</dt><dd>${esc(b.goal)}</dd>`;
675
+ if (b.done?.length) h += `<dt>Done</dt><dd>${list(b.done)}</dd>`;
676
+ if (b.open?.length) h += `<dt>Open</dt><dd>${list(b.open)}</dd>`;
677
+ if (b.blocked) h += `<dt>Blocked on</dt><dd>${esc(b.blocked)}</dd>`;
678
+ if (b.next) h += `<dt>Next</dt><dd>${esc(b.next)}</dd>`;
679
+ if (B?.at) h += `<dt>Summary of</dt><dd>${B.turns || "?"} turns, read ${esc(fmtD(B.at))}</dd>`;
680
+ if (left.length) h += `<dt>Follow-ups</dt><dd><ul class="fu">${left.map(i => fu(i)).join("")}</ul></dd>`;
681
+ if (closed.length) h += `<dt>Closed here</dt><dd><ul class="fu">${closed.map(i => fu(i, "")).join("")}</ul></dd>`;
682
+ return h;
683
+ }
684
+
639
685
  // ---------- history ----------
640
686
  const STATE_LABEL = {busy: "Working", idle: "Idle", running: "Running", exited: "Exited", closed: "Closed"};
641
687
  function renderHistory(sessions) {
@@ -644,7 +690,7 @@ function renderHistory(sessions) {
644
690
  if (sf === "live" && !isLive(s)) return false;
645
691
  if (sf && sf !== "live" && s.state !== sf) return false;
646
692
  if (!q) return true;
647
- return [s.project, s.first_prompt, s.last_prompt, s.id, s.title, s.cwd].some(v => (v||"").toLowerCase().includes(q));
693
+ return [s.project, s.first_prompt, s.last_prompt, s.id, s.title, s.cwd, briefOf(s)?.brief?.goal].some(v => (v||"").toLowerCase().includes(q));
648
694
  });
649
695
  const val = {start: s => s.start||"", end: s => s.end||"", project: s => s.project, hours: s => s.hours||0,
650
696
  prompts: s => s.prompts||0, out: s => s.usage.output||0, total: s => tokTotal(s.usage), state: s => s.state};
@@ -665,9 +711,10 @@ function renderHistory(sessions) {
665
711
  const u = s.usage, exit = s.state === "exited"
666
712
  ? `${esc(REASONS[s.exit_reason] || s.exit_reason)} at ${fmtD(s.exit_at)}`
667
713
  : s.state === "closed" ? "No exit event recorded (closed before the exit hook existed, or the terminal was killed)" : "Still running";
668
- html += `<tr class="detail"><td colspan="9"><dl>
669
- <dt>Session</dt><dd><code>${s.id}</code></dd>
714
+ const brief = briefRows(s);
715
+ html += `<tr class="detail"><td colspan="9"><dl>${brief}${brief ? `<dt class="sep" aria-hidden="true"></dt>` : ""}
670
716
  <dt>Resume</dt><dd><code>cd ${esc(s.cwd)} &amp;&amp; claude --resume ${s.id}</code><button class="copy" data-copy="cd ${esc(s.cwd)} && claude --resume ${s.id}">Copy</button></dd>
717
+ <dt>Session</dt><dd><code>${s.id}</code></dd>
671
718
  <dt>Directory</dt><dd>${esc(s.cwd)}</dd>
672
719
  <dt>Exit</dt><dd>${exit}</dd>
673
720
  <dt>Model</dt><dd>${esc(shortModel(s.model))}${s.version ? " · Claude Code " + esc(s.version) : ""}</dd>
@@ -764,7 +811,7 @@ function renderTodos() {
764
811
  const kinds = {}; g.forEach(i => { if (i.kind) kinds[i.kind] = (kinds[i.kind]||0) + 1; });
765
812
  return `<li><details class="pgroup" data-p="${esc(p)}" ${isOpen ? "open" : ""}><summary>${esc(p || "No project")}
766
813
  <span class="n">${g.length} · ${esc(ago(Date.parse(newest(g))))}</span>
767
- <span class="kinds">${Object.entries(kinds).map(([k, n]) => `<span class="kindtag k-${esc(k)}" title="${esc(KIND[k] || k)}">${n}</span>`).join("")}</span>
814
+ <span class="kinds">${Object.entries(kinds).map(([k, n]) => `<span class="kindtag k-${esc(k)}">${n} ${esc(KIND[k] || k)}</span>`).join("")}</span>
768
815
  <button class="dismiss-all" data-ids="${esc(g.map(i => i.id).join(","))}" title="Remove every open item in this group">Dismiss all</button></summary>
769
816
  <ul>${g.slice().sort((a, b) => (b.session_at || b.created).localeCompare(a.session_at || a.created)).map(i => todoRow(i, false, true)).join("")}</ul></details></li>`;
770
817
  }).join("")
@@ -866,16 +913,16 @@ function moveOp(i, col) {
866
913
  }
867
914
  const card = i => {
868
915
  const born = i.session_at || i.created, cols = COLS[BY], here = colOf(i), parked = PARKED.includes(here);
916
+ const asking = i.source === "session" && DISMISSING === i.id;
869
917
  return `<div class="card2 k-${esc(i.kind || "mine")}${i.doing && here !== "done" && !parked ? " doing" : ""}${i.done_at ? " done" : ""}${parked ? " parked" : ""}" draggable="true" data-id="${esc(i.id)}">
870
- <div class="t">${(BY === "status" || parked) && i.kind ? `<span class="kindtag k-${esc(i.kind)}">${esc(KIND[i.kind])}</span>` : ""}${esc(i.text)}</div>
918
+ ${asking ? "" : delBtn(i)}<div class="t">${(BY === "status" || parked) && i.kind ? `<span class="kindtag k-${esc(i.kind)}">${esc(KIND[i.kind])}</span>` : ""}${esc(i.text)}</div>
871
919
  ${i.detail ? `<div class="d" title="Click to expand">${esc(i.detail)}</div>` : ""}${PARKED.includes(colOf(i)) ? "" : dupNote(i)}
872
920
  <div class="meta">${i.doing && !i.done_at && !parked && BY === "kind" ? `<span class="doing-pill">Doing</span>` : ""}${i.project ? `<span class="tag" title="${esc(i.project)}">${esc(i.project.split("/").pop())}</span>` : ""}
873
921
  <span title="${i.done_at ? "Done " + esc(fmtD(i.done_at)) : (i.session_at ? "Discussed " : "Added ") + esc(fmtD(born))}">${i.done_at ? "done " + ago(Date.parse(i.done_at)) : ago(Date.parse(born))}</span>
874
922
  ${i.closed_by && i.done_at ? `<span title="A later session showed this was done">· auto</span>` : ""}
875
923
  <span class="acts">${i.source === "session" && i.session ? `<button class="why-btn" data-why="${esc(i.id)}" title="${i.closed_by && i.done_at ? "What closed it" : "Where this came from"}">Why?</button>` : ""}${i.session && !i.done_at && !parked ? `<button class="copy" data-copy="cd ${esc(i.cwd || "")} && claude --resume ${esc(i.session)}" title="Copy the command that reopens the session this came from">Resume</button>` : ""}
876
- <select data-move="${esc(i.id)}" aria-label="Move to"><option value="">Move…</option>${cols.filter(c => c[0] !== here).map(c => `<option value="${c[0]}">${c[1]}</option>`).join("")}</select>
877
- ${delBtn(i)}</span>
878
- </div></div>`;
924
+ <select data-move="${esc(i.id)}" aria-label="Move to"><option value="">Move…</option>${cols.filter(c => c[0] !== here).map(c => `<option value="${c[0]}">${c[1]}</option>`).join("")}</select></span>
925
+ </div>${asking ? delBtn(i) : ""}</div>`;
879
926
  };
880
927
 
881
928
  function renderBoard() {
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessionpulse
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A quiet instrument panel for Claude Code: live sessions, usage, and a to-do board that fills itself from your sessions. Local only.
5
5
  Author: Vijay Shukla
6
6
  License-Expression: MIT
@@ -288,6 +288,15 @@ class ServerTests(Fixture):
288
288
  self.assertEqual(self.get("/api/export?format=exe", cookie)[0], 400)
289
289
  self.assertEqual(self.get("/api/export")[0], 403)
290
290
 
291
+ def test_data_carries_briefs_of_known_sessions(self):
292
+ brief = {"goal": "Ship the recipe site", "done": [], "open": [], "blocked": "", "next": "Deploy"}
293
+ followups._save_brief(self.cfg, {"id": SID, "project": "p"}, brief, 4)
294
+ followups._save_brief(self.cfg, {"id": "gone", "project": "p"}, brief, 2)
295
+ cookie = self.get(f"/?token={config.token(self.cfg)}")[1]["Set-Cookie"].split(";")[0]
296
+ briefs = json.loads(self.get("/api/data", {"Cookie": cookie})[2])["briefs"]
297
+ self.assertEqual(list(briefs), [SID])
298
+ self.assertEqual((briefs[SID]["brief"]["next"], briefs[SID]["turns"]), ("Deploy", 4))
299
+
291
300
  def test_excerpt_shows_turns_around_one(self):
292
301
  rows = [user(self.t0, f"prompt {n}") | {"uuid": f"u{n}"} for n in range(6)]
293
302
  rows[3]["message"]["content"] = "my DB_PASSWORD=hunter2 is set"
@@ -624,9 +633,11 @@ if mode == "across":
624
633
  if mode == "junk":
625
634
  items = [5, "text", {"text": ""}, {"text": ["x"]}, {"kind": "task"}, {"text": "Call the bank", "detail": 7}]
626
635
  resolved = resolved + ["not-shown", 3, None, os.environ.get("FAKE_EXTRA_RESOLVED")]
636
+ brief = {"goal": "Draft the vendor message", "done": ["drafted it"], "open": ["ask the vendor"],
637
+ "blocked": "", "next": "send it"}
627
638
  print(json.dumps({"is_error": False, "total_cost_usd": 0.0025, "duration_ms": 1500,
628
639
  "usage": {"input_tokens": 900, "output_tokens": 60, "cache_read_input_tokens": 100},
629
- "structured_output": {"items": items, "resolved": resolved}}))
640
+ "structured_output": {"items": items, "resolved": resolved, "brief": brief}}))
630
641
  """
631
642
 
632
643
 
@@ -907,6 +918,42 @@ class FollowupTests(Fixture):
907
918
  self.assertEqual(items[0]["detail"], "Test account only. Then: Send a test reminder to yourself")
908
919
  self.assertEqual([i["text"] for i in items], ["Get the SMTP login from IT", "Renew the domain"])
909
920
 
921
+ def test_grown_session_sends_only_new_turns_with_the_brief(self):
922
+ old = datetime.now().astimezone() - timedelta(hours=2)
923
+ first = [user(old, "draft the vendor message"), assistant(old, "m1", 5),
924
+ entry(old, "assistant", message={"id": "m2", "role": "assistant", "model": "claude-test-1",
925
+ "content": [{"type": "text", "text": "Still open: ask the vendor."}]})]
926
+ followups.scan(self.cfg)
927
+ b = followups.load_briefs(self.cfg)[SID]
928
+ self.assertEqual((b["turns"], b["brief"]["next"]), (3, "send it"))
929
+ self.write(first + [assistant(old, "m3", 5, tool=True)]) # only tool use: nothing new to read
930
+ self.assertEqual(followups.scan(self.cfg)[0], 1)
931
+ self.assertEqual(len(self.calls()), 1)
932
+ self.write(first + [user(old, "the vendor replied, now book the call")])
933
+ followups.scan(self.cfg)
934
+ prompt = self.calls()[-1]["prompt"]
935
+ self.assertIn("## Earlier in this session", prompt)
936
+ self.assertIn('"next": "send it"', prompt)
937
+ self.assertIn("### #4 USER", prompt)
938
+ self.assertNotIn("draft the vendor message", prompt)
939
+ self.assertEqual(followups.load_briefs(self.cfg)[SID]["turns"], 4)
940
+ followups.scan(self.cfg, force=True) # --again: from the start
941
+ self.assertIn("draft the vendor message", self.calls()[-1]["prompt"])
942
+ self.assertNotIn("## Earlier in this session", self.calls()[-1]["prompt"])
943
+
944
+ def test_long_first_read_goes_in_windows(self):
945
+ conv = [{"uuid": str(n), "at": None, "role": "user", "text": f"turn {n} " + "x" * 900} for n in range(40)]
946
+ w = followups.windows(conv, limit=5000)
947
+ self.assertEqual([t["n"] for t in w[0]][:2], [1, 2])
948
+ self.assertTrue(all(sum(len(t["part"]) for t in x) <= 5000 for x in w))
949
+ self.assertEqual(w[-1][-1]["n"], 40)
950
+ capped = followups.windows(conv, limit=5000, most=3)
951
+ self.assertEqual(len(capped), 3)
952
+ self.assertEqual((capped[0][0]["n"], capped[-1][-1]["n"]), (1, 40))
953
+ self.assertEqual([w[0]["n"] for w in followups.windows(conv, limit=5000, most=1)], [capped[-1][0]["n"]])
954
+ self.assertEqual(followups.windows(conv, start=40), [])
955
+ self.assertEqual(followups.windows(conv, start=38)[0][0]["n"], 39)
956
+
910
957
  def test_checked_keeps_only_shown_ids(self):
911
958
  items, resolved = followups.checked({"items": "nonsense", "resolved": ["a", "b", "a", 1]}, {"a"})
912
959
  self.assertEqual((items, resolved), ([], [{"id": "a"}]))
@@ -986,7 +1033,9 @@ class EvalTests(unittest.TestCase):
986
1033
  sess, path = eval_followups.build("10", self.cases["10-long-session"], self.root)[0]
987
1034
  d = followups.digest(path, sess["project"])
988
1035
  self.assertIn("ingest lag", d)
989
- self.assertNotIn("quota", d) # trimmed away: why this item is marked hard
1036
+ self.assertNotIn("quota", d) # a one-shot digest cuts the middle (how 0.2.0 and earlier lost it)
1037
+ read = "\n".join(t["part"] for w in followups.windows(followups.conversation(path)) for t in w)
1038
+ self.assertIn("quota", read)
990
1039
 
991
1040
  def test_run_case_with_fake_claude(self):
992
1041
  fake = self.root / "fake-claude"
File without changes
File without changes
File without changes