diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index e5ca94aa9..cecc09d8a 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -2317,9 +2317,13 @@ func forwardLast(b, key []byte) int { // without decoding the rest of it. func tsAt(b []byte, last bool) time.Time { key := []byte(`"timestamp":"`) - i := bytes.Index(b, key) + // the first is looked for only when it is the one asked: found before + // each last one too, it was ~2 s of a first start's CPU (#2278) + var i int if last { i = lastIndex(b, key) + } else { + i = bytes.Index(b, key) } if i < 0 { return time.Time{} diff --git a/internal/sessions/tsat_test.go b/internal/sessions/tsat_test.go new file mode 100644 index 000000000..ba7a2a6fd --- /dev/null +++ b/internal/sessions/tsat_test.go @@ -0,0 +1,24 @@ +package sessions + +import ( + "strings" + "testing" + "time" +) + +// A line's time is its own "timestamp", the last: a tool's result +// before it may hold another, as Claude Code writes its own after the +// message. +func TestTsAtLastIsTheLines(t *testing.T) { + inner := `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"{\"x\":1,\"y\":{\"timestamp\":\"x\"}} {"}]},"toolUseResult":{"timestamp":"2020-01-01T00:00:00Z"},` + for _, pad := range []int{0, 2000} { + b := []byte(inner + `"pad":"` + strings.Repeat("a", pad) + `","timestamp":"2026-10-31T08:00:00.123Z"}`) + want := time.Date(2026, 10, 31, 8, 0, 0, 123e6, time.UTC) + if got := tsAt(b, true); !got.Equal(want) { + t.Fatalf("pad %d: last = %v, want %v", pad, got, want) + } + if got := tsAt(b, false); !got.Equal(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)) { + t.Fatalf("pad %d: first = %v", pad, got) + } + } +}