返回 DeepSeek-Reasonix
sessions_http.go
根目录 / internal / serve / sessions_http.go
1 package serve
2
3 import (
4 "encoding/json"
5 "net/http"
6 "os"
7 "path/filepath"
8 "sort"
9 "strings"
10
11 "reasonix/internal/agent"
12 "reasonix/internal/control"
13 "reasonix/internal/session"
14 "reasonix/internal/store"
15 )
16
17 type sessionListEntry struct {
18 HostID string `json:"hostId,omitempty"`
19 SessionID string `json:"sessionId,omitempty"`
20 Name string `json:"name"`
21 Path string `json:"path"`
22 Title string `json:"title,omitempty"`
23 Turns int `json:"turns,omitempty"`
24 Current bool `json:"current,omitempty"`
25 Running bool `json:"running,omitempty"`
26 TakenOver bool `json:"takenOver,omitempty"`
27 MtimeMilli int64 `json:"mtimeMilli"`
28
29 Preview string `json:"preview,omitempty"`
30 MetadataReady bool `json:"metadataReady,omitempty"`
31 // A pointer distinguishes a supported zero baseline from legacy listings.
32 ResultSequence *uint64 `json:"resultSequence,omitempty"`
33 }
34
35 // sessions lists saved sessions with event-log-aware titles and turn counts.
36 func (s *Server) sessions(w http.ResponseWriter, r *http.Request) {
37 ctrl := s.ctl()
38 entries, ok := readSessionDir(ctrl.SessionDir())
39 if !ok {
40 writeJSON(w, []any{})
41 return
42 }
43 out := mergeSessionRows(s.legacySessionRows(r, ctrl, entries))
44 sort.SliceStable(out, func(i, j int) bool { return out[i].MtimeMilli > out[j].MtimeMilli })
45 writeJSON(w, out)
46 }
47
48 // readSessionDir reports ok=false only when the directory exists but cannot be
49 // read; a missing directory is an empty session list, not a failure.
50 func readSessionDir(dir string) ([]os.DirEntry, bool) {
51 if dir == "" {
52 return nil, true
53 }
54 entries, err := os.ReadDir(dir)
55 switch {
56 case os.IsNotExist(err):
57 return nil, true
58 case err != nil:
59 return nil, false
60 }
61 return entries, true
62 }
63
64 // legacySessionRows builds one row per .jsonl transcript plus the same rows
65 // keyed by canonical path, which is how a canonical row later finds the
66 // migrated source whose title and turn count it borrows.
67 func (s *Server) legacySessionRows(r *http.Request, ctrl control.SessionAPI, entries []os.DirEntry) ([]sessionListEntry, map[string]sessionListEntry, []canonicalSessionRow) {
68 dir := ctrl.SessionDir()
69 current := agent.CanonicalSessionPath(ctrl.SessionPath())
70 running := s.detachedRuntimeWork()
71 rows := make([]sessionListEntry, 0, len(entries))
72 byPath := make(map[string]sessionListEntry, len(entries))
73 for _, entry := range entries {
74 if entry.IsDir() || !store.IsSessionTranscriptName(entry.Name()) {
75 continue
76 }
77 path := agent.CanonicalSessionPath(filepath.Join(dir, entry.Name()))
78 if agent.IsCleanupPending(path) {
79 continue
80 }
81 mtime := agent.SessionContentModTime(path)
82 cleanPath := agent.CanonicalSessionPath(path)
83 row := sessionListEntry{
84 Name: strings.TrimSuffix(entry.Name(), ".jsonl"),
85 Path: path,
86 Current: cleanPath == current,
87 Running: running[cleanPath],
88 TakenOver: s.sessionMirrored(cleanPath) || leaseHeldByForeignRuntime(cleanPath),
89 MtimeMilli: mtime.UnixMilli(),
90 }
91 if row.Current {
92 row.Running = controllerHasActiveRuntimeWork(ctrl) && !row.TakenOver
93 }
94 first, turns, cached := agent.SessionPreviewCached(path)
95 if !cached {
96 first, turns = agent.SessionPreview(path)
97 }
98 if turns > 0 {
99 row.Turns = turns
100 row.Title = s.sessionTitle(r.Context(), entry.Name(), first, mtime.UnixNano())
101 }
102 rows = append(rows, row)
103 byPath[cleanPath] = row
104 }
105 return rows, byPath, s.canonicalSessionRows(r, ctrl)
106 }
107
108 func (s *Server) detachedRuntimeWork() map[string]bool {
109 running := map[string]bool{}
110 s.detachedMu.Lock()
111 defer s.detachedMu.Unlock()
112 for path, detached := range s.detached {
113 running[filepath.Clean(path)] = controllerHasActiveRuntimeWork(detached.ctrl)
114 }
115 return running
116 }
117
118 // canonicalSessionRows follows the catalog cursor to the end. One List call
119 // caps at 100 rows ordered by the random session id, so a workspace past 100
120 // sessions would otherwise hide an arbitrary subset — including a session just
121 // taken over. The row bound keeps a broken cursor from looping forever.
122 func (s *Server) canonicalSessionRows(r *http.Request, ctrl control.SessionAPI) []canonicalSessionRow {
123 rows := make([]canonicalSessionRow, 0)
124 concrete, ok := ctrl.(*control.Controller)
125 if !ok {
126 return rows
127 }
128 service := concrete.SessionService()
129 if service == nil {
130 return rows
131 }
132 _, runtime, bound := concrete.SessionBinding()
133 const pageLimit = 100
134 const maxCanonicalRows = 500
135 cursor := ""
136 for pages := 1; ; pages++ {
137 page, err := service.Query().List(r.Context(), cursor, pageLimit)
138 if err != nil {
139 break
140 }
141 if len(rows) == 0 {
142 rows = make([]canonicalSessionRow, 0, len(page.Sessions))
143 }
144 for _, info := range page.Sessions {
145 resultSequence := info.ResultSequence
146 row := sessionListEntry{
147 HostID: info.Ref.HostID, SessionID: info.Ref.SessionID, Name: info.SessionID,
148 Title: info.Title, Turns: info.Turns, MtimeMilli: info.CreatedAt.UnixMilli(),
149 Current: bound && info.Ref == runtime.Ref(),
150 Preview: info.Preview,
151 MetadataReady: info.MetadataStatus == session.MetadataReady,
152 ResultSequence: &resultSequence,
153 TakenOver: s.sessionMirrored(remoteSessionIDQueryPrefix + info.Ref.SessionID),
154 }
155 // Canonical rows carry no legacy preview fallback, so a chatted
156 // session would list as untitled until the model renames it.
157 if strings.TrimSpace(row.Title) == "" && strings.TrimSpace(info.Preview) != "" {
158 row.Title = truncatedPreview(info.Preview)
159 }
160 if live, exists := service.Runtime(info.Ref); exists {
161 row.Running = live.Snapshot().Phase.Busy()
162 }
163 rows = append(rows, canonicalSessionRow{row: row, info: info})
164 }
165 if page.NextCursor == "" || page.NextCursor == cursor || pages*pageLimit >= maxCanonicalRows || len(rows) >= maxCanonicalRows {
166 break
167 }
168 cursor = page.NextCursor
169 }
170 return rows
171 }
172
173 // truncatedPreview clamps a catalog preview the way previewTitle clamps a
174 // transcript's first message. Catalog previews are already plain user text, so
175 // they need no paste-label stripping.
176 func truncatedPreview(preview string) string {
177 preview = strings.TrimSpace(preview)
178 if r := []rune(preview); len(r) > 50 {
179 return string(r[:47]) + "..."
180 }
181 return preview
182 }
183
184 // mergeSessionRows produces the user-visible list from both catalogs.
185 //
186 // Migration deliberately preserves the old transcript, so a host can contain
187 // both the source .jsonl and its canonical session directory. The source is not
188 // a second user-visible session once the migration map proves there is exactly
189 // one canonical target for it; the canonical row stays the authoritative
190 // open/delete identity and borrows the old preview title until its asynchronous
191 // catalog metadata is ready.
192 func mergeSessionRows(legacyRows []sessionListEntry, legacyByPath map[string]sessionListEntry, canonicalRows []canonicalSessionRow) []sessionListEntry {
193 migration := migrationIndexFor(canonicalRows)
194 // The engine mirrors an in-flight legacy transcript into a final-format
195 // event log keyed by the legacy branch id. That mirror is plumbing, not a
196 // second conversation, except when it is the current row's own tree badge.
197 legacyBranchIDs := make(map[string]struct{}, len(legacyByPath))
198 for path := range legacyByPath {
199 legacyBranchIDs[agent.BranchID(path)] = struct{}{}
200 }
201 out := make([]sessionListEntry, 0, len(legacyRows)+len(canonicalRows))
202 for _, row := range legacyRows {
203 if _, migrated := migration.bySource[agent.CanonicalSessionPath(row.Path)]; migrated {
204 continue
205 }
206 out = append(out, row)
207 }
208 for i := range canonicalRows {
209 row := &canonicalRows[i].row
210 if !row.Current {
211 if _, mirrored := legacyBranchIDs[row.SessionID]; mirrored {
212 continue
213 }
214 }
215 if source, ok := migration.byTarget[row.SessionID]; ok {
216 inheritLegacyRow(row, legacyByPath[source])
217 }
218 out = append(out, *row)
219 }
220 return out
221 }
222
223 func inheritLegacyRow(row *sessionListEntry, legacy sessionListEntry) {
224 if row.Title == "" {
225 row.Title = legacy.Title
226 }
227 if row.Turns == 0 {
228 row.Turns = legacy.Turns
229 }
230 if row.MtimeMilli < legacy.MtimeMilli {
231 row.MtimeMilli = legacy.MtimeMilli
232 }
233 }
234
235 func migrationIndexFor(canonicalRows []canonicalSessionRow) migrationSourceIndex {
236 canonicalIDs := make(map[string]struct{}, len(canonicalRows))
237 roots := make(map[string]struct{})
238 for _, row := range canonicalRows {
239 if row.row.SessionID != "" {
240 canonicalIDs[row.row.SessionID] = struct{}{}
241 }
242 if path := strings.TrimSpace(row.info.Path); path != "" {
243 roots[filepath.Dir(filepath.Clean(path))] = struct{}{}
244 }
245 }
246 return loadMigrationIndex(roots, func(targetID string) bool {
247 _, exists := canonicalIDs[targetID]
248 return exists
249 })
250 }
251
252 type canonicalSessionRow struct {
253 row sessionListEntry
254 info session.SessionInfo
255 }
256
257 // migrationSourceIndex is the one rule for when a frozen legacy transcript is
258 // hidden behind its canonical row. Listing consults it to fold the source out
259 // of /sessions; deletion consults it to decide whether removing a canonical row
260 // may also remove the source. Both answers must agree, or a delete can remove a
261 // transcript the listing still shows as a distinct session.
262 type migrationSourceIndex struct {
263 bySource map[string]struct{}
264 byTarget map[string]string
265 }
266
267 // loadMigrationIndex reads the migration maps under roots and keeps only
268 // unambiguous source->target mappings. Multiple canonical targets can
269 // legitimately be produced from one legacy DAG head, in which case hiding or
270 // deleting the source would remove a still-distinct view. exists reports
271 // whether a target id is a live canonical row; targets that are gone do not
272 // count, so a source whose other targets were already deleted is again the
273 // sole source of the remaining one.
274 func loadMigrationIndex(roots map[string]struct{}, exists func(targetID string) bool) migrationSourceIndex {
275 index := migrationSourceIndex{bySource: map[string]struct{}{}, byTarget: map[string]string{}}
276 targetsBySource := make(map[string][]string)
277 for root := range roots {
278 data, err := os.ReadFile(filepath.Join(root, "migration-map.json"))
279 if err != nil {
280 continue
281 }
282 var mapping session.MigrationMapping
283 if json.Unmarshal(data, &mapping) != nil || mapping.SchemaVersion != session.SchemaVersion {
284 continue
285 }
286 for _, entry := range mapping.Entries {
287 source := agent.CanonicalSessionPath(entry.SourcePath)
288 target := strings.TrimSpace(entry.TargetID)
289 if source == "" || target == "" || !exists(target) {
290 continue
291 }
292 seen := false
293 for _, existing := range targetsBySource[source] {
294 seen = seen || existing == target
295 }
296 if !seen {
297 targetsBySource[source] = append(targetsBySource[source], target)
298 }
299 }
300 }
301 for source, targets := range targetsBySource {
302 if len(targets) != 1 {
303 continue
304 }
305 index.bySource[source] = struct{}{}
306 index.byTarget[targets[0]] = source
307 }
308 return index
309 }
310
310 lines GO