fix(coderd): truncate task prompt to 160 characters in notifications (#20147)

Truncates the task prompt used in notifications to a maximum of 160
characters. The length of 160 characters was chosen arbitrarily.
This commit is contained in:
Cian Johnston
2025-10-02 19:54:07 +01:00
committed by GitHub
parent 4d1003eace
commit ffcb7a1693
4 changed files with 123 additions and 13 deletions
+52 -3
View File
@@ -23,15 +23,64 @@ func JoinWithConjunction(s []string) string {
)
}
// Truncate returns the first n characters of s.
func Truncate(s string, n int) string {
type TruncateOption int
func (o TruncateOption) String() string {
switch o {
case TruncateWithEllipsis:
return "TruncateWithEllipsis"
case TruncateWithFullWords:
return "TruncateWithFullWords"
default:
return fmt.Sprintf("TruncateOption(%d)", o)
}
}
const (
// TruncateWithEllipsis adds a Unicode ellipsis character to the end of the string.
TruncateWithEllipsis TruncateOption = 1 << 0
// TruncateWithFullWords ensures that words are not split in the middle.
// As a special case, if there is no word boundary, the string is truncated.
TruncateWithFullWords TruncateOption = 1 << 1
)
// Truncate truncates s to n characters.
// Additional behaviors can be specified using TruncateOptions.
func Truncate(s string, n int, opts ...TruncateOption) string {
var options TruncateOption
for _, opt := range opts {
options |= opt
}
if n < 1 {
return ""
}
if len(s) <= n {
return s
}
return s[:n]
maxLen := n
if options&TruncateWithEllipsis != 0 {
maxLen--
}
var sb strings.Builder
// If we need to truncate to full words, find the last word boundary before n.
if options&TruncateWithFullWords != 0 {
lastWordBoundary := strings.LastIndexFunc(s[:maxLen], unicode.IsSpace)
if lastWordBoundary < 0 {
// We cannot find a word boundary. At this point, we'll truncate the string.
// It's better than nothing.
_, _ = sb.WriteString(s[:maxLen])
} else { // lastWordBoundary <= maxLen
_, _ = sb.WriteString(s[:lastWordBoundary])
}
} else {
_, _ = sb.WriteString(s[:maxLen])
}
if options&TruncateWithEllipsis != 0 {
_, _ = sb.WriteString("…")
}
return sb.String()
}
var bmPolicy = bluemonday.StrictPolicy()