@andrioid/paseo-attention-span 0.4.9 → 0.4.11

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.
Files changed (42) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +164 -49
  3. package/client/card.tsx +25 -9
  4. package/client/coverage-settings.tsx +36 -1
  5. package/client/entity.tsx +118 -0
  6. package/client/feedback.tsx +2 -2
  7. package/client/icons.ts +5 -0
  8. package/client/next-up.tsx +148 -76
  9. package/client/session-menu.ts +2 -1
  10. package/client/sheet.tsx +141 -23
  11. package/client/ui.tsx +104 -6
  12. package/docs/architecture.md +17 -11
  13. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  14. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  15. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  16. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  17. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  18. package/docs/screenshots/desktop-dark-doing.png +0 -0
  19. package/docs/screenshots/desktop-dark-history-reviewed.png +0 -0
  20. package/docs/screenshots/desktop-dark-history.png +0 -0
  21. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  22. package/docs/screenshots/desktop-dark-settings.png +0 -0
  23. package/docs/screenshots/desktop-dark-waiting-too-long.png +0 -0
  24. package/docs/screenshots/desktop-dark-waiting.png +0 -0
  25. package/docs/screenshots/phone-dark-doing.png +0 -0
  26. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  27. package/index.server.ts +2 -0
  28. package/package.json +1 -1
  29. package/requirements.yaml +4 -2
  30. package/server/classify.ts +56 -12
  31. package/server/details.ts +3 -2
  32. package/server/fixture.ts +50 -10
  33. package/server/gh.ts +29 -12
  34. package/server/github-types.ts +19 -2
  35. package/server/projects.ts +47 -0
  36. package/server/queries.ts +41 -6
  37. package/server/service.ts +138 -22
  38. package/server/store.ts +2 -0
  39. package/server/view.ts +2 -0
  40. package/shared/attention.ts +57 -0
  41. package/shared/checks.ts +66 -0
  42. package/shared/rpc.ts +5 -1
@@ -4,7 +4,9 @@ import {
4
4
  type Chip,
5
5
  type Item,
6
6
  type NextUpIssue,
7
+ type IssueProject,
7
8
  type Person,
9
+ type ProjectInfo,
8
10
  type Reviewer,
9
11
  SECTION_ORDER,
10
12
  SECTIONS,
@@ -16,7 +18,7 @@ import {
16
18
  import { type AttentionConfig, FIELD_ROLES, type MergeMethod, nextUpField, sameField } from "../shared/config";
17
19
  import { ago, daysSince } from "../shared/format";
18
20
  import { workChip, workKind } from "../shared/work";
19
- import type { Actor, Comment, Details, HistoryResult, IssueNode, LinkedIssue, LiveResult, MentionNode, PickableNode, PullRequestNode, RequestedReviewer } from "./github-types";
21
+ import type { Actor, Comment, Details, HistoryResult, IssueNode, LinkedIssue, LiveResult, MentionNode, PickableNode, ProjectItemNode, PullRequestNode, RequestedReviewer } from "./github-types";
20
22
  import { asksQuestion, excerpt, plainText, taggedIn } from "./markdown";
21
23
  import { prKey } from "./queries";
22
24
  import { issueFor } from "./references";
@@ -417,6 +419,7 @@ export function classify({ data, details, config, now }: ClassifyInput): Attenti
417
419
  // Assigned issues not already in progress come before unclaimed ones [NXT-06].
418
420
  assigned: rankIssues(compact(data.assigned.nodes).filter((issue) => !listed.has(prKey(issue))), details, config),
419
421
  unclaimed: rankIssues(compact(data.unclaimed.nodes), details, config),
422
+ projects: issueProjects([...compact(data.assigned.nodes), ...compact(data.unclaimed.nodes)], details),
420
423
  };
421
424
  }
422
425
 
@@ -580,18 +583,33 @@ export function mergeMethodFor(pr: PullRequestNode, config: AttentionConfig): Me
580
583
  function rankIssues(nodes: PickableNode[], details: Details, config: AttentionConfig): NextUpIssue[] {
581
584
  const [priority, effort, scope] = FIELD_ROLES.map((role) => nextUpField(config, role));
582
585
  const valueOf = (node: PickableNode, field: string | undefined) => node.issueFieldValues.nodes.find((value) => sameField(value.field?.name, field))?.name;
583
- const optionsOf = (field: string) => Object.entries(details.fieldOptions).find(([name]) => sameField(name, field))?.[1];
584
- // Position in the configured order (matched by name), else in the field's own options; missing goes last.
585
- const position = (value: string | undefined, ranked: { field: string; order?: string[] } | undefined) => {
586
+ // A field of the issue's own org: its options' order, or the colors it gave them. Two orgs may both have a Priority field,
587
+ // ordered and colored differently [NXT-02, NXT-10].
588
+ const ofOrg = <T,>(byOrg: Record<string, Record<string, T>> | undefined, node: PickableNode, field: string) =>
589
+ Object.entries(byOrg?.[node.repository.nameWithOwner.split("/")[0].toLowerCase()] ?? {}).find(([name]) => sameField(name, field))?.[1];
590
+ // Position in the configured order (matched by name), else in the issue's org's own options; missing goes last.
591
+ const position = (node: PickableNode, ranked: { field: string; order?: string[] } | undefined) => {
592
+ const value = valueOf(node, ranked?.field);
586
593
  if (!value || !ranked) return Infinity;
587
- const order = ranked.order ?? optionsOf(ranked.field) ?? [];
594
+ const order = ranked.order ?? ofOrg(details.fieldOptions, node, ranked.field) ?? [];
588
595
  const index = order.findIndex((name) => value.toLowerCase().includes(name.toLowerCase()));
589
596
  return index < 0 ? Infinity : index;
590
597
  };
598
+ // The color the issue's own org gave its priority, where that org colored any of them; otherwise the card ranks it by
599
+ // color itself [NXT-10].
600
+ const colorsOf = (node: PickableNode) => {
601
+ const colors = priority ? ofOrg(details.fieldColors, node, priority.field) : undefined;
602
+ return colors && Object.values(colors).some((color) => color !== "GRAY") ? colors : undefined;
603
+ };
591
604
  return nodes
592
605
  .map((node) => {
593
- const rank = position(valueOf(node, priority?.field), priority);
606
+ const rank = position(node, priority);
607
+ const priorityValue = valueOf(node, priority?.field);
608
+ const priorityColor = priorityValue ? colorsOf(node)?.[priorityValue] : undefined;
609
+ const projects = issueBoards(node);
594
610
  return {
611
+ // Kept out of the issue, for sorting only.
612
+ effortRank: position(node, effort),
595
613
  key: prKey(node),
596
614
  repo: node.repository.nameWithOwner,
597
615
  number: node.number,
@@ -605,17 +623,43 @@ function rankIssues(nodes: PickableNode[], details: Details, config: AttentionCo
605
623
  defaultBranch: node.repository.defaultBranchRef?.name,
606
624
  sources: node.sources ?? [],
607
625
  priorityRank: Number.isFinite(rank) ? rank : undefined,
626
+ ...(priorityColor ? { priorityColor } : {}),
627
+ ...(projects ? { projects } : {}),
608
628
  openPrs: (node.closedByPullRequestsReferences?.nodes ?? [])
609
629
  .filter((pr) => pr?.state === "OPEN")
610
630
  .map((pr) => ({ number: pr.number, url: pr.url, author: pr.author?.login ?? null })),
611
631
  };
612
632
  })
613
- .sort(
614
- (a, b) =>
615
- position(a.priority, priority) - position(b.priority, priority) ||
616
- position(a.effort, effort) - position(b.effort, effort) ||
617
- a.createdAt.localeCompare(b.createdAt),
618
- );
633
+ .sort((a, b) => (a.priorityRank ?? Infinity) - (b.priorityRank ?? Infinity) || a.effortRank - b.effortRank || a.createdAt.localeCompare(b.createdAt))
634
+ .map(({ effortRank: _, ...issue }) => issue);
635
+ }
636
+
637
+ // The items of an issue on open projects; a closed project's board is done with [NXT-12].
638
+ function openItems(node: PickableNode): { project: NonNullable<ProjectItemNode["project"]>; status: ProjectItemNode["status"] }[] {
639
+ return (node.projectItems?.nodes ?? []).flatMap((item) => (item?.project && !item.project.closed ? [{ project: item.project, status: item.status }] : []));
640
+ }
641
+
642
+ // The open boards an issue is on, with its Status on each [NXT-12]. Undefined when projects weren't read, or when GitHub cut
643
+ // the list short with none open in what came: then which boards it's on is unknown, rather than none.
644
+ function issueBoards(node: PickableNode): IssueProject[] | undefined {
645
+ if (!node.projectItems) return undefined;
646
+ const open = openItems(node);
647
+ if (open.length === 0 && node.projectItems.pageInfo?.hasNextPage) return undefined;
648
+ return open.map(({ project, status }) => ({ id: project.id, title: project.title, ...(status?.name ? { status: status.name, color: status.color } : {}) }));
649
+ }
650
+
651
+ // The ids of the open boards Next up's issues are on, for projectStatusesQuery [NXT-03].
652
+ export function issueBoardIds(nodes: (PickableNode | null)[]): string[] {
653
+ return [...new Set(nodes.flatMap((node) => (node ? openItems(node).map(({ project }) => project.id) : [])))];
654
+ }
655
+
656
+ // Every open project Next up's issues are on, once, with its Status options in the board's order, for the filter [NXT-03].
657
+ function issueProjects(nodes: PickableNode[], details: Details): ProjectInfo[] {
658
+ const byId = new Map<string, ProjectInfo>();
659
+ for (const { project } of nodes.flatMap(openItems)) {
660
+ if (!byId.has(project.id)) byId.set(project.id, { id: project.id, title: project.title, statuses: details.projectStatuses?.[project.id] ?? [] });
661
+ }
662
+ return [...byId.values()].sort((a, b) => a.title.localeCompare(b.title));
619
663
  }
620
664
 
621
665
  // ---- Mentions still waiting on me [MEN-01..06] ----
package/server/details.ts CHANGED
@@ -43,7 +43,7 @@ export async function itemDetails(subject: Subject, target: Target | undefined,
43
43
  const linked = "nodes { number title url state }";
44
44
  const query = `query {
45
45
  s: ${repository(subject.repo)} { issueOrPullRequest(number: ${subject.number}) {
46
- ... on Issue { closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { ${linked} } }
46
+ ... on Issue { closedByPullRequestsReferences(first: 5, includeClosedPrs: false) { ${linked} } }
47
47
  ... on PullRequest { closingIssuesReferences(first: 5) { ${linked} } }
48
48
  } }
49
49
  ${numbers.map((number, index) => ` p${index}: ${repository(pr!.repo)} { pullRequest(number: ${number}) { number additions deletions changedFiles ${checks ? contexts : ""} } }`).join("\n")}
@@ -67,7 +67,8 @@ ${numbers.map((number, index) => ` p${index}: ${repository(pr!.repo)} { pullReq
67
67
 
68
68
  return {
69
69
  size: own ? { additions: own.additions, deletions: own.deletions, files: own.changedFiles } : undefined,
70
- linked: (node?.closingIssuesReferences ?? node?.closedByPullRequestsReferences)?.nodes ?? [],
70
+ // An issue's open PRs only, as its card knows them, so the sheet holds the right room for them; closed ones are on GitHub [ATT-06].
71
+ linked: node?.closingIssuesReferences?.nodes ?? (node?.closedByPullRequestsReferences?.nodes ?? []).filter((link) => link.state === "OPEN"),
71
72
  failing,
72
73
  };
73
74
  }
package/server/fixture.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AgentSummary, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
1
+ import type { AgentSummary, GithubColor, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
2
2
  import type { SessionKind } from "../shared/config";
3
3
  import type { IssueField } from "../shared/setup";
4
4
  import type { Actor, Comment, Details, IssueNode, MentionNode, PickableNode, PullRequestNode, SearchResult } from "./github-types";
@@ -20,6 +20,23 @@ export const FIXTURE_ISSUE_FIELDS: IssueField[] = [
20
20
  { name: "Scope", options: ["🔙 Backend", "🖌 Frontend", "🕵 Full-stack", "📱 Mobile app"], orgs: ["acme"] },
21
21
  { name: "Team", options: ["Platform", "Payments"], orgs: ["acme"] },
22
22
  ];
23
+ // The org's colors for its priorities [NXT-10]; P3 is left gray, which shows untinted.
24
+ const PRIORITY_COLORS: Record<string, GithubColor> = { "🌋 P0 Urgent": "RED", "🏔 P1 High": "ORANGE", "🏕P2 Medium": "YELLOW", "🏝 P3 Low": "GRAY" };
25
+ // Two org projects with the board's built-in Status field, its options as the details request reads them [NXT-12].
26
+ const TODO_BOARD = { id: "PVT_todo", title: "TODO", closed: false };
27
+ const IDEAS_BOARD = { id: "PVT_ideas", title: "Ideas", closed: false };
28
+ const BOARD_STATUSES: Details["projectStatuses"] = {
29
+ [TODO_BOARD.id]: [s("Backlog", "GRAY"), s("Todo", "BLUE"), s("In progress", "YELLOW"), s("Done", "GREEN")],
30
+ [IDEAS_BOARD.id]: [s("New", "GRAY"), s("Exploring", "PINK"), s("Shaped", "PURPLE")],
31
+ };
32
+ function s(name: string, color: GithubColor) {
33
+ return { name, color };
34
+ }
35
+ // An issue's place on a board: its Status, or none.
36
+ function onBoard(board: typeof TODO_BOARD, status?: string): Pick<PickableNode, "projectItems"> {
37
+ const option = BOARD_STATUSES[board.id].find((o) => o.name === status);
38
+ return { projectItems: { nodes: [{ project: board, status: option ?? null }], pageInfo: { hasNextPage: false } } };
39
+ }
23
40
  const repository = { nameWithOwner: REPO, squashMergeAllowed: true, defaultBranchRef: { name: "main" } };
24
41
  const avatar = (id: number) => `https://avatars.githubusercontent.com/u/${id}?v=4`;
25
42
 
@@ -237,23 +254,28 @@ export function fixture(now: Date): { data: SearchResult; details: Details } {
237
254
  ],
238
255
  // My own issue, asked about long ago and never answered [ATT-11].
239
256
  asked: [issue(141, [comment(me, "Is this still needed?", 40)], "Rotate the analytics token", { author: me, createdAt: daysAgo(90) })],
257
+ // Each on a project board, where projects can be read [NXT-12].
240
258
  assigned: [
241
- pickable(150, fields("🏔 P1 High", "🐇 Small (0.5-2d)", "🔙 Backend"), 20, "Bug", "Orders export times out for big shops"),
242
- pickable(151, fields("🏕P2 Medium", "🐟 Tiny (< 4h)", "🔙 Backend"), 5, "Bug", "Price list import skips quoted rows", ISSUES_REPO),
259
+ { ...pickable(150, fields("🏔 P1 High", "🐇 Small (0.5-2d)", "🔙 Backend"), 20, "Bug", "Orders export times out for big shops"), ...onBoard(TODO_BOARD, "In progress") },
260
+ { ...pickable(151, fields("🏕P2 Medium", "🐟 Tiny (< 4h)", "🔙 Backend"), 5, "Bug", "Price list import skips quoted rows", ISSUES_REPO), ...onBoard(TODO_BOARD, "Todo") },
243
261
  ],
244
262
  // Found by the preview config's Next up sources [NXT-09].
245
263
  unclaimed: [
246
- { ...pickable(160, fields("🌋 P0 Urgent", "🐂 Medium (2-5d)", "🕵 Full-stack"), 40, "Feature", "Follow-up emails for unanswered offers"), sources: ["org:acme"] },
264
+ { ...pickable(160, fields("🌋 P0 Urgent", "🐂 Medium (2-5d)", "🕵 Full-stack"), 40, "Feature", "Follow-up emails for unanswered offers"), ...onBoard(TODO_BOARD, "Todo"), sources: ["org:acme"] },
247
265
  // Nobody's assigned, but alice has a PR open for it [NXT-10].
248
266
  {
249
267
  ...pickable(161, fields("🏝 P3 Low", "🐟 Tiny (< 4h)", "🔙 Backend"), 15, "Bug", "Deleted employee still shows in the calendar"),
268
+ ...onBoard(TODO_BOARD, "Backlog"),
250
269
  closedByPullRequestsReferences: { nodes: [{ number: 190, url: `https://github.com/${REPO}/pull/190`, state: "OPEN", author: { login: "alice" } }] },
251
270
  sources: ["org:acme"],
252
271
  },
253
- { ...pickable(162, fields("🏝 P3 Low", "🐇 Small (0.5-2d)", "🔙 Backend"), 30, "Debt", "Merge the two import commands"), sources: ["org:acme"] },
254
- { ...pickable(163, fields("🏝 P3 Low", "🐇 Small (0.5-2d)", "🖌 Frontend"), 8, "Bug", "Moving a task in the calendar loses its colour"), sources: ["org:acme"] },
255
- { ...pickable(164, fields("🏝 P3 Low", "🦑 Large (1-2w)", "📱 Mobile app"), 60, "Feature", "Offline mode for time tracking"), sources: ["org:acme"] },
256
- { ...pickable(165, {}, 3, "Task", "Devcontainers for pull requests", "me/tool"), sources: ["mine"] },
272
+ { ...pickable(162, fields("🏝 P3 Low", "🐇 Small (0.5-2d)", "🔙 Backend"), 30, "Debt", "Merge the two import commands"), ...onBoard(TODO_BOARD, "Backlog"), sources: ["org:acme"] },
273
+ { ...pickable(163, fields("🏝 P3 Low", "🐇 Small (0.5-2d)", "🖌 Frontend"), 8, "Bug", "Moving a task in the calendar loses its colour"), ...onBoard(TODO_BOARD, "Todo"), sources: ["org:acme"] },
274
+ { ...pickable(164, fields("🏝 P3 Low", "🦑 Large (1-2w)", "📱 Mobile app"), 60, "Feature", "Offline mode for time tracking"), ...onBoard(IDEAS_BOARD, "Exploring"), sources: ["org:acme"] },
275
+ // On a board without a status yet.
276
+ { ...pickable(166, { Effort: "🐂 Medium (2-5d)", Scope: "🖌 Frontend" }, 150, "Feature", "Dark mode for the planner"), ...onBoard(IDEAS_BOARD), sources: ["org:acme"] },
277
+ // On no board.
278
+ { ...pickable(165, {}, 3, "Task", "Devcontainers for pull requests", "me/tool"), projectItems: { nodes: [] }, sources: ["mine"] },
257
279
  ],
258
280
  merged: [
259
281
  merged(170, "Nightly backup check", 1, 171),
@@ -278,7 +300,9 @@ export function fixture(now: Date): { data: SearchResult; details: Details } {
278
300
  data,
279
301
  details: {
280
302
  behind: { [key(103)]: 1, [key(106)]: 12, [key(108)]: 139, [key(110)]: 2307, [key(114)]: 3, [key(115)]: 40 },
281
- fieldOptions: { Priority: ["🌋 P0 Urgent", "🏔 P1 High", "🏕P2 Medium", "🏝 P3 Low"] },
303
+ fieldOptions: { acme: { Priority: ["🌋 P0 Urgent", "🏔 P1 High", "🏕P2 Medium", "🏝 P3 Low"] } },
304
+ fieldColors: { acme: { Priority: PRIORITY_COLORS } },
305
+ projectStatuses: BOARD_STATUSES,
282
306
  issues: { [key(132)]: { number: 132, title: "The calendar can't be used with a keyboard", url: `https://github.com/${REPO}/issues/132`, repository } },
283
307
  checks: { [key(128)]: { required: 2, failing: 0, pending: 0 }, [key(129)]: { required: 1, failing: 0, pending: 0 } },
284
308
  mergeState: {},
@@ -330,6 +354,22 @@ export function fixtureDetails(subject: { kind: "pr" | "issue"; repo: string; nu
330
354
  return {
331
355
  size: pr ? { additions: 84 + (pr.number % 7) * 13, deletions: 12 + (pr.number % 5), files: 2 + (pr.number % 4) } : undefined,
332
356
  linked: subject.number === 120 ? [{ number: 200, title: "Customers can't tell when the shop is down", url: `https://github.com/${REPO}/issues/200`, state: "OPEN" }] : [],
333
- failing: checks && pr ? [{ pr: pr.number, checks: [{ name: "lint", rerunnable: true }, { name: "e2e (chromium)", rerunnable: true }], runs: [{ id: 9001, attempt: 1 }] }] : [],
357
+ // A matrix's jobs, a check from outside Actions, and a run rerun once already: "5 failed · lint, e2e ×3, Vercel · ↻ rerun once" [PRS-09].
358
+ failing:
359
+ checks && pr
360
+ ? [
361
+ {
362
+ pr: pr.number,
363
+ checks: [
364
+ { name: "lint", rerunnable: true },
365
+ { name: "e2e (chromium)", rerunnable: true },
366
+ { name: "e2e (firefox)", rerunnable: true },
367
+ { name: "e2e (webkit)", rerunnable: true },
368
+ { name: "Vercel", rerunnable: false },
369
+ ],
370
+ runs: [{ id: 9001, attempt: 2 }],
371
+ },
372
+ ]
373
+ : [],
334
374
  };
335
375
  }
package/server/gh.ts CHANGED
@@ -5,32 +5,49 @@ import { spawn } from "node:child_process";
5
5
  // Previews run on made-up data and never reach GitHub.
6
6
  export const FIXTURE = process.env.PASEO_ATTENTION_SPAN_FIXTURE === "1";
7
7
 
8
- export function runGh(args: string[], input?: string): Promise<{ code: number; stdout: string; stderr: string }> {
8
+ // `timeoutMs` stops gh and fails the call when GitHub takes longer, for asks that mustn't hold anything else up.
9
+ export function runGh(args: string[], input?: string, { timeoutMs }: { timeoutMs?: number } = {}): Promise<{ code: number; stdout: string; stderr: string }> {
9
10
  if (FIXTURE) return Promise.reject(new Error("GitHub is off in fixture mode."));
10
11
  return new Promise((resolve, reject) => {
11
12
  const child = spawn("gh", args, { stdio: ["pipe", "pipe", "pipe"] });
12
13
  let stdout = "";
13
14
  let stderr = "";
15
+ const timer = timeoutMs
16
+ ? setTimeout(() => {
17
+ child.kill();
18
+ reject(new Error(`GitHub didn't answer within ${Math.round(timeoutMs / 1000)} s`));
19
+ }, timeoutMs)
20
+ : undefined;
14
21
  child.stdout.on("data", (chunk) => (stdout += chunk));
15
22
  child.stderr.on("data", (chunk) => (stderr += chunk));
16
- child.on("error", (error: NodeJS.ErrnoException) =>
17
- reject(error.code === "ENOENT" ? new Error("The GitHub CLI (gh) isn't on the daemon's PATH.") : error),
18
- );
19
- child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
23
+ child.on("error", (error: NodeJS.ErrnoException) => {
24
+ clearTimeout(timer);
25
+ reject(error.code === "ENOENT" ? new Error("The GitHub CLI (gh) isn't on the daemon's PATH.") : error);
26
+ });
27
+ child.on("close", (code) => {
28
+ clearTimeout(timer);
29
+ resolve({ code: code ?? 1, stdout, stderr });
30
+ });
20
31
  child.stdin.end(input ?? "");
21
32
  });
22
33
  }
23
34
 
24
- // Partial errors (e.g. a deleted branch in a compare) still return the data that resolved.
25
- export async function graphql<T>(query: string, variables: Record<string, unknown> = {}): Promise<T> {
26
- const { code, stdout, stderr } = await runGh(["api", "graphql", "--input", "-"], JSON.stringify({ query, variables }));
27
- let parsed: { data?: T; errors?: { message: string }[] } | undefined;
35
+ // GitHub's answer with its errors kept beside whatever data resolved, for callers that must tell a partial answer from a
36
+ // whole one. Throws only when nothing came back at all.
37
+ export async function graphqlResult<T>(query: string, variables: Record<string, unknown> = {}, options: { timeoutMs?: number } = {}): Promise<{ data: T | null; errors: string[] }> {
38
+ const { code, stdout, stderr } = await runGh(["api", "graphql", "--input", "-"], JSON.stringify({ query, variables }), options);
39
+ let parsed: { data?: T | null; errors?: { message: string }[] } | undefined;
28
40
  try {
29
41
  parsed = JSON.parse(stdout);
30
42
  } catch {
31
43
  // Not JSON: an auth or network failure.
32
44
  }
33
- if (parsed?.data) return parsed.data;
34
- const message = parsed?.errors?.map((error) => error.message).join("; ") || stderr.trim() || `gh exited with ${code}`;
35
- throw new Error(message);
45
+ const errors = (parsed?.errors ?? []).map((error) => error.message);
46
+ if (parsed?.data) return { data: parsed.data, errors };
47
+ throw new Error(errors.join("; ") || stderr.trim() || `gh exited with ${code}`);
48
+ }
49
+
50
+ // Partial errors (e.g. a deleted branch in a compare) still return the data that resolved.
51
+ export async function graphql<T>(query: string, variables: Record<string, unknown> = {}): Promise<T> {
52
+ return (await graphqlResult<T>(query, variables)).data as T;
36
53
  }
@@ -1,5 +1,7 @@
1
1
  // Shapes returned by the queries in queries.ts.
2
2
 
3
+ import type { GithubColor } from "../shared/attention";
4
+
3
5
  type Nodes<T> = { nodes: T[] };
4
6
  type Repo = { nameWithOwner: string; defaultBranchRef?: { name: string } | null };
5
7
 
@@ -103,10 +105,19 @@ export interface PickableNode {
103
105
  issueFieldValues: Nodes<{ name?: string; field?: { name: string } }>;
104
106
  // Open PRs that close it, so a card can say someone is on it [NXT-10].
105
107
  closedByPullRequestsReferences?: Nodes<{ number: number; url: string; state: string; author: { login: string } | null }>;
108
+ // Only when projects can be read: the projects it's on, with the board's Status field and where it is on it [NXT-12].
109
+ projectItems?: Nodes<ProjectItemNode | null> & { pageInfo?: { hasNextPage: boolean } };
106
110
  // Added after the search: the Next up sources that found it [NXT-09].
107
111
  sources?: string[];
108
112
  }
109
113
 
114
+ export interface ProjectItemNode {
115
+ // Null for a board the token can't see, like one in an org that enforces SSO.
116
+ project: { id: string; title: string; closed: boolean } | null;
117
+ // The built-in Status field's value; empty when the item has none.
118
+ status: { name?: string; color?: GithubColor } | null;
119
+ }
120
+
110
121
  // One request per search, merged [GH-01].
111
122
  export interface LiveResult {
112
123
  viewer: { login: string; id: string };
@@ -135,8 +146,14 @@ export type SearchResult = LiveResult & HistoryResult;
135
146
  export interface Details {
136
147
  // "owner/name#number" -> commits the head is behind its base.
137
148
  behind: Record<string, number>;
138
- // Issue field name -> its options in order.
139
- fieldOptions: Record<string, string[]>;
149
+ // Org (lower case) -> issue field name -> its options in that org's order. Per org, as two orgs may order a Priority
150
+ // field differently [NXT-02].
151
+ fieldOptions: Record<string, Record<string, string[]>>;
152
+ // Org (lower case) -> issue field name -> option name -> the color that org gave it. Per org, as two orgs may both have a
153
+ // Priority field and color it differently [NXT-10].
154
+ fieldColors: Record<string, Record<string, Record<string, GithubColor>>>;
155
+ // Project id -> its Status options in the board's order, for Next up's filter [NXT-03].
156
+ projectStatuses: Record<string, { name: string; color: GithubColor }[]>;
140
157
  // "owner/name#number" -> the open issue my PRs' descriptions refer to; PRs and closed issues are left out [ATT-03].
141
158
  issues: Record<string, LinkedIssue>;
142
159
  // "owner/name#number" -> the checks the repo requires on my PR's last commit, as far as they've reported [PRS-14].
@@ -0,0 +1,47 @@
1
+ import type { ProjectsAccess } from "../shared/attention";
2
+ import { missingProjectScope } from "./queries";
3
+
4
+ // Projects are extra on Next up's issues [NXT-12]: these decide, from what GitHub answered, whether they can be read, and
5
+ // keep anything that goes wrong with them from costing the search they ride on.
6
+
7
+ type Answer = Pick<ProjectsAccess, "state" | "error">;
8
+
9
+ // Why projects can't be read: the scope, or something else in GitHub's own words.
10
+ export function projectsFailure(message: string): Answer {
11
+ return missingProjectScope(message) ? { state: "missing" } : { state: "failed", error: message };
12
+ }
13
+
14
+ // What the probe's answer says. On only when GitHub actually lists the viewer's projects: a partial answer with errors, or
15
+ // no answer at all, isn't a yes. `before` is the last answer: a failure for another reason after projects worked leaves
16
+ // them on, as each search falls back on its own.
17
+ export function probeAnswer(result: { data: { viewer?: { projectsV2?: unknown } | null } | null; errors: string[] } | Error, before: Answer["state"]): Answer {
18
+ // The scope missing is said whatever else came back.
19
+ const scope = !(result instanceof Error) && result.errors.find((error) => projectsFailure(error).state === "missing");
20
+ if (!scope && !(result instanceof Error) && result.data?.viewer?.projectsV2) return { state: "on" };
21
+ const answer = projectsFailure(result instanceof Error ? result.message : result.errors.join("; ") || "GitHub didn't list your projects");
22
+ return answer.state === "failed" && before === "on" ? { state: "on", error: answer.error } : answer;
23
+ }
24
+
25
+ // What went wrong reading projects in one refresh, each said once, for Settings; nothing when all went well.
26
+ export function projectsWarning(problems: string[]): string | undefined {
27
+ return problems.length ? [...new Set(problems.flatMap((problem) => problem.split("; ")))].join("; ") : undefined;
28
+ }
29
+
30
+ // One of Next up's searches with projects, falling back to the same search without them whatever goes wrong: GitHub
31
+ // failing it, or answering without its results. Boards the token can't see come back empty within an answer that has
32
+ // its results, which is kept. `failure` says what went wrong, for Settings.
33
+ export async function searchWithProjects<T>(
34
+ withProjects: () => Promise<{ data: T | null; errors: string[] }>,
35
+ without: () => Promise<T>,
36
+ hasResults: (data: T) => boolean,
37
+ ): Promise<{ data: T; failure?: string; partly?: string }> {
38
+ let failure: string;
39
+ try {
40
+ const { data, errors } = await withProjects();
41
+ if (data && hasResults(data)) return errors.length ? { data, partly: errors.join("; ") } : { data };
42
+ failure = errors.join("; ") || "GitHub returned no results";
43
+ } catch (error) {
44
+ failure = (error as Error).message;
45
+ }
46
+ return { data: await without(), failure };
47
+ }
package/server/queries.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { UnclaimedSource } from "../shared/attention";
1
+ import type { GithubColor, UnclaimedSource } from "../shared/attention";
2
2
  import type { AttentionConfig } from "../shared/config";
3
3
  import type { PickableNode, PullRequestNode, RequiredChecks } from "./github-types";
4
4
  import type { IssueRef } from "./references";
@@ -56,6 +56,18 @@ const FRAGMENTS: Record<string, string> = {
56
56
  issueType { name }
57
57
  issueFieldValues(first: 20) { nodes { ... on IssueFieldSingleSelectValue { name field { ... on IssueFieldCommon { name } } } } }
58
58
  closedByPullRequestsReferences(first: 5, includeClosedPrs: false) { nodes { number url state author { login } } }
59
+ }`,
60
+ // Needs read:project, so only asked for once the login is known to have it; without it GitHub fails the whole search [NXT-12].
61
+ // Archived items are off the board, so they don't count. Each board's Status options come once per board, from
62
+ // projectStatusesQuery, not with every issue on it [GH-01]. hasNextPage says when the list was cut short.
63
+ projects: `fragment projects on Issue {
64
+ projectItems(first: 10, includeArchived: false) {
65
+ pageInfo { hasNextPage }
66
+ nodes {
67
+ project { id title closed }
68
+ status: fieldValueByName(name: "Status") { ... on ProjectV2ItemFieldSingleSelectValue { name color } }
69
+ }
70
+ }
59
71
  }`,
60
72
  pr: `fragment pr on PullRequest {
61
73
  id number title url body isDraft createdAt updatedAt
@@ -79,10 +91,14 @@ const FRAGMENTS: Record<string, string> = {
79
91
  }`,
80
92
  };
81
93
 
94
+ // Next up's searches, which read the projects of what they find when they can [NXT-12].
95
+ const PICKABLE_SEARCHES: readonly SearchName[] = ["assigned", "unclaimed"];
96
+
82
97
  // A query for some searches, as aliases named after them, with only the fragments they use; GitHub rejects unused ones.
83
98
  // GitHub runs the searches in one request one after another, so the live ones go out as separate requests in parallel [GH-01].
84
- export function searchQuery(names: readonly SearchName[], withViewer = false): string {
85
- const fields = names.map((name) => ` ${name}: search(type: ISSUE, query: $${name}, first: ${SEARCHES[name].first}) {\n nodes { ${SEARCHES[name].nodes} }\n }`);
99
+ export function searchQuery(names: readonly SearchName[], withViewer = false, { projects = false } = {}): string {
100
+ const nodes = (name: SearchName) => `${SEARCHES[name].nodes}${projects && PICKABLE_SEARCHES.includes(name) ? " ...projects" : ""}`;
101
+ const fields = names.map((name) => ` ${name}: search(type: ISSUE, query: $${name}, first: ${SEARCHES[name].first}) {\n nodes { ${nodes(name)} }\n }`);
86
102
  const used = new Set<string>();
87
103
  const collect = (text: string) => {
88
104
  for (const [, name] of text.matchAll(/\.\.\.(\w+)/g)) {
@@ -212,11 +228,30 @@ export function detailsQuery(prs: PullRequestNode[], orgs: string[], refs: Issue
212
228
  return { query: `query Details {\n${fields.join("\n")}\n}`, compares };
213
229
  }
214
230
 
215
- // An org's single-select issue fields with their options, in the org's order [NXT-02].
231
+ // An org's single-select issue fields with their options, in the org's order [NXT-02], and the colors it gave them [NXT-10].
216
232
  const orgFields = (alias: string, org: string) => `${alias}: organization(login: ${JSON.stringify(org)}) {
217
- issueFields(first: 50) { nodes { ... on IssueFieldSingleSelect { name options { name } } } }
233
+ issueFields(first: 50) { nodes { ... on IssueFieldSingleSelect { name options { name color } } } }
218
234
  }`;
219
- export type OrgFields = { issueFields?: { nodes: { name?: string; options?: { name: string }[] }[] } } | null;
235
+ export type OrgFields = { issueFields?: { nodes: { name?: string; options?: { name: string; color?: GithubColor }[] }[] } } | null;
236
+
237
+ // The Status options of the boards Next up's issues are on, in each board's order, once per board [NXT-03, GH-01].
238
+ // Asked apart from the details request, so a board that can't be read costs only the filter's statuses.
239
+ export function projectStatusesQuery(ids: string[]): string {
240
+ const fields = ids.map(
241
+ (id, index) => `b${index}: node(id: ${JSON.stringify(id)}) { ... on ProjectV2 { field(name: "Status") { ... on ProjectV2SingleSelectField { options { name color } } } } }`,
242
+ );
243
+ return `query ProjectStatuses {\n${fields.join("\n")}\n}`;
244
+ }
245
+ export type ProjectStatusesResult = Record<string, { field?: { options?: { name: string; color: GithubColor }[] } | null } | null>;
246
+
247
+ // Answers only when the login may read projects; without read:project GitHub refuses it, which is how Next up tells [NXT-12].
248
+ // It must ask for a field read:project guards: totalCount isn't, so a token without the scope answered it. GitHub checks
249
+ // the scope against the query, not the data, so it's refused even for someone with no projects (seen 2026-11-11). One
250
+ // node keeps it small and within GitHub's documented 1–100.
251
+ export const PROJECTS_PROBE = "query ProjectsProbe { viewer { projectsV2(first: 1) { nodes { id } } } }";
252
+
253
+ // How GitHub says the login lacks read:project.
254
+ export const missingProjectScope = (error: unknown): boolean => /read:project/i.test(typeof error === "string" ? error : ((error as Error)?.message ?? ""));
220
255
 
221
256
  // The fields settings offers for Next up, from every org it might pick from [NXT-04]. An owner that's a person fails only its own field.
222
257
  export function issueFieldsQuery(orgs: string[]): string {