| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "maps" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/http/cookiejar" |
| 13 | "net/url" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "reasonix/internal/servecontract" |
| 18 | ) |
| 19 | |
| 20 | const ( |
| 21 | serveSnapshotMaxBytes = 32 << 20 |
| 22 | serveSessionsMaxBytes = 8 << 20 |
| 23 | serveEventMaxBytes = 8 << 20 |
| 24 | ) |
| 25 | |
| 26 | // This listing-only bridge lets project groups show sessions before the full |
| 27 | // remote-tab attach and event-pump surface lands. |
| 28 | |
| 29 | // serveSessionEntry mirrors one GET /sessions row from the Serve. |
| 30 | type serveSessionEntry struct { |
| 31 | HostID string `json:"hostId"` |
| 32 | SessionID string `json:"sessionId"` |
| 33 | Name string `json:"name"` |
| 34 | Path string `json:"path"` |
| 35 | Title string `json:"title"` |
| 36 | Turns int `json:"turns"` |
| 37 | Current bool `json:"current"` |
| 38 | Running bool `json:"running"` |
| 39 | TakenOver bool `json:"takenOver,omitempty"` |
| 40 | MtimeMilli int64 `json:"mtimeMilli"` |
| 41 | |
| 42 | Preview string `json:"preview,omitempty"` |
| 43 | MetadataReady bool `json:"metadataReady,omitempty"` |
| 44 | ResultSequence *uint64 `json:"resultSequence,omitempty"` |
| 45 | } |
| 46 | |
| 47 | type serveHTTPStatusError struct { |
| 48 | data map[string]any |
| 49 | url string |
| 50 | statusCode int |
| 51 | message string |
| 52 | } |
| 53 | |
| 54 | func (e *serveHTTPStatusError) RPCErrorData() map[string]any { return e.data } |
| 55 | |
| 56 | func (e *serveHTTPStatusError) Error() string { |
| 57 | if e.message != "" { |
| 58 | return fmt.Sprintf("%s: status %d: %s", e.url, e.statusCode, e.message) |
| 59 | } |
| 60 | return fmt.Sprintf("%s: status %d", e.url, e.statusCode) |
| 61 | } |
| 62 | |
| 63 | // RemoteSessionView mirrors one serve /sessions entry on the frontend side. |
| 64 | type RemoteSessionView struct { |
| 65 | HostID string `json:"hostId,omitempty"` |
| 66 | SessionID string `json:"sessionId,omitempty"` |
| 67 | Name string `json:"name"` |
| 68 | Path string `json:"path,omitempty"` |
| 69 | Title string `json:"title,omitempty"` |
| 70 | Turns int `json:"turns,omitempty"` |
| 71 | Current bool `json:"current,omitempty"` |
| 72 | Running bool `json:"running,omitempty"` |
| 73 | LastActivityAt int64 `json:"lastActivityAt,omitempty"` |
| 74 | ResultSequence *uint64 `json:"resultSequence,omitempty"` |
| 75 | MetadataReady bool `json:"metadataReady,omitempty"` |
| 76 | Pinned bool `json:"pinned,omitempty"` |
| 77 | } |
| 78 | |
| 79 | // serveURL joins a serve base URL and an API path. |
| 80 | func serveURL(base, path string) string { |
| 81 | return strings.TrimRight(base, "/") + path |
| 82 | } |
| 83 | |
| 84 | func newServeHTTPClient(base string) (*http.Client, error) { |
| 85 | parsed, err := url.Parse(strings.TrimSpace(base)) |
| 86 | if err != nil { |
| 87 | return nil, fmt.Errorf("invalid remote serve URL: %w", err) |
| 88 | } |
| 89 | ip := net.ParseIP(parsed.Hostname()) |
| 90 | if parsed.Scheme != "http" || ip == nil || !ip.IsLoopback() || parsed.User != nil { |
| 91 | return nil, fmt.Errorf("remote serve URL must use loopback HTTP") |
| 92 | } |
| 93 | jar, err := cookiejar.New(nil) |
| 94 | if err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | transport := http.DefaultTransport.(*http.Transport).Clone() |
| 98 | transport.Proxy = nil |
| 99 | return &http.Client{ |
| 100 | Jar: jar, |
| 101 | Transport: transport, |
| 102 | CheckRedirect: func(*http.Request, []*http.Request) error { |
| 103 | return http.ErrUseLastResponse |
| 104 | }, |
| 105 | }, nil |
| 106 | } |
| 107 | |
| 108 | // servePost keeps the bounded response text in failures so remote lease and |
| 109 | // busy-state hints reach the desktop surface. |
| 110 | func servePost(ctx context.Context, client *http.Client, url string, body []byte) error { |
| 111 | _, err := servePostSessionPath(ctx, client, url, body) |
| 112 | return err |
| 113 | } |
| 114 | |
| 115 | const expectedSessionPathHeader = "X-Reasonix-Expected-Session-Path" |
| 116 | const expectedSessionIDHeader = "X-Reasonix-Expected-Session-ID" |
| 117 | const expectedModelSettingsHeader = "X-Reasonix-Expected-Model-Settings" |
| 118 | const remoteSessionIDRoutePrefix = "session-id:" |
| 119 | |
| 120 | func remoteSessionIdentityRoute(path, sessionID string) string { |
| 121 | // A session the Serve migrated into the identity catalog keeps its legacy |
| 122 | // path only as a read-only artifact; the identity is the live route. |
| 123 | if sessionID = strings.TrimSpace(sessionID); sessionID != "" { |
| 124 | return remoteSessionIDRoutePrefix + sessionID |
| 125 | } |
| 126 | if path = strings.TrimSpace(path); path != "" { |
| 127 | return path |
| 128 | } |
| 129 | return "" |
| 130 | } |
| 131 | |
| 132 | func remoteSessionRoute(entry serveSessionEntry) string { |
| 133 | return remoteSessionIdentityRoute(entry.Path, entry.SessionID) |
| 134 | } |
| 135 | |
| 136 | // remoteSessionRouteIdentity inverts remoteSessionIdentityRoute: rows built |
| 137 | // from a live route must expose an identity route as SessionID, never as a |
| 138 | // path, or resuming the row sends Serve a filesystem path it cannot resolve. |
| 139 | func remoteSessionRouteIdentity(route string) (path, sessionID string) { |
| 140 | if id, ok := strings.CutPrefix(route, remoteSessionIDRoutePrefix); ok { |
| 141 | return "", id |
| 142 | } |
| 143 | return route, "" |
| 144 | } |
| 145 | |
| 146 | // servePostForSession fences a foreground mutation to the session the Desktop |
| 147 | // tab displayed when the command was issued. Older Serve binaries ignore the |
| 148 | // optional header and retain their single-session behavior. |
| 149 | func servePostForSession(ctx context.Context, client *http.Client, url string, body []byte, expectedPath string, modelRevision ...string) error { |
| 150 | if body == nil { |
| 151 | body = []byte("{}") |
| 152 | } |
| 153 | resp, err := serveDoForSession(ctx, client, http.MethodPost, url, body, expectedPath, modelRevision...) |
| 154 | if err != nil { |
| 155 | return err |
| 156 | } |
| 157 | defer resp.Body.Close() |
| 158 | data, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) |
| 159 | if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| 160 | return nil |
| 161 | } |
| 162 | var detail struct { |
| 163 | Message string `json:"message"` |
| 164 | Data map[string]any `json:"data"` |
| 165 | } |
| 166 | _ = json.Unmarshal(data, &detail) |
| 167 | message := strings.TrimSpace(string(data)) |
| 168 | if detail.Message != "" { |
| 169 | message = detail.Message |
| 170 | } |
| 171 | return &serveHTTPStatusError{ |
| 172 | data: detail.Data, |
| 173 | url: url, statusCode: resp.StatusCode, message: message, |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // servePostSessionPath preserves the ordinary 2xx contract while reading the |
| 178 | // optional path header returned by session-rotation endpoints. Older Serve |
| 179 | // binaries omit it and keep their legacy untagged single-session behavior. |
| 180 | func servePostSessionPath(ctx context.Context, client *http.Client, url string, body []byte) (string, error) { |
| 181 | identity, err := servePostSessionIdentityForSession(ctx, client, url, body, "") |
| 182 | return identity.Path, err |
| 183 | } |
| 184 | |
| 185 | type serveSessionIdentity struct { |
| 186 | Path string |
| 187 | SessionID string |
| 188 | TakenOver bool |
| 189 | } |
| 190 | |
| 191 | const sessionTakenOverHeader = "X-Reasonix-Taken-Over" |
| 192 | |
| 193 | func servePostSessionIdentityForSession(ctx context.Context, client *http.Client, url string, body []byte, expectedPath string) (serveSessionIdentity, error) { |
| 194 | if body == nil { |
| 195 | body = []byte("{}") |
| 196 | } |
| 197 | if strings.HasSuffix(strings.TrimRight(url, "/"), "/resume") { |
| 198 | var request struct { |
| 199 | Path string `json:"path"` |
| 200 | SessionID string `json:"sessionId"` |
| 201 | } |
| 202 | if err := json.Unmarshal(body, &request); err != nil { |
| 203 | return serveSessionIdentity{}, fmt.Errorf("invalid remote resume request: %w", err) |
| 204 | } |
| 205 | if strings.TrimSpace(request.Path) == "" && strings.TrimSpace(request.SessionID) == "" { |
| 206 | return serveSessionIdentity{}, fmt.Errorf("remote resume requires a session path or sessionId") |
| 207 | } |
| 208 | } |
| 209 | resp, err := serveDoForSession(ctx, client, http.MethodPost, url, body, expectedPath) |
| 210 | if err != nil { |
| 211 | return serveSessionIdentity{}, err |
| 212 | } |
| 213 | defer resp.Body.Close() |
| 214 | data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) |
| 215 | if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| 216 | return serveSessionIdentity{ |
| 217 | Path: strings.TrimSpace(resp.Header.Get("X-Reasonix-Session-Path")), |
| 218 | SessionID: strings.TrimSpace(resp.Header.Get("X-Reasonix-Session-ID")), |
| 219 | // A 204 with the taken-over header means the serve mounted this |
| 220 | // caller as a read-only spectator: another runtime owns the writer. |
| 221 | TakenOver: strings.TrimSpace(resp.Header.Get(sessionTakenOverHeader)) != "", |
| 222 | }, nil |
| 223 | } |
| 224 | return serveSessionIdentity{}, &serveHTTPStatusError{ |
| 225 | url: url, statusCode: resp.StatusCode, message: strings.TrimSpace(string(data)), |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | // serveDo issues a JSON request; the csrf guard rejects non-JSON POSTs. |
| 230 | func serveDo(ctx context.Context, client *http.Client, method, url string, body []byte) (*http.Response, error) { |
| 231 | return serveDoForSession(ctx, client, method, url, body, "") |
| 232 | } |
| 233 | |
| 234 | func serveDoForSession(ctx context.Context, client *http.Client, method, url string, body []byte, expectedPath string, modelRevision ...string) (*http.Response, error) { |
| 235 | req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body)) |
| 236 | if err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | req.Header.Set("Content-Type", "application/json") |
| 240 | if len(modelRevision) > 0 && modelRevision[0] != "" { |
| 241 | req.Header.Set(expectedModelSettingsHeader, modelRevision[0]) |
| 242 | } |
| 243 | if expectedPath = strings.TrimSpace(expectedPath); expectedPath != "" { |
| 244 | if sessionID, ok := strings.CutPrefix(expectedPath, remoteSessionIDRoutePrefix); ok { |
| 245 | req.Header.Set(expectedSessionIDHeader, sessionID) |
| 246 | } else { |
| 247 | req.Header.Set(expectedSessionPathHeader, expectedPath) |
| 248 | } |
| 249 | } |
| 250 | return client.Do(req) |
| 251 | } |
| 252 | |
| 253 | // serveCapabilitiesHeader carries the comma-joined capability tokens a serve |
| 254 | // advertises on a successful token handshake (e.g. "browser"). |
| 255 | const serveCapabilitiesHeader = "X-Reasonix-Serve-Capabilities" |
| 256 | const serveCapabilityExecutionV2 = "execution-v2" |
| 257 | const serveCapabilitySessions = "session-history-v1" |
| 258 | const serveCapabilitySessionContentV1 = "session-content-v1" |
| 259 | const serveCapabilitySessionReadV2 = "session-read-v2" |
| 260 | |
| 261 | const serveCapabilityHistoryWindowV1 = "history-window-v1" |
| 262 | const serveCapabilityExtensionFormInstanceV1 = "extension-form-instance-v1" |
| 263 | const serveCapabilityInteractionTargetV1 = "interaction-target-v1" |
| 264 | const serveCapabilitySessionIdentityV1 = "session-identity-v1" |
| 265 | const serveCapabilitySessionOwnershipV1 = "session-ownership-v1" |
| 266 | const serveCapabilityGoalLifecycleV2 = servecontract.GoalLifecycleV2 |
| 267 | const serveCapabilitySessionForkTargetsV1 = servecontract.SessionForkTargetsV1 |
| 268 | |
| 269 | // serveHandshakeCapabilities exchanges the pre-shared token for the session |
| 270 | // cookie and returns the serve's advertised capabilities; older serves omit |
| 271 | // the header and yield nil, which callers must read as "no capabilities". |
| 272 | func serveHandshakeCapabilities(ctx context.Context, client *http.Client, base, token string) ([]string, error) { |
| 273 | body, err := json.Marshal(map[string]string{"token": token}) |
| 274 | if err != nil { |
| 275 | return nil, err |
| 276 | } |
| 277 | resp, err := serveDo(ctx, client, http.MethodPost, serveURL(base, "/auth/token"), body) |
| 278 | if err != nil { |
| 279 | return nil, err |
| 280 | } |
| 281 | defer resp.Body.Close() |
| 282 | _, _ = io.Copy(io.Discard, resp.Body) |
| 283 | if resp.StatusCode != http.StatusNoContent { |
| 284 | return nil, fmt.Errorf("serve auth handshake: status %d", resp.StatusCode) |
| 285 | } |
| 286 | var caps []string |
| 287 | for cap := range strings.SplitSeq(resp.Header.Get(serveCapabilitiesHeader), ",") { |
| 288 | if cap = strings.TrimSpace(cap); cap != "" { |
| 289 | caps = append(caps, cap) |
| 290 | } |
| 291 | } |
| 292 | return caps, nil |
| 293 | } |
| 294 | |
| 295 | // serveHandshake exchanges the pre-shared token for the session cookie. |
| 296 | // Serve replies 204 on success; the cookie lands in client's jar. |
| 297 | func serveHandshake(ctx context.Context, client *http.Client, base, token string) error { |
| 298 | _, err := serveHandshakeCapabilities(ctx, client, base, token) |
| 299 | return err |
| 300 | } |
| 301 | |
| 302 | // serveSessions lists the serve's sessions. |
| 303 | func serveSessions(ctx context.Context, client *http.Client, base string) ([]serveSessionEntry, error) { |
| 304 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, serveURL(base, "/sessions"), nil) |
| 305 | if err != nil { |
| 306 | return nil, err |
| 307 | } |
| 308 | resp, err := client.Do(req) |
| 309 | if err != nil { |
| 310 | return nil, err |
| 311 | } |
| 312 | defer resp.Body.Close() |
| 313 | if resp.StatusCode != http.StatusOK { |
| 314 | return nil, fmt.Errorf("serve /sessions: status %d", resp.StatusCode) |
| 315 | } |
| 316 | data, err := io.ReadAll(io.LimitReader(resp.Body, serveSessionsMaxBytes+1)) |
| 317 | if err != nil { |
| 318 | return nil, err |
| 319 | } |
| 320 | if len(data) > serveSessionsMaxBytes { |
| 321 | return nil, fmt.Errorf("serve /sessions response exceeds %d bytes", serveSessionsMaxBytes) |
| 322 | } |
| 323 | var out []serveSessionEntry |
| 324 | if err := json.Unmarshal(data, &out); err != nil { |
| 325 | return nil, err |
| 326 | } |
| 327 | return out, nil |
| 328 | } |
| 329 | |
| 330 | func singleCurrentServeSession(entries []serveSessionEntry) *serveSessionEntry { |
| 331 | var current *serveSessionEntry |
| 332 | for i := range entries { |
| 333 | if !entries[i].Current { |
| 334 | continue |
| 335 | } |
| 336 | if current != nil { |
| 337 | return nil |
| 338 | } |
| 339 | current = &entries[i] |
| 340 | } |
| 341 | return current |
| 342 | } |
| 343 | |
| 344 | // serveClientForRef resolves an HTTP client for a host+workspace WITHOUT |
| 345 | // waking anything: a one-shot handshake against an already-ready serve |
| 346 | // registration. A serve that is not running reports an error — query paths |
| 347 | // must never cold-start one. |
| 348 | func (a *App) serveClientForRef(hostID, workspace string) (*http.Client, string, func(), error) { |
| 349 | a.remoteTabMu.Lock() |
| 350 | for _, tab := range a.remoteTabs { |
| 351 | if tab.ref.HostID == hostID && tab.ref.Workspace == workspace && tab.state == "ready" && tab.client != nil { |
| 352 | client, base := tab.client, tab.base |
| 353 | a.remoteTabMu.Unlock() |
| 354 | return client, base, func() {}, nil |
| 355 | } |
| 356 | } |
| 357 | a.remoteTabMu.Unlock() |
| 358 | |
| 359 | rt, err := a.remoteRT() |
| 360 | if err != nil { |
| 361 | return nil, "", nil, err |
| 362 | } |
| 363 | view, token, ok := rt.ServeSnapshot(hostID, workspace) |
| 364 | if !ok { |
| 365 | return nil, "", nil, fmt.Errorf("remote serve for %s:%s is not running", hostID, workspace) |
| 366 | } |
| 367 | ctx := a.bootContext() |
| 368 | if ctx == nil { |
| 369 | ctx = context.Background() |
| 370 | } |
| 371 | callCtx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 372 | client, clientErr := newServeHTTPClient(view.LocalURL) |
| 373 | if clientErr != nil { |
| 374 | cancel() |
| 375 | return nil, "", nil, clientErr |
| 376 | } |
| 377 | if err := serveHandshake(callCtx, client, view.LocalURL, token); err != nil { |
| 378 | cancel() |
| 379 | return nil, "", nil, err |
| 380 | } |
| 381 | return client, view.LocalURL, cancel, nil |
| 382 | } |
| 383 | |
| 384 | // serveClientEnsured may connect the host and start Serve, so only explicit |
| 385 | // user-intent paths should use it. Passive listings remain read-only. |
| 386 | func (a *App) serveClientEnsured(hostID, workspace string) (*http.Client, string, func(), error) { |
| 387 | if client, base, done, err := a.serveClientForRef(hostID, workspace); err == nil { |
| 388 | return client, base, done, nil |
| 389 | } |
| 390 | rt, err := a.remoteRT() |
| 391 | if err != nil { |
| 392 | return nil, "", nil, err |
| 393 | } |
| 394 | if err := rt.Connect(hostID); err != nil { |
| 395 | return nil, "", nil, err |
| 396 | } |
| 397 | if err := waitForRemoteHost(rt, hostID, 60*time.Second); err != nil { |
| 398 | return nil, "", nil, err |
| 399 | } |
| 400 | bootCtx := a.bootContext() |
| 401 | if bootCtx == nil { |
| 402 | bootCtx = context.Background() |
| 403 | } |
| 404 | view, token, err := rt.EnsureServer(bootCtx, hostID, workspace) |
| 405 | if err != nil { |
| 406 | return nil, "", nil, err |
| 407 | } |
| 408 | callCtx, cancel := context.WithTimeout(bootCtx, 30*time.Second) |
| 409 | client, err := newServeHTTPClient(view.LocalURL) |
| 410 | if err != nil { |
| 411 | cancel() |
| 412 | return nil, "", nil, err |
| 413 | } |
| 414 | if err := serveHandshake(callCtx, client, view.LocalURL, token); err != nil { |
| 415 | cancel() |
| 416 | return nil, "", nil, err |
| 417 | } |
| 418 | return client, view.LocalURL, cancel, nil |
| 419 | } |
| 420 | |
| 421 | // RemoteProjectSessions lists a remote project's serve sessions for the |
| 422 | // project tree. Live-tab fast paths, desktop title overrides and pinned |
| 423 | // synthesis arrive with the remote sessions PR. |
| 424 | func (a *App) RemoteProjectSessions(hostID, workspace string) ([]RemoteSessionView, error) { |
| 425 | client, base, done, err := a.serveClientForRef(hostID, workspace) |
| 426 | if err != nil { |
| 427 | return nil, err |
| 428 | } |
| 429 | defer done() |
| 430 | ctx, cancel := commandContext(a) |
| 431 | defer cancel() |
| 432 | return a.remoteProjectSessions(ctx, client, base, hostID, workspace) |
| 433 | } |
| 434 | |
| 435 | // EnsureRemoteProjectSessions is the explicit group-open listing path. It can |
| 436 | // wake the SSH host and Serve before returning sessions. |
| 437 | func (a *App) EnsureRemoteProjectSessions(hostID, workspace string) ([]RemoteSessionView, error) { |
| 438 | client, base, done, err := a.serveClientEnsured(hostID, workspace) |
| 439 | if err != nil { |
| 440 | return nil, err |
| 441 | } |
| 442 | defer done() |
| 443 | ctx, cancel := commandContext(a) |
| 444 | defer cancel() |
| 445 | return a.remoteProjectSessions(ctx, client, base, hostID, workspace) |
| 446 | } |
| 447 | |
| 448 | func (a *App) remoteProjectSessions(ctx context.Context, client *http.Client, base, hostID, workspace string) ([]RemoteSessionView, error) { |
| 449 | listing, err := a.fetchRemoteSessionListing(ctx, client, base, hostID, workspace) |
| 450 | if err != nil { |
| 451 | return nil, err |
| 452 | } |
| 453 | entries := listing.entries |
| 454 | liveRunning := listing.liveRunning |
| 455 | liveCurrentPath := listing.liveCurrentPath |
| 456 | preferLiveCurrent := listing.preferLive |
| 457 | out := make([]RemoteSessionView, 0, len(entries)) |
| 458 | pinned := make([]RemoteSessionView, 0, len(entries)) |
| 459 | prefs := remotePrefsSnapshot() |
| 460 | hasCurrent := false |
| 461 | for _, e := range entries { |
| 462 | title := strings.TrimSpace(e.Title) |
| 463 | prefKey := remoteSessionPrefKey(hostID, workspace, e.Name) |
| 464 | if override := prefs.SessionTitles[prefKey]; override != "" { |
| 465 | title = override |
| 466 | } |
| 467 | pinnedRow := remoteSessionPinnedLocked(prefs, prefKey) |
| 468 | // A never-chatted canonical session is the remote analog of a local |
| 469 | // blank, so hide it unless pinned. MetadataReady gates the check: a |
| 470 | // stale catalog must not hide a real conversation. |
| 471 | if e.SessionID != "" && !e.Current && !pinnedRow && e.Turns == 0 && title == "" && e.Preview == "" && e.MetadataReady { |
| 472 | continue |
| 473 | } |
| 474 | current := e.Current |
| 475 | route := remoteSessionRoute(e) |
| 476 | if preferLiveCurrent { |
| 477 | current = liveCurrentPath != "" && route == liveCurrentPath |
| 478 | } |
| 479 | view := RemoteSessionView{ |
| 480 | HostID: e.HostID, SessionID: e.SessionID, Name: e.Name, Path: e.Path, Title: title, Turns: e.Turns, Current: current, |
| 481 | Running: remoteSessionRunning(e.Running, liveRunning, route, preferLiveCurrent), |
| 482 | LastActivityAt: e.MtimeMilli, |
| 483 | ResultSequence: e.ResultSequence, |
| 484 | MetadataReady: e.MetadataReady, |
| 485 | Pinned: pinnedRow, |
| 486 | } |
| 487 | hasCurrent = hasCurrent || view.Current |
| 488 | if view.Pinned { |
| 489 | pinned = append(pinned, view) |
| 490 | } else { |
| 491 | out = append(out, view) |
| 492 | } |
| 493 | } |
| 494 | if !hasCurrent { |
| 495 | // A fresh foreground session stays absent from /sessions until its first |
| 496 | // transcript save. Synthesize it from the live route rather than reset, |
| 497 | // which status clears as soon as Serve names the not-yet-listed session. |
| 498 | a.remoteTabMu.Lock() |
| 499 | listedRoutes := make(map[string]bool, len(entries)) |
| 500 | for _, e := range entries { |
| 501 | listedRoutes[remoteSessionIdentityRoute(strings.TrimSpace(e.Path), strings.TrimSpace(e.SessionID))] = true |
| 502 | } |
| 503 | var blank *RemoteSessionView |
| 504 | for _, tab := range a.remoteTabs { |
| 505 | if tab.ref.HostID != hostID || tab.ref.Workspace != workspace { |
| 506 | continue |
| 507 | } |
| 508 | if tab.state != "ready" || blank != nil { |
| 509 | continue |
| 510 | } |
| 511 | // Known current path: blank while the serve listing cannot see it |
| 512 | // yet. Unknown path (a legacy /new without a path header): blank |
| 513 | // while the fresh-session marker is still set. |
| 514 | if route := tab.routing.currentPath; route != "" { |
| 515 | if !listedRoutes[route] { |
| 516 | path, sessionID := remoteSessionRouteIdentity(route) |
| 517 | blank = &RemoteSessionView{Name: "", Path: path, SessionID: sessionID, Title: tab.topicTitle, Current: true, Running: tab.runtime.running, LastActivityAt: time.Now().UnixMilli()} |
| 518 | } |
| 519 | } else if tab.session.reset { |
| 520 | blank = &RemoteSessionView{Name: "", Title: tab.topicTitle, Current: true, Running: tab.runtime.running, LastActivityAt: time.Now().UnixMilli()} |
| 521 | } |
| 522 | } |
| 523 | a.remoteTabMu.Unlock() |
| 524 | if blank != nil { |
| 525 | return append([]RemoteSessionView{*blank}, append(pinned, out...)...), nil |
| 526 | } |
| 527 | } |
| 528 | return append(pinned, out...), nil |
| 529 | } |
| 530 | |
| 531 | type remoteSessionListing struct { |
| 532 | entries []serveSessionEntry |
| 533 | liveRunning map[string]bool |
| 534 | liveCurrentPath string |
| 535 | preferLive bool |
| 536 | } |
| 537 | |
| 538 | func (a *App) fetchRemoteSessionListing(ctx context.Context, client *http.Client, base, hostID, workspace string) (remoteSessionListing, error) { |
| 539 | const maxRaceRetries = 2 |
| 540 | |
| 541 | listingAttempt: |
| 542 | for attempt := 0; ; attempt++ { |
| 543 | a.remoteTabMu.Lock() |
| 544 | var observedTab *remoteTab |
| 545 | var observedRevision uint64 |
| 546 | for _, tab := range a.remoteTabs { |
| 547 | if tab.ref.HostID == hostID && tab.ref.Workspace == workspace { |
| 548 | observedTab, observedRevision = tab, tab.routing.revision |
| 549 | break |
| 550 | } |
| 551 | } |
| 552 | a.remoteTabMu.Unlock() |
| 553 | entries, err := serveSessions(ctx, client, base) |
| 554 | if err != nil { |
| 555 | return remoteSessionListing{}, err |
| 556 | } |
| 557 | authoritativeCurrent := singleCurrentServeSession(entries) |
| 558 | authoritativeTitle := remoteAuthoritativeSessionTitle(hostID, workspace, authoritativeCurrent) |
| 559 | unlockRoute := lockRemoteTabRoute(observedTab) |
| 560 | a.remoteTabMu.Lock() |
| 561 | liveRunning := map[string]bool{} |
| 562 | liveCurrentPath := "" |
| 563 | preferLiveCurrent := false |
| 564 | var routeUpdate *TabMeta |
| 565 | routeReadyBarrier := false |
| 566 | for _, tab := range a.remoteTabs { |
| 567 | if tab.ref.HostID != hostID || tab.ref.Workspace != workspace { |
| 568 | continue |
| 569 | } |
| 570 | // Without a newer SSE/status revision, /sessions replaces the running |
| 571 | // cache and current route. A raced revision preserves the newer live route |
| 572 | // instead of marking both its row and the stale server row current. |
| 573 | authoritativeListing := tab == observedTab && tab.routing.revision == observedRevision |
| 574 | if !authoritativeListing && attempt < maxRaceRetries && remoteSessionRunningConflict(entries, tab.routing.running) { |
| 575 | a.remoteTabMu.Unlock() |
| 576 | unlockRoute() |
| 577 | continue listingAttempt |
| 578 | } |
| 579 | if authoritativeListing { |
| 580 | authoritative := make(map[string]bool, len(entries)) |
| 581 | for _, entry := range entries { |
| 582 | route := remoteSessionRoute(entry) |
| 583 | authoritative[route] = entry.Running |
| 584 | if route == tab.routing.currentPath { |
| 585 | tab.session.takenOver = entry.TakenOver |
| 586 | } |
| 587 | } |
| 588 | tab.routing.running = authoritative |
| 589 | if authoritativeCurrent != nil { |
| 590 | path := remoteSessionRoute(*authoritativeCurrent) |
| 591 | // The listing's "current" is Serve's foreground; it must not |
| 592 | // re-route a spectator's explicitly selected session. |
| 593 | if path == tab.routing.currentPath || !tab.session.takenOver { |
| 594 | pathChanged := adoptRemoteTabSessionPathLocked(tab, path) |
| 595 | tab.session.name = strings.TrimSpace(authoritativeCurrent.Name) |
| 596 | if pathChanged { |
| 597 | tab.topicTitle = authoritativeTitle |
| 598 | meta := remoteTabMetaLocked(tab) |
| 599 | routeUpdate = &meta |
| 600 | routeReadyBarrier = remoteTabReadyBarrier(tab, true) |
| 601 | } |
| 602 | } |
| 603 | } |
| 604 | } else { |
| 605 | preferLiveCurrent = true |
| 606 | } |
| 607 | liveCurrentPath = tab.routing.currentPath |
| 608 | maps.Copy(liveRunning, tab.routing.running) |
| 609 | break |
| 610 | } |
| 611 | a.remoteTabMu.Unlock() |
| 612 | if routeUpdate != nil { |
| 613 | a.emitRemoteEvent("remote-tab:updated", *routeUpdate) |
| 614 | if routeReadyBarrier { |
| 615 | a.publishRemoteTabState(routeUpdate.ID, RemoteTabStateView{State: "ready"}) |
| 616 | } |
| 617 | } |
| 618 | unlockRoute() |
| 619 | return remoteSessionListing{ |
| 620 | entries: entries, liveRunning: liveRunning, |
| 621 | liveCurrentPath: liveCurrentPath, preferLive: preferLiveCurrent, |
| 622 | }, nil |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | func remoteSessionRunningConflict(entries []serveSessionEntry, live map[string]bool) bool { |
| 627 | listedPaths := make(map[string]struct{}, len(entries)) |
| 628 | for _, entry := range entries { |
| 629 | route := remoteSessionRoute(entry) |
| 630 | listedPaths[route] = struct{}{} |
| 631 | if running, ok := live[route]; entry.Running && ok && !running { |
| 632 | return true |
| 633 | } |
| 634 | } |
| 635 | for path, running := range live { |
| 636 | if _, listed := listedPaths[path]; !running && !listed { |
| 637 | return true |
| 638 | } |
| 639 | } |
| 640 | return false |
| 641 | } |
| 642 | |
| 643 | func remoteSessionRunning(listed bool, live map[string]bool, path string, preferLive bool) bool { |
| 644 | if preferLive { |
| 645 | if running, ok := live[path]; ok { |
| 646 | // A raced false can mean a completed turn or remaining background jobs. |
| 647 | // The bounded refresh resolves the ordinary case; after repeated races, |
| 648 | // retain the conservative row rather than hiding active background work. |
| 649 | if listed && !running { |
| 650 | return true |
| 651 | } |
| 652 | return running |
| 653 | } |
| 654 | } |
| 655 | return listed || live[path] |
| 656 | } |
| 657 | |
| 658 | func remoteAuthoritativeSessionTitle(hostID, workspace string, current *serveSessionEntry) string { |
| 659 | if current == nil { |
| 660 | return "" |
| 661 | } |
| 662 | title := strings.TrimSpace(current.Title) |
| 663 | if override := remoteSessionTitleOverride(hostID, workspace, current.Name); override != "" { |
| 664 | title = override |
| 665 | } |
| 666 | if title == "" { |
| 667 | title = remoteWorkspaceName(workspace) |
| 668 | } |
| 669 | return title |
| 670 | } |
| 671 |