patchrelay 0.35.12 → 0.35.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,590 @@
1
+ import { buildStateHistory } from "./history-builder.js";
2
+ import { buildTimelineRows } from "./timeline-presentation.js";
3
+ import { planStepColor, planStepSymbol } from "./plan-helpers.js";
4
+ import { progressBar } from "./format-utils.js";
5
+ import { describePatchRelayFreshness } from "./freshness.js";
6
+ import { hasDisplayPrBlocker, isRereviewNeeded, prChecksFact } from "./pr-status.js";
7
+ import { renderRichTextLines, renderTextLines } from "./render-rich-text.js";
8
+ const SESSION_DISPLAY = {
9
+ idle: { label: "idle", color: "blueBright" },
10
+ running: { label: "running", color: "cyan" },
11
+ waiting_input: { label: "needs input", color: "yellow" },
12
+ done: { label: "done", color: "green" },
13
+ failed: { label: "needs help", color: "red" },
14
+ };
15
+ const STAGE_DISPLAY = {
16
+ blocked: "blocked",
17
+ ready: "ready",
18
+ delegated: "delegated",
19
+ implementing: "implementing",
20
+ pr_open: "PR open",
21
+ changes_requested: "review changes",
22
+ repairing_ci: "repairing CI",
23
+ awaiting_queue: "waiting downstream",
24
+ repairing_queue: "repairing queue",
25
+ done: "merged",
26
+ failed: "failed",
27
+ escalated: "escalated",
28
+ awaiting_input: "needs input",
29
+ };
30
+ const RUN_LABELS = {
31
+ implementation: "implementation",
32
+ ci_repair: "ci repair",
33
+ review_fix: "review fix",
34
+ queue_repair: "queue repair",
35
+ };
36
+ const STATE_LABELS = {
37
+ delegated: "delegated",
38
+ implementing: "implementing",
39
+ pr_open: "pr open",
40
+ changes_requested: "changes requested",
41
+ repairing_ci: "repairing ci",
42
+ awaiting_queue: "awaiting queue",
43
+ repairing_queue: "repairing queue",
44
+ awaiting_input: "awaiting input",
45
+ escalated: "escalated",
46
+ done: "done",
47
+ failed: "failed",
48
+ };
49
+ export function buildDetailLines(input) {
50
+ const width = Math.max(20, input.width);
51
+ const lines = [];
52
+ const history = buildStateHistory(input.rawRuns, input.rawFeedEvents, input.issue.factoryState, input.activeRunId);
53
+ lines.push(...buildHeaderLines(input, width));
54
+ lines.push(blankLine("header-gap"));
55
+ if (input.detailTab === "timeline") {
56
+ lines.push(...buildPlanLines(input.plan, width));
57
+ if (input.plan?.length) {
58
+ lines.push(blankLine("plan-gap"));
59
+ }
60
+ lines.push(...buildTimelineLines(input.timeline, width));
61
+ }
62
+ else {
63
+ lines.push(...buildHistoryIntroLines(width));
64
+ lines.push(blankLine("history-intro-gap"));
65
+ lines.push(...buildHistoryLines(history, input.plan, input.activeRunId, width));
66
+ }
67
+ return trimTrailingBlankLines(lines);
68
+ }
69
+ function buildHeaderLines(input, width) {
70
+ const issue = input.issue;
71
+ const session = sessionDisplay(issue);
72
+ const stage = stageDisplay(issue);
73
+ const facts = buildFacts(issue, input.issueContext);
74
+ const meta = buildMeta(input.tokenUsage, input.diffSummary, input.issueContext);
75
+ const headerSegments = [
76
+ { text: issue.issueKey ?? issue.projectId, bold: true },
77
+ { text: " " },
78
+ { text: session.label, color: session.color, bold: true },
79
+ { text: " ", dimColor: true },
80
+ { text: stage, dimColor: true },
81
+ ];
82
+ if (facts.length > 0) {
83
+ headerSegments.push({ text: " ", dimColor: true });
84
+ headerSegments.push({ text: facts.join(" · "), dimColor: true });
85
+ }
86
+ if (input.activeRunStartedAt) {
87
+ headerSegments.push({ text: " ", dimColor: true });
88
+ headerSegments.push({ text: elapsedLabel(input.activeRunStartedAt), dimColor: true });
89
+ }
90
+ if (meta.length > 0) {
91
+ headerSegments.push({ text: " ", dimColor: true });
92
+ headerSegments.push({ text: meta.join(" "), dimColor: true });
93
+ }
94
+ headerSegments.push({ text: " ", dimColor: true });
95
+ headerSegments.push(...freshnessSegments(input.connected, input.lastServerMessageAt));
96
+ if (input.follow) {
97
+ headerSegments.push({ text: " " });
98
+ headerSegments.push({ text: "live", color: "yellow", bold: true });
99
+ }
100
+ const lines = renderTextLines(segmentsToText(headerSegments), {
101
+ key: "detail-header",
102
+ width,
103
+ });
104
+ lines[0] = { key: lines[0].key, segments: headerSegments };
105
+ if (issue.title) {
106
+ lines.push(...renderTextLines(issue.title, {
107
+ key: "detail-title",
108
+ width,
109
+ style: { bold: true },
110
+ }));
111
+ }
112
+ const blocker = blockerText(issue, input.issueContext);
113
+ if (blocker) {
114
+ lines.push(...renderTextLines(blocker, {
115
+ key: "detail-blocker",
116
+ width,
117
+ style: { color: "yellow" },
118
+ }));
119
+ }
120
+ if (issue.statusNote && issue.statusNote !== blocker) {
121
+ lines.push(...renderRichTextLines(issue.statusNote, {
122
+ key: "detail-note",
123
+ width,
124
+ style: { dimColor: true },
125
+ }));
126
+ }
127
+ if (input.issueContext?.latestFailureSummary) {
128
+ const failurePrefix = input.issueContext.latestFailureSource === "queue_eviction" ? "Queue failure: " : "Latest failure: ";
129
+ const head = input.issueContext.latestFailureHeadSha ? ` @ ${input.issueContext.latestFailureHeadSha.slice(0, 8)}` : "";
130
+ lines.push(...renderTextLines(`${failurePrefix}${input.issueContext.latestFailureSummary}${head}`, {
131
+ key: "detail-failure",
132
+ width,
133
+ style: { color: input.issueContext.latestFailureSource === "queue_eviction" ? "yellow" : "red" },
134
+ }));
135
+ }
136
+ return lines;
137
+ }
138
+ function buildPlanLines(plan, width) {
139
+ if (!plan || plan.length === 0)
140
+ return [];
141
+ const completed = plan.filter((step) => step.status === "completed").length;
142
+ const lines = renderTextLines(`Plan ${progressBar(completed, plan.length, 16)} ${completed}/${plan.length}`, {
143
+ key: "detail-plan-header",
144
+ width,
145
+ style: { dimColor: true },
146
+ });
147
+ for (const [index, entry] of plan.entries()) {
148
+ lines.push({
149
+ key: `detail-plan-${index}`,
150
+ segments: [
151
+ { text: `[${planStepSymbol(entry.status)}]`, color: planStepColor(entry.status) },
152
+ { text: " " },
153
+ { text: entry.step },
154
+ ],
155
+ });
156
+ }
157
+ return lines;
158
+ }
159
+ function buildTimelineLines(entries, width) {
160
+ const rows = buildTimelineRows(entries);
161
+ if (rows.length === 0) {
162
+ return renderTextLines("No timeline events yet.", {
163
+ key: "timeline-empty",
164
+ width,
165
+ style: { dimColor: true },
166
+ });
167
+ }
168
+ const lines = [];
169
+ for (const row of rows) {
170
+ switch (row.kind) {
171
+ case "feed":
172
+ lines.push(...renderRichTextLines(`${feedGlyph(row.feed.status)} ${row.feed.summary}${row.repeatCount && row.repeatCount > 1 ? ` ×${row.repeatCount}` : ""}`, {
173
+ key: row.id,
174
+ width,
175
+ style: { dimColor: true },
176
+ }));
177
+ break;
178
+ case "ci-checks":
179
+ lines.push(...renderTextLines(`● checks ${row.ciChecks.checks.map((check) => `${check.status === "passed" ? "✓" : check.status === "failed" ? "✗" : "●"} ${check.name}`).join(" ")}`, {
180
+ key: row.id,
181
+ width,
182
+ style: { color: row.ciChecks.overall === "failed" ? "red" : row.ciChecks.overall === "passed" ? "green" : "yellow", bold: true },
183
+ }));
184
+ break;
185
+ case "item":
186
+ lines.push(...renderTimelineItemLines(row.id, row.item, width, 0));
187
+ break;
188
+ case "run":
189
+ lines.push(...buildTimelineRunLines(row.id, row.run, row.items.map((item) => item.item), row.details, width));
190
+ break;
191
+ }
192
+ lines.push(blankLine(`${row.id}-gap`));
193
+ }
194
+ return trimTrailingBlankLines(lines);
195
+ }
196
+ function buildTimelineRunLines(key, run, items, details, width) {
197
+ const statusColor = run.status === "completed" ? "green" : run.status === "failed" ? "red" : run.status === "running" ? "yellow" : "white";
198
+ const headerText = `● ${RUN_LABELS[run.runType] ?? run.runType} ${run.status}${run.endedAt ? ` ${formatDuration(run.startedAt, run.endedAt)}` : ""}`;
199
+ const lines = renderTextLines(headerText, {
200
+ key: `${key}-header`,
201
+ width,
202
+ style: { color: statusColor, bold: true },
203
+ });
204
+ const showVerboseItems = run.status === "running";
205
+ if (showVerboseItems) {
206
+ for (const item of items) {
207
+ lines.push(...renderTimelineItemLines(`${key}-${item.id}`, item, width, 2));
208
+ }
209
+ return lines;
210
+ }
211
+ for (const [index, detail] of details.entries()) {
212
+ if (detail.tone === "message" || detail.tone === "user") {
213
+ lines.push(...renderRichTextLines(detail.tone === "user" ? `you: ${detail.text}` : detail.text, {
214
+ key: `${key}-detail-${index}`,
215
+ width,
216
+ firstPrefix: [{ text: " " }],
217
+ continuationPrefix: [{ text: " " }],
218
+ style: { color: detail.tone === "user" ? "yellow" : undefined },
219
+ }));
220
+ continue;
221
+ }
222
+ lines.push(...renderTextLines(`${detail.tone === "command" ? "$ " : ""}${detail.text}`, {
223
+ key: `${key}-detail-${index}`,
224
+ width,
225
+ firstPrefix: [{ text: " " }],
226
+ continuationPrefix: [{ text: " " }],
227
+ style: detail.tone === "command" ? { color: "white" } : { dimColor: true },
228
+ }));
229
+ }
230
+ return lines;
231
+ }
232
+ function renderTimelineItemLines(key, item, width, indent) {
233
+ const prefix = [{ text: " ".repeat(indent) }];
234
+ if (item.type === "agentMessage" || item.type === "userMessage" || item.type === "plan" || item.type === "reasoning") {
235
+ return renderRichTextLines(item.type === "userMessage" ? `you: ${item.text ?? ""}` : item.text ?? "", {
236
+ key,
237
+ width,
238
+ firstPrefix: prefix,
239
+ continuationPrefix: prefix,
240
+ style: item.type === "userMessage" ? { color: "yellow" } : undefined,
241
+ });
242
+ }
243
+ const summary = itemSummary(item);
244
+ const lines = renderTextLines(summary, {
245
+ key,
246
+ width,
247
+ firstPrefix: prefix,
248
+ continuationPrefix: prefix,
249
+ style: item.status === "failed" || item.status === "declined"
250
+ ? { color: "red" }
251
+ : item.status === "inProgress"
252
+ ? { color: "yellow" }
253
+ : item.type === "commandExecution"
254
+ ? { color: "white" }
255
+ : { dimColor: item.type !== "commandExecution" },
256
+ });
257
+ if (item.output && item.status === "inProgress") {
258
+ lines.push(...renderTextLines(lastNonEmptyLine(item.output), {
259
+ key: `${key}-output`,
260
+ width,
261
+ firstPrefix: [{ text: `${" ".repeat(indent + 2)}` }],
262
+ continuationPrefix: [{ text: `${" ".repeat(indent + 2)}` }],
263
+ style: { dimColor: true },
264
+ }));
265
+ }
266
+ return lines;
267
+ }
268
+ function buildHistoryIntroLines(width) {
269
+ return [
270
+ ...renderTextLines("PatchRelay activity history.", {
271
+ key: "history-intro-1",
272
+ width,
273
+ style: { dimColor: true },
274
+ }),
275
+ ...renderTextLines("Runs, waits, and wake-ups are shown here in PatchRelay order.", {
276
+ key: "history-intro-2",
277
+ width,
278
+ style: { dimColor: true },
279
+ }),
280
+ ];
281
+ }
282
+ function buildHistoryLines(history, plan, activeRunId, width) {
283
+ if (history.length === 0) {
284
+ return renderTextLines("No state history available.", {
285
+ key: "history-empty",
286
+ width,
287
+ style: { dimColor: true },
288
+ });
289
+ }
290
+ const lines = [];
291
+ let runCounter = 0;
292
+ for (const [nodeIndex, node] of history.entries()) {
293
+ lines.push(...renderTextLines(`${node.isCurrent ? "◉" : "○"} ${STATE_LABELS[node.state] ?? node.state} ${formatTime(node.enteredAt)}`, {
294
+ key: `history-node-${nodeIndex}`,
295
+ width,
296
+ style: { color: node.isCurrent ? "green" : undefined, bold: node.isCurrent },
297
+ }));
298
+ if (node.reason) {
299
+ lines.push(...renderRichTextLines(node.reason, {
300
+ key: `history-node-${nodeIndex}-reason`,
301
+ width,
302
+ firstPrefix: [{ text: "│ ", dimColor: true }],
303
+ continuationPrefix: [{ text: "│ ", dimColor: true }],
304
+ style: { dimColor: true },
305
+ }));
306
+ }
307
+ if (node.runs.length > 5) {
308
+ lines.push(...renderTextLines(historyRunSummary(node.runs), {
309
+ key: `history-node-${nodeIndex}-summary`,
310
+ width,
311
+ firstPrefix: [{ text: "│ ", dimColor: true }],
312
+ continuationPrefix: [{ text: "│ ", dimColor: true }],
313
+ style: { dimColor: true },
314
+ }));
315
+ }
316
+ for (const run of node.runs) {
317
+ lines.push(...renderHistoryRunLines(run, runCounter, width, "│ "));
318
+ if (run.id === activeRunId && plan?.length) {
319
+ for (const [index, entry] of plan.entries()) {
320
+ lines.push({
321
+ key: `history-run-${run.id}-plan-${index}`,
322
+ segments: [
323
+ { text: "│ ", dimColor: true },
324
+ { text: `[${planStepSymbol(entry.status)}]`, color: planStepColor(entry.status) },
325
+ { text: " " },
326
+ { text: entry.step },
327
+ ],
328
+ });
329
+ }
330
+ }
331
+ runCounter += 1;
332
+ }
333
+ for (const [tripIndex, trip] of node.sideTrips.entries()) {
334
+ lines.push(...renderSideTripLines(trip, runCounter, width));
335
+ runCounter += trip.runs.length;
336
+ if (tripIndex < node.sideTrips.length - 1) {
337
+ lines.push({ key: `history-trip-gap-${nodeIndex}-${tripIndex}`, segments: [{ text: "│", dimColor: true }] });
338
+ }
339
+ }
340
+ if (nodeIndex < history.length - 1) {
341
+ lines.push({ key: `history-node-connector-${nodeIndex}`, segments: [{ text: "│", dimColor: true }] });
342
+ }
343
+ }
344
+ return lines;
345
+ }
346
+ function renderHistoryRunLines(run, index, width, gutter) {
347
+ const statusColor = run.status === "completed" ? "green" : run.status === "failed" ? "red" : run.status === "running" ? "yellow" : "white";
348
+ const duration = run.endedAt ? formatDuration(run.startedAt, run.endedAt) : undefined;
349
+ const stats = [
350
+ run.messageCount !== undefined ? `${run.messageCount} msgs` : null,
351
+ run.commandCount ? `${run.commandCount} cmds` : null,
352
+ run.fileChangeCount ? `${run.fileChangeCount} files` : null,
353
+ ].filter((value) => Boolean(value));
354
+ const lines = renderTextLines(`${gutter}${run.status === "completed" ? "✓" : run.status === "failed" ? "✗" : run.status === "running" ? "▸" : "•"} #${index + 1} (${RUN_LABELS[run.runType] ?? run.runType})${duration ? ` ${duration}` : ""}${stats.length ? ` ${stats.join(", ")}` : ""}`, {
355
+ key: `history-run-${run.id}`,
356
+ width,
357
+ style: { color: statusColor },
358
+ });
359
+ if (run.lastMessage) {
360
+ lines.push(...renderRichTextLines(run.lastMessage, {
361
+ key: `history-run-${run.id}-message`,
362
+ width,
363
+ firstPrefix: [{ text: `${gutter} `, dimColor: true }],
364
+ continuationPrefix: [{ text: `${gutter} `, dimColor: true }],
365
+ style: { dimColor: true },
366
+ }));
367
+ }
368
+ return lines;
369
+ }
370
+ function renderSideTripLines(trip, runOffset, width) {
371
+ const lines = renderTextLines(`│ ┌ ${STATE_LABELS[trip.state] ?? trip.state} ${formatTime(trip.enteredAt)}`, {
372
+ key: `history-trip-${trip.state}-${trip.enteredAt}`,
373
+ width,
374
+ style: { color: "magenta", bold: true },
375
+ });
376
+ if (trip.reason) {
377
+ lines.push(...renderRichTextLines(trip.reason, {
378
+ key: `history-trip-${trip.state}-${trip.enteredAt}-reason`,
379
+ width,
380
+ firstPrefix: [{ text: "│ │ ", dimColor: true }],
381
+ continuationPrefix: [{ text: "│ │ ", dimColor: true }],
382
+ style: { dimColor: true },
383
+ }));
384
+ }
385
+ for (const [index, run] of trip.runs.entries()) {
386
+ lines.push(...renderHistoryRunLines(run, runOffset + index, width, "│ │ "));
387
+ }
388
+ const returnLabel = trip.returnedAt
389
+ ? `│ └→ ${STATE_LABELS[trip.returnState] ?? trip.returnState} ${formatTime(trip.returnedAt)}`
390
+ : "│ └─ (active)";
391
+ lines.push(...renderTextLines(returnLabel, {
392
+ key: `history-trip-${trip.state}-${trip.enteredAt}-return`,
393
+ width,
394
+ style: { dimColor: !trip.returnedAt },
395
+ }));
396
+ return lines;
397
+ }
398
+ function buildFacts(issue, issueContext) {
399
+ const facts = [];
400
+ const rereviewNeeded = isRereviewNeeded(issue);
401
+ if (issue.prNumber !== undefined)
402
+ facts.push(`PR #${issue.prNumber}`);
403
+ if (issue.prReviewState === "approved")
404
+ facts.push("approved");
405
+ else if (rereviewNeeded)
406
+ facts.push("re-review needed");
407
+ else if (issue.prReviewState === "changes_requested")
408
+ facts.push("changes requested");
409
+ if (issue.waitingReason && issue.sessionState === "waiting_input")
410
+ facts.push(issue.waitingReason);
411
+ const checks = prChecksFact({
412
+ ...issue,
413
+ latestFailureCheckName: issueContext?.latestFailureCheckName ?? issue.latestFailureCheckName,
414
+ });
415
+ if (checks) {
416
+ facts.push(checks.text);
417
+ }
418
+ return facts;
419
+ }
420
+ function buildMeta(tokenUsage, diffSummary, issueContext) {
421
+ const meta = [];
422
+ if (tokenUsage)
423
+ meta.push(`${formatTokens(tokenUsage.inputTokens)} in / ${formatTokens(tokenUsage.outputTokens)} out`);
424
+ if (diffSummary && diffSummary.filesChanged > 0)
425
+ meta.push(`${diffSummary.filesChanged}f +${diffSummary.linesAdded} -${diffSummary.linesRemoved}`);
426
+ if (issueContext?.runCount)
427
+ meta.push(`${issueContext.runCount} runs`);
428
+ return meta;
429
+ }
430
+ function formatTokens(value) {
431
+ if (value >= 1_000_000)
432
+ return `${(value / 1_000_000).toFixed(1)}M`;
433
+ if (value >= 1_000)
434
+ return `${(value / 1_000).toFixed(1)}k`;
435
+ return String(value);
436
+ }
437
+ function formatDuration(startedAt, endedAt) {
438
+ const ms = new Date(endedAt).getTime() - new Date(startedAt).getTime();
439
+ const seconds = Math.floor(ms / 1000);
440
+ if (seconds < 60)
441
+ return `${seconds}s`;
442
+ const minutes = Math.floor(seconds / 60);
443
+ const remainder = seconds % 60;
444
+ return `${minutes}m${remainder > 0 ? ` ${String(remainder).padStart(2, "0")}s` : ""}`;
445
+ }
446
+ function formatTime(iso) {
447
+ return new Date(iso).toLocaleTimeString("en-GB", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" });
448
+ }
449
+ function elapsedLabel(startedAt) {
450
+ const elapsed = Math.max(0, Math.floor((Date.now() - new Date(startedAt).getTime()) / 1000));
451
+ const minutes = Math.floor(elapsed / 60);
452
+ const seconds = elapsed % 60;
453
+ return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
454
+ }
455
+ function itemSummary(item) {
456
+ switch (item.type) {
457
+ case "commandExecution": {
458
+ const exit = item.exitCode !== undefined && item.exitCode !== 0 ? ` exit ${item.exitCode}` : "";
459
+ const duration = item.durationMs && item.durationMs >= 1000 ? ` ${Math.floor(item.durationMs / 1000)}s` : "";
460
+ return `$ ${cleanCommand(item.command ?? "?")}${exit}${duration}`;
461
+ }
462
+ case "fileChange":
463
+ return summarizeFileChanges(item.changes ?? []);
464
+ case "mcpToolCall":
465
+ case "dynamicToolCall":
466
+ return `used ${item.toolName ?? item.type}`;
467
+ default:
468
+ return (item.text ?? item.type).replace(/\s+/g, " ").trim();
469
+ }
470
+ }
471
+ function summarizeFileChanges(changes) {
472
+ const files = Array.from(new Set(changes
473
+ .map((change) => {
474
+ if (!change || typeof change !== "object")
475
+ return undefined;
476
+ const path = change.path;
477
+ return typeof path === "string" && path.trim().length > 0 ? path : undefined;
478
+ })
479
+ .filter((path) => Boolean(path))));
480
+ if (files.length === 0) {
481
+ return `updated ${changes.length} file${changes.length === 1 ? "" : "s"}`;
482
+ }
483
+ const names = files.map((path) => path.split("/").at(-1) ?? path);
484
+ return `updated ${files.length} file${files.length === 1 ? "" : "s"}: ${names.slice(0, 3).join(", ")}${names.length > 3 ? ` +${names.length - 3}` : ""}`;
485
+ }
486
+ function sessionDisplay(issue) {
487
+ if (issue.sessionState === "failed" || issue.factoryState === "failed" || issue.factoryState === "escalated") {
488
+ return { label: "needs help", color: "red" };
489
+ }
490
+ const state = issue.sessionState ?? "unknown";
491
+ return SESSION_DISPLAY[state] ?? { label: state, color: "white" };
492
+ }
493
+ function stageDisplay(issue) {
494
+ return STAGE_DISPLAY[effectiveState(issue)] ?? issue.factoryState;
495
+ }
496
+ function effectiveState(issue) {
497
+ if (issue.sessionState === "done")
498
+ return "done";
499
+ if (issue.sessionState === "failed")
500
+ return "failed";
501
+ if (issue.blockedByCount > 0 && !issue.activeRunType)
502
+ return "blocked";
503
+ if (issue.sessionState === "waiting_input")
504
+ return "awaiting_input";
505
+ if (issue.readyForExecution && !issue.activeRunType && !hasDisplayPrBlocker(issue))
506
+ return "ready";
507
+ return issue.factoryState;
508
+ }
509
+ function blockerText(issue, issueContext) {
510
+ const rereviewNeeded = isRereviewNeeded(issue);
511
+ if (issue.sessionState === "waiting_input")
512
+ return issue.waitingReason ?? "Waiting for input";
513
+ if (issue.sessionState === "failed" || issue.factoryState === "failed" || issue.factoryState === "escalated") {
514
+ return issue.statusNote ?? issue.waitingReason ?? "Needs operator intervention";
515
+ }
516
+ if (issue.waitingReason && !issue.activeRunType)
517
+ return issue.waitingReason;
518
+ if (issue.blockedByCount > 0)
519
+ return `Waiting on ${issue.blockedByKeys.join(", ")}`;
520
+ if (effectiveState(issue) === "repairing_queue")
521
+ return "Merge queue conflict, repairing branch";
522
+ if (effectiveState(issue) === "repairing_ci") {
523
+ const check = issueContext?.latestFailureCheckName ?? issue.latestFailureCheckName ?? "CI";
524
+ return `Repairing ${check}`;
525
+ }
526
+ const checks = prChecksFact({
527
+ ...issue,
528
+ latestFailureCheckName: issueContext?.latestFailureCheckName ?? issue.latestFailureCheckName,
529
+ });
530
+ if (checks?.color === "red") {
531
+ return checks.text;
532
+ }
533
+ if (checks?.color === "yellow" && checks.text.startsWith("checks ")) {
534
+ return `${checks.text} still running`;
535
+ }
536
+ if (rereviewNeeded)
537
+ return "Awaiting re-review after requested changes";
538
+ if (issue.prReviewState === "changes_requested")
539
+ return "Review changes requested";
540
+ if (issue.prNumber !== undefined && !issue.prReviewState && effectiveState(issue) !== "done")
541
+ return "Awaiting review";
542
+ return null;
543
+ }
544
+ function cleanCommand(raw) {
545
+ const bashMatch = raw.match(/^\/bin\/(?:ba)?sh\s+-\w*c\s+['"](.+?)['"]$/s);
546
+ if (bashMatch?.[1])
547
+ return bashMatch[1];
548
+ const bashMatch2 = raw.match(/^\/bin\/(?:ba)?sh\s+-\w*c\s+"(.+?)"$/s);
549
+ if (bashMatch2?.[1])
550
+ return bashMatch2[1];
551
+ return raw;
552
+ }
553
+ function lastNonEmptyLine(output) {
554
+ return output.split("\n").filter((line) => line.trim().length > 0).at(-1) ?? "";
555
+ }
556
+ function historyRunSummary(runs) {
557
+ const completed = runs.filter((run) => run.status === "completed").length;
558
+ const failed = runs.filter((run) => run.status === "failed").length;
559
+ const running = runs.filter((run) => run.status === "running").length;
560
+ const parts = [
561
+ completed > 0 ? `${completed} completed` : null,
562
+ failed > 0 ? `${failed} failed` : null,
563
+ running > 0 ? `${running} active` : null,
564
+ ].filter((value) => Boolean(value));
565
+ return `${runs.length} runs: ${parts.join(", ")}`;
566
+ }
567
+ function feedGlyph(status) {
568
+ if (status === "failed")
569
+ return "✗";
570
+ if (status === "completed" || status === "pr_merged")
571
+ return "✓";
572
+ return "●";
573
+ }
574
+ function freshnessSegments(connected, lastServerMessageAt) {
575
+ const freshness = describePatchRelayFreshness(connected, lastServerMessageAt);
576
+ return [{ text: freshness.label, color: freshness.color, bold: true }];
577
+ }
578
+ function blankLine(key) {
579
+ return { key, segments: [] };
580
+ }
581
+ function trimTrailingBlankLines(lines) {
582
+ const result = [...lines];
583
+ while (result.length > 0 && result[result.length - 1]?.segments.length === 0) {
584
+ result.pop();
585
+ }
586
+ return result;
587
+ }
588
+ function segmentsToText(segments) {
589
+ return segments.map((segment) => segment.text).join("");
590
+ }
@@ -0,0 +1,74 @@
1
+ function isPassingCheckStatus(status) {
2
+ return status === "passed" || status === "success";
3
+ }
4
+ function isFailingCheckStatus(status) {
5
+ return status === "failed" || status === "failure";
6
+ }
7
+ function isPendingCheckStatus(status) {
8
+ return status === "pending" || status === "in_progress";
9
+ }
10
+ export function hasPendingPrChecks(issue) {
11
+ const summary = issue.prChecksSummary;
12
+ if (summary?.total) {
13
+ return summary.pending > 0 || summary.completed < summary.total;
14
+ }
15
+ return isPendingCheckStatus(issue.prCheckStatus);
16
+ }
17
+ export function hasFailedPrChecks(issue) {
18
+ const summary = issue.prChecksSummary;
19
+ if (summary?.total) {
20
+ return summary.failed > 0 || summary.overall === "failure";
21
+ }
22
+ return isFailingCheckStatus(issue.prCheckStatus);
23
+ }
24
+ export function arePrChecksCompleteAndGreen(issue) {
25
+ const summary = issue.prChecksSummary;
26
+ if (summary?.total) {
27
+ return summary.pending === 0 && summary.failed === 0;
28
+ }
29
+ return isPassingCheckStatus(issue.prCheckStatus);
30
+ }
31
+ export function isRereviewNeeded(issue) {
32
+ return issue.prReviewState === "changes_requested"
33
+ && arePrChecksCompleteAndGreen(issue)
34
+ && !issue.activeRunType;
35
+ }
36
+ export function prChecksFact(issue) {
37
+ const summary = issue.prChecksSummary;
38
+ if (hasFailedPrChecks(issue)) {
39
+ const failedNames = summary?.failedNames ?? [];
40
+ const checkInfo = issue.latestFailureCheckName
41
+ ?? (failedNames.length > 0 ? failedNames.slice(0, 2).join(", ") : "checks");
42
+ return { text: `${checkInfo} failed`, color: "red" };
43
+ }
44
+ if (summary?.total) {
45
+ if (summary.pending > 0 || summary.completed < summary.total) {
46
+ return { text: `checks ${summary.completed}/${summary.total}`, color: "yellow" };
47
+ }
48
+ if (summary.failed === 0) {
49
+ return { text: "checks passed", color: "green" };
50
+ }
51
+ }
52
+ if (isPassingCheckStatus(issue.prCheckStatus)) {
53
+ return { text: "checks passed", color: "green" };
54
+ }
55
+ if (isPendingCheckStatus(issue.prCheckStatus)) {
56
+ return { text: "checks running", color: "yellow" };
57
+ }
58
+ return undefined;
59
+ }
60
+ export function hasDisplayPrBlocker(issue) {
61
+ if (issue.prNumber === undefined || issue.activeRunType) {
62
+ return false;
63
+ }
64
+ if (hasPendingPrChecks(issue) || hasFailedPrChecks(issue)) {
65
+ return true;
66
+ }
67
+ if (issue.prReviewState === "changes_requested" && !isRereviewNeeded(issue)) {
68
+ return true;
69
+ }
70
+ if (!issue.prReviewState && issue.factoryState === "pr_open") {
71
+ return true;
72
+ }
73
+ return false;
74
+ }