返回 DeepSeek-Reasonix
remote_runtime_state.go
根目录 / desktop / remote_runtime_state.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "maps"
9 "net/http"
10 "reflect"
11 "sort"
12 "sync"
13 "sync/atomic"
14 "time"
15
16 "reasonix/internal/event"
17 )
18
19 type remoteRuntimeSync struct {
20 mu sync.Mutex
21 pending bool
22 unsupported map[string]string
23 }
24
25 var remoteRuntimeDiagnostics struct {
26 stale, conflicts, failures atomic.Uint64
27 }
28
29 func validRuntimeState(state event.RuntimeStateSnapshot) bool {
30 return state.SchemaVersion == 1 && state.RuntimeEpoch != "" && state.Revision > 0 && state.BackgroundJobs >= 0 &&
31 state.DurableSeq <= state.CommittedSeq &&
32 (state.Phase == "idle" || state.Phase == "executing" || state.Phase == "finishing" || state.Phase == "cancelling" || state.Phase == "recovery_required" || state.Phase == "closed")
33 }
34
35 // acceptRemoteRuntimeStateLocked shares source ordering for GET and SSE. Host
36 // generation and route validation remain the caller's responsibility.
37 func acceptRemoteRuntimeStateLocked(tab *remoteTab, path string, next event.RuntimeStateSnapshot, authoritative bool) bool {
38 if !validRuntimeState(next) {
39 return false
40 }
41 if path == "" {
42 path = tab.routing.currentPath
43 }
44 if tab.runtimeStates == nil {
45 tab.runtimeStates = map[string]event.RuntimeStateSnapshot{}
46 }
47 previous, found := tab.runtimeStates[path]
48 if found && previous.RuntimeEpoch != next.RuntimeEpoch && !authoritative {
49 return false
50 }
51 if !found && !authoritative {
52 return false
53 }
54 if found && previous.RuntimeEpoch == next.RuntimeEpoch {
55 if next.Revision < previous.Revision {
56 slog.Debug("remote runtime stale snapshot discarded", "source", "serve", "revision", next.Revision, "stale", remoteRuntimeDiagnostics.stale.Add(1))
57 return false
58 }
59 if next.Revision == previous.Revision {
60 if !reflect.DeepEqual(previous, next) {
61 slog.Warn("remote runtime snapshot version conflict", "source", "serve", "revision", next.Revision, "conflicts", remoteRuntimeDiagnostics.conflicts.Add(1))
62 return false
63 }
64 if !authoritative || tab.runtimeUnknown[path] == 0 {
65 return false
66 }
67 }
68 }
69 tab.runtimeStates[path] = next
70 tab.runtime.syncFailed = false
71 delete(tab.runtimeUnknown, path)
72 delete(tab.runtimeConflicts, path)
73 if path == tab.routing.currentPath {
74 tab.runtime.snapshot = next
75 tab.runtime.running, tab.runtime.pendingPrompt = next.Running, next.PendingPrompt
76 tab.runtime.backgroundJobs, tab.runtime.cancellable, tab.runtime.cancelRequested = next.BackgroundJobs, next.Cancellable, next.CancelRequested
77 }
78 if tab.routing.running == nil {
79 tab.routing.running = map[string]bool{}
80 }
81 tab.routing.running[path] = next.ActiveWork()
82 tab.runtime.revision++
83 return true
84 }
85
86 func (a *App) acceptRemoteRuntimeFrame(tabID string, gen uint64, path string, frame json.RawMessage) {
87 var payload struct {
88 State json.RawMessage `json:"runtimeState"`
89 }
90 if json.Unmarshal(frame, &payload) != nil || len(payload.State) == 0 {
91 return
92 }
93 state, decodeErr := decodeRemoteRuntimeState(payload.State)
94 // Older Serve frames omit envelope identity while retaining it in the
95 // runtime snapshot. Never attribute a background result to the foreground.
96 if decodeErr == nil && state.SessionID != "" {
97 path = remoteSessionIdentityRoute("", state.SessionID)
98 }
99 a.remoteTabMu.Lock()
100 tab := a.remoteTabs[tabID]
101 a.remoteTabMu.Unlock()
102 if tab == nil {
103 return
104 }
105 tab.routeEventMu.Lock()
106 defer tab.routeEventMu.Unlock()
107 a.remoteTabMu.Lock()
108 if a.remoteTabs[tabID] != tab || tab.gen != gen {
109 a.remoteTabMu.Unlock()
110 return
111 }
112 if path == "" {
113 path = tab.routing.currentPath
114 }
115 if decodeErr != nil {
116 markRemoteRuntimeUnknownLocked(tab, path)
117 a.remoteTabMu.Unlock()
118 a.emitRuntimeStateChanged()
119 a.goRemoteTabSafe("remoteRuntimeSync", func() { _, _ = a.SyncRuntimeState() })
120 return
121 }
122 previous, found := tab.runtimeStates[path]
123 resync := !found || previous.RuntimeEpoch != state.RuntimeEpoch || (previous.Revision == state.Revision && !reflect.DeepEqual(previous, state))
124 if resync {
125 if reflect.DeepEqual(tab.runtimeConflicts[path], state) {
126 resync = false
127 } else {
128 if tab.runtimeConflicts == nil {
129 tab.runtimeConflicts = map[string]event.RuntimeStateSnapshot{}
130 }
131 tab.runtimeConflicts[path] = state
132 }
133 }
134 changed := acceptRemoteRuntimeStateLocked(tab, path, state, false)
135 meta := remoteTabMetaLocked(tab)
136 a.remoteTabMu.Unlock()
137 if changed {
138 a.emitRemoteEvent("remote-tab:updated", meta)
139 a.emitRuntimeStateChanged()
140 } else if resync {
141 a.goRemoteTabSafe("remoteRuntimeSync", func() { _, _ = a.SyncRuntimeState() })
142 }
143 }
144
145 type remoteRuntimeTarget struct {
146 id string
147 gen, selection uint64
148 client *http.Client
149 states map[string]event.RuntimeStateSnapshot
150 unknown map[string]uint64
151 // pathRevision fences a payload observed before a session switch: it cannot
152 // speak for the route the tab shows now.
153 pathRevision uint64
154 }
155 type remoteRuntimeConnection struct {
156 id, key, base string
157 client *http.Client
158 targets []remoteRuntimeTarget
159 }
160
161 // SyncRuntimeState reconciles each Serve connection once, regardless of how
162 // many tabs it owns. It is separate from the memory-only snapshot getter.
163 func (a *App) SyncRuntimeState() (RuntimeStateProjection, error) {
164 syncer := &a.remoteRuntimeSync
165 syncer.mu.Lock()
166 if syncer.pending {
167 syncer.mu.Unlock()
168 return a.GetRuntimeStateSnapshot(), nil
169 }
170 syncer.pending = true
171 if syncer.unsupported == nil {
172 syncer.unsupported = map[string]string{}
173 }
174 syncer.mu.Unlock()
175 defer func() { syncer.mu.Lock(); syncer.pending = false; syncer.mu.Unlock() }()
176 connections := map[string]remoteRuntimeConnection{}
177 a.remoteTabMu.Lock()
178 for id, tab := range a.remoteTabs {
179 if tab.client == nil || tab.state != "ready" {
180 continue
181 }
182 key := fmt.Sprintf("%s\x00%s\x00%s", tab.ref.HostID, tab.ref.Workspace, tab.base)
183 conn := connections[key]
184 conn.id, conn.key, conn.base, conn.client = id, key, tab.base, tab.client
185 states := map[string]event.RuntimeStateSnapshot{}
186 maps.Copy(states, tab.runtimeStates)
187 conn.targets = append(conn.targets, remoteRuntimeTarget{
188 id: id, gen: tab.gen, selection: tab.selectionRevision, client: tab.client,
189 states: states, unknown: maps.Clone(tab.runtimeUnknown), pathRevision: tab.routing.pathRevision,
190 })
191 connections[key] = conn
192 }
193 a.remoteTabMu.Unlock()
194 var firstErr error
195
196 for _, conn := range connections {
197 if err := a.syncRemoteRuntimeConnection(conn); err != nil && firstErr == nil {
198 firstErr = err
199 }
200 }
201 if firstErr != nil {
202 slog.Warn("remote runtime synchronization failed", "source", "serve", "reason", "reconcile", "connections", len(connections), "failures", remoteRuntimeDiagnostics.failures.Add(1))
203 }
204 a.emitRuntimeStateChanged()
205 return a.GetRuntimeStateSnapshot(), firstErr
206 }
207
208 func (a *App) markRemoteRuntimeSyncFailed(targets []remoteRuntimeTarget, failed bool) {
209 a.remoteTabMu.Lock()
210 defer a.remoteTabMu.Unlock()
211 for _, target := range targets {
212 if tab := a.remoteTabs[target.id]; tab != nil && tab.gen == target.gen && tab.client == target.client && tab.selectionRevision == target.selection && tab.routing.pathRevision == target.pathRevision && tab.routing.rehydratingPath == "" {
213 tab.runtime.syncFailed = failed
214 if failed {
215 markRemoteRuntimeUnknownLocked(tab, tab.routing.currentPath)
216 for path := range tab.runtimeStates {
217 markRemoteRuntimeUnknownLocked(tab, path)
218 }
219 }
220 }
221 }
222 }
223
224 func (a *App) syncRemoteRuntimeConnection(conn remoteRuntimeConnection) error {
225 syncer := &a.remoteRuntimeSync
226 sort.Slice(conn.targets, func(i, j int) bool { return conn.targets[i].id < conn.targets[j].id })
227 first := conn.targets[0]
228 capabilityKey := fmt.Sprintf("%s\x00%s\x00%d\x00%p", conn.key, first.id, first.gen, first.client)
229 syncer.mu.Lock()
230 unsupported := syncer.unsupported[conn.key] == capabilityKey
231 syncer.mu.Unlock()
232 if unsupported {
233 _, err := a.RemoteTabStatus(conn.id)
234 a.markRemoteRuntimeSyncFailed(conn.targets, err != nil)
235 return err
236 }
237 ctx, cancel := context.WithTimeout(a.bootContext(), 5*time.Second)
238 req, err := http.NewRequestWithContext(ctx, http.MethodGet, serveURL(conn.base, "/runtime-states"), nil)
239 if err != nil {
240 cancel()
241 a.markRemoteRuntimeSyncFailed(conn.targets, true)
242 return err
243 }
244 resp, err := conn.client.Do(req)
245 if err != nil {
246 cancel()
247 a.markRemoteRuntimeSyncFailed(conn.targets, true)
248 return err
249 }
250 if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusNotImplemented {
251 resp.Body.Close()
252 cancel()
253 syncer.mu.Lock()
254 syncer.unsupported[conn.key] = capabilityKey
255 syncer.mu.Unlock()
256 _, err := a.RemoteTabStatus(conn.id)
257 a.markRemoteRuntimeSyncFailed(conn.targets, err != nil)
258 return err
259 }
260 var payload struct {
261 SchemaVersion int `json:"schemaVersion"`
262 Sessions []struct {
263 SessionPath string `json:"sessionPath"`
264 State json.RawMessage `json:"state"`
265 } `json:"sessions"`
266 }
267 err = json.NewDecoder(http.MaxBytesReader(nil, resp.Body, 4<<20)).Decode(&payload)
268 resp.Body.Close()
269 cancel()
270 if err != nil || resp.StatusCode != http.StatusOK || payload.SchemaVersion != 1 || payload.Sessions == nil {
271 a.markRemoteRuntimeSyncFailed(conn.targets, true)
272 return fmt.Errorf("runtime state synchronization failed")
273 }
274 states := make(map[string]event.RuntimeStateSnapshot, len(payload.Sessions))
275 for _, session := range payload.Sessions {
276 state, decodeErr := decodeRemoteRuntimeState(session.State)
277 // Identity runtimes from older Serve versions have no legacy path.
278 // Resolve their durable identity before validation and missing-row checks.
279 if state.SessionID != "" {
280 session.SessionPath = remoteSessionIdentityRoute("", state.SessionID)
281 }
282 _, duplicate := states[session.SessionPath]
283 if decodeErr != nil || duplicate {
284 a.markRemoteRuntimeSyncFailed(conn.targets, true)
285 return fmt.Errorf("invalid runtime state synchronization payload")
286 }
287 if session.SessionPath == "" {
288 // An identity session a Serve has not routed yet reports no legacy
289 // path; skip it instead of failing the whole reconciliation.
290 continue
291 }
292 states[session.SessionPath] = state
293 }
294 a.applyRemoteRuntimeSnapshot(conn, states)
295 return nil
296 }
297
298 func (a *App) applyRemoteRuntimeSnapshot(conn remoteRuntimeConnection, states map[string]event.RuntimeStateSnapshot) {
299 a.remoteTabMu.Lock()
300 defer a.remoteTabMu.Unlock()
301 for _, target := range conn.targets {
302 tab := a.remoteTabs[target.id]
303 if tab == nil || tab.base != conn.base || tab.gen != target.gen || tab.client != target.client || tab.selectionRevision != target.selection || tab.routing.pathRevision != target.pathRevision || tab.routing.rehydratingPath != "" {
304 continue
305 }
306 tab.runtime.syncFailed = false
307 seen := map[string]bool{}
308 for path, state := range states {
309 seen[path] = true
310 // A failure or malformed frame observed after this GET started
311 // requires a fresh request, even when the cached facts are unchanged.
312 if tab.runtimeUnknown[path] != target.unknown[path] {
313 continue
314 }
315 previous := tab.runtimeStates[path]
316 // A GET can establish an epoch only if no newer source update
317 // has changed this binding while it was in flight.
318 if previous.RuntimeEpoch != state.RuntimeEpoch && !reflect.DeepEqual(previous, target.states[path]) {
319 continue
320 }
321 acceptRemoteRuntimeStateLocked(tab, path, state, true)
322 }
323 // Only a request for this route can retire background rows or declare the
324 // selected session missing. The route fence above also applies to
325 // success/failure flags, so an old GET cannot poison a newer SSE state.
326 if !seen[tab.routing.currentPath] && reflect.DeepEqual(tab.runtimeStates[tab.routing.currentPath], target.states[tab.routing.currentPath]) {
327 markRemoteRuntimeUnknownLocked(tab, tab.routing.currentPath)
328 }
329 for path, state := range tab.runtimeStates {
330 if !seen[path] && path != tab.routing.currentPath && reflect.DeepEqual(state, target.states[path]) && tab.runtimeUnknown[path] == target.unknown[path] {
331 delete(tab.runtimeStates, path)
332 delete(tab.runtimeUnknown, path)
333 delete(tab.routing.running, path)
334 }
335 }
336 }
337 }
338
339 func markRemoteRuntimeUnknownLocked(tab *remoteTab, path string) {
340 if tab.runtimeUnknown == nil {
341 tab.runtimeUnknown = map[string]uint64{}
342 }
343 tab.runtime.revision++
344 tab.runtimeUnknown[path] = tab.runtime.revision
345 }
346
346 lines GO