sessions: Hermes Agent's sessions are on the Sessions page, read from its SQLite stores read-only (#569)
Hermes Agent's sessions are read from its SQLite stores — $HERMES_HOME (else ~/.hermes) and each named profile under profiles/, a selected profile home resolving back to its root — through a mode=ro connection, each session parsed in one read transaction for a consistent snapshot while Hermes writes in WAL mode. state.db itself is never modified; SQLite may create an empty state.db-wal and a state.db-shm beside a cleanly closed store, as for OpenCode's. A session's id carries a hash of its store's path, so the same id in two profiles stays two sessions. Titles, messages (respecting Hermes's active/compacted history and model-only display metadata, older schemas' missing columns read as defaults), models and token usage (session_model_usage rows, plus the session counters' main-loop residual) reach the Sessions page and Stats; the cache key includes the WAL's size and time, since usage and titles change without state.db's. Hermes usage is session-level, so it is not in Calls and the ledger is unchanged. Hermes sessions are read only: no resume, no delete, no folder or bar checkbox, with a note saying so (en and zh). Tests: hermes_test, hermes_compaction_test, hermes_display_test, hermes_usage_residual_test, hermes_visibility_test; sessions-manage.test.cjs covers the read-only view. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME, and go test -race ./internal/sessions ./internal/usage pass. (#569)
This commit is contained in:
@@ -1252,8 +1252,11 @@ const I18N = {
|
||||
// the Sessions page (sessions.js)
|
||||
"Filter sessions": "筛选会话",
|
||||
"No sessions yet": "还没有会话",
|
||||
"Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.": "这台电脑上 Claude Code、Codex、OpenCode、Pi 等的会话会按运行时所在的文件夹列在这里。",
|
||||
"Claude Code's, Codex's, Hermes's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.": "这台电脑上 Claude Code、Codex、Hermes、OpenCode、Pi 等的会话会按运行时所在的文件夹列在这里。",
|
||||
"magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.": "magpie 可以列出并继续 {agent} 的会话,但不能删除:它们没有各自独立的文件。",
|
||||
"magpie can list {agent}'s sessions, but cannot resume or delete them.": "magpie 可以列出 {agent} 的会话,但不能继续或删除。",
|
||||
"These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.": "这些 {agent} 会话为只读;magpie 可以列出,但不能继续或删除。",
|
||||
"Some {agent} sessions are read only and cannot be deleted.": "部分 {agent} 会话为只读,无法删除。",
|
||||
"Select every session shown": "选中所有显示的会话",
|
||||
"Select": "选择",
|
||||
"Delete": "删除",
|
||||
@@ -1293,7 +1296,7 @@ const I18N = {
|
||||
"at effective prices": "按生效价格",
|
||||
"just now": "刚刚",
|
||||
"No session matches.": "没有匹配的会话。",
|
||||
"No sessions yet. Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。这台电脑上 Claude Code、Codex、OpenCode 和 Pi 的会话会显示在这里,附带各自的费用和继续会话的命令。",
|
||||
"No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。这台电脑上 Claude Code、Codex、Hermes、OpenCode 和 Pi 的会话会显示在这里,附带各自的费用和继续会话的命令。",
|
||||
"Reading the agents' session files…": "正在读取 Agent 的会话文件…",
|
||||
"Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合计统计 Agent 自己文件里的全部会话;列表为按最近活动取的 {n} 个 · {dirs}",
|
||||
"90 days": "90 天",
|
||||
|
||||
@@ -159,12 +159,22 @@
|
||||
if (trashOn) { box.append(...trash()); return box; }
|
||||
if (!data.agents.length) {
|
||||
const e = el("div", "empty-state");
|
||||
e.append(el("b", "", t("No sessions yet")), el("span", "", t("Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.")));
|
||||
e.append(el("b", "", t("No sessions yet")), el("span", "", t("Claude Code's, Codex's, Hermes's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.")));
|
||||
box.append(e);
|
||||
return box;
|
||||
}
|
||||
const a = current();
|
||||
if (a && !a.deletable) box.append(el("p", "usage-note sm-note", t("magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.", { agent: a.name })));
|
||||
if (a && (data.sessions.some((s) => s.read_only) || !a.deletable)) {
|
||||
const canResume = data.sessions.some((s) => s.resume);
|
||||
const key = data.sessions.some((s) => s.read_only)
|
||||
? canResume
|
||||
? "Some {agent} sessions are read only and cannot be deleted."
|
||||
: "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them."
|
||||
: canResume
|
||||
? "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own."
|
||||
: "magpie can list {agent}'s sessions, but cannot resume or delete them.";
|
||||
box.append(el("p", "usage-note sm-note", t(key, { agent: a.name })));
|
||||
}
|
||||
box.append(selectBar(), el("div", "sm-tree"));
|
||||
queueMicrotask(redrawList);
|
||||
return box;
|
||||
@@ -175,7 +185,7 @@
|
||||
const bar = el("div", "row-head sm-bar");
|
||||
const a = current();
|
||||
if (!a?.deletable) { bar.hidden = true; return bar; }
|
||||
const list = shown();
|
||||
const list = shown().filter((s) => !s.read_only);
|
||||
const all = el("input", "sm-check");
|
||||
all.type = "checkbox";
|
||||
all.checked = list.length > 0 && list.every((s) => picked.has(s.id));
|
||||
@@ -235,22 +245,23 @@
|
||||
const open = !!q || opened.has(cwd);
|
||||
const g = el("div", "list sm-group");
|
||||
const r = el("div", "row sm-folder");
|
||||
const writable = items.filter((s) => !s.read_only);
|
||||
// the folder's box picks every session of it shown, folded or not,
|
||||
// for the bar's Delete; the bar still counts sessions (#527)
|
||||
if (current()?.deletable) {
|
||||
if (current()?.deletable && writable.length) {
|
||||
const c = el("input", "sm-check sm-folder-check");
|
||||
c.type = "checkbox";
|
||||
// a session's own box ticked or not shows here at once
|
||||
c.sync = () => {
|
||||
c.checked = items.every((s) => picked.has(s.id));
|
||||
c.indeterminate = !c.checked && items.some((s) => picked.has(s.id));
|
||||
c.checked = writable.every((s) => picked.has(s.id));
|
||||
c.indeterminate = !c.checked && writable.some((s) => picked.has(s.id));
|
||||
};
|
||||
c.sync();
|
||||
folderBoxes.set(cwd, c);
|
||||
c.setAttribute("aria-label", t("Select every session in {folder}", { folder: cwd ? baseName(cwd) : t("No folder") }));
|
||||
c.onclick = (e) => e.stopPropagation();
|
||||
c.onchange = () => {
|
||||
for (const s of items) c.checked ? picked.add(s.id) : picked.delete(s.id);
|
||||
for (const s of writable) c.checked ? picked.add(s.id) : picked.delete(s.id);
|
||||
redrawList();
|
||||
};
|
||||
r.append(c);
|
||||
@@ -264,6 +275,7 @@
|
||||
redrawList();
|
||||
};
|
||||
r.append(fold, el("span", "sub sm-path", cwd), el("span", "grow"), el("span", "note", t(items.length === 1 ? "{n} session" : "{n} sessions", { n: items.length })));
|
||||
|
||||
r.title = cwd;
|
||||
g.append(r);
|
||||
if (open) for (const s of items) g.append(item(s));
|
||||
@@ -276,7 +288,7 @@
|
||||
const wrap = el("div", "sess-item sm-item" + (detail === s.id ? " open" : ""));
|
||||
const r = el("div", "row sess sm-sess");
|
||||
r.dataset.id = s.id;
|
||||
if (a?.deletable) {
|
||||
if (a?.deletable && !s.read_only) {
|
||||
const c = el("input", "sm-check");
|
||||
c.type = "checkbox";
|
||||
c.checked = picked.has(s.id);
|
||||
@@ -314,7 +326,7 @@
|
||||
r.append(term);
|
||||
}
|
||||
}
|
||||
if (a?.deletable) {
|
||||
if (a?.deletable && !s.read_only) {
|
||||
const del = el("button", "copy sm-del");
|
||||
del.type = "button";
|
||||
del.title = t("Delete");
|
||||
|
||||
@@ -26,6 +26,7 @@ function fixture() {
|
||||
return {
|
||||
claude: [...app, sess("b-1", "/work/blog", "write the post", 120), sess("b-2", "/work/blog", "", 240)],
|
||||
opencode: [{ ...sess("o-1", "/work/app", "an opencode chat", 5), agent: "opencode", deletable: false, resume: "opencode -s o-1" }],
|
||||
hermes: [{ ...sess("h-1", "/work/hermes", "Hermes chat", 8), agent: "hermes", deletable: false, read_only: true, resume: "" }],
|
||||
trash: [],
|
||||
};
|
||||
}
|
||||
@@ -44,11 +45,12 @@ function serve(lang, calls) {
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/sessions/manage") {
|
||||
const want = url.searchParams.get("agent");
|
||||
const agent = want === "opencode" ? "opencode" : "claude";
|
||||
const agent = ["opencode", "hermes"].includes(want) ? want : "claude";
|
||||
return json({
|
||||
agents: [
|
||||
{ agent: "claude", count: store.claude.length, deletable: true, name: "Claude Code", icon: "claudecode-color" },
|
||||
{ agent: "opencode", count: store.opencode.length, deletable: false, name: "OpenCode", icon: "opencode" },
|
||||
{ agent: "hermes", count: store.hermes.length, deletable: false, name: "Hermes", icon: "hermes" },
|
||||
],
|
||||
agent, sessions: store[agent], terminal: true, trash: store.trash, trashDir: "~/Library/Application Support/magpie/trash/sessions",
|
||||
});
|
||||
@@ -89,6 +91,8 @@ const words = {
|
||||
active: "still running is still being written to; close it in Claude Code and try again in a minute",
|
||||
restored: "fix the login form restored", picked: "2 selected", filter: "Filter sessions",
|
||||
cant: "magpie can list OpenCode's sessions and resume them, but not delete them: they aren't kept as files of their own.",
|
||||
hermesNote: "These Hermes sessions are read only; magpie can list them, but cannot resume or delete them.",
|
||||
codexNote: "Some Codex sessions are read only and cannot be deleted.",
|
||||
idLine: "Session ID",
|
||||
},
|
||||
zh: {
|
||||
@@ -97,6 +101,8 @@ const words = {
|
||||
active: "「still running」仍在写入;请在 Claude Code 中关闭它,一分钟后再试",
|
||||
restored: "已恢复「fix the login form」", picked: "已选 2 个", filter: "筛选会话",
|
||||
cant: "magpie 可以列出并继续 OpenCode 的会话,但不能删除:它们没有各自独立的文件。",
|
||||
hermesNote: "这些 Hermes 会话为只读;magpie 可以列出,但不能继续或删除。",
|
||||
codexNote: "部分 Codex 会话为只读,无法删除。",
|
||||
idLine: "会话 ID",
|
||||
},
|
||||
};
|
||||
@@ -236,6 +242,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal((await view.locator(".sm-note").textContent()).trim(), w.cant);
|
||||
assert.equal(await view.locator(".sm-del, .sm-check").count(), 0);
|
||||
assert(!(await view.locator(".sm-bar").isVisible()));
|
||||
const mutationCount = calls.length;
|
||||
await view.locator(".sm-agents .opt", { hasText: "Hermes" }).click();
|
||||
const hermes = view.locator('.row.sm-sess[data-id="h-1"]');
|
||||
await hermes.waitFor();
|
||||
assert.equal((await view.locator(".sm-note").textContent()).trim(), w.hermesNote);
|
||||
assert.equal(await hermes.locator(".sm-resume, .sess-resume, .sess-term, .sm-del, .sm-check").count(), 0);
|
||||
assert.equal(await view.locator(".sm-folder-del").count(), 0);
|
||||
assert(!(await view.locator(".sm-bar").isVisible()));
|
||||
assert.equal(calls.length, mutationCount, "viewing Hermes sessions sends no mutation");
|
||||
if (process.env.SCREENSHOT_DIR) {
|
||||
await fs.mkdir(process.env.SCREENSHOT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, `${engine}-${lang}-hermes.png`), fullPage: true });
|
||||
}
|
||||
|
||||
const missing = await page.evaluate(() => [
|
||||
"Sessions", "Filter sessions", "No sessions yet", "Select every session shown", "Select", "Delete", "Trash", "No folder", "deleted {when}",
|
||||
@@ -243,8 +262,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
"{title} is still being written to; close it in {agent} and try again in a minute",
|
||||
"{n} sessions are still being written to; close them in {agent} and try again in a minute",
|
||||
"Trash is empty", "Sessions deleted here wait in magpie's trash, to be restored.",
|
||||
"Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.",
|
||||
"Claude Code's, Codex's, Hermes's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.",
|
||||
"magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.",
|
||||
"magpie can list {agent}'s sessions, but cannot resume or delete them.",
|
||||
"These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.",
|
||||
"Some {agent} sessions are read only and cannot be deleted.",
|
||||
"Their files are moved to magpie's trash ({dir}), not erased: Trash puts them back. A session written to in the last minute is left alone, as {agent} may still be running it.",
|
||||
"Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.",
|
||||
].filter((k) => !I18N.zh[k]));
|
||||
|
||||
@@ -27,6 +27,7 @@ func setupCalls(t *testing.T) callDirs {
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data"))
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", d.claude)
|
||||
t.Setenv("CODEX_HOME", d.codex)
|
||||
|
||||
t.Setenv("HOME", filepath.Join(dir, "home"))
|
||||
t.Setenv("USERPROFILE", filepath.Join(dir, "home"))
|
||||
callDesktopDirs = func() []string { return []string{d.desktop} }
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Hermes stores canonical, non-overlapping input/cache buckets. Reasoning is
|
||||
// already included in output. session_model_usage includes auxiliary tasks and
|
||||
// multiple billing routes; sessions supplies only unattributed main-loop usage.
|
||||
// These tables contain aggregates, not individual API request usage.
|
||||
func HermesDir() string {
|
||||
if home := os.Getenv("HERMES_HOME"); home != "" {
|
||||
return filepath.Clean(home)
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".hermes")
|
||||
}
|
||||
|
||||
// HermesDirs includes the default store and live named profiles. A selected
|
||||
// profile home resolves back to its root, as Hermes's profile resolver does.
|
||||
func HermesDirs() []string {
|
||||
root := HermesDir()
|
||||
if filepath.Base(filepath.Dir(root)) == "profiles" {
|
||||
root = filepath.Dir(filepath.Dir(root))
|
||||
}
|
||||
dirs := []string{root}
|
||||
for _, e := range readDirectory(filepath.Join(root, "profiles")) {
|
||||
if !strings.HasPrefix(e.Name(), ".") && (e.IsDir() || e.Type()&os.ModeSymlink != 0) {
|
||||
dirs = append(dirs, filepath.Join(root, "profiles", e.Name()))
|
||||
}
|
||||
}
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, dir := range dirs {
|
||||
path := canonicalHermesPath(filepath.Join(dir, "state.db"))
|
||||
if fileExists(path) && !seen[path] {
|
||||
seen[path] = true
|
||||
out = append(out, filepath.Dir(path))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func canonicalHermesPath(path string) string {
|
||||
if abs, err := filepath.Abs(path); err == nil {
|
||||
path = abs
|
||||
}
|
||||
if real, err := filepath.EvalSymlinks(path); err == nil {
|
||||
path = real
|
||||
}
|
||||
return filepath.Clean(path)
|
||||
}
|
||||
|
||||
func hermesID(path, sid string) string {
|
||||
// Include the store even for the default profile so selecting another home
|
||||
// cannot collide with a previously indexed store or a copied session id.
|
||||
h := sha256.Sum256([]byte(canonicalHermesPath(path)))
|
||||
return "h" + hex.EncodeToString(h[:8]) + "-" + sid
|
||||
}
|
||||
|
||||
type hermesDB struct {
|
||||
db *sql.DB
|
||||
sessions, messages, usage map[string]bool
|
||||
revision string
|
||||
}
|
||||
|
||||
// WAL writes do not touch the main database file. Include both files in the
|
||||
// cache identity, including WAL removal or truncation after a checkpoint.
|
||||
func hermesRevision(path string) string {
|
||||
var parts []string
|
||||
for _, p := range []string{path, path + "-wal"} {
|
||||
info, err := os.Stat(p)
|
||||
if err != nil {
|
||||
if p == path || !os.IsNotExist(err) {
|
||||
return "" // an unknown revision is never reused
|
||||
}
|
||||
parts = append(parts, "absent")
|
||||
continue
|
||||
}
|
||||
parts = append(parts, strconv.FormatInt(info.Size(), 10), strconv.FormatInt(info.ModTime().UnixNano(), 10))
|
||||
}
|
||||
return strings.Join(parts, ":")
|
||||
}
|
||||
|
||||
type hermesQuery interface {
|
||||
Query(string, ...any) (*sql.Rows, error)
|
||||
QueryRow(string, ...any) *sql.Row
|
||||
}
|
||||
|
||||
// Only fixed table and column names below are interpolated. Values use bind
|
||||
// parameters; absent columns on older schemas become harmless defaults.
|
||||
func hermesColumns(db *sql.DB, table string) map[string]bool {
|
||||
cols := map[string]bool{}
|
||||
rows, err := db.Query("PRAGMA table_info(" + table + ")")
|
||||
if err != nil {
|
||||
return cols
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var cid, required, pk int
|
||||
var name, kind string
|
||||
var def any
|
||||
if rows.Scan(&cid, &name, &kind, &required, &def, &pk) == nil {
|
||||
cols[name] = true
|
||||
}
|
||||
}
|
||||
return cols
|
||||
}
|
||||
|
||||
func newHermesDB(db *sql.DB) *hermesDB {
|
||||
return &hermesDB{
|
||||
db: db,
|
||||
sessions: hermesColumns(db, "sessions"),
|
||||
messages: hermesColumns(db, "messages"),
|
||||
usage: hermesColumns(db, "session_model_usage"),
|
||||
}
|
||||
}
|
||||
|
||||
func hermesExpr(cols map[string]bool, name, fallback string) string {
|
||||
if cols[name] {
|
||||
return "COALESCE(" + name + ", " + fallback + ")"
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func hermesSelect(cols map[string]bool, names []string, fallback string) string {
|
||||
parts := make([]string, len(names))
|
||||
for i, name := range names {
|
||||
parts[i] = hermesExpr(cols, name, fallback)
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func hermesFiles() []file {
|
||||
var out []file
|
||||
for _, dir := range HermesDirs() {
|
||||
path := filepath.Join(dir, "state.db")
|
||||
db := openDB(path)
|
||||
if db == nil {
|
||||
continue
|
||||
}
|
||||
store := newHermesDB(db)
|
||||
store.revision = hermesRevision(path)
|
||||
if !store.sessions["id"] {
|
||||
continue
|
||||
}
|
||||
messageLast, usageLast := "0", "0"
|
||||
if store.messages["session_id"] && store.messages["timestamp"] {
|
||||
messageLast = "COALESCE((SELECT MAX(timestamp) FROM messages m WHERE m.session_id = sessions.id), 0)"
|
||||
}
|
||||
if store.usage["session_id"] && store.usage["last_seen"] {
|
||||
usageLast = "COALESCE((SELECT MAX(last_seen) FROM session_model_usage u WHERE u.session_id = sessions.id), 0)"
|
||||
}
|
||||
query := "SELECT id, " + hermesSelect(
|
||||
store.sessions,
|
||||
[]string{"started_at", "ended_at", "last_activity_at"},
|
||||
"0",
|
||||
) + ", " + messageLast + ", " + usageLast + " FROM sessions"
|
||||
rows, err := db.Query(query)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for rows.Next() {
|
||||
var sid string
|
||||
var start, end, last, messageAt, usageAt float64
|
||||
if rows.Scan(&sid, &start, &end, &last, &messageAt, &usageAt) != nil || sid == "" {
|
||||
continue
|
||||
}
|
||||
id := hermesID(path, sid)
|
||||
out = append(out, file{
|
||||
agent: "hermes",
|
||||
key: "hermes:" + id,
|
||||
path: path + "#" + url.QueryEscape(sid),
|
||||
sid: sid,
|
||||
main: true,
|
||||
mod: hermesTime(max(start, end, last, messageAt, usageAt)),
|
||||
hermes: store,
|
||||
readOnly: true,
|
||||
})
|
||||
}
|
||||
rows.Close()
|
||||
if rows.Err() != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hermesTime(seconds float64) time.Time {
|
||||
if seconds <= 0 || math.IsNaN(seconds) || math.IsInf(seconds, 0) {
|
||||
return time.Time{}
|
||||
}
|
||||
whole, fraction := math.Modf(seconds)
|
||||
return time.Unix(int64(whole), int64(fraction*1e9))
|
||||
}
|
||||
|
||||
type hermesUsage struct {
|
||||
model, upstream, task string
|
||||
Tokens
|
||||
reasoning, calls int
|
||||
last float64
|
||||
}
|
||||
|
||||
func (h *hermesDB) usages(q hermesQuery, sid string, fallback hermesUsage) ([]hermesUsage, error) {
|
||||
if !h.usage["session_id"] || !h.usage["model"] {
|
||||
return []hermesUsage{fallback}, nil
|
||||
}
|
||||
query := "SELECT " + hermesSelect(
|
||||
h.usage,
|
||||
[]string{"model", "billing_provider", "task"},
|
||||
"''",
|
||||
) + ", " + hermesSelect(
|
||||
h.usage,
|
||||
[]string{
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
"reasoning_tokens",
|
||||
"api_call_count",
|
||||
"last_seen",
|
||||
},
|
||||
"0",
|
||||
) + " FROM session_model_usage WHERE session_id = ?"
|
||||
rows, err := q.Query(query, sid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []hermesUsage
|
||||
for rows.Next() {
|
||||
var u hermesUsage
|
||||
if err := rows.Scan(
|
||||
&u.model,
|
||||
&u.upstream,
|
||||
&u.task,
|
||||
&u.Input,
|
||||
&u.Output,
|
||||
&u.CacheRead,
|
||||
&u.CacheWrite,
|
||||
&u.reasoning,
|
||||
&u.calls,
|
||||
&u.last,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, u)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(out) == 0 {
|
||||
out = append(out, fallback)
|
||||
} else if h.usage["task"] {
|
||||
// Auxiliary rows (task != '') are not included in Hermes's sessions
|
||||
// counters. Reconcile only against main-loop rows so an aux-only set
|
||||
// cannot hide the main total, while already attributed main usage is
|
||||
// subtracted exactly once.
|
||||
var main hermesUsage
|
||||
for _, u := range out {
|
||||
if u.task == "" {
|
||||
main.Tokens.add(u.Tokens)
|
||||
main.reasoning += u.reasoning
|
||||
main.calls += u.calls
|
||||
}
|
||||
}
|
||||
residual := fallback
|
||||
residual.Input = max(0, fallback.Input-main.Input)
|
||||
residual.Output = max(0, fallback.Output-main.Output)
|
||||
residual.CacheRead = max(0, fallback.CacheRead-main.CacheRead)
|
||||
residual.CacheWrite = max(0, fallback.CacheWrite-main.CacheWrite)
|
||||
residual.reasoning = max(0, fallback.reasoning-main.reasoning)
|
||||
residual.calls = max(0, fallback.calls-main.calls)
|
||||
if !residual.Tokens.zero() || residual.reasoning != 0 || residual.calls != 0 {
|
||||
out = append(out, residual)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (h *hermesDB) metadata(q hermesQuery, sid string, s *state) (hermesUsage, error) {
|
||||
var u hermesUsage
|
||||
var start, end, last float64
|
||||
query := "SELECT " + hermesSelect(
|
||||
h.sessions,
|
||||
[]string{"title", "cwd", "model", "billing_provider"},
|
||||
"''",
|
||||
) + ", " + hermesSelect(
|
||||
h.sessions,
|
||||
[]string{
|
||||
"started_at",
|
||||
"ended_at",
|
||||
"last_activity_at",
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
"reasoning_tokens",
|
||||
"api_call_count",
|
||||
},
|
||||
"0",
|
||||
) + " FROM sessions WHERE id = ?"
|
||||
err := q.QueryRow(query, sid).Scan(&s.Title, &s.Cwd, &u.model, &u.upstream, &start, &end, &last, &u.Input, &u.Output, &u.CacheRead, &u.CacheWrite, &u.reasoning, &u.calls)
|
||||
s.Title = title(s.Title)
|
||||
s.Start, s.Last = hermesTime(start), hermesTime(max(start, end, last))
|
||||
u.last = max(start, end, last)
|
||||
return u, err
|
||||
}
|
||||
|
||||
type hermesMessage struct {
|
||||
role, content, tools string
|
||||
at float64
|
||||
id int64
|
||||
}
|
||||
|
||||
func (h *hermesDB) eachMessage(q hermesQuery, sid string, fn func(hermesMessage)) error {
|
||||
if !h.messages["session_id"] || !h.messages["role"] {
|
||||
return nil
|
||||
}
|
||||
// Match Hermes's display identity, including NULL versus empty tool fields.
|
||||
// Content alone would collapse legitimate repeated turns and tool results.
|
||||
type identity struct {
|
||||
role, content, tools, toolID, toolName sql.NullString
|
||||
at float64
|
||||
}
|
||||
column := func(name string) string {
|
||||
if h.messages[name] {
|
||||
return name
|
||||
}
|
||||
return "NULL"
|
||||
}
|
||||
query := "SELECT " + strings.Join([]string{
|
||||
column("role"), column("content"), column("tool_calls"),
|
||||
column("tool_call_id"), column("tool_name"), column("display_kind"),
|
||||
}, ", ") + ", " + hermesExpr(h.messages, "timestamp", "0") +
|
||||
", " + hermesExpr(h.messages, "active", "1") +
|
||||
", " + hermesExpr(h.messages, "id", "rowid") +
|
||||
" FROM messages WHERE session_id = ?"
|
||||
if h.messages["active"] {
|
||||
query += " AND (COALESCE(active, 1) != 0"
|
||||
if h.messages["compacted"] {
|
||||
query += " OR COALESCE(compacted, 0) != 0"
|
||||
}
|
||||
query += ")"
|
||||
}
|
||||
if h.messages["display_metadata"] {
|
||||
// Native display projections omit model-only scaffolding. Old schemas
|
||||
// have no metadata column, and malformed legacy JSON remains visible.
|
||||
query += " AND COALESCE(json_extract(CASE WHEN json_valid(display_metadata) THEN display_metadata ELSE '{}' END, '$.model_only'), 0) = 0"
|
||||
}
|
||||
query += " ORDER BY " + hermesExpr(h.messages, "id", "rowid")
|
||||
rows, err := q.Query(query, sid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
type representative struct {
|
||||
message hermesMessage
|
||||
active int
|
||||
}
|
||||
seen := map[identity]int{}
|
||||
var messages []representative
|
||||
for rows.Next() {
|
||||
var key identity
|
||||
var m hermesMessage
|
||||
var displayKind sql.NullString
|
||||
var active int
|
||||
if err := rows.Scan(&key.role, &key.content, &key.tools, &key.toolID, &key.toolName, &displayKind, &key.at, &active, &m.id); err != nil {
|
||||
return err
|
||||
}
|
||||
m.role, m.content, m.tools, m.at = key.role.String, key.content.String, key.tools.String, key.at
|
||||
if m.role == "user" && key.content.Valid {
|
||||
key.content.String = hermesDisplayContent(m.content, displayKind.String)
|
||||
}
|
||||
if i, ok := seen[key]; ok {
|
||||
current := messages[i]
|
||||
if active > current.active || active == current.active && m.id > current.message.id {
|
||||
messages[i] = representative{m, active}
|
||||
}
|
||||
} else {
|
||||
seen[key] = len(messages)
|
||||
messages = append(messages, representative{m, active})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// A copied tail retains its first row's place, even if its selected live
|
||||
// representative was inserted after later turns in another generation.
|
||||
for _, r := range messages {
|
||||
fn(r.message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseHermes uses a read transaction for a consistent snapshot while the
|
||||
// writer runs in WAL mode. The connection opens in mode=ro, which does not
|
||||
// modify state.db itself; SQLite may create an empty state.db-wal and a
|
||||
// state.db-shm when the store was cleanly closed. Cache identity includes
|
||||
// the WAL: usage and titles can change without a DB-file mtime change.
|
||||
func parseHermes(f file) *state {
|
||||
s := &state{Size: f.size, Mod: f.mod.UnixNano()}
|
||||
if f.hermes == nil {
|
||||
return s
|
||||
}
|
||||
// The connection enforces mode=ro; the transaction needs only a snapshot.
|
||||
tx, err := f.hermes.db.BeginTx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
defer tx.Rollback()
|
||||
u, err := f.hermes.metadata(tx, f.sid, s)
|
||||
if err != nil {
|
||||
return &state{}
|
||||
}
|
||||
// Activity comes from message gaps, not the entire duration of the session.
|
||||
last := s.Last
|
||||
s.Last = s.Start
|
||||
if err := f.hermes.eachMessage(tx, f.sid, func(m hermesMessage) {
|
||||
at := hermesTime(m.at)
|
||||
s.saw(at, true)
|
||||
d := s.day(dateOf(at))
|
||||
switch m.role {
|
||||
case "user":
|
||||
d.Prompts++
|
||||
if s.Title == "" {
|
||||
s.Title = title(hermesText(m.content))
|
||||
}
|
||||
case "assistant":
|
||||
d.Replies++
|
||||
for _, tool := range hermesTools(m.tools) {
|
||||
s.tool(at, tool.Function.Name, "")
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
return &state{}
|
||||
}
|
||||
if last.After(s.Last) {
|
||||
s.Last = last
|
||||
}
|
||||
usage, err := f.hermes.usages(tx, f.sid, u)
|
||||
if err != nil {
|
||||
return &state{}
|
||||
}
|
||||
for _, u := range usage {
|
||||
at := hermesTime(u.last)
|
||||
if at.IsZero() {
|
||||
at = s.Last
|
||||
}
|
||||
s.use(dateOf(at), u.model, u.Tokens)
|
||||
if at.After(s.Last) {
|
||||
s.Last = at
|
||||
}
|
||||
}
|
||||
s.DBRevision = f.hermes.revision
|
||||
return s
|
||||
}
|
||||
|
||||
type hermesTool struct {
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
func hermesTools(raw string) []hermesTool {
|
||||
var tools []hermesTool
|
||||
_ = json.Unmarshal([]byte(raw), &tools)
|
||||
return tools
|
||||
}
|
||||
|
||||
func hermesText(raw string) string {
|
||||
encoded, ok := strings.CutPrefix(raw, "\x00json:")
|
||||
if !ok {
|
||||
return raw
|
||||
}
|
||||
raw = encoded
|
||||
var parts []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if json.Unmarshal([]byte(raw), &parts) == nil {
|
||||
var text []string
|
||||
for _, p := range parts {
|
||||
if p.Type == "text" {
|
||||
text = append(text, p.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(text, "\n")
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHermesCompactionLogicalMessages(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "compaction", false)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec(`ALTER TABLE messages ADD COLUMN active INTEGER DEFAULT 1;
|
||||
ALTER TABLE messages ADD COLUMN compacted INTEGER DEFAULT 0;
|
||||
ALTER TABLE messages ADD COLUMN tool_call_id TEXT;
|
||||
ALTER TABLE messages ADD COLUMN tool_name TEXT;
|
||||
DELETE FROM messages;
|
||||
INSERT INTO messages (id, session_id, role, content, tool_calls, timestamp, active, compacted, tool_call_id, tool_name) VALUES
|
||||
(1, 'compaction', 'user', 'archived only', NULL, 100, 0, 1, NULL, NULL),
|
||||
(2, 'compaction', 'user', 'repeat', NULL, 200, 0, 1, NULL, NULL),
|
||||
(3, 'compaction', 'assistant', 'answer', '[]', 300, 0, 1, NULL, NULL),
|
||||
(4, 'compaction', 'user', 'repeat', NULL, 400, 1, 0, NULL, NULL),
|
||||
(5, 'compaction', 'tool', 'same result', NULL, 500, 0, 1, 'call-a', 'read'),
|
||||
(6, 'compaction', 'tool', 'same result', NULL, 500, 1, 0, 'call-b', 'read'),
|
||||
(7, 'compaction', 'tool', 'same result', NULL, 500, 1, 0, 'call-a', 'write'),
|
||||
(8, 'compaction', 'assistant', 'answer', '[{"function":{"name":"read","arguments":{}}}]', 300, 1, 0, NULL, NULL),
|
||||
(9, 'compaction', 'user', 'repeat', NULL, 200, 0, 1, NULL, NULL),
|
||||
(10, 'compaction', 'assistant', 'answer', '[]', 300, 1, 0, NULL, NULL),
|
||||
(11, 'compaction', 'user', 'repeat', NULL, 200, 1, 0, NULL, NULL),
|
||||
(12, 'compaction', 'tool', 'same result', NULL, 500, 1, 0, 'call-a', 'read'),
|
||||
(13, 'compaction', 'user', 'discarded', NULL, 600, 0, 0, NULL, NULL),
|
||||
(14, 'compaction', 'user', 'older timestamp later turn', NULL, 50, 1, 0, NULL, NULL),
|
||||
(15, 'compaction', 'user', 'repeat', NULL, 200, 0, 1, NULL, NULL),
|
||||
(16, 'compaction', 'assistant', 'answer', '[]', 300, 1, 0, NULL, NULL);`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var texts []string
|
||||
var ids []int64
|
||||
if err := newHermesDB(db).eachMessage(db, "compaction", func(m hermesMessage) {
|
||||
texts = append(texts, m.content)
|
||||
ids = append(ids, m.id)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"archived only", "repeat", "answer", "repeat", "same result", "same result", "same result", "answer", "older timestamp later turn"}
|
||||
if !reflect.DeepEqual(texts, want) {
|
||||
t.Fatalf("logical transcript = %q, want %q", texts, want)
|
||||
}
|
||||
if wantIDs := []int64{1, 11, 16, 4, 12, 6, 7, 8, 14}; !reflect.DeepEqual(ids, wantIDs) {
|
||||
t.Fatalf("active/newest representatives in first-row order = %v, want %v", ids, wantIDs)
|
||||
}
|
||||
s := hermesSessionByID(t, hermesID(path, "compaction"))
|
||||
assertHermesMessageStats(t, s.ID, 4, 2, 1)
|
||||
}
|
||||
|
||||
func TestHermesModelOnlyMessages(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "model-only", false)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec(`ALTER TABLE messages ADD COLUMN display_metadata TEXT;
|
||||
UPDATE messages SET display_metadata='{"model_only":true}' WHERE id IN (1, 2);
|
||||
UPDATE messages SET display_metadata='{invalid' WHERE id=3;
|
||||
UPDATE messages SET display_metadata='{"model_only":false}' WHERE id=4;`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var texts []string
|
||||
if err := newHermesDB(db).eachMessage(db, "model-only", func(m hermesMessage) {
|
||||
texts = append(texts, m.content)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(texts) != 2 {
|
||||
t.Fatalf("model-only rows entered transcript: %q", texts)
|
||||
}
|
||||
s := hermesSessionByID(t, hermesID(path, "model-only"))
|
||||
assertHermesMessageStats(t, s.ID, 0, 1, 0)
|
||||
}
|
||||
|
||||
func assertHermesMessageStats(t *testing.T, sid string, prompts, replies, tools int) {
|
||||
t.Helper()
|
||||
for _, summary := range StatsFor(0).Sessions {
|
||||
if summary.Agent == "hermes" && summary.ID == sid {
|
||||
if summary.Prompts != prompts || summary.Replies != replies || summary.ToolCalls != tools {
|
||||
t.Fatalf("logical message statistics: %+v", summary)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("missing Hermes summary")
|
||||
}
|
||||
|
||||
func TestHermesCompactionUserHandoffIdentity(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
path := hermesFixture(t, root, "", "handoff", false)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec(`ALTER TABLE messages ADD COLUMN active INTEGER DEFAULT 1;
|
||||
ALTER TABLE messages ADD COLUMN compacted INTEGER DEFAULT 0;
|
||||
ALTER TABLE messages ADD COLUMN display_kind TEXT;
|
||||
DELETE FROM messages;`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const boundary = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"
|
||||
carrier := "[CONTEXT SUMMARY]: summary\n" + boundary + "\ncurrent ask"
|
||||
standalone := "[CONTEXT SUMMARY]: summary\n" + boundary
|
||||
_, err = db.Exec(`INSERT INTO messages (id, session_id, role, content, timestamp, active, compacted, display_kind) VALUES
|
||||
(1, 'handoff', 'user', 'current ask', 100, 0, 1, NULL),
|
||||
(2, 'handoff', 'user', 'later turn', 200, 1, 0, NULL),
|
||||
(3, 'handoff', 'user', ?, 100, 1, 0, 'hidden'),
|
||||
(4, 'handoff', 'user', ?, 100, 0, 1, 'hidden'),
|
||||
(5, 'handoff', 'user', ?, 300, 1, 0, 'hidden')`, carrier, carrier, standalone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ids []int64
|
||||
if err := newHermesDB(db).eachMessage(db, "handoff", func(m hermesMessage) {
|
||||
ids = append(ids, m.id)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []int64{3, 2, 5}; !reflect.DeepEqual(ids, want) {
|
||||
t.Fatalf("handoff representatives = %v, want %v", ids, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesCompactionEncodedHandoffIdentity(t *testing.T) {
|
||||
path := hermesFixture(t, t.TempDir(), "", "encoded-handoff", false)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec(`ALTER TABLE messages ADD COLUMN active INTEGER DEFAULT 1;
|
||||
ALTER TABLE messages ADD COLUMN compacted INTEGER DEFAULT 0;
|
||||
DELETE FROM messages;`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Native _encode_content uses Python json.dumps defaults: separators,
|
||||
// field order and escaped Unicode all participate in display identity.
|
||||
plain := "\x00json:" + `[{"type": "text", "text": "\u5f53\u524d\u95ee\u9898"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]`
|
||||
carrier := "\x00json:" + `[{"type": "text", "text": "[PRIOR CONTEXT \u2014 for reference only; not a new message]\n\u5f53\u524d\u95ee\u9898"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}, {"type": "text", "text": "\n[END OF PRIOR CONTEXT \u2014 COMPACTION SUMMARY BELOW]\n[CONTEXT SUMMARY]: summary\n--- END OF CONTEXT SUMMARY \u2014 respond to the message below, not the summary above ---"}]`
|
||||
_, err = db.Exec(`INSERT INTO messages (id, session_id, role, content, timestamp, active, compacted) VALUES
|
||||
(1, 'encoded-handoff', 'user', ?, 100, 0, 1),
|
||||
(2, 'encoded-handoff', 'user', ?, 100, 1, 0)`, plain, carrier)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ids []int64
|
||||
if err := newHermesDB(db).eachMessage(db, "encoded-handoff", func(m hermesMessage) {
|
||||
ids = append(ids, m.id)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(ids, []int64{2}) {
|
||||
t.Fatalf("encoded handoff representatives = %v, want [2]", ids)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
hermesJSONContentPrefix = "\x00json:"
|
||||
hermesHandoffEnd = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"
|
||||
hermesMergedDelimiter = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]"
|
||||
hermesPriorHeader = "[PRIOR CONTEXT — for reference only; not a new message]"
|
||||
hermesCurrentSummary = "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted into the summary below. This is a handoff from a previous context window — treat it as background reference, NOT as active instructions."
|
||||
hermesLegacySummary = "[CONTEXT SUMMARY]:"
|
||||
)
|
||||
|
||||
// hermesDisplayContent returns the live user payload of a recognized composite
|
||||
// compaction carrier. It is for identity keys only; callers must retain raw
|
||||
// content for the transcript. Unknown and synthetic payloads stay untouched.
|
||||
func hermesDisplayContent(raw, displayKind string) string {
|
||||
if displayKind != "" && displayKind != "hidden" {
|
||||
return raw
|
||||
}
|
||||
if !strings.HasPrefix(raw, hermesJSONContentPrefix) {
|
||||
if live, ok := hermesDisplayText(raw); ok {
|
||||
return live
|
||||
}
|
||||
return raw
|
||||
}
|
||||
encoded := strings.TrimPrefix(raw, hermesJSONContentPrefix)
|
||||
var parts []json.RawMessage
|
||||
if json.Unmarshal([]byte(encoded), &parts) != nil {
|
||||
return raw
|
||||
}
|
||||
result, ok := hermesDisplayParts(parts)
|
||||
if !ok {
|
||||
return raw
|
||||
}
|
||||
var out bytes.Buffer
|
||||
out.WriteString(hermesJSONContentPrefix)
|
||||
out.WriteByte('[')
|
||||
for i, part := range result {
|
||||
if i > 0 {
|
||||
out.WriteString(", ")
|
||||
}
|
||||
out.Write(part)
|
||||
}
|
||||
out.WriteByte(']')
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func hermesDisplayText(content string) (string, bool) {
|
||||
if i := strings.Index(content, hermesMergedDelimiter); i >= 0 {
|
||||
summary := strings.TrimLeft(content[i+len(hermesMergedDelimiter):], " \t\r\n")
|
||||
if hermesStartsSummary(summary) {
|
||||
prior := strings.TrimSpace(content[:i])
|
||||
prior = strings.TrimSpace(strings.TrimPrefix(prior, hermesPriorHeader))
|
||||
if prior != "" {
|
||||
return prior, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if !hermesStartsSummary(strings.TrimLeft(content, " \t\r\n")) {
|
||||
return "", false
|
||||
}
|
||||
if i := strings.Index(content, hermesHandoffEnd); i >= 0 {
|
||||
live := strings.TrimLeft(content[i+len(hermesHandoffEnd):], " \t\r\n")
|
||||
if strings.TrimSpace(live) != "" {
|
||||
return live, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func hermesStartsSummary(text string) bool {
|
||||
return strings.HasPrefix(text, hermesCurrentSummary) || strings.HasPrefix(text, hermesLegacySummary)
|
||||
}
|
||||
|
||||
func hermesDisplayParts(parts []json.RawMessage) ([]json.RawMessage, bool) {
|
||||
texts := make([]string, len(parts))
|
||||
for i, part := range parts {
|
||||
if json.Unmarshal(part, &texts[i]) == nil {
|
||||
continue
|
||||
}
|
||||
var node struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if json.Unmarshal(part, &node) == nil {
|
||||
texts[i] = node.Text
|
||||
}
|
||||
}
|
||||
allText := strings.Join(texts, "\n")
|
||||
if i := strings.Index(allText, hermesMergedDelimiter); i >= 0 {
|
||||
summary := strings.TrimLeft(allText[i+len(hermesMergedDelimiter):], " \t\r\n")
|
||||
if !hermesStartsSummary(summary) {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]json.RawMessage, 0, len(parts))
|
||||
for idx, part := range parts {
|
||||
at := strings.Index(texts[idx], hermesMergedDelimiter)
|
||||
if at < 0 {
|
||||
out = append(out, part)
|
||||
continue
|
||||
}
|
||||
prefix := texts[idx][:at]
|
||||
if strings.TrimSpace(prefix) != "" {
|
||||
updated, ok := hermesPartWithText(part, prefix)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, updated)
|
||||
}
|
||||
break
|
||||
}
|
||||
out, found := hermesStripPriorHeader(out)
|
||||
if found && hermesPartsHaveLiveContent(out) {
|
||||
return out, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
if !hermesStartsSummary(strings.TrimLeft(allText, " \t\r\n")) {
|
||||
return nil, false
|
||||
}
|
||||
marker := strings.Index(allText, hermesHandoffEnd)
|
||||
if marker < 0 {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]json.RawMessage, 0, len(parts))
|
||||
consumed := 0
|
||||
for idx, part := range parts {
|
||||
text := texts[idx]
|
||||
if consumed+len(text) < marker+len(hermesHandoffEnd) {
|
||||
consumed += len(text) + 1
|
||||
continue
|
||||
}
|
||||
start := marker + len(hermesHandoffEnd) - consumed
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if start < len(text) {
|
||||
updated, ok := hermesPartWithText(part, strings.TrimLeft(text[start:], " \t\r\n"))
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
if strings.TrimSpace(text[start:]) != "" {
|
||||
out = append(out, updated)
|
||||
}
|
||||
}
|
||||
for later := idx + 1; later < len(parts); later++ {
|
||||
out = append(out, parts[later])
|
||||
}
|
||||
break
|
||||
}
|
||||
if hermesPartsHaveLiveContent(out) {
|
||||
return out, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func hermesPartWithText(part json.RawMessage, text string) (json.RawMessage, bool) {
|
||||
var stringPart string
|
||||
if json.Unmarshal(part, &stringPart) == nil {
|
||||
return json.RawMessage(hermesPythonQuote(text)), true
|
||||
}
|
||||
var node map[string]json.RawMessage
|
||||
if json.Unmarshal(part, &node) != nil || node["text"] == nil {
|
||||
return nil, false
|
||||
}
|
||||
quoted := hermesPythonQuote(text)
|
||||
value := gjson.GetBytes(part, "text")
|
||||
if !value.Exists() || value.Type != gjson.String || value.Index < 0 {
|
||||
return nil, false
|
||||
}
|
||||
valueStart, valueEnd := value.Index, value.Index+len(value.Raw)
|
||||
if valueStart > len(part) || valueEnd > len(part) {
|
||||
return nil, false
|
||||
}
|
||||
updated := make([]byte, 0, len(part)-len(value.Raw)+len(quoted))
|
||||
updated = append(updated, part[:valueStart]...)
|
||||
updated = append(updated, quoted...)
|
||||
updated = append(updated, part[valueEnd:]...)
|
||||
return json.RawMessage(updated), true
|
||||
}
|
||||
|
||||
func hermesStripPriorHeader(parts []json.RawMessage) ([]json.RawMessage, bool) {
|
||||
for i, part := range parts {
|
||||
var text string
|
||||
if json.Unmarshal(part, &text) == nil {
|
||||
trimmed := strings.TrimLeft(text, " \t\r\n")
|
||||
if strings.HasPrefix(trimmed, hermesPriorHeader) {
|
||||
live := strings.TrimLeft(strings.TrimPrefix(trimmed, hermesPriorHeader), " \t\r\n")
|
||||
if live == "" {
|
||||
return append(parts[:i], parts[i+1:]...), true
|
||||
}
|
||||
updated, ok := hermesPartWithText(part, live)
|
||||
if ok {
|
||||
parts[i] = updated
|
||||
}
|
||||
return parts, true
|
||||
}
|
||||
continue
|
||||
}
|
||||
value := gjson.GetBytes(part, "text")
|
||||
if value.Type == gjson.String && strings.TrimSpace(value.Str) != "" {
|
||||
trimmed := strings.TrimLeft(value.Str, " \t\r\n")
|
||||
if strings.HasPrefix(trimmed, hermesPriorHeader) {
|
||||
live := strings.TrimLeft(strings.TrimPrefix(trimmed, hermesPriorHeader), " \t\r\n")
|
||||
if live == "" {
|
||||
return append(parts[:i], parts[i+1:]...), true
|
||||
}
|
||||
updated, ok := hermesPartWithText(part, live)
|
||||
if ok {
|
||||
parts[i] = updated
|
||||
}
|
||||
return parts, true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
return parts, len(parts) > 0
|
||||
}
|
||||
|
||||
// hermesPythonQuote matches json.dumps(string)'s default ensure_ascii output,
|
||||
// so a sliced payload retains the same durable identity as an ordinary row.
|
||||
func hermesPythonQuote(text string) string {
|
||||
var b bytes.Buffer
|
||||
enc := json.NewEncoder(&b)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(text); err != nil {
|
||||
return `""`
|
||||
}
|
||||
quoted := strings.TrimSuffix(b.String(), "\n")
|
||||
var out strings.Builder
|
||||
for _, r := range quoted {
|
||||
if r < 0x7f {
|
||||
out.WriteRune(r)
|
||||
} else if r <= 0xffff {
|
||||
fmt.Fprintf(&out, `\u%04x`, r)
|
||||
} else {
|
||||
r -= 0x10000
|
||||
fmt.Fprintf(&out, `\u%04x\u%04x`, 0xd800+(r>>10), 0xdc00+(r&0x3ff))
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func hermesPartsHaveLiveContent(parts []json.RawMessage) bool {
|
||||
for _, part := range parts {
|
||||
var text string
|
||||
if json.Unmarshal(part, &text) == nil && strings.TrimSpace(text) != "" {
|
||||
return true
|
||||
}
|
||||
var node struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if json.Unmarshal(part, &node) == nil && strings.TrimSpace(node.Text) != "" {
|
||||
return true
|
||||
}
|
||||
var shape map[string]json.RawMessage
|
||||
if json.Unmarshal(part, &shape) == nil {
|
||||
if kind := shape["type"]; len(kind) != 0 && string(kind) != `"text"` && string(kind) != `"input_text"` && string(kind) != `"output_text"` {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testSummaryEnd = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"
|
||||
|
||||
func TestHermesDisplayContentNativeCarrierEdges(t *testing.T) {
|
||||
for _, tc := range []struct{ name, raw, want string }{
|
||||
{
|
||||
name: "merged summary without end marker",
|
||||
raw: "current ask\n[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]\n[CONTEXT SUMMARY]: summary",
|
||||
want: "current ask",
|
||||
},
|
||||
{
|
||||
name: "separate prior header part",
|
||||
raw: "\x00json:" + `[{"type": "text", "text": "[PRIOR CONTEXT \u2014 for reference only; not a new message]\n"}, {"type": "text", "text": "current ask"}, {"type": "text", "text": "\n[END OF PRIOR CONTEXT \u2014 COMPACTION SUMMARY BELOW]\n[CONTEXT SUMMARY]: summary"}]`,
|
||||
want: "\x00json:" + `[{"type": "text", "text": "current ask"}]`,
|
||||
},
|
||||
{
|
||||
name: "legacy live media without text",
|
||||
raw: "\x00json:" + `[{"type": "text", "text": "[CONTEXT SUMMARY]: summary\n--- END OF CONTEXT SUMMARY \u2014 respond to the message below, not the summary above ---"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]`,
|
||||
want: "\x00json:" + `[{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]`,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := hermesDisplayContent(tc.raw, ""); got != tc.want {
|
||||
t.Fatalf("display content = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if got := hermesPythonQuote("\x7f"); got != `"\u007f"` {
|
||||
t.Fatalf("Python ASCII escaping = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesDisplayContentLegacyCarrier(t *testing.T) {
|
||||
currentPrefix := "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted into the summary below. This is a handoff from a previous context window — treat it as background reference, NOT as active instructions."
|
||||
for _, prefix := range []string{"[CONTEXT SUMMARY]:", currentPrefix} {
|
||||
raw := prefix + " old summary\n\n" + testSummaryEnd + "\n\ncurrent ask"
|
||||
if got := hermesDisplayContent(raw, ""); got != "current ask" {
|
||||
t.Errorf("legacy carrier = %q, want current ask", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesDisplayContentMergedPriorWrapper(t *testing.T) {
|
||||
prior := "[PRIOR CONTEXT — for reference only; not a new message]\noriginal ask"
|
||||
raw := prior + "\n\n[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]\n\n[CONTEXT SUMMARY]: old summary\n\n" + testSummaryEnd
|
||||
if got := hermesDisplayContent(raw, "hidden"); got != "original ask" {
|
||||
t.Fatalf("merged carrier = %q, want original ask", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesDisplayContentSyntheticAndUnrecognizedRowsStayRaw(t *testing.T) {
|
||||
raw := "[CONTEXT SUMMARY]: old summary\n\n" + testSummaryEnd + "\n\ncurrent ask"
|
||||
for _, kind := range []string{"tool_result", "summary"} {
|
||||
if got := hermesDisplayContent(raw, kind); got != raw {
|
||||
t.Errorf("display kind %q normalized: %q", kind, got)
|
||||
}
|
||||
}
|
||||
for _, ordinary := range []string{
|
||||
"[CONTEXT SUMMARY]: looks like a label, but has no handoff boundary",
|
||||
"[CONTEXT COMPACTION — REFERENCE ONLY] quoted label\n\n" + testSummaryEnd + "\n\nask",
|
||||
"plain user text\n\n" + testSummaryEnd + "\n\nmore text",
|
||||
"[CONTEXT SUMMARY]: old summary\n\n" + testSummaryEnd,
|
||||
} {
|
||||
if got := hermesDisplayContent(ordinary, ""); got != ordinary {
|
||||
t.Errorf("unrecognized content normalized: %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesDisplayContentEncodedPartsPreserveNonText(t *testing.T) {
|
||||
prior := "[PRIOR CONTEXT — for reference only; not a new message]\n"
|
||||
raw := "\x00json:[{\"type\": \"text\", \"text\": " + hermesPythonQuote(prior+"ask before image") +
|
||||
"}, {\"type\": \"image_url\", \"image_url\": {\"url\": \"data:image/png;base64,AA==\"}}, {\"type\": \"text\", \"text\": " +
|
||||
hermesPythonQuote("\n\n[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]\n\n[CONTEXT SUMMARY]: summary\n\n"+testSummaryEnd) + "}]"
|
||||
got := hermesDisplayContent(raw, "")
|
||||
if !strings.HasPrefix(got, "\x00json:") {
|
||||
t.Fatalf("encoded content lost sentinel: %q", got)
|
||||
}
|
||||
var gotParts []map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(got, "\x00json:")), &gotParts); err != nil {
|
||||
t.Fatalf("normalized parts are invalid JSON: %v: %q", err, got)
|
||||
}
|
||||
if len(gotParts) != 2 {
|
||||
t.Fatalf("normalized parts count = %d, want prior text and image", len(gotParts))
|
||||
}
|
||||
var text string
|
||||
if err := json.Unmarshal(gotParts[0]["text"], &text); err != nil || text != "ask before image" {
|
||||
t.Fatalf("normalized prior text = %q, error = %v", text, err)
|
||||
}
|
||||
var image map[string]any
|
||||
if err := json.Unmarshal(gotParts[1]["image_url"], &image); err != nil || image["url"] == nil {
|
||||
t.Fatalf("prior image was not preserved: %s, error = %v", gotParts[1]["image_url"], err)
|
||||
}
|
||||
want := "\x00json:[{\"type\": \"text\", \"text\": " + hermesPythonQuote("ask before image") +
|
||||
"}, {\"type\": \"image_url\", \"image_url\": {\"url\": \"data:image/png;base64,AA==\"}}]"
|
||||
if got != want {
|
||||
t.Fatalf("normalized Python JSON identity = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const hermesSchema = `
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY, title TEXT, cwd TEXT, model TEXT,
|
||||
started_at REAL, ended_at REAL, last_activity_at REAL,
|
||||
input_tokens INTEGER, output_tokens INTEGER, cache_read_tokens INTEGER,
|
||||
cache_write_tokens INTEGER, reasoning_tokens INTEGER, api_call_count INTEGER
|
||||
);
|
||||
CREATE TABLE messages (
|
||||
id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT,
|
||||
tool_calls TEXT, timestamp REAL
|
||||
);
|
||||
CREATE TABLE session_model_usage (
|
||||
session_id TEXT, model TEXT, billing_provider TEXT,
|
||||
input_tokens INTEGER, output_tokens INTEGER, cache_read_tokens INTEGER,
|
||||
cache_write_tokens INTEGER, reasoning_tokens INTEGER, api_call_count INTEGER,
|
||||
last_seen REAL
|
||||
);`
|
||||
|
||||
func hermesFixture(t *testing.T, root, profile, sid string, withUsage bool) string {
|
||||
t.Helper()
|
||||
dir := root
|
||||
if profile != "" {
|
||||
dir = filepath.Join(root, "profiles", profile)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "state.db")
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(hermesSchema); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := time.Date(2026, 9, 28, 10, 0, 0, 0, time.UTC).Unix()
|
||||
_, err = db.Exec(`INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
sid, "A Hermes task", "/work/hermes", "fallback-model", float64(base), nil, float64(base+12), 90, 30, 40, 10, 5, 2)
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec(`INSERT INTO messages VALUES
|
||||
(1, ?, 'user', ?, '[]', ?),
|
||||
(2, ?, 'assistant', ?, ?, ?),
|
||||
(3, ?, 'tool', ?, '[]', ?),
|
||||
(4, ?, 'assistant', ?, '[]', ?)`,
|
||||
sid, "\x00json:"+`[{"type":"text","text":"Please inspect this"}]`, float64(base+1),
|
||||
sid, `[{"type":"text","text":"I will inspect it"}]`, `[{"function":{"name":"read_file","arguments":{"path":"a.txt"}}}]`, float64(base+4),
|
||||
sid, `[{"type":"text","text":"file contents"}]`, float64(base+7),
|
||||
sid, `[{"type":"text","text":"Done"}]`, float64(base+12))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if withUsage {
|
||||
_, err = db.Exec(`INSERT INTO session_model_usage VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, sid, "actual-model", "router", 100, 50, 25, 15, 8, 3, float64(base+12))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func hermesSessionByID(t *testing.T, sid string) Session {
|
||||
t.Helper()
|
||||
for _, s := range List(0) {
|
||||
if s.Agent == "hermes" && s.ID == sid {
|
||||
return s
|
||||
}
|
||||
}
|
||||
t.Fatalf("Hermes session %q not found in %+v", sid, List(0))
|
||||
return Session{}
|
||||
}
|
||||
|
||||
func TestHermesListStatsCallsAndContent(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "same-id", true)
|
||||
profilePath := hermesFixture(t, root, "work", "same-id", true)
|
||||
_ = path
|
||||
_ = profilePath
|
||||
|
||||
listed := List(0)
|
||||
var hs []Session
|
||||
for _, s := range listed {
|
||||
if s.Agent == "hermes" {
|
||||
hs = append(hs, s)
|
||||
}
|
||||
}
|
||||
if len(hs) != 2 {
|
||||
t.Fatalf("want default and profile sessions, got %+v", hs)
|
||||
}
|
||||
if hs[0].ID == hs[1].ID {
|
||||
t.Fatalf("duplicate database IDs were not namespaced: %q", hs[0].ID)
|
||||
}
|
||||
for _, s := range hs {
|
||||
if !s.ReadOnly || s.Resume != "" || s.Title != "A Hermes task" || s.Cwd != "/work/hermes" {
|
||||
t.Errorf("metadata/read-only state: %+v", s)
|
||||
}
|
||||
if m := model(s, "actual-model"); m.Tokens != (Tokens{100, 50, 25, 15}) {
|
||||
t.Errorf("usage aggregate: %+v", m)
|
||||
}
|
||||
if model(s, "fallback-model").Model != "" {
|
||||
t.Errorf("session fallback was added to authoritative usage rows: %+v", s.Models)
|
||||
}
|
||||
}
|
||||
for _, managed := range ListAgent("hermes") {
|
||||
if managed.Deletable || managed.Resume != "" {
|
||||
t.Errorf("Hermes must not expose mutation or resume: %+v", managed)
|
||||
}
|
||||
}
|
||||
|
||||
// Each DB has the same session id and usage; both are included exactly once.
|
||||
day := time.Date(2026, 9, 28, 12, 0, 0, 0, time.UTC)
|
||||
stats := StatsAt(0, day)
|
||||
var total Tokens
|
||||
for _, d := range stats.Days {
|
||||
for _, u := range d.Usage {
|
||||
if u.Agent == "hermes" {
|
||||
total.add(u.Tokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
if total != (Tokens{200, 100, 50, 30}) {
|
||||
t.Errorf("Hermes stats total = %+v", total)
|
||||
}
|
||||
|
||||
// hermesCalls is intentionally absent: Hermes usage is session-level
|
||||
// and has no production consumer in callsFor or FindCall.
|
||||
calls := Calls(time.Time{})
|
||||
for _, c := range calls {
|
||||
if c.Agent == "hermes" {
|
||||
t.Errorf("Hermes should not appear in Calls: %+v", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesUsageFallbackAndLiveRefresh(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "fallback", false)
|
||||
|
||||
first := hermesSessionByID(t, hermesID(path, "fallback"))
|
||||
if got := model(first, "fallback-model").Tokens; got != (Tokens{90, 30, 40, 10}) {
|
||||
t.Fatalf("session aggregate fallback = %+v", got)
|
||||
}
|
||||
|
||||
// Repeated discovery must see SQLite WAL changes to aggregate usage and
|
||||
// the title even when the main database file's mtime has not moved, without
|
||||
// resetting Magpie's cache.
|
||||
oldInfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO session_model_usage VALUES ('fallback', 'new-model', NULL, 11, 7, 3, 2, 1, 1, ?)`, float64(time.Date(2026, 9, 28, 10, 1, 0, 0, time.UTC).Unix())); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE sessions SET title = 'Updated title' WHERE id = 'fallback'`); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chtimes(path, oldInfo.ModTime(), oldInfo.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := hermesSessionByID(t, hermesID(path, "fallback"))
|
||||
if updated.Title != "Updated title" {
|
||||
t.Errorf("title not refreshed: %q", updated.Title)
|
||||
}
|
||||
if got := model(updated, "new-model").Tokens; got != (Tokens{11, 7, 3, 2}) {
|
||||
t.Errorf("WAL usage not refreshed: %+v", got)
|
||||
}
|
||||
// The bucket timestamp intentionally stays fixed. Newly observed usage
|
||||
// must still be visible on the next scan, and not be treated as a second
|
||||
// synthetic request or merged with the session-level fallback.
|
||||
if _, err := db.Exec(`UPDATE session_model_usage SET input_tokens=13, output_tokens=9, cache_read_tokens=4, cache_write_tokens=3 WHERE session_id='fallback'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE sessions SET title='Changed again' WHERE id='fallback'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated = hermesSessionByID(t, hermesID(path, "fallback"))
|
||||
if updated.Title != "Changed again" || model(updated, "new-model").Tokens != (Tokens{13, 9, 4, 3}) {
|
||||
t.Errorf("same-mtime usage/title refresh: %+v", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesOlderSchemaAndNullFields(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
dir := filepath.Join(root, "profiles", "old")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "state.db")
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec(`CREATE TABLE sessions (id TEXT, title TEXT, cwd TEXT, model TEXT, started_at REAL, ended_at REAL, last_activity_at REAL);
|
||||
INSERT INTO sessions VALUES ('old', NULL, NULL, NULL, NULL, NULL, NULL);
|
||||
CREATE TABLE messages (session_id TEXT, role TEXT, content TEXT, tool_calls TEXT, timestamp REAL);
|
||||
INSERT INTO messages VALUES ('old', 'user', 'hello', '[]', NULL);`)
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.Close()
|
||||
// Older schemas can omit usage columns. Nullable metadata and times must
|
||||
// coalesce safely while the available message content remains readable.
|
||||
defer closeDBs()
|
||||
found := false
|
||||
for _, f := range hermesFiles() {
|
||||
if f.sid == "old" {
|
||||
found = true
|
||||
st := parseHermes(f)
|
||||
if st == nil || st.Title != "hello" || !st.Start.IsZero() {
|
||||
t.Errorf("old schema parse: %+v", st)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("old profile session not discovered")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesStatsIncludesRecentUsageForOldTranscript(t *testing.T) {
|
||||
setup(t)
|
||||
inZone(t, 0)
|
||||
// The background cache writer reads time.Local; drain it before inZone
|
||||
// restores the zone. Cleanups run LIFO, so this runs before inZone's.
|
||||
t.Cleanup(func() {
|
||||
saving.Lock()
|
||||
for saving.running {
|
||||
saving.Wait()
|
||||
}
|
||||
saving.Unlock()
|
||||
})
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "old-transcript", true)
|
||||
now := time.Date(2026, 10, 2, 18, 0, 0, 0, time.UTC)
|
||||
old := time.Date(2026, 8, 1, 9, 0, 0, 0, time.UTC).Unix()
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE sessions SET started_at=?, ended_at=?, last_activity_at=? WHERE id='old-transcript'`, float64(old), float64(old), float64(old)); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE messages SET timestamp=? WHERE session_id='old-transcript'`, float64(old)); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE session_model_usage SET last_seen=?, input_tokens=17 WHERE session_id='old-transcript'`, float64(now.Unix())); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
stats := StatsAt(1, now)
|
||||
if len(stats.Days) != 1 || stats.Days[0].Date != "2026-10-02" {
|
||||
t.Fatalf("today's stats should include recent auxiliary usage for an old transcript: %+v", stats)
|
||||
}
|
||||
found := false
|
||||
for _, u := range stats.Days[0].Usage {
|
||||
if u.Agent == "hermes" && u.Model == "actual-model" && u.Input == 17 {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("recent Hermes usage missing from today's stats: %+v", stats.Days[0].Usage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesOpensStateDatabaseReadOnly(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "read-only", true)
|
||||
|
||||
db, err := provider.OpenReadOnly(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec(`UPDATE sessions SET title='should not persist' WHERE id='read-only'`); err == nil {
|
||||
t.Fatal("Hermes database accepted a write through read-only connection")
|
||||
}
|
||||
var title string
|
||||
if err := db.QueryRow(`SELECT title FROM sessions WHERE id='read-only'`).Scan(&title); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if title != "A Hermes task" {
|
||||
t.Fatalf("read-only probe changed fixture title to %q", title)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func hermesTaskUsageFixture(t *testing.T, sid string, main *Tokens) string {
|
||||
t.Helper()
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", sid, true)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`ALTER TABLE session_model_usage ADD COLUMN task TEXT NOT NULL DEFAULT ''`); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`ALTER TABLE sessions ADD COLUMN billing_provider TEXT`); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE sessions SET billing_provider='session-provider' WHERE id=?`, sid); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE session_model_usage SET task='vision' WHERE session_id=?`, sid); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if main != nil {
|
||||
_, err = db.Exec(`INSERT INTO session_model_usage
|
||||
(session_id, model, billing_provider, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, api_call_count, last_seen, task)
|
||||
VALUES (?, 'main-model', 'main-provider', ?, ?, ?, ?, 2, 1, ?, '')`,
|
||||
sid, main.Input, main.Output, main.CacheRead, main.CacheWrite, float64(time.Date(2026, 9, 28, 10, 0, 12, 0, time.UTC).Unix()))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestHermesUsageAddsMainResidualWhenOnlyAuxiliaryRowsExist(t *testing.T) {
|
||||
setup(t)
|
||||
path := hermesTaskUsageFixture(t, "aux-only", nil)
|
||||
s := hermesSessionByID(t, hermesID(path, "aux-only"))
|
||||
if got := model(s, "fallback-model").Tokens; got != (Tokens{90, 30, 40, 10}) {
|
||||
t.Fatalf("main-loop residual = %+v, want sessions aggregate", got)
|
||||
}
|
||||
if got := model(s, "actual-model").Tokens; got != (Tokens{100, 50, 25, 15}) {
|
||||
t.Fatalf("auxiliary usage = %+v", got)
|
||||
}
|
||||
// Hermes does not emit Calls; verify no leakage.
|
||||
for _, c := range Calls(time.Time{}) {
|
||||
if c.Agent == "hermes" {
|
||||
t.Fatalf("unexpected Hermes call: %+v", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesUsageResidualDoesNotDuplicateCoveredOrOvercoveredMainRows(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rows []Tokens
|
||||
}{
|
||||
{
|
||||
name: "multiple main routes cover session total",
|
||||
rows: []Tokens{{Input: 50, Output: 10, CacheRead: 20, CacheWrite: 5}, {Input: 40, Output: 20, CacheRead: 20, CacheWrite: 5}},
|
||||
},
|
||||
{
|
||||
name: "main routes exceed session total",
|
||||
rows: []Tokens{{Input: 70, Output: 20, CacheRead: 30, CacheWrite: 8}, {Input: 40, Output: 20, CacheRead: 20, CacheWrite: 5}},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
setup(t)
|
||||
path := hermesTaskUsageFixture(t, "covered", nil)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, row := range tc.rows {
|
||||
_, err = db.Exec(`INSERT INTO session_model_usage
|
||||
(session_id, model, billing_provider, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, api_call_count, last_seen, task)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1, ?, '')`,
|
||||
"covered", "main-route-"+itoa(i), "provider-"+itoa(i), row.Input, row.Output, row.CacheRead, row.CacheWrite,
|
||||
float64(time.Date(2026, 9, 28, 10, 0, 12, 0, time.UTC).Unix()))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := hermesSessionByID(t, hermesID(path, "covered"))
|
||||
if got := model(s, "fallback-model").Tokens; !got.zero() {
|
||||
t.Fatalf("unexpected duplicate main residual: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesUsageResidualSubtractsMainAttributionOnly(t *testing.T) {
|
||||
setup(t)
|
||||
path := hermesTaskUsageFixture(t, "mixed", &Tokens{Input: 60, Output: 20, CacheRead: 10, CacheWrite: 5})
|
||||
s := hermesSessionByID(t, hermesID(path, "mixed"))
|
||||
if got := model(s, "main-model").Tokens; got != (Tokens{60, 20, 10, 5}) {
|
||||
t.Fatalf("main attribution = %+v", got)
|
||||
}
|
||||
if got := model(s, "fallback-model").Tokens; got != (Tokens{30, 10, 30, 5}) {
|
||||
t.Fatalf("main residual = %+v, want remaining sessions aggregate", got)
|
||||
}
|
||||
if got := model(s, "actual-model").Tokens; got != (Tokens{100, 50, 25, 15}) {
|
||||
t.Fatalf("auxiliary usage changed = %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHermesLiteralJSONText(t *testing.T) {
|
||||
for _, text := range []string{"[]", "null", `[{"name":"item"}]`, `[{"type":"text","text":"literal"}]`} {
|
||||
if got := hermesText(text); got != text {
|
||||
t.Fatalf("literal %q became %q", text, got)
|
||||
}
|
||||
}
|
||||
if got := hermesText("\x00json:" + `[{"type":"text","text":"encoded"}]`); got != "encoded" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHermesMessageVisibility(t *testing.T) {
|
||||
setup(t)
|
||||
root := filepath.Join(t.TempDir(), "hermes")
|
||||
t.Setenv("HERMES_HOME", root)
|
||||
path := hermesFixture(t, root, "", "visibility", false)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec(`ALTER TABLE messages ADD COLUMN active INTEGER DEFAULT 1;
|
||||
ALTER TABLE messages ADD COLUMN compacted INTEGER DEFAULT 0;
|
||||
UPDATE messages SET active=0 WHERE id=2;
|
||||
UPDATE messages SET active=0, compacted=1 WHERE id=1;`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := newHermesDB(db)
|
||||
var texts []string
|
||||
err = h.eachMessage(db, "visibility", func(m hermesMessage) { texts = append(texts, hermesText(m.content)) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(texts) != 3 || texts[0] != "Please inspect this" {
|
||||
t.Fatalf("visible messages: %v", texts)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,8 @@ var ErrActive = errors.New("the session was written to in the last minute; it ma
|
||||
|
||||
// Agents are the agents with sessions on this computer, by how many.
|
||||
func Agents() []AgentCount {
|
||||
dbReadMu.Lock()
|
||||
defer dbReadMu.Unlock()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
defer closeDBs()
|
||||
@@ -111,10 +113,10 @@ func ListAgent(agent string) []Managed {
|
||||
out := []Managed{}
|
||||
for _, fs := range groups {
|
||||
s, _ := assemble(fs, price)
|
||||
if s.Resume == "" {
|
||||
if s.Resume == "" && !s.ReadOnly {
|
||||
s.Resume = ResumeCommand(s.Agent, s.ID, s.Cwd)
|
||||
}
|
||||
m := Managed{Session: s, Files: len(fs), Deletable: Deletable(agent)}
|
||||
m := Managed{Session: s, Files: len(fs), Deletable: Deletable(agent) && !s.ReadOnly}
|
||||
for _, f := range fs {
|
||||
m.Size += f.size
|
||||
if st := cache[f.path]; st != nil && f.main {
|
||||
|
||||
@@ -69,13 +69,14 @@ type Model struct {
|
||||
|
||||
// Session is one agent session.
|
||||
type Session struct {
|
||||
Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, cursor
|
||||
ID string `json:"id"`
|
||||
Cwd string `json:"cwd"`
|
||||
Title string `json:"title"` // the first prompt, else the agent's own title
|
||||
Start time.Time `json:"start"`
|
||||
Last time.Time `json:"last"`
|
||||
Models []Model `json:"models"`
|
||||
ReadOnly bool `json:"read_only,omitempty"`
|
||||
Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, cursor, hermes
|
||||
ID string `json:"id"`
|
||||
Cwd string `json:"cwd"`
|
||||
Title string `json:"title"` // the first prompt, else the agent's own title
|
||||
Start time.Time `json:"start"`
|
||||
Last time.Time `json:"last"`
|
||||
Models []Model `json:"models"`
|
||||
Tokens
|
||||
Cost float64 `json:"cost"` // USD at the effective price, for the priced models
|
||||
Unpriced int `json:"unpriced"` // models that spent tokens but have no known price
|
||||
@@ -93,6 +94,7 @@ const Limit = 200
|
||||
|
||||
// state is what one file's parse has come to, enough to read on from Off.
|
||||
type state struct {
|
||||
DBRevision string `json:"db_revision,omitempty"`
|
||||
Head string `json:"head,omitempty"`
|
||||
HeadSize int `json:"head_size,omitempty"`
|
||||
ContentHash string `json:"content_hash,omitempty"`
|
||||
@@ -291,6 +293,8 @@ type file struct {
|
||||
// Cline: the session's manifest, beside its messages; Grok Build: its
|
||||
// summary.json, beside its updates
|
||||
manifest string
|
||||
hermes *hermesDB
|
||||
readOnly bool
|
||||
}
|
||||
|
||||
// ClaudeDir is Claude Code's folder: $CLAUDE_CONFIG_DIR, else ~/.claude.
|
||||
@@ -361,7 +365,7 @@ func allFiles() []file {
|
||||
var out []file
|
||||
for _, fs := range [][]file{callFiles(), openCodeFiles(), piFiles(),
|
||||
zcodeFiles(), dshFiles(), clineFiles(), ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn")),
|
||||
grokFiles(), workbuddyFiles(), ompFiles(), cursorFiles()} {
|
||||
grokFiles(), workbuddyFiles(), ompFiles(), cursorFiles(), hermesFiles()} {
|
||||
out = append(out, fs...)
|
||||
}
|
||||
return out
|
||||
@@ -388,6 +392,7 @@ func Dirs() []string {
|
||||
out = append(out, d.dir)
|
||||
}
|
||||
}
|
||||
out = append(out, HermesDirs()...)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -592,7 +597,7 @@ func writeCache(c *save) {
|
||||
func refresh(want, all []file) {
|
||||
var todo []file
|
||||
for _, f := range want {
|
||||
if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() {
|
||||
if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.hermes.revision == "" || s.DBRevision != f.hermes.revision)) {
|
||||
todo = append(todo, f)
|
||||
}
|
||||
}
|
||||
@@ -824,6 +829,9 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) {
|
||||
return filepath.Base(fs[i].path) < filepath.Base(fs[j].path)
|
||||
})
|
||||
s := Session{Agent: fs[0].agent, Path: fs[0].path, Models: []Model{}}
|
||||
for _, f := range fs {
|
||||
s.ReadOnly = s.ReadOnly || f.readOnly
|
||||
}
|
||||
s.ID = strings.TrimPrefix(fs[0].key, s.Agent+":")
|
||||
var named, first string
|
||||
models := map[string]*Model{}
|
||||
@@ -893,13 +901,17 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) {
|
||||
if s.Title == "" && s.Tokens.zero() {
|
||||
return s, false // nothing was said in it
|
||||
}
|
||||
s.Resume = ResumeCommand(s.Agent, s.ID, s.Cwd)
|
||||
if !s.ReadOnly {
|
||||
s.Resume = ResumeCommand(s.Agent, s.ID, s.Cwd)
|
||||
}
|
||||
return s, true
|
||||
}
|
||||
|
||||
// parse reads a file on from where old left it, or from the start.
|
||||
func parse(f file, old *state) *state {
|
||||
switch f.agent {
|
||||
case "hermes":
|
||||
return parseHermes(f)
|
||||
case "opencode", "zcode":
|
||||
return parseOpenCode(f)
|
||||
case "dsh":
|
||||
|
||||
@@ -46,6 +46,7 @@ func setup(t *testing.T) (claude, codex string) {
|
||||
}
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", claude)
|
||||
t.Setenv("CODEX_HOME", codex)
|
||||
t.Setenv("HERMES_HOME", filepath.Join(dir, "hermes"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
|
||||
// OpenCode and Pi keep nothing here unless a test puts it there
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data"))
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
func sessionsHome(t *testing.T) {
|
||||
t.Helper()
|
||||
h := home(t)
|
||||
t.Setenv("HERMES_HOME", filepath.Join(h, ".hermes"))
|
||||
for from, env := range map[string]string{"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME"} {
|
||||
dir := filepath.Join(h, "sessions", from)
|
||||
if err := os.CopyFS(dir, os.DirFS(filepath.Join("..", "sessions", "testdata", from))); err != nil {
|
||||
|
||||
@@ -31,6 +31,7 @@ func sessionsHome(t *testing.T) time.Time {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
t.Setenv("PI_CODING_AGENT_DIR", filepath.Join(h, ".pi", "agent"))
|
||||
|
||||
for from, env := range map[string]string{"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME"} {
|
||||
dir := filepath.Join(h, "."+from)
|
||||
if err := os.CopyFS(dir, os.DirFS(filepath.Join("internal", "sessions", "testdata", from))); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user