返回 DeepSeek-Reasonix
ids.go
1 package sessioninbox
2
3 import (
4 "crypto/rand"
5 "crypto/sha256"
6 "encoding/hex"
7 "fmt"
8 "strings"
9 "sync"
10 "unicode/utf8"
11 )
12
13 var processRunID = sync.OnceValue(func() string {
14 return newRandomID()
15 })
16
17 // ProcessRunID returns a process-stable run identifier used to detect
18 // cross-process crash recovery without mistaking tab switches for crashes.
19 func ProcessRunID() string {
20 return processRunID()
21 }
22
23 func newRandomID() string {
24 var b [16]byte
25 if _, err := rand.Read(b[:]); err != nil {
26 // crypto/rand failure is exceptional; fall back to a hashed time-ish value.
27 sum := sha256.Sum256(fmt.Appendf(nil, "fallback-%p", &b))
28 return hex.EncodeToString(sum[:16])
29 }
30 // UUID-like layout without external deps: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
31 b[6] = (b[6] & 0x0f) | 0x40
32 b[8] = (b[8] & 0x3f) | 0x80
33 h := hex.EncodeToString(b[:])
34 return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]
35 }
36
37 func sha256Hex(data []byte) string {
38 sum := sha256.Sum256(data)
39 return hex.EncodeToString(sum[:])
40 }
41
42 // PreviewText returns a bounded single-line preview without materializing the
43 // whole body as []rune when unnecessary.
44 func PreviewText(text string, maxRunes int) string {
45 if maxRunes <= 0 {
46 maxRunes = DefaultPreviewRunes
47 }
48 text = strings.TrimSpace(text)
49 if text == "" {
50 return ""
51 }
52 // Collapse internal whitespace for the shelf preview.
53 var b strings.Builder
54 b.Grow(min(len(text), maxRunes*4))
55 prevSpace := false
56 count := 0
57 for i := 0; i < len(text); {
58 r, size := utf8.DecodeRuneInString(text[i:])
59 i += size
60 if r == utf8.RuneError && size == 1 {
61 continue
62 }
63 if r == '\n' || r == '\r' || r == '\t' || r == ' ' {
64 if prevSpace || count == 0 {
65 continue
66 }
67 b.WriteByte(' ')
68 prevSpace = true
69 count++
70 if count >= maxRunes {
71 break
72 }
73 continue
74 }
75 prevSpace = false
76 b.WriteRune(r)
77 count++
78 if count >= maxRunes {
79 // Peek if more content remains.
80 if i < len(text) {
81 b.WriteString("…")
82 }
83 break
84 }
85 }
86 return strings.TrimSpace(b.String())
87 }
88
88 lines GO