-
Notifications
You must be signed in to change notification settings - Fork 545
Expand file tree
/
Copy pathserialize.ts
More file actions
468 lines (423 loc) · 15.4 KB
/
serialize.ts
File metadata and controls
468 lines (423 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* Core Session → DashboardSession serialization.
*
* Converts core types (Date objects, PRInfo) into dashboard types
* (string dates, flattened DashboardPR) suitable for JSON serialization.
*/
import {
SESSION_STATUS,
updateMetadata,
type Session,
type Agent,
type SCM,
type PRInfo,
type SessionStatus,
type Tracker,
type ProjectConfig,
type OrchestratorConfig,
type PluginRegistry,
} from "@composio/ao-core";
import type { DashboardSession, DashboardPR, DashboardStats } from "./types.js";
import {
TTLCache,
prCache,
prCacheKey,
PR_CACHE_TTL_SUCCESS_MS,
PR_CACHE_TTL_RATE_LIMIT_MS,
type PREnrichmentData,
} from "./cache";
/** Cache for issue titles (5 min TTL — issue titles rarely change) */
const issueTitleCache = new TTLCache<string>(300_000);
/** Resolve which project a session belongs to. */
export function resolveProject(
core: Session,
projects: Record<string, ProjectConfig>,
): ProjectConfig | undefined {
// Try explicit projectId first
const direct = projects[core.projectId];
if (direct) return direct;
// Match by session prefix
const entry = Object.entries(projects).find(([, p]) => core.id.startsWith(p.sessionPrefix));
if (entry) return entry[1];
// Fall back to first project
const firstKey = Object.keys(projects)[0];
return firstKey ? projects[firstKey] : undefined;
}
/** Convert a core Session to a DashboardSession (without PR/issue enrichment). */
export function sessionToDashboard(session: Session): DashboardSession {
const agentSummary = session.agentInfo?.summary;
const summary = agentSummary ?? session.metadata["summary"] ?? null;
return {
id: session.id,
projectId: session.projectId,
status: session.status,
activity: session.activity,
branch: session.branch,
issueId: session.issueId, // Deprecated: kept for backwards compatibility
issueUrl: session.issueId, // issueId is actually the full URL
issueLabel: null, // Will be enriched by enrichSessionIssue()
issueTitle: null, // Will be enriched by enrichSessionIssueTitle()
summary,
summaryIsFallback: agentSummary
? (session.agentInfo?.summaryIsFallback ?? false)
: false,
createdAt: session.createdAt.toISOString(),
lastActivityAt: session.lastActivityAt.toISOString(),
pr: session.pr ? basicPRToDashboard(session.pr) : null,
metadata: session.metadata,
};
}
/**
* Convert minimal PRInfo to a DashboardPR with default values for enriched fields.
* These defaults indicate "data not yet loaded" rather than "failing".
* Use enrichSessionPR() to populate with live data from SCM.
*/
function basicPRToDashboard(pr: PRInfo): DashboardPR {
return {
number: pr.number,
url: pr.url,
title: pr.title,
owner: pr.owner,
repo: pr.repo,
branch: pr.branch,
baseBranch: pr.baseBranch,
isDraft: pr.isDraft,
state: "open",
additions: 0,
deletions: 0,
ciStatus: "none", // "none" is neutral (no checks configured)
ciChecks: [],
reviewDecision: "none", // "none" is neutral (no review required)
mergeability: {
mergeable: false,
ciPassing: false, // Conservative default
approved: false,
noConflicts: true, // Optimistic default (conflicts are rare)
blockers: ["Data not loaded"], // Explicit blocker
},
unresolvedThreads: 0,
unresolvedComments: [],
};
}
/**
* Enrich a DashboardSession's PR with live data from the SCM plugin.
* Uses cache to reduce API calls and handles rate limit errors gracefully.
*/
export async function enrichSessionPR(
dashboard: DashboardSession,
scm: SCM,
pr: PRInfo,
opts?: {
cacheOnly?: boolean;
bypassCache?: boolean;
metadata?: {
sessionsDir: string;
sessionId: string;
currentStatus: SessionStatus;
};
},
): Promise<boolean> {
if (!dashboard.pr) return false;
const cacheKey = prCacheKey(pr.owner, pr.repo, pr.number);
// Check cache first
const cached = opts?.bypassCache ? null : prCache.get(cacheKey);
if (cached && dashboard.pr) {
dashboard.pr.state = cached.state;
dashboard.pr.title = cached.title;
dashboard.pr.additions = cached.additions;
dashboard.pr.deletions = cached.deletions;
dashboard.pr.ciStatus = cached.ciStatus;
dashboard.pr.ciChecks = cached.ciChecks;
dashboard.pr.reviewDecision = cached.reviewDecision;
dashboard.pr.mergeability = cached.mergeability;
dashboard.pr.unresolvedThreads = cached.unresolvedThreads;
dashboard.pr.unresolvedComments = cached.unresolvedComments;
maybeWriteSessionStatusTransition(dashboard, opts?.metadata, isPRRateLimited(dashboard.pr));
return true;
}
// Cache miss — if cacheOnly, signal caller to refresh in background
if (opts?.cacheOnly) return false;
// Fetch from SCM
const results = await Promise.allSettled([
scm.getPRSummary
? scm.getPRSummary(pr)
: scm.getPRState(pr).then((state) => ({ state, title: "", additions: 0, deletions: 0 })),
scm.getCIChecks(pr),
scm.getCISummary(pr),
scm.getReviewDecision(pr),
scm.getMergeability(pr),
scm.getPendingComments(pr),
]);
const [summaryR, checksR, ciR, reviewR, mergeR, commentsR] = results;
// Check if most critical requests failed (likely rate limit)
// Note: Some methods (like getCISummary) return fallback values instead of rejecting,
// so we can't rely on "all rejected" — check if majority failed instead
const failedCount = results.filter((r) => r.status === "rejected").length;
const mostFailed = failedCount >= results.length / 2;
if (mostFailed) {
const rejectedResults = results.filter(
(r) => r.status === "rejected",
) as PromiseRejectedResult[];
const firstError = rejectedResults[0]?.reason;
console.warn(
`[enrichSessionPR] ${failedCount}/${results.length} API calls failed for PR #${pr.number} (rate limited or unavailable):`,
String(firstError),
);
// Don't return early — apply any successful results below
}
// Apply successful results
if (summaryR.status === "fulfilled") {
dashboard.pr.state = summaryR.value.state;
dashboard.pr.additions = summaryR.value.additions;
dashboard.pr.deletions = summaryR.value.deletions;
if (summaryR.value.title) {
dashboard.pr.title = summaryR.value.title;
}
}
if (checksR.status === "fulfilled") {
dashboard.pr.ciChecks = checksR.value.map((c) => ({
name: c.name,
status: c.status,
url: c.url,
}));
}
if (ciR.status === "fulfilled") {
dashboard.pr.ciStatus = ciR.value;
}
if (reviewR.status === "fulfilled") {
dashboard.pr.reviewDecision = reviewR.value;
}
if (mergeR.status === "fulfilled") {
dashboard.pr.mergeability = mergeR.value;
} else {
// Mergeability failed — mark as unavailable
dashboard.pr.mergeability.blockers = ["Merge status unavailable"];
}
if (commentsR.status === "fulfilled") {
const comments = commentsR.value;
dashboard.pr.unresolvedThreads = comments.length;
dashboard.pr.unresolvedComments = comments.map((c) => ({
url: c.url,
path: c.path ?? "",
author: c.author,
body: c.body,
}));
}
// Add rate-limit warning blocker if most requests failed
// (but we still applied any successful results above)
if (
mostFailed &&
!dashboard.pr.mergeability.blockers.includes("API rate limited or unavailable")
) {
dashboard.pr.mergeability.blockers.push("API rate limited or unavailable");
}
// If rate limited, cache the partial data with a long TTL (5 min) so we stop
// hammering the API on every page load. The rate-limit blocker flag tells the
// UI to show stale-data warnings instead of making decisions on bad data.
if (mostFailed) {
const rateLimitedData: PREnrichmentData = {
state: dashboard.pr.state,
title: dashboard.pr.title,
additions: dashboard.pr.additions,
deletions: dashboard.pr.deletions,
ciStatus: dashboard.pr.ciStatus,
ciChecks: dashboard.pr.ciChecks,
reviewDecision: dashboard.pr.reviewDecision,
mergeability: dashboard.pr.mergeability,
unresolvedThreads: dashboard.pr.unresolvedThreads,
unresolvedComments: dashboard.pr.unresolvedComments,
};
if (!opts?.bypassCache) {
prCache.set(cacheKey, rateLimitedData, PR_CACHE_TTL_RATE_LIMIT_MS);
}
maybeWriteSessionStatusTransition(dashboard, opts?.metadata, true);
return true;
}
const cacheData: PREnrichmentData = {
state: dashboard.pr.state,
title: dashboard.pr.title,
additions: dashboard.pr.additions,
deletions: dashboard.pr.deletions,
ciStatus: dashboard.pr.ciStatus,
ciChecks: dashboard.pr.ciChecks,
reviewDecision: dashboard.pr.reviewDecision,
mergeability: dashboard.pr.mergeability,
unresolvedThreads: dashboard.pr.unresolvedThreads,
unresolvedComments: dashboard.pr.unresolvedComments,
};
if (!opts?.bypassCache) {
prCache.set(cacheKey, cacheData, PR_CACHE_TTL_SUCCESS_MS);
}
maybeWriteSessionStatusTransition(dashboard, opts?.metadata, false);
return true;
}
function isPRRateLimited(pr: DashboardPR): boolean {
return pr.mergeability.blockers.includes("API rate limited or unavailable");
}
function deriveSessionStatusTransition(
currentStatus: SessionStatus,
pr: DashboardPR,
rateLimited: boolean,
): SessionStatus | null {
if (pr.state === "merged") return SESSION_STATUS.MERGED;
if (pr.state === "closed") return SESSION_STATUS.DONE;
// During rate limiting, CI/review data can be stale defaults.
if (rateLimited) return null;
if (currentStatus === SESSION_STATUS.CI_FAILED && pr.ciStatus === "passing") {
return SESSION_STATUS.PR_OPEN;
}
if (pr.reviewDecision === "approved") {
return SESSION_STATUS.APPROVED;
}
if (pr.reviewDecision === "changes_requested") {
return SESSION_STATUS.CHANGES_REQUESTED;
}
return null;
}
function maybeWriteSessionStatusTransition(
dashboard: DashboardSession,
metadata:
| {
sessionsDir: string;
sessionId: string;
currentStatus: SessionStatus;
}
| undefined,
rateLimited: boolean,
): void {
if (!dashboard.pr || !metadata) return;
const nextStatus = deriveSessionStatusTransition(metadata.currentStatus, dashboard.pr, rateLimited);
if (!nextStatus || nextStatus === metadata.currentStatus) return;
try {
updateMetadata(metadata.sessionsDir, metadata.sessionId, { status: nextStatus });
dashboard.status = nextStatus;
} catch (error) {
console.warn(
`[enrichSessionPR] failed to update metadata for session ${metadata.sessionId}:`,
error,
);
}
}
/** Enrich a DashboardSession's issue label using the tracker plugin. */
export function enrichSessionIssue(
dashboard: DashboardSession,
tracker: Tracker,
project: ProjectConfig,
): void {
if (!dashboard.issueUrl) return;
// Use tracker plugin to extract human-readable label from URL
if (tracker.issueLabel) {
try {
dashboard.issueLabel = tracker.issueLabel(dashboard.issueUrl, project);
} catch {
// If extraction fails, fall back to extracting from URL manually
const parts = dashboard.issueUrl.split("/");
dashboard.issueLabel = parts[parts.length - 1] || dashboard.issueUrl;
}
} else {
// Fallback if tracker doesn't implement issueLabel method
const parts = dashboard.issueUrl.split("/");
dashboard.issueLabel = parts[parts.length - 1] || dashboard.issueUrl;
}
}
/**
* Enrich a DashboardSession's summary by calling agent.getSessionInfo().
* Only fetches when the session doesn't already have a summary.
* Reads the agent's JSONL file on disk — fast local I/O, not an API call.
*/
export async function enrichSessionAgentSummary(
dashboard: DashboardSession,
coreSession: Session,
agent: Agent,
): Promise<void> {
if (dashboard.summary) return;
try {
const info = await agent.getSessionInfo(coreSession);
if (info?.summary) {
dashboard.summary = info.summary;
dashboard.summaryIsFallback = info.summaryIsFallback ?? false;
}
} catch {
// Can't read agent session info — keep summary null
}
}
/**
* Enrich a DashboardSession's issue title by calling tracker.getIssue().
* Extracts the identifier from the issue URL using issueLabel(),
* then fetches full issue details for the title.
*/
export async function enrichSessionIssueTitle(
dashboard: DashboardSession,
tracker: Tracker,
project: ProjectConfig,
): Promise<void> {
if (!dashboard.issueUrl || !dashboard.issueLabel) return;
// Check cache first
const cached = issueTitleCache.get(dashboard.issueUrl);
if (cached) {
dashboard.issueTitle = cached;
return;
}
try {
// Strip "#" prefix from GitHub-style labels to get the identifier
const identifier = dashboard.issueLabel.replace(/^#/, "");
const issue = await tracker.getIssue(identifier, project);
if (issue.title) {
dashboard.issueTitle = issue.title;
issueTitleCache.set(dashboard.issueUrl, issue.title);
}
} catch {
// Can't fetch issue — keep issueTitle null
}
}
/**
* Enrich dashboard sessions with metadata (issue labels, agent summaries, issue titles).
* Orchestrates sync + async enrichment in parallel. Does NOT enrich PR data — callers
* handle that separately since strategies differ (e.g. terminal-session cache optimization).
*/
export async function enrichSessionsMetadata(
coreSessions: Session[],
dashboardSessions: DashboardSession[],
config: OrchestratorConfig,
registry: PluginRegistry,
): Promise<void> {
// Resolve projects once per session (avoids repeated Object.entries lookups)
const projects = coreSessions.map((core) => resolveProject(core, config.projects));
// Enrich issue labels (synchronous — must run before async title enrichment)
projects.forEach((project, i) => {
if (!dashboardSessions[i].issueUrl || !project?.tracker) return;
const tracker = registry.get<Tracker>("tracker", project.tracker.plugin);
if (!tracker) return;
enrichSessionIssue(dashboardSessions[i], tracker, project);
});
// Enrich agent summaries (reads agent's JSONL — local I/O, not an API call)
const summaryPromises = coreSessions.map((core, i) => {
if (dashboardSessions[i].summary) return Promise.resolve();
const agentName = projects[i]?.agent ?? config.defaults.agent;
if (!agentName) return Promise.resolve();
const agent = registry.get<Agent>("agent", agentName);
if (!agent) return Promise.resolve();
return enrichSessionAgentSummary(dashboardSessions[i], core, agent);
});
// Enrich issue titles (fetches from tracker API, cached with TTL)
const issueTitlePromises = projects.map((project, i) => {
if (!dashboardSessions[i].issueUrl || !dashboardSessions[i].issueLabel) {
return Promise.resolve();
}
if (!project?.tracker) return Promise.resolve();
const tracker = registry.get<Tracker>("tracker", project.tracker.plugin);
if (!tracker) return Promise.resolve();
return enrichSessionIssueTitle(dashboardSessions[i], tracker, project);
});
await Promise.allSettled([...summaryPromises, ...issueTitlePromises]);
}
/** Compute dashboard stats from a list of sessions. */
export function computeStats(sessions: DashboardSession[]): DashboardStats {
return {
totalSessions: sessions.length,
workingSessions: sessions.filter((s) => s.activity !== null && s.activity !== "exited").length,
openPRs: sessions.filter((s) => s.pr?.state === "open").length,
needsReview: sessions.filter((s) => s.pr && !s.pr.isDraft && s.pr.reviewDecision === "pending")
.length,
};
}