-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.ts
More file actions
751 lines (694 loc) · 23.8 KB
/
utils.ts
File metadata and controls
751 lines (694 loc) · 23.8 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/**
* Shared utilities for issue commands
*
* Common functionality used by explain, plan, view, and other issue commands.
*/
import pLimit from "p-limit";
import {
findProjectsBySlug,
getAutofixState,
getIssue,
getIssueByShortId,
getIssueInOrg,
type IssueSort,
listIssuesPaginated,
listOrganizations,
ORG_FANOUT_CONCURRENCY,
triggerRootCauseAnalysis,
tryGetIssueByShortId,
} from "../../lib/api-client.js";
import { type IssueSelector, parseIssueArg } from "../../lib/arg-parsing.js";
import { getProjectByAlias } from "../../lib/db/project-aliases.js";
import { detectAllDsns } from "../../lib/dsn/index.js";
import {
ApiError,
type AuthGuardFailure,
ContextError,
ResolutionError,
withAuthGuard,
} from "../../lib/errors.js";
import { getProgressMessage } from "../../lib/formatters/seer.js";
import { expandToFullShortId, isShortSuffix } from "../../lib/issue-id.js";
import { logger } from "../../lib/logger.js";
import { poll } from "../../lib/polling.js";
import { resolveEffectiveOrg } from "../../lib/region.js";
import {
resolveFromDsn,
resolveOrg,
resolveOrgAndProject,
} from "../../lib/resolve-target.js";
import { parseSentryUrl } from "../../lib/sentry-url-parser.js";
import { buildIssueUrl } from "../../lib/sentry-urls.js";
import { isAllDigits } from "../../lib/utils.js";
import type { SentryIssue } from "../../types/index.js";
import { type AutofixState, isTerminalStatus } from "../../types/seer.js";
const log = logger.withTag("issue.utils");
/** Shared positional parameter for issue ID */
export const issueIdPositional = {
kind: "tuple",
parameters: [
{
placeholder: "issue",
brief:
"Issue: @latest, @most_frequent, <org>/ID, <project>-suffix, ID, or suffix",
parse: String,
},
],
} as const;
/**
* Build a command hint string for error messages.
*
* Returns context-aware hints based on the issue ID format:
* - Numeric ID (e.g., "123456789") → suggest `<org>/123456789`
* - Suffix only (e.g., "G") → suggest `<project>-G`
* - Has dash (e.g., "cli-G") → suggest `<org>/cli-G`
*
* @param command - The issue subcommand (e.g., "view", "explain")
* @param issueId - The user-provided issue ID
*/
export function buildCommandHint(command: string, issueId: string): string {
// Selectors already include the @ prefix and are self-contained
if (issueId.startsWith("@")) {
return `sentry issue ${command} <org>/${issueId}`;
}
// Numeric IDs always need org context - can't be combined with project
if (isAllDigits(issueId)) {
return `sentry issue ${command} <org>/${issueId}`;
}
// Short suffixes can be combined with project prefix
if (isShortSuffix(issueId)) {
return `sentry issue ${command} <project>-${issueId}`;
}
// Everything else (has dash) needs org prefix
return `sentry issue ${command} <org>/${issueId}`;
}
/** Default timeout in milliseconds (6 minutes) */
const DEFAULT_TIMEOUT_MS = 360_000;
/**
* Result of resolving an issue ID - includes full issue object.
* Used by view command which needs the complete issue data.
*/
export type ResolvedIssueResult = {
/** Resolved organization slug (may be undefined for numeric IDs without context) */
org: string | undefined;
/** Full issue object from API */
issue: SentryIssue;
};
/** Internal type for strict resolution (org required) */
type StrictResolvedIssue = {
/** Resolved organization slug */
org: string;
/** Full issue object from API */
issue: SentryIssue;
};
/**
* Try to resolve via alias cache.
* Returns null if the alias is not found in cache or fingerprint doesn't match.
*
* @param alias - The project alias (lowercase)
* @param suffix - The issue suffix (uppercase)
* @param cwd - Current working directory for DSN detection
*/
async function tryResolveFromAlias(
alias: string,
suffix: string,
cwd: string
): Promise<StrictResolvedIssue | null> {
// Detect DSNs to get fingerprint for validation
const detection = await detectAllDsns(cwd);
const fingerprint = detection.fingerprint;
const projectEntry = await getProjectByAlias(alias, fingerprint);
if (!projectEntry) {
return null;
}
const resolvedShortId = expandToFullShortId(suffix, projectEntry.projectSlug);
const issue = await getIssueByShortId(projectEntry.orgSlug, resolvedShortId);
return { org: projectEntry.orgSlug, issue };
}
/**
* Fallback for when the fast shortid fan-out found no matches.
* Uses findProjectsBySlug to give a precise error ("project not found" vs
* "issue not found") and retries the issue lookup on transient failures.
*/
async function resolveProjectSearchFallback(
projectSlug: string,
suffix: string,
commandHint: string
): Promise<StrictResolvedIssue> {
const { projects } = await findProjectsBySlug(projectSlug.toLowerCase());
if (projects.length === 0) {
throw new ResolutionError(
`Project '${projectSlug}'`,
"not found",
commandHint,
["No project with this slug found in any accessible organization"]
);
}
if (projects.length > 1) {
const orgList = projects.map((p) => p.orgSlug).join(", ");
throw new ResolutionError(
`Project '${projectSlug}'`,
"is ambiguous",
commandHint,
[
`Found in: ${orgList}`,
`Specify the org: sentry issue ... <org>/${projectSlug}-${suffix}`,
]
);
}
// Project exists — retry the issue lookup. The fast path may have failed
// due to a transient error (5xx, timeout); retrying here either succeeds
// or propagates the real error to the user.
const matchedProject = projects[0];
const matchedOrg = matchedProject?.orgSlug;
if (matchedOrg && matchedProject) {
const retryShortId = expandToFullShortId(suffix, matchedProject.slug);
const issue = await getIssueByShortId(matchedOrg, retryShortId);
return { org: matchedOrg, issue };
}
throw new ResolutionError(
`Project '${projectSlug}'`,
"not found",
commandHint
);
}
/**
* Resolve project-search type: search for project across orgs, then fetch issue.
*
* Resolution order:
* 1. Try alias cache (fast, local)
* 2. Check DSN detection cache
* 3. Try shortid endpoint directly across all orgs (fast path)
* 4. Fall back to findProjectsBySlug for precise error messages
*
* @param projectSlug - Project slug to search for
* @param suffix - Issue suffix (uppercase)
* @param cwd - Current working directory
* @param commandHint - Hint for error messages
*/
async function resolveProjectSearch(
projectSlug: string,
suffix: string,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
// 1. Try alias cache first (fast, local lookup)
const aliasResult = await tryResolveFromAlias(
projectSlug.toLowerCase(),
suffix,
cwd
);
if (aliasResult) {
return aliasResult;
}
// 2. Check if DSN detection already resolved this project.
// resolveFromDsn() reads from the DSN cache (populated by detectAllDsns
// in tryResolveFromAlias above) + project cache. This avoids the expensive
// listOrganizations() fan-out when the DSN matches the target project.
// Only catch resolveFromDsn errors — getIssueByShortId errors (e.g. 404)
// must propagate so we don't duplicate the expensive call via fallback.
let dsnTarget: Awaited<ReturnType<typeof resolveFromDsn>> | undefined;
try {
dsnTarget = await resolveFromDsn(cwd);
} catch {
// DSN resolution failed — fall through to full search
}
if (
dsnTarget &&
dsnTarget.project.toLowerCase() === projectSlug.toLowerCase()
) {
const fullShortId = expandToFullShortId(suffix, dsnTarget.project);
const issue = await getIssueByShortId(dsnTarget.org, fullShortId);
return { org: dsnTarget.org, issue };
}
// 3. Fast path: try resolving the short ID directly across all orgs.
// The shortid endpoint validates both project existence and issue existence
// in a single call, eliminating the separate getProject() round-trip.
// Concurrency-limited to avoid overwhelming the API for enterprise users.
const fullShortId = expandToFullShortId(suffix, projectSlug);
const orgs = await listOrganizations();
const limit = pLimit(ORG_FANOUT_CONCURRENCY);
const results = await Promise.all(
orgs.map((org) =>
limit(() =>
withAuthGuard(() => tryGetIssueByShortId(org.slug, fullShortId))
)
)
);
const successes: StrictResolvedIssue[] = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
const org = orgs[i];
if (result && org && result.ok && result.value) {
successes.push({ org: org.slug, issue: result.value });
}
}
if (successes.length === 1 && successes[0]) {
return successes[0];
}
if (successes.length > 1) {
const orgList = successes.map((s) => s.org).join(", ");
throw new ResolutionError(
`Project '${projectSlug}'`,
"is ambiguous",
commandHint,
[
`Found in: ${orgList}`,
`Specify the org: sentry issue ... <org>/${projectSlug}-${suffix}`,
]
);
}
// If every org failed with a real error (403, 5xx, network timeout),
// surface it instead of falling through to a misleading "not found".
// Only throw when ALL results are errors — if some orgs returned clean
// 404s ({ok: true, value: null}), fall through to the fallback for a
// precise error message.
const realErrors = results.filter(
(r): r is AuthGuardFailure => r !== undefined && !r.ok
);
if (realErrors.length === results.length && realErrors.length > 0) {
const firstError = realErrors[0]?.error;
if (firstError instanceof Error) {
throw firstError;
}
}
// 4. Fall back to findProjectsBySlug for precise error messages
// and retry the issue lookup (handles transient failures).
return resolveProjectSearchFallback(projectSlug, suffix, commandHint);
}
/**
* Resolve suffix-only type using DSN detection for project context.
*
* @param suffix - The issue suffix (uppercase)
* @param cwd - Current working directory for DSN detection
* @param commandHint - Hint for error messages
*/
async function resolveSuffixOnly(
suffix: string,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
const target = await resolveOrgAndProject({ cwd });
if (!target) {
throw new ResolutionError(
`Issue suffix '${suffix}'`,
"could not be resolved without project context",
commandHint
);
}
const fullShortId = expandToFullShortId(suffix, target.project);
const issue = await getIssueByShortId(target.org, fullShortId);
return { org: target.org, issue };
}
/**
* Resolve explicit-org-suffix type: org provided but only suffix given.
*
* This format (`org/suffix`) is ambiguous - we have org but no project.
* We don't use DSN detection here because mixing explicit org with
* DSN-detected project (which belongs to a potentially different org)
* would be semantically wrong and confusing.
*
* @param org - Explicit organization slug
* @param suffix - Issue suffix (uppercase)
* @param commandHint - Hint for error messages
*/
function resolveExplicitOrgSuffix(
org: string,
suffix: string,
commandHint: string
): never {
throw new ResolutionError(
`Issue suffix '${suffix}'`,
"could not be resolved without project context",
commandHint,
[
`The format '${org}/${suffix}' requires a project to build the full issue ID.`,
`Use: sentry issue ... ${org}/<project>-${suffix}`,
]
);
}
/**
* Map magic selectors to Sentry issue list sort parameters.
*
* `@latest` → `"date"` (most recent `lastSeen` timestamp)
* `@most_frequent` → `"freq"` (highest event frequency)
*/
const SELECTOR_SORT_MAP: Record<IssueSelector, IssueSort> = {
"@latest": "date",
"@most_frequent": "freq",
};
/**
* Human-readable labels for selectors (used in error messages).
*/
const SELECTOR_LABELS: Record<IssueSelector, string> = {
"@latest": "most recent",
"@most_frequent": "most frequent",
};
/**
* Resolve a magic `@` selector to the top matching issue.
*
* Fetches the issue list sorted by the selector's criteria and returns
* the first result. Requires organization context (explicit or auto-detected).
*
* @param selector - The magic selector (e.g., `@latest`, `@most_frequent`)
* @param explicitOrg - Optional explicit org slug from `org/@selector` format
* @param cwd - Current working directory for context resolution
* @param commandHint - Hint for error messages
* @returns The resolved issue with org context
* @throws {ContextError} When organization cannot be resolved
* @throws {ResolutionError} When no issues match the selector
*/
async function resolveSelector(
selector: IssueSelector,
explicitOrg: string | undefined,
cwd: string,
commandHint: string
): Promise<StrictResolvedIssue> {
// Resolve org: explicit from `org/@latest` or auto-detected from DSN/defaults
let orgSlug: string;
if (explicitOrg) {
orgSlug = await resolveEffectiveOrg(explicitOrg);
} else {
const resolved = await resolveOrg({ cwd });
if (!resolved) {
throw new ContextError("Organization", commandHint);
}
orgSlug = resolved.org;
}
const sort = SELECTOR_SORT_MAP[selector];
const label = SELECTOR_LABELS[selector];
// Fetch just the top issue with the appropriate sort
const { data: issues } = await listIssuesPaginated(orgSlug, "", {
sort,
perPage: 1,
query: "is:unresolved",
});
const issue = issues[0];
if (!issue) {
throw new ResolutionError(
`Selector '${selector}'`,
"no unresolved issues found",
commandHint,
[
`No unresolved issues found in org '${orgSlug}'.`,
`The ${label} issue selector only matches unresolved issues.`,
]
);
}
return { org: orgSlug, issue };
}
/**
* Options for resolving an issue ID.
*/
export type ResolveIssueOptions = {
/** User-provided issue argument (raw CLI input) */
issueArg: string;
/** Current working directory for context resolution */
cwd: string;
/** Command name for error messages (e.g., "view", "explain") */
command: string;
};
/**
* Extract the organization slug from a Sentry issue permalink.
*
* Handles both path-based (`https://sentry.io/organizations/{org}/issues/...`)
* and subdomain-style (`https://{org}.sentry.io/issues/...`) SaaS URLs.
* Returns undefined if the permalink is missing or not a recognized format.
*
* @param permalink - Issue permalink URL from the Sentry API response
*/
function extractOrgFromPermalink(
permalink: string | undefined
): string | undefined {
if (!permalink) {
return;
}
return parseSentryUrl(permalink)?.org;
}
/**
* Resolve a bare numeric issue ID.
*
* Attempts org-scoped resolution with region routing when org context can be
* derived from the working directory (DSN / env vars / config defaults).
* Falls back to the legacy unscoped endpoint otherwise.
* Extracts the org slug from the response permalink so callers like
* {@link resolveOrgAndIssueId} can proceed without explicit org context.
*/
async function resolveNumericIssue(
id: string,
cwd: string,
command: string,
commandHint: string
): Promise<ResolvedIssueResult> {
const resolvedOrg = await resolveOrg({ cwd });
try {
const issue = resolvedOrg
? await getIssueInOrg(resolvedOrg.org, id)
: await getIssue(id);
// Extract org from the response permalink as a fallback so that callers
// like resolveOrgAndIssueId (used by explain/plan) get the org slug even
// when no org context was available before the fetch.
const org = resolvedOrg?.org ?? extractOrgFromPermalink(issue.permalink);
return { org, issue };
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
// Improve on the generic "Issue not found" message by including the ID
// and suggesting the short-ID format, since users often confuse numeric
// group IDs with short-ID suffixes.
throw new ResolutionError(`Issue ${id}`, "not found", commandHint, [
`No issue with numeric ID ${id} found — you may not have access, or it may have been deleted.`,
`If this is a short ID suffix, try: sentry issue ${command} <project>-${id}`,
]);
}
throw err;
}
}
/**
* Resolve an issue ID to organization slug and full issue object.
*
* Supports all issue ID formats (now parsed by parseIssueArg in arg-parsing.ts):
* - selector: "@latest", "sentry/@most_frequent" → top issue by criteria
* - explicit: "sentry/cli-G" → org + project + suffix
* - explicit-org-suffix: "sentry/G" → org + suffix (needs DSN for project)
* - explicit-org-numeric: "sentry/123456789" → org + numeric ID
* - project-search: "cli-G" → search for project across orgs
* - suffix-only: "G" (requires DSN context)
* - numeric: "123456789" (direct fetch, no org)
*
* @param options - Resolution options
* @returns Object with org slug and full issue
* @throws {ContextError} When required context (org) is missing
* @throws {ResolutionError} When an issue or project could not be found or resolved
*/
export async function resolveIssue(
options: ResolveIssueOptions
): Promise<ResolvedIssueResult> {
const { issueArg, cwd, command } = options;
const parsed = parseIssueArg(issueArg);
const commandHint = buildCommandHint(command, issueArg);
switch (parsed.type) {
case "numeric":
return resolveNumericIssue(parsed.id, cwd, command, commandHint);
case "explicit": {
// Full context: org + project + suffix
const org = await resolveEffectiveOrg(parsed.org);
const fullShortId = expandToFullShortId(parsed.suffix, parsed.project);
const issue = await getIssueByShortId(org, fullShortId);
return { org, issue };
}
case "explicit-org-numeric": {
// Org + numeric ID — use org-scoped endpoint for proper region routing.
const org = await resolveEffectiveOrg(parsed.org);
try {
const issue = await getIssueInOrg(org, parsed.numericId);
return { org, issue };
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
throw new ResolutionError(
`Issue ${parsed.numericId}`,
"not found",
commandHint,
[
`No issue with numeric ID ${parsed.numericId} found in org '${org}' — you may not have access, or it may have been deleted.`,
`If this is a short ID suffix, try: sentry issue ${command} <project>-${parsed.numericId}`,
]
);
}
throw err;
}
}
case "explicit-org-suffix": {
// Org + suffix only - ambiguous without project, always errors
const org = await resolveEffectiveOrg(parsed.org);
return resolveExplicitOrgSuffix(org, parsed.suffix, commandHint);
}
case "project-search":
// Project slug + suffix - search across orgs
return resolveProjectSearch(
parsed.projectSlug,
parsed.suffix,
cwd,
commandHint
);
case "suffix-only":
// Just suffix - need DSN for org and project
return resolveSuffixOnly(parsed.suffix, cwd, commandHint);
case "selector":
// Magic @ selector - fetch top issue by sort criteria
return resolveSelector(parsed.selector, parsed.org, cwd, commandHint);
default: {
// Exhaustive check - this should never be reached
const _exhaustive: never = parsed;
throw new Error(
`Unexpected issue arg type: ${JSON.stringify(_exhaustive)}`
);
}
}
}
/**
* Resolve both organization slug and numeric issue ID.
* Required for autofix endpoints that need both org and issue ID.
* This is a stricter wrapper around resolveIssue that throws if org is undefined.
*
* @param options - Resolution options
* @returns Object with org slug and numeric issue ID
* @throws {ContextError} When organization cannot be resolved
*/
export async function resolveOrgAndIssueId(
options: ResolveIssueOptions
): Promise<{ org: string; issueId: string }> {
const result = await resolveIssue(options);
if (!result.org) {
const commandHint = buildCommandHint(options.command, options.issueArg);
throw new ContextError("Organization", commandHint);
}
return { org: result.org, issueId: result.issue.id };
}
type PollAutofixOptions = {
/** Organization slug */
orgSlug: string;
/** Numeric issue ID */
issueId: string;
/** Whether to suppress progress output (JSON mode) */
json: boolean;
/** Polling interval in milliseconds (default: 1000) */
pollIntervalMs?: number;
/** Maximum time to wait in milliseconds (default: 360000 = 6 minutes) */
timeoutMs?: number;
/** Custom timeout error message */
timeoutMessage?: string;
/** Stop polling when status is WAITING_FOR_USER_RESPONSE (default: false) */
stopOnWaitingForUser?: boolean;
};
type EnsureRootCauseOptions = {
/** Organization slug */
org: string;
/** Numeric issue ID */
issueId: string;
/** Whether to suppress progress output (JSON mode) */
json: boolean;
/** Force new analysis even if one exists */
force?: boolean;
};
/**
* Ensure root cause analysis exists for an issue.
*
* If no analysis exists (or force is true), triggers a new analysis.
* If analysis is in progress, waits for it to complete.
* If analysis failed (ERROR status), retries automatically.
*
* @param options - Configuration options
* @returns The completed autofix state with root causes
*/
export async function ensureRootCauseAnalysis(
options: EnsureRootCauseOptions
): Promise<AutofixState> {
const { org, issueId, json, force = false } = options;
// 1. Check for existing analysis (skip if --force)
let state = force ? null : await getAutofixState(org, issueId);
// Handle error status - we will retry the analysis
if (state?.status === "ERROR") {
if (!json) {
log.info("Previous analysis failed, retrying...");
}
state = null;
}
// 2. Trigger new analysis if none exists or forced
if (!state) {
if (!json) {
const prefix = force ? "Forcing fresh" : "Starting";
log.info(`${prefix} root cause analysis, it can take several minutes...`);
}
await triggerRootCauseAnalysis(org, issueId);
}
// 3. Poll until complete (if not already completed)
if (
!state ||
(state.status !== "COMPLETED" &&
state.status !== "WAITING_FOR_USER_RESPONSE")
) {
state = await pollAutofixState({
orgSlug: org,
issueId,
json,
stopOnWaitingForUser: true,
});
}
return state;
}
/**
* Check if polling should stop based on current state.
*
* @param state - Current autofix state
* @param stopOnWaitingForUser - Whether to stop on WAITING_FOR_USER_RESPONSE status
* @returns True if polling should stop
*/
function shouldStopPolling(
state: AutofixState,
stopOnWaitingForUser: boolean
): boolean {
if (isTerminalStatus(state.status)) {
return true;
}
if (stopOnWaitingForUser && state.status === "WAITING_FOR_USER_RESPONSE") {
return true;
}
return false;
}
/**
* Poll autofix state until completion or timeout.
* Uses the generic poll utility with autofix-specific configuration.
*
* @param options - Polling configuration
* @returns Final autofix state
* @throws {Error} On timeout
*/
export async function pollAutofixState(
options: PollAutofixOptions
): Promise<AutofixState> {
const {
orgSlug,
issueId,
json,
pollIntervalMs,
timeoutMs = DEFAULT_TIMEOUT_MS,
timeoutMessage = "Operation timed out after 6 minutes. Try again or check the issue in Sentry web UI.",
stopOnWaitingForUser = false,
} = options;
const issueUrl = buildIssueUrl(orgSlug, issueId);
const timeoutHint =
"The analysis may still complete in the background.\n" +
` View in Sentry: ${issueUrl}\n` +
` Or retry: sentry issue explain ${issueId}`;
return await poll<AutofixState>({
fetchState: () => getAutofixState(orgSlug, issueId),
shouldStop: (state) => shouldStopPolling(state, stopOnWaitingForUser),
getProgressMessage,
json,
pollIntervalMs,
timeoutMs,
timeoutMessage,
timeoutHint,
initialMessage: "Waiting for analysis to start...",
});
}