MCPcopy Create free account
hub / github.com/cli/cli / ListLatestSessionsForViewer

Method ListLatestSessionsForViewer

pkg/cmd/agent-task/capi/sessions.go:212–291  ·  view source on GitHub ↗

ListLatestSessionsForViewer lists all agent sessions for the authenticated user up to limit.

(ctx context.Context, limit int)

Source from the content-addressed store, hash-verified

210// ListLatestSessionsForViewer lists all agent sessions for the
211// authenticated user up to limit.
212func (c *CAPIClient) ListLatestSessionsForViewer(ctx context.Context, limit int) ([]*Session, error) {
213 if limit == 0 {
214 return nil, nil
215 }
216
217 sessionsURL, err := safeurl.JoinPathWithHostPrefix(c.capiBaseURL, "agents", "sessions")
218 if err != nil {
219 return nil, err
220 }
221 pageSize := defaultSessionsPerPage
222
223 seenResources := make(map[int64]struct{})
224 latestSessions := make([]session, 0, limit)
225 for page := 1; ; page++ {
226 req, err := http.NewRequestWithContext(ctx, http.MethodGet, sessionsURL.String(), http.NoBody)
227 if err != nil {
228 return nil, err
229 }
230
231 q := req.URL.Query()
232 q.Set("page_size", strconv.Itoa(pageSize))
233 q.Set("page_number", strconv.Itoa(page))
234 q.Set("sort", "last_updated_at,desc")
235 req.URL.RawQuery = q.Encode()
236
237 res, err := c.httpClient.Do(req)
238 if err != nil {
239 return nil, err
240 }
241 defer res.Body.Close()
242 if res.StatusCode != http.StatusOK {
243 return nil, fmt.Errorf("failed to list sessions: %s", res.Status)
244 }
245 var response struct {
246 Sessions []session `json:"sessions"`
247 }
248 if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
249 return nil, fmt.Errorf("failed to decode sessions response: %w", err)
250 }
251
252 // Process only the newly fetched page worth of sessions.
253 pageSessions := response.Sessions
254
255 // De-duplicate sessions by resource ID.
256 // Because the API returns newest first, once we've seen
257 // a resource ID we can ignore any older sessions for it.
258 for _, s := range pageSessions {
259 if _, exists := seenResources[s.ResourceID]; exists {
260 continue
261 }
262
263 // A zero resource ID is a temporary situation before a PR/resource
264 // is associated with the session. We should not mark such case as seen.
265 if s.ResourceID != 0 {
266 seenResources[s.ResourceID] = struct{}{}
267 }
268
269 latestSessions = append(latestSessions, s)

Callers 1

Calls 8

JoinPathWithHostPrefixFunction · 0.92
StringMethod · 0.65
QueryMethod · 0.65
SetMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
ErrorfMethod · 0.65

Tested by 1