@andrioid/paseo-attention-span 0.4.9 → 0.4.10

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 (41) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +33 -17
  3. package/client/card.tsx +31 -8
  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 +145 -74
  9. package/client/sheet.tsx +91 -10
  10. package/client/ui.tsx +97 -6
  11. package/docs/architecture.md +12 -6
  12. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  13. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  14. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  15. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  16. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  17. package/docs/screenshots/desktop-dark-doing.png +0 -0
  18. package/docs/screenshots/desktop-dark-history-reviewed.png +0 -0
  19. package/docs/screenshots/desktop-dark-history.png +0 -0
  20. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  21. package/docs/screenshots/desktop-dark-settings.png +0 -0
  22. package/docs/screenshots/desktop-dark-waiting-too-long.png +0 -0
  23. package/docs/screenshots/desktop-dark-waiting.png +0 -0
  24. package/docs/screenshots/phone-dark-doing.png +0 -0
  25. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  26. package/index.server.ts +2 -0
  27. package/package.json +1 -1
  28. package/requirements.yaml +4 -2
  29. package/server/classify.ts +56 -12
  30. package/server/details.ts +3 -2
  31. package/server/fixture.ts +33 -9
  32. package/server/gh.ts +29 -12
  33. package/server/github-types.ts +19 -2
  34. package/server/projects.ts +47 -0
  35. package/server/queries.ts +41 -6
  36. package/server/service.ts +138 -22
  37. package/server/store.ts +2 -0
  38. package/server/view.ts +2 -0
  39. package/shared/attention.ts +57 -0
  40. package/shared/opening.ts +31 -0
  41. package/shared/rpc.ts +5 -1
@@ -27,7 +27,7 @@ flowchart LR
27
27
  - Client: one screen and a sidebar header item. React Native primitives only, so it works on phone and desktop [REACH-01].
28
28
  - Server: RPC handlers for fetching and for GitHub actions.
29
29
  - With several hosts, each runs its own copy, with its own `gh` login, `config.json` and `state.json`. Paseo shows one sidebar row for all of them and switches hosts with the picker in the screen's header; the row follows the host in view, else the one picked last.
30
- - **GitHub access** goes through the host's existing `gh` login. The plugin stores no token [SEC-01].
30
+ - **GitHub access** goes through the host's existing `gh` login. The plugin stores no token [SEC-01]. Projects need the `read:project` scope, which `gh auth login` doesn't ask for; Next up reads them only once the login has it [NXT-12].
31
31
  - **Setup checklist** [SET-01]: when a refresh fails, the screen asks the server what setup needs (`gh api user` for whether `gh` is there and who it's signed in as, and whether `config.json` parses). If `gh` is missing or signed out, or the file is broken, a checklist takes the tabs' place. Each line says how to fix it, and Check again refreshes. It also lists what's covered, the Paseo projects with a GitHub remote, and which profile sessions will use. Other failures, like a network error, stay a red line above the tabs.
32
32
  - **Settings screen** [SRC-02], under Settings → Plugins → Attention Span and the gear next to ⟳: orgs and repos, one per row. Each is checked with `gh api users/<org>` (it must be an organization, since searches use `org:`) or `gh api repos/<owner>/<name>` before it's saved, and GitHub's exact name is kept. Saving rewrites only `orgs` and `repos` in `config.json`, refuses a file that doesn't parse, and refreshes the lists. A Replies section has one switch, Follow threads I've commented on, which writes only `followThreads` [ATT-17].
33
33
  - **Local files** live in `~/.config/paseo-attention-span/`:
@@ -40,7 +40,7 @@ flowchart LR
40
40
  - optional merge method per repo [PRS-04]
41
41
  - `codeRepos`: where an issue repo's code lives, for issues kept in their own repo [SES-07]
42
42
  - `nextUp`: where unclaimed issues come from (`mine`, `orgs`, `repos`, set in Settings) and the org issue fields for priority, effort and scope [NXT-04]
43
- - `state.json`: dismissals [ATT-08], the scopes and sources ticked in Next up's filter [NXT-03, NXT-09], my Paseo projects' GitHub repos [NXT-08], the update put off with Not now [UPD-01] and the last fetch of each feed, so the screen shows instantly after a restart [PRIV-01].
43
+ - `state.json`: dismissals [ATT-08], the scopes, sources and project statuses ticked in Next up's filter [NXT-03, NXT-09], my Paseo projects' GitHub repos [NXT-08], the update put off with Not now [UPD-01] and the last fetch of each feed, so the screen shows instantly after a restart [PRIV-01].
44
44
 
45
45
  ## Tabs
46
46
 
@@ -53,7 +53,9 @@ The tabs tell the story of my work, left to right: what I finished, what needs m
53
53
  | Waiting | My work where someone else has the next move [WAI-01]: *Waiting for review* (while GitHub records a review as owed: a pending request, or an approval or requested changes; or approved but blocked by a repo rule [PRS-13]), *Waiting for the reviewer* (after I replied or pushed), *CI running*, *Questions I asked* (threads where my comment is the last from a person, bots don't count, and my comments since someone else last spoke ask something: a question mark outside quotes, code and links, read from GitHub's rendered comments (`bodyHTML`) so code and links count however they were written; a statement, tagged or not, waits on nobody and isn't listed): on my own issues however old, on others' only while my comment is within `mentionDays` [ATT-11]. Each shows who it waits on, never a guess [WAI-02]: on a PR, the reviewers currently requested and, after I replied, whoever requested changes, but nobody when a repo rule blocks it; on a question, the people and teams my comments since the last answer tag, read from GitHub's rendered comments (`bodyHTML`), where only real accounts and teams I can see are linked, never in code; tags in quotes don't count, and only the last 10 comments are read. Waiting groups it all by who it waits on, not by those reasons [WAI-01]: one group per person or team (a person tagged with other capitals is one), whoever blocks the most items first, ties by whose oldest item has waited longest, then requested bots, who can't be nudged, and last *Not on a person* for work nobody is on record for. In each group, work with a session that needs me leads, then one that's working, then the rest, oldest first; a finished session I've seen doesn't lift it. Work waiting on several is under each, saying "also waiting on" the rest, and counts once in the tab. Each card says why it waits (review, re-review or question; nothing where its chips say, like approved, blocked by repo rules, or CI running) and since when. A group's **Copy list** copies its items oldest first as a Markdown list, each line led by why and how long ("- Review 2h: [title](url)"), for a nudge; a requested bot gets none [WAI-03]. My PRs in Doing that wait on people or teams I asked, approved or not, are listed here too, under each of them [PRS-15]. Once something has waited `waitingTooLongDays` (default 3), its age turns amber with ⌛ and says so on hover, but only where a nudge is fair: not while CI fails or runs, nor with conflicts, changes to make or a reply I owe (`nudgeable` in `server/rules.ts`) [ATT-11]. In Doing, one person shows by name, several by picture, named on hover and in the sheet. |
54
54
  | Next up | *Assigned to you* [NXT-06], then *Unclaimed* [NXT-01] |
55
55
 
56
- Every card in every tab is the same component, `CardRow` in `client/card.tsx` [ATT-05]: a tinted mark for what it is, a title of at most two lines, then "repo #number", when it happened and signal chips, then content only some lists have (tags, a quote, a stack line), and its actions: on the right on desktop, labelled under the text on phones. A change on GitHub asks first in a `ConfirmBar` on the card [SAFE-01]. Tabs differ only in what they pass in: each maps its data to the card's mark, meta, actions and slots. Marks and signals take a tone, never a raw theme color, because some themes draw `accent` close to white.
56
+ Every card in every tab is the same component, `CardRow` in `client/card.tsx` [ATT-05]: a tinted mark for what it is, a title of at most two lines, then the item's number, its repo (the name brighter than the owner, which my own repos leave out) [ATT-20], when it happened and signal chips, then content only some lists have (pills, a quote, a stack line), and its actions: on the right on desktop, labelled under the text on phones. A change on GitHub asks first in a `ConfirmBar` on the card [SAFE-01]. Tabs differ only in what they pass in: each maps its data to the card's mark, meta, actions and slots. Marks and signals take a tone, never a raw theme color, because some themes draw `accent` close to white. How an item itself is shown, its number and repo and an issue's pills, lives in `client/entity.tsx` (`PlaceText`, `IssuePills`, `ProjectPill`, `FieldPill`, GitHub's option colors), so cards and sheets compose the same pieces rather than format their own; `client/ui.tsx` keeps the generic ones (`Meta`, `Pill`, `Signal`).
57
+
58
+ A sheet shows what the card knows on top, in the same pieces as the card, then every action, then what's fetched when it opens (a PR's size, linked PRs or issues). So the sheet doesn't change once open, a tapped card fetches them first and opens its sheet when they're in, with a spinner in place of › meanwhile (`useSheetOpener` in `client/sheet.tsx`); resting the pointer on a card for 300 ms fetches them ahead, best effort, and they stay fresh for a minute, so the card and its sheet share one query. Past 1.5 s the sheet opens anyway, and `Skeleton` bars hold the room of the lines the card expects, at the lines' own height: one for the size of the PR its actions apply to, one per open PR a Next up issue is known to have. An issue's sheet lists only its open PRs, as its card knows them. A failed fetch opens the sheet with its error line. Any other dialog appearing (an action's picker, Filter, feedback) takes over from a card still waiting, as every dialog is the plugin's `Modal` wrapper in `client/sheet.tsx` [ATT-06, GH-01].
57
59
 
58
60
  Something whose meaning isn't obvious, like a face on a card or an amber age, explains itself with `Hint` in `client/ui.tsx` [ATT-19, ATT-11]: its text is the screen-reader label, and on desktop it shows after a 300 ms rest of the pointer. It floats over the layout rather than in it, so showing it moves nothing, and it's sized to the room left in the nearest `HintArea` (a card's text column, a sheet's top), beside its content and wrapping upward, or above it where there's too little room beside. A chip takes one through `hint`.
59
61
 
@@ -100,7 +102,11 @@ Top to bottom. Each item appears once, under its most urgent reason [ATT-02]. `s
100
102
 
101
103
  ## Next up
102
104
 
103
- A second tab lists open issues nobody is assigned to [NXT-01], from the sources chosen under Next up in Settings: my own repos (`user:<login>`, forks left out), orgs I belong to (picked from `viewer.organizations`), and single repos checked on GitHub [NXT-04]. Each source is its own search, so an issue knows which sources found it and no query outgrows GitHub's length limit; one found by several is listed once. With more than one source, the Filter button on Unclaimed also filters by source, and what I tick is saved in `state.json` [NXT-09]. With no sources chosen, it looks in the configured orgs and repos. With neither, it looks in the GitHub repos of my Paseo projects, listed at each refresh through the app's last connection and kept in `state.json` for refreshes before the app connects; with no projects either, it says where to add some [NXT-08]. Unlike the other searches it isn't about me, so it never runs across all of GitHub. They are ordered by priority, then effort, then age [NXT-02]. Priority and effort are org issue fields named in `config.json`; a value ranks by the configured `order` (matched by name, so "Small" matches "🐇 Small (0.5-2d)") or else by the field's own option order. Issues without a value go last. Each card shows the repo's name and number, its age, and priority, effort and scope as tags with the org's emoji and notes in brackets trimmed; the top two priorities are tinted. An open PR that closes the issue (`closedByPullRequestsReferences`, from the same search) shows as "PR by alice", without changing the order [NXT-10]. The type is a badge tinted with theme colors. **Close issue** in the sheet asks on the card for the reason (completed or not planned) and an optional comment, then runs `gh issue close`; Undo reopens it [NXT-11]. The Filter button on Unclaimed opens a sheet (a dialog on desktop) with a checkbox per source and per scope; ticks apply right away, all are off at first, and what I tick is saved in `state.json` [NXT-03]. **Claim & start** assigns me with `gh issue edit --add-assignee @me`, then starts a "start" session on a new branch [NXT-05]. Each row's sheet shows the issue's PRs, and offers **Claim** without starting, or **Unclaim** (`--remove-assignee @me`) on issues assigned to me; each is the other's Undo [NXT-07].
105
+ A second tab lists open issues nobody is assigned to [NXT-01], from the sources chosen under Next up in Settings: my own repos (`user:<login>`, forks left out), orgs I belong to (picked from `viewer.organizations`), and single repos checked on GitHub [NXT-04]. Each source is its own search, so an issue knows which sources found it and no query outgrows GitHub's length limit; one found by several is listed once. With more than one source, the Filter button on Unclaimed also filters by source, and what I tick is saved in `state.json` [NXT-09]. With no sources chosen, it looks in the configured orgs and repos. With neither, it looks in the GitHub repos of my Paseo projects, listed at each refresh through the app's last connection and kept in `state.json` for refreshes before the app connects; with no projects either, it says where to add some [NXT-08]. Unlike the other searches it isn't about me, so it never runs across all of GitHub. They are ordered by priority, then effort, then age [NXT-02]. Priority and effort are org issue fields named in `config.json`; a value ranks by the configured `order` (matched by name, so "Small" matches "🐇 Small (0.5-2d)") or else by the field's own option order in the issue's own org, as two orgs may order a Priority field differently. Issues without a value go last. Each card shows the issue's number and repo, its age, then pills, each an icon half and a value half: the projects it's on with its Status there (a board icon and the project's name), then priority (flag), effort (weight) and scope (layers), values with the org's emoji and notes in brackets trimmed. Pointing at a pill names it ("Priority: P1 High"), and the sheet lists each by name, as phones can't point. Status and priority get a soft fill in the color GitHub has for the option, drawn in GitHub's shade for a dark or light theme (told by the theme's base surface); GRAY is what an option looks like with no color chosen, so it's left plain. Where an org colored none of its priorities, the top two are warm and accent instead. An open PR that closes the issue (`closedByPullRequestsReferences`, from the same search) shows as "PR by alice", without changing the order [NXT-10]. The type is a badge tinted with theme colors. **Close issue** in the sheet asks on the card for the reason (completed or not planned) and an optional comment, then runs `gh issue close`; Undo reopens it [NXT-11]. The Filter button on Unclaimed opens a sheet (a dialog on desktop) with a checkbox per source, per project and per scope; ticks apply right away, all are off at first, and what I tick is saved in `state.json` [NXT-03]. Each project the unclaimed issues are on lists every option of its Status field under it, in the board's order with its color, dimmed where no unclaimed issue has it, plus *No status* where some issue on it has none; *No project* comes last. Ticking a project ticks all its statuses; ticking some shows it partly ticked. An issue shows when any of its projects' ticks is on.
106
+
107
+ **Projects** [NXT-12] are the open org or user projects an issue's on (`projectItems`, the first 10, archived items left out), with the value of the board's built-in Status field. Boards the token can't see, like an SSO org's, come back empty and are left out. When GitHub cuts the list short and none of the first 10 is open, the issue's boards are unknown: no pill, and a project filter hides it rather than call it on no project. Each board's Status options come once per board, in their own request after the searches (`projectStatusesQuery`), so a board that can't be read costs only its statuses in the filter.
108
+
109
+ Projects are extra, so they never cost the searches they ride on (`server/projects.ts`). They need `read:project`, and without it GitHub fails the whole search, so the server first asks a one-line probe (`viewer { projectsV2(first: 1) }`), at most hourly and for 10 s at most, and adds the `projects` fragment to Next up's two searches only when the probe actually lists projects. Whatever then goes wrong with a search that reads them (GitHub failing it, answering without its results, whatever the words, or taking over 20 s), it's sent again without, and Settings says why. The boards' statuses get 20 s per batch of 50 boards too, so nothing about projects can hold up the refresh. Settings › Next up fields has a **Projects** row, asked again each time Settings opens: On; with a `gh` login missing the scope, the `gh auth refresh -s read:project` command with Copy command; with a token from `GH_TOKEN` or `GITHUB_TOKEN`, which `gh` reads first, the permission to give it (`read:project` classic, *Projects: read* fine-grained) and a daemon restart; otherwise GitHub's own words. While on, what went wrong reading them on the last refresh, like boards an org's SSO hides, shows as "On, but GitHub said: …" until a refresh reads them cleanly. Doing, Waiting and History never read projects: the pills are about picking work up. **Claim & start** assigns me with `gh issue edit --add-assignee @me`, then starts a "start" session on a new branch [NXT-05]. Each row's sheet shows the issue's PRs, and offers **Claim** without starting, or **Unclaim** (`--remove-assignee @me`) on issues assigned to me; each is the other's Undo [NXT-07].
104
110
 
105
111
  ## Actions
106
112
 
@@ -180,9 +186,9 @@ One GraphQL request per search, sent in parallel. GitHub runs the searches in on
180
186
  - `is:issue is:open assignee:@me`
181
187
  - `is:open involves:@me updated:>=<30 days ago> sort:updated-desc`, 100 at most, issues and PRs with their last 10 conversation comments, as for mentions (for Answered and fresh questions) [ATT-16]
182
188
  - `is:issue is:open author:@me commenter:@me sort:updated-desc`, 50 at most, no date limit, the same fields (questions on my own issues nobody answered, however old) [ATT-11]
183
- - `is:issue is:open no:assignee` (Next up, with issue type and field values; one request per source [NXT-09], skipped when there's nowhere to look [NXT-08]). "My repos" needs my login, taken from the last fetch or asked once with `viewer { login }`
189
+ - `is:issue is:open no:assignee` (Next up, with issue type and field values, and projects when the login may read them [NXT-12]; one request per source [NXT-09], skipped when there's nowhere to look [NXT-08]). "My repos" needs my login, taken from the last fetch or asked once with `viewer { login }`
184
190
 
185
- Once my PRs and both issue searches are back, one batched **details** request asks for `Ref.compare` behind counts for my PRs, the open issues their descriptions refer to (at most 100), and the option order of org issue fields when Next up needs it. The other searches carry on meanwhile.
191
+ Once my PRs and both issue searches are back, one batched **details** request asks for `Ref.compare` behind counts for my PRs, the open issues their descriptions refer to (at most 100), and the option order and colors of org issue fields when Next up needs them [NXT-02, NXT-10]. The other searches carry on meanwhile.
186
192
 
187
193
  A live refresh is 8 requests and about 85 points, of the 5,000 GitHub allows per hour. Points depend on how much a query asks for, not how many requests carry it; my PRs (34) and review requests (20) cost the most.
188
194
 
package/index.server.ts CHANGED
@@ -53,6 +53,8 @@ export default function contribute(server: PluginServerContext) {
53
53
  server.handle(rpc.myOrgs, async () => ({ orgs: await myOrgs() }));
54
54
  server.handle(rpc.setScopes, ({ scopes }) => ready(() => attention.setScopes(scopes)).then(() => ({ ok: true as const })));
55
55
  server.handle(rpc.setSources, ({ sources }) => ready(() => attention.setSources(sources)).then(() => ({ ok: true as const })));
56
+ server.handle(rpc.setProjectFilter, ({ projects }) => ready(() => attention.setProjectFilter(projects)).then(() => ({ ok: true as const })));
57
+ server.handle(rpc.projectsAccess, () => ready(() => attention.projectsAccess(true)));
56
58
  server.handle(rpc.updateBranch, ({ key, target }) => act(key, () => updateBranch(target), chip("updating")));
57
59
  server.handle(rpc.mergePullRequest, ({ key, target }) => act(key, () => mergePullRequest(target), { kind: "finished" }));
58
60
  server.handle(rpc.closePullRequest, ({ key, target, comment }) => act(key, () => closePullRequest(target, comment), { kind: "gone" }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrioid/paseo-attention-span",
3
- "version": "0.4.9",
3
+ "version": "0.4.10",
4
4
  "description": "For when your attention is spread thin: the GitHub issues and pull requests waiting on you, grouped by why, with one-tap Paseo sessions.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/requirements.yaml CHANGED
@@ -36,6 +36,7 @@ functional:
36
36
  ATT-17: choose to follow threads I've commented on, so recent replies after mine there show without a tag, off by default; so that surfacing other people's threads is my choice, and the list stays signal, not noise.
37
37
  ATT-18: see a calm, restful scene in Doing when nothing needs me, only once a refresh has confirmed it; so that a clear list feels like rest rather than a blank page, and calm never stands in for a check that failed or hasn't run.
38
38
  ATT-19: tell at a glance what each person shown on an item is to it: someone I'm waiting on, who opened it, or whose comments are left to address, with an icon by their picture and the meaning in words when I point at it; so that a face and a time never leave me guessing.
39
+ ATT-20: tell which item a card is on every tab by its number first, then its repository with the repository's name standing out from its owner, which my own repositories leave out; so that cards from several repositories scan without reading each one in full.
39
40
  mentions:
40
41
  As a developer, I can:
41
42
  MEN-01: see open threads where a person mentioned me and is still waiting for my response; so that I only hear about mentions when someone is waiting for me.
@@ -89,15 +90,16 @@ functional:
89
90
  As a developer, I can:
90
91
  NXT-01: see open issues nobody is assigned to, apart from the work that needs me; so that I can get an idea of what to do next.
91
92
  NXT-02: see unclaimed issues ordered by priority, then effort, then age; so that the most important quick wins come first.
92
- NXT-03: filter unclaimed issues by scope, and have my choice remembered; so that I only see work I'd pick up.
93
+ NXT-03: filter unclaimed issues by scope, and by project and its statuses, each project's statuses listed under it in the board's order, with issues on no project or without a status as choices of their own, and have my choice remembered; so that I only see work I'd pick up.
93
94
  NXT-04: choose in the app where unclaimed issues come from (my own repositories, organizations I belong to, or single repositories) and choose which issue fields the list uses, with fields named Priority, Effort and Scope used until I do; so that the plugin can be used elsewhere without editing files.
94
95
  NXT-05: claim an issue and start a session on it in one step; so that teammates see it's taken and I can start right away.
95
96
  NXT-06: see issues assigned to me before unclaimed ones; so that I finish what I've taken before picking more.
96
97
  NXT-07: claim an issue without starting a session, and give back one assigned to me; so that what I've taken matches what I'll do.
97
98
  NXT-08: see unclaimed issues from the repositories of my Paseo projects when I haven't chosen any; so that Next up is useful without setup and never fills with strangers' issues.
98
99
  NXT-09: filter unclaimed issues by where they came from, and have my choice remembered; so that I can focus on one source at a time.
99
- NXT-10: see on each issue its repository, priority, effort and scope at a glance, and whether an open pull request already closes it and by whom; so that I can judge whether to pick it up without opening it.
100
+ NXT-10: see on each issue its repository, its projects with their status, and its priority, effort and scope at a glance, each a pill whose icon says what it is, named in words when I point at it and in the sheet, with status and priority softly in the color GitHub has for them (none for gray, and the top two priorities warm and accent where the org colored none), and whether an open pull request already closes it and by whom; so that I can judge whether to pick it up without opening it.
100
101
  NXT-11: close an issue from Next up as completed or not planned, with an optional comment, and undo it; so that work that's done or won't be done stops being suggested.
102
+ NXT-12: see which open GitHub projects my Next up issues are on, and where on each board, once my gh login may read projects, with Settings saying the one command that allows it until then; so that I know whether work is planned or just an idea, without Next up breaking for anyone who hasn't allowed it.
101
103
  waiting:
102
104
  As a developer, I can:
103
105
  WAI-01: see my work that is waiting on others, grouped by who it waits on with whoever blocks the most first, bots after people, and work no person holds up last, each group with work that has an active session first, and each card saying why it waits and for how long, including my pull requests in Doing that wait on whom I asked, where a pull request waits for review only once someone has been asked, and a thread only once my last words ask a question; so that I know that work is tracked and who is blocking me most.
@@ -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: {},
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
+ }