@andrioid/paseo-attention-span 0.6.0 → 0.7.0

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 (78) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +61 -1174
  3. package/client/coverage-settings.tsx +5 -4
  4. package/client/data.ts +4 -2
  5. package/client/feedback.tsx +21 -25
  6. package/client/history.tsx +12 -50
  7. package/client/item-actions.ts +387 -0
  8. package/client/item-row.tsx +450 -0
  9. package/client/new-issue.tsx +244 -0
  10. package/client/next-up.tsx +22 -183
  11. package/client/pickers.tsx +238 -0
  12. package/client/session-menu.ts +3 -11
  13. package/client/sessions.ts +58 -57
  14. package/client/setup.tsx +2 -1
  15. package/client/sheet.tsx +92 -15
  16. package/client/ui.tsx +23 -14
  17. package/client/wrap-up.tsx +151 -85
  18. package/docs/architecture.md +24 -13
  19. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  20. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  21. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  22. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  23. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  24. package/docs/screenshots/desktop-dark-doing-wrap-dirty.png +0 -0
  25. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  26. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  27. package/docs/screenshots/desktop-dark-doing.png +0 -0
  28. package/docs/screenshots/desktop-dark-history-filtered.png +0 -0
  29. package/docs/screenshots/desktop-dark-history.png +0 -0
  30. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  31. package/docs/screenshots/desktop-dark-settings.png +0 -0
  32. package/docs/screenshots/desktop-dark-setup.png +0 -0
  33. package/docs/screenshots/desktop-dark-waiting-too-long.png +0 -0
  34. package/docs/screenshots/desktop-dark-waiting.png +0 -0
  35. package/docs/screenshots/phone-dark-doing.png +0 -0
  36. package/docs/screenshots/phone-dark-history.png +0 -0
  37. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  38. package/index.client.tsx +19 -0
  39. package/index.server.ts +43 -26
  40. package/package.json +2 -1
  41. package/requirements.yaml +10 -3
  42. package/server/actions.ts +2 -1
  43. package/server/archive.ts +146 -67
  44. package/server/archived.ts +12 -16
  45. package/server/changes.ts +34 -54
  46. package/server/classify.ts +157 -139
  47. package/server/context.ts +95 -3
  48. package/server/feedback.ts +2 -6
  49. package/server/fetch.ts +262 -0
  50. package/server/fixture.ts +88 -14
  51. package/server/github-types.ts +5 -2
  52. package/server/markdown.ts +3 -1
  53. package/server/port.ts +46 -0
  54. package/server/queries.ts +34 -24
  55. package/server/service.ts +155 -272
  56. package/server/setup.ts +15 -14
  57. package/server/store.ts +94 -80
  58. package/server/update.ts +34 -13
  59. package/server/view.ts +16 -15
  60. package/shared/archive.ts +116 -13
  61. package/shared/attention.ts +63 -18
  62. package/shared/changes.ts +2 -1
  63. package/shared/config.ts +2 -6
  64. package/shared/drafting.ts +17 -0
  65. package/shared/feedback.ts +6 -5
  66. package/shared/format.ts +2 -1
  67. package/shared/history-report.ts +2 -1
  68. package/shared/item-sessions.ts +76 -0
  69. package/shared/item-view.ts +224 -0
  70. package/shared/linked-sessions.ts +59 -8
  71. package/shared/names.ts +17 -0
  72. package/shared/new-issue.ts +129 -0
  73. package/shared/next-up-filter.ts +137 -0
  74. package/shared/paging.ts +16 -0
  75. package/shared/prompts.ts +39 -22
  76. package/shared/rpc.ts +23 -10
  77. package/shared/setup.ts +3 -1
  78. package/shared/wrap-up.ts +20 -23
package/server/service.ts CHANGED
@@ -1,42 +1,19 @@
1
- import { type Attention, type AttentionView, type FeedId, type FeedStatus, type GithubColor, type HistoryFilter, type Item, keySet, memberKeys, type ProjectsAccess, type Reviewer, uniqueKeys } from "../shared/attention";
1
+ import { type Attention, type AttentionView, type FeedId, type FeedStatus, type HistoryFilter, type Item, memberKeys, type ProjectsAccess, type Reviewer } from "../shared/attention";
2
2
  import type { PluginHandlerContext } from "@getpaseo/plugin/server";
3
- import { AttentionConfig, type FieldRole, githubRepoOf, nextUpField } from "../shared/config";
3
+ import { AttentionConfig, type FieldRole } from "../shared/config";
4
+ import { newIssueRepos } from "../shared/new-issue";
4
5
  import type { IssueField } from "../shared/setup";
5
- import type { ArchiveOutcome, ArchiveTarget } from "../shared/archive";
6
- import { archiveSessions } from "./archive";
6
+ import type { ArchiveOutcome, ArchiveTarget, KeptRow, KeptWorktree } from "../shared/archive";
7
7
  import { rememberGroups } from "../shared/wrap-up";
8
- import { acknowledge, changeCandidates, ownClosed, nextLedger, type Lookups, type ReopenLookups, reopenCandidates, withGotIt } from "./changes";
9
- import { classify, classifyHistory, issueBoardIds } from "./classify";
10
- import { probeAnswer, projectsFailure, projectsWarning, searchWithProjects } from "./projects";
11
- import { FIXTURE, graphql, graphqlResult } from "./gh";
12
- import { FIXTURE_AGENTS, FIXTURE_ISSUE_FIELDS, fixtureChanges, fixtureGotIt, fixtureNow, quiet } from "./fixture";
13
- import type { AssignmentSubject, Details, HistoryResult, LinkedIssue, LiveResult, MergeStateStatus, PullRequestNode, ReopenSubject } from "./github-types";
14
- import {
15
- ASSIGNMENT_BATCH,
16
- assignmentsQuery,
17
- type CheckContext,
18
- detailsQuery,
19
- HISTORY_SEARCHES,
20
- issueFieldsQuery,
21
- type OrgFields,
22
- MERGE_STATE_BATCH,
23
- mergeStateQuery,
24
- mergeUnclaimed,
25
- prKey,
26
- PROJECTS_PROBE,
27
- projectStatusesQuery,
28
- type ProjectStatusesResult,
29
- reopenQuery,
30
- requiredChecks,
31
- type SearchName,
32
- searchQuery,
33
- searchVariables,
34
- type UnclaimedSearch,
35
- unclaimedSearches,
36
- } from "./queries";
37
- import { toLookUp } from "./references";
38
- import { loadConfig, loadState, moveOldFiles, saveCodeRepo, saveCoverage, saveFollowThreads, saveNextUpFields, saveNextUpSources, saveState, State } from "./store";
8
+ import { acknowledge, ownClosed } from "./changes";
9
+ import { classify, classifyHistory } from "./classify";
10
+ import { probeAnswer, projectsFailure, projectsWarning } from "./projects";
11
+ import type { Port } from "./port";
12
+ import { isTimeZone, type UnclaimedSearch, unclaimedSearches } from "./queries";
13
+ import type { Details, LiveResult } from "./github-types";
14
+ import { State } from "./store";
39
15
  import { applyPending, buildView, doneItem, type Effect, isPending, SETTLE_MS } from "./view";
16
+ import { keySet, uniqueKeys } from "../shared/names";
40
17
 
41
18
  // History changes only when I finish something, so it's fetched daily, on ⟳ in its tab and after a merge.
42
19
  const HISTORY_MAX_AGE_SECONDS = 24 * 60 * 60;
@@ -44,13 +21,6 @@ const HISTORY_MAX_AGE_SECONDS = 24 * 60 * 60;
44
21
  const RETRY_MS = 5 * 60_000;
45
22
  // Whether projects can be read is asked again at most this often, unless Settings asks [NXT-12].
46
23
  const PROJECTS_CHECK_MS = 60 * 60_000;
47
- // The check waits this long at most, as the refresh waits on it.
48
- const PROBE_TIMEOUT_MS = 10_000;
49
- // A search with projects, or a batch of boards' statuses, waits this long at most before the refresh goes on without them.
50
- const PROJECTS_SEARCH_TIMEOUT_MS = 20_000;
51
- const BOARDS_PER_REQUEST = 50;
52
- // Batches of boards asked at once, so many boards don't burst requests [GH-01].
53
- const BOARD_BATCHES_AT_ONCE = 2;
54
24
 
55
25
  // Where gh's token comes from: an environment variable, which gh reads before its own login, or that login [NXT-12].
56
26
  const tokenSource = (): ProjectsAccess["token"] => (process.env.GH_TOKEN ? "GH_TOKEN" : process.env.GITHUB_TOKEN ? "GITHUB_TOKEN" : "gh");
@@ -69,6 +39,10 @@ interface Feed {
69
39
  // Owns the cache and the background refresh of each feed [FRESH-01, PRIV-01].
70
40
  export class AttentionService {
71
41
  private state: State = State.parse({});
42
+ // Workspaces Paseo said were archived; an archive that keeps one of them after the fact adds no row for it [ATT-22].
43
+ private archivedWorkspaces = new Set<string>();
44
+ // Merged PRs of mine a History fetch was asked for, once each, so a search slow to show one doesn't fetch on every refresh.
45
+ private historyAskedFor = new Set<string>();
72
46
  private config: AttentionConfig = AttentionConfig.parse({});
73
47
  private configError: string | null = null;
74
48
  private feeds: Record<FeedId, Feed> = {
@@ -76,8 +50,8 @@ export class AttentionService {
76
50
  history: { inFlight: null, next: null, lastAttemptAt: 0, error: null },
77
51
  };
78
52
  private saving: Promise<void> = Promise.resolve();
79
- private timer: ReturnType<typeof setInterval> | null = null;
80
- private followUps: Partial<Record<FeedId, ReturnType<typeof setTimeout>>> = {};
53
+ private timer: (() => void) | null = null;
54
+ private followUps: Partial<Record<FeedId, () => void>> = {};
81
55
  private intervalMinutes = 0;
82
56
  private projects: { access: ProjectsAccess; checkedAt: number } = { access: { state: "unknown", token: tokenSource() }, checkedAt: 0 };
83
57
  private projectsProbe: Promise<ProjectsAccess> | null = null;
@@ -85,9 +59,11 @@ export class AttentionService {
85
59
  // The app's connection to Paseo, from its last request; background refreshes have none of their own.
86
60
  private paseo: PluginHandlerContext["paseo"] | null = null;
87
61
 
62
+ constructor(private readonly port: Port) {}
63
+
88
64
  async start(): Promise<void> {
89
- await moveOldFiles().catch((error) => console.error("Couldn't move the old settings folder:", error));
90
- this.state = await loadState();
65
+ await this.port.store.moveOldFiles().catch((error) => console.error("Couldn't move the old settings folder:", error));
66
+ this.state = await this.port.store.loadState();
91
67
  await this.reloadConfig().catch(() => {}); // shown as the screen's error
92
68
  this.schedule();
93
69
  void this.refreshStale();
@@ -98,19 +74,31 @@ export class AttentionService {
98
74
  }
99
75
 
100
76
  stop(): void {
101
- if (this.timer) clearInterval(this.timer);
77
+ this.timer?.();
102
78
  this.timer = null;
103
- for (const timeout of Object.values(this.followUps)) clearTimeout(timeout);
79
+ for (const cancel of Object.values(this.followUps)) cancel();
104
80
  }
105
81
 
106
82
  // ⟳ fetches its tab's feed now; otherwise feeds older than their schedule are fetched first.
107
- // `cached` answers from memory, with no GitHub refresh first.
108
- async get(refresh?: FeedId, cached?: boolean): Promise<AttentionView> {
83
+ // `cached` answers from memory, with no GitHub refresh first. `timeZone` is the device's: History's weeks follow the last
84
+ // one sent, so a new one fetches History again, once [HIS-01].
85
+ async get(refresh?: FeedId, cached?: boolean, timeZone?: string): Promise<AttentionView> {
86
+ const rezoned = !!timeZone && timeZone !== this.timeZone && isTimeZone(timeZone);
87
+ if (rezoned) {
88
+ this.state.timeZone = timeZone;
89
+ await this.save();
90
+ }
91
+ const history = rezoned && refresh !== "history" ? this.refresh("history", true).catch(() => {}) : null;
109
92
  if (refresh) await this.refresh(refresh).catch(() => {});
110
93
  else if (!cached) await this.refreshStale();
94
+ if (!cached) await history;
111
95
  return this.view();
112
96
  }
113
97
 
98
+ private get timeZone(): string {
99
+ return this.state.timeZone ?? "UTC";
100
+ }
101
+
114
102
  async dismiss(key: string): Promise<AttentionView> {
115
103
  const item = this.items().find((candidate) => candidate.key === key);
116
104
  if (item) {
@@ -122,7 +110,7 @@ export class AttentionService {
122
110
 
123
111
  async undismiss(key: string): Promise<AttentionView> {
124
112
  delete this.state.dismissed[key];
125
- await saveState(this.state);
113
+ await this.save();
126
114
  return this.view();
127
115
  }
128
116
 
@@ -168,67 +156,91 @@ export class AttentionService {
168
156
 
169
157
  // Archive a Wrap up row's sessions; success acknowledges the events on that work, so they go to their week as cleared, not
170
158
  // History's unread notes [ATT-22, HIS-07]. A failure leaves the row to try again.
171
- async archive(paseo: PluginHandlerContext["paseo"], targets: ArchiveTarget[], confirm: boolean): Promise<ArchiveOutcome> {
172
- // Previews have no Paseo agents, but still acknowledge, so their screenshots can show the cleanup.
173
- if (FIXTURE) return { ok: true, view: await this.acknowledge(targets.flatMap((target) => target.keys)) };
174
- const answer = await archiveSessions(paseo, targets.flatMap((target) => target.agentIds), confirm);
159
+ // A worktree that stayed keeps its row, as a kept row [ATT-22].
160
+ async archive(paseo: PluginHandlerContext["paseo"], targets: ArchiveTarget[], confirm: boolean, terminals: string[] = []): Promise<ArchiveOutcome> {
161
+ const answer = await this.port.paseo.archive(paseo, targets.flatMap((target) => target.agentIds), confirm, terminals, []);
175
162
  if (!answer.ok) return { ...answer, view: this.view() };
163
+ this.remember(answer.kept, (kept) => targets.find((target) => target.agentIds.some((id) => kept.sessionIds.includes(id))));
176
164
  const view = await this.acknowledge(targets.flatMap((target) => target.keys));
177
- return answer.warning ? { ok: true, view, warning: answer.warning } : { ok: true, view };
165
+ return { ...answer, view };
166
+ }
167
+
168
+ // A kept worktree tried again on its own, with the same checks; it stays kept, perhaps for a new reason, until it goes.
169
+ async archiveWorktree(paseo: PluginHandlerContext["paseo"], workspaceId: string, confirm: boolean, terminals: string[] = []): Promise<ArchiveOutcome> {
170
+ const row = this.state.kept.find((kept) => kept.workspaceId === workspaceId);
171
+ const answer = await this.port.paseo.archive(paseo, [], confirm, terminals, [workspaceId]);
172
+ if (!answer.ok) return { ...answer, view: this.view() };
173
+ this.state.kept = this.state.kept.filter((kept) => kept.workspaceId !== workspaceId);
174
+ if (row) this.remember(answer.kept, () => row);
175
+ await this.save();
176
+ return { ...answer, view: this.view() };
177
+ }
178
+
179
+ // Dismiss on a kept row: the worktree stays, and so does Paseo's sidebar entry; Wrap up stops showing it [ATT-22].
180
+ async dismissKept(workspaceId: string): Promise<AttentionView> {
181
+ await this.forgetKept(workspaceId);
182
+ return this.view();
183
+ }
184
+
185
+ // A kept worktree archived anywhere, Paseo's sidebar included, takes its row with it [ATT-22]. Remembered, so an archive
186
+ // still running that keeps it afterwards doesn't bring the row back.
187
+ async forgetKept(workspaceId: string): Promise<void> {
188
+ this.archivedWorkspaces.add(workspaceId);
189
+ if (!this.state.kept.some((kept) => kept.workspaceId === workspaceId)) return;
190
+ this.state.kept = this.state.kept.filter((kept) => kept.workspaceId !== workspaceId);
191
+ await this.save();
192
+ }
193
+
194
+ private remember(kept: KeptWorktree[], rowOf: (kept: KeptWorktree) => Pick<KeptRow, "itemKey" | "title" | "repo" | "number" | "kind"> | undefined): void {
195
+ const at = new Date(this.port.now()).toISOString();
196
+ for (const found of kept) {
197
+ const row = rowOf(found);
198
+ if (!row || this.archivedWorkspaces.has(found.workspaceId)) continue;
199
+ const { sessionIds, ...worktree } = found;
200
+ const { itemKey, title, repo, number, kind } = row;
201
+ this.state.kept = [...this.state.kept.filter((other) => other.workspaceId !== worktree.workspaceId), { ...worktree, itemKey, title, repo, number, kind, at }];
202
+ }
178
203
  }
179
204
 
180
205
  // Remember where an issue repo's code lives [SES-07].
181
206
  async setCodeRepo(issueRepo: string, codeRepo: string): Promise<AttentionView> {
182
- this.config = await saveCodeRepo(issueRepo, codeRepo);
207
+ this.config = await this.port.store.saveCodeRepo(issueRepo, codeRepo);
183
208
  return this.view();
184
209
  }
185
210
 
186
211
  // Orgs and repos chosen in settings [SRC-02]. The lists follow right away; History catches up behind them.
187
212
  async setCoverage(orgs: string[], repos: string[]): Promise<void> {
188
- this.config = await saveCoverage(orgs, repos);
213
+ this.config = await this.port.store.saveCoverage(orgs, repos);
189
214
  void this.refresh("history").catch(() => {});
190
215
  await this.refresh("live").catch(() => {});
191
216
  }
192
217
 
193
218
  // Where Next up looks, chosen in settings [NXT-04]. Only the live feed has Next up.
194
219
  async setNextUpSources(sources: Pick<AttentionConfig["nextUp"], "mine" | "orgs" | "repos">): Promise<void> {
195
- this.config = await saveNextUpSources(sources);
220
+ this.config = await this.port.store.saveNextUpSources(sources);
196
221
  await this.refresh("live").catch(() => {});
197
222
  }
198
223
 
199
224
  // Which org issue fields Next up uses, chosen in settings [NXT-04]. Only the live feed has Next up.
200
225
  async setNextUpFields(fields: Partial<Record<FieldRole, string | null>>): Promise<void> {
201
- this.config = await saveNextUpFields(fields);
226
+ this.config = await this.port.store.saveNextUpFields(fields);
202
227
  await this.refresh("live").catch(() => {});
203
228
  }
204
229
 
205
230
  // The single-select fields of every org Next up might pick from, merged by name, for settings [NXT-04]:
206
231
  // the orgs chosen, the owners of the repos chosen and of my projects, and of the issues it last showed.
207
232
  async issueFields(): Promise<IssueField[]> {
208
- if (FIXTURE) return FIXTURE_ISSUE_FIELDS;
209
233
  await this.reloadConfig().catch(() => {});
210
234
  const { orgs, repos, nextUp } = this.config;
211
235
  const live = this.state.live?.attention;
212
236
  const shown = [...(live?.unclaimed ?? []), ...(live?.assigned ?? [])].map((issue) => issue.repo);
213
237
  const owners = [...orgs, ...nextUp.orgs, ...[...repos, ...nextUp.repos, ...this.state.projectRepos, ...shown].map((repo) => repo.split("/")[0])];
214
- const unique = [...new Map(owners.map((owner) => [owner.toLowerCase(), owner])).values()];
215
- if (unique.length === 0) return [];
216
- const result = await graphql<Record<string, OrgFields>>(issueFieldsQuery(unique));
217
- const merged = new Map<string, IssueField>();
218
- unique.forEach((org, index) => {
219
- for (const field of result[`o${index}`]?.issueFields?.nodes ?? []) {
220
- if (!field.name || !field.options) continue;
221
- const known = merged.get(field.name.toLowerCase());
222
- if (known) known.orgs.push(org);
223
- else merged.set(field.name.toLowerCase(), { name: field.name, options: field.options.map((option) => option.name), orgs: [org] });
224
- }
225
- });
226
- return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
238
+ return this.port.github.issueFields(uniqueKeys(owners));
227
239
  }
228
240
 
229
241
  // Replies on others' threads without a tag [ATT-17]. Only the live feed has them.
230
242
  async setFollowThreads(on: boolean): Promise<void> {
231
- this.config = await saveFollowThreads(on);
243
+ this.config = await this.port.store.saveFollowThreads(on);
232
244
  await this.refresh("live").catch(() => {});
233
245
  }
234
246
 
@@ -242,6 +254,12 @@ export class AttentionService {
242
254
  await this.save();
243
255
  }
244
256
 
257
+ // What the New issue sheet starts with next time [ISS-01].
258
+ async setNewIssueChoice(repo: string, profileId: string | null): Promise<void> {
259
+ this.state.newIssue = { repo, profileId };
260
+ await this.save();
261
+ }
262
+
245
263
  async setProjectFilter(projects: string[]): Promise<void> {
246
264
  this.state.projectFilter = projects;
247
265
  await this.save();
@@ -268,7 +286,7 @@ export class AttentionService {
268
286
  async act(key: string, work: () => Promise<void>, change: Change): Promise<AttentionView> {
269
287
  await work();
270
288
  const before = this.state.pending[key];
271
- const at = new Date().toISOString();
289
+ const at = new Date(this.port.now()).toISOString();
272
290
  if (change) this.state.pending[key] = { at, effect: change.kind === "finished" ? this.finished(key, at, change.notPlanned) : change };
273
291
  else delete this.state.pending[key];
274
292
  await this.save();
@@ -285,10 +303,23 @@ export class AttentionService {
285
303
  return source ? { kind: "done", item: doneItem(source, at, notPlanned) } : { kind: "gone" };
286
304
  }
287
305
 
306
+ // A PR of mine the live feed saw merged, which History doesn't list yet, perhaps merged on GitHub: History is fetched
307
+ // once its search has caught up, once per PR [FRESH-03]. Until then the live feed's own entry stands in (ownClosed).
308
+ private followMerges(): void {
309
+ const listed = new Set((this.state.history?.items ?? []).flatMap((item) => [item.key, ...item.children.map((child) => child.key)]).map((key) => key.toLowerCase()));
310
+ const merged = (this.state.live?.attention.ownClosed ?? []).filter((item) => !item.closedUnmerged).map((item) => item.key.toLowerCase());
311
+ // Kept only while the live feed still lists them, so the record stays as small as its recent closes.
312
+ this.historyAskedFor = new Set(merged.filter((key) => this.historyAskedFor.has(key)));
313
+ const unseen = merged.filter((key) => !listed.has(key) && !this.historyAskedFor.has(key));
314
+ if (unseen.length === 0) return;
315
+ for (const key of unseen) this.historyAskedFor.add(key);
316
+ this.followUp("history");
317
+ }
318
+
288
319
  // One fetch once GitHub's search has caught up with the latest change, which ends what's pending.
289
320
  private followUp(id: FeedId): void {
290
- clearTimeout(this.followUps[id]);
291
- this.followUps[id] = setTimeout(() => void this.refresh(id, true).catch(() => {}), SETTLE_MS);
321
+ this.followUps[id]?.();
322
+ this.followUps[id] = this.port.setTimer(() => void this.refresh(id, true).catch(() => {}), SETTLE_MS);
292
323
  }
293
324
 
294
325
  // Concurrent callers share one refresh per feed. `fresh` won't share one that began before the call, which can't show a change just made.
@@ -309,21 +340,22 @@ export class AttentionService {
309
340
 
310
341
  private async fetch(id: FeedId): Promise<void> {
311
342
  const feed = this.feeds[id];
312
- feed.lastAttemptAt = Date.now();
343
+ feed.lastAttemptAt = this.port.now();
313
344
  try {
314
345
  await this.reloadConfig();
315
- const now = new Date();
346
+ const now = new Date(this.port.now());
316
347
  const fetchedAt = now.toISOString();
317
348
  if (id === "live") {
318
349
  this.state.live = { fetchedAt, attention: await this.fetchLive(now) };
319
350
  this.state.groups = rememberGroups(this.state.groups, this.state.live.attention.items, now, Math.max(this.config.mentionDays, this.config.historyWeeks * 7 + 7));
351
+ this.followMerges();
320
352
  }
321
353
  else this.state.history = { fetchedAt, items: await this.fetchHistory(now) };
322
354
  // Forget dismissals of items that are gone.
323
355
  const keys = new Set(this.items().map((item) => item.key));
324
356
  for (const key of Object.keys(this.state.dismissed)) if (!keys.has(key)) delete this.state.dismissed[key];
325
357
  // And changes GitHub now shows for itself.
326
- for (const [key, pending] of Object.entries(this.state.pending)) if (!isPending(pending, this.fetchedAt(), Date.now())) delete this.state.pending[key];
358
+ for (const [key, pending] of Object.entries(this.state.pending)) if (!isPending(pending, this.fetchedAt(), this.port.now())) delete this.state.pending[key];
327
359
  feed.error = null;
328
360
  await this.save();
329
361
  } catch (error) {
@@ -334,72 +366,18 @@ export class AttentionService {
334
366
  }
335
367
 
336
368
  private async fetchLive(now: Date): Promise<Attention> {
337
- const projectRepos = FIXTURE ? [] : await this.projectRepos();
338
- const login = FIXTURE ? "me" : this.config.nextUp.mine ? await this.login() : null;
369
+ const projectRepos = await this.projectRepos();
370
+ const login = this.config.nextUp.mine ? await this.login() : null;
339
371
  const unclaimed = unclaimedSearches(this.config, projectRepos, login);
340
- const { data, details } = FIXTURE ? fixtureNow(now) : await this.searchLive(now, unclaimed.searches);
341
- await this.trackChanges(data, now);
342
- const own = FIXTURE ? [] : ownClosed(data, data.viewer.login);
372
+ const { data, details } = await this.searchLive(now, unclaimed.searches);
373
+ this.state.changes = await this.port.github.changes(this.state.changes, data, now, this.config, () => this.state.changes.gotIt);
374
+ const own = ownClosed(data, data.viewer.login);
343
375
  return { ...classify({ data, details, config: this.config, now }), unclaimedFrom: unclaimed.from, ...(own.length ? { ownClosed: own } : {}) };
344
376
  }
345
377
 
346
- // What others did to my work since the last refresh [HIS-07]. Only PRs whose hands changed and issues that left my assigned
347
- // search are looked up, a batch per request; a failed batch is asked again next time [GH-01]. Kept long enough for History.
348
- private async trackChanges(data: LiveResult, now: Date): Promise<void> {
349
- const ledger = this.state.changes;
350
- if (FIXTURE) {
351
- // Previews start each layout with a refresh, which brings the notes back: Got it would otherwise outlive a layout.
352
- this.state.changes = { ...ledger, events: quiet() ? [] : fixtureChanges(now), gotIt: fixtureGotIt(now) };
353
- return;
354
- }
355
- const me = data.viewer.login;
356
- const candidates = changeCandidates(ledger, data, me);
357
- const lookups: Lookups = new Map();
358
- for (let at = 0; at < candidates.length; at += ASSIGNMENT_BATCH) {
359
- const batch = candidates.slice(at, at + ASSIGNMENT_BATCH);
360
- try {
361
- const { data: result, failures } = await graphqlResult<Record<string, AssignmentSubject | null>>(assignmentsQuery(batch));
362
- batch.forEach((id, index) => {
363
- const alias = `a${index}`;
364
- // A node GitHub can't find is gone for good; one it failed on is asked again next refresh.
365
- const failed = failures.some((failure) => failure.path?.[0] === alias && failure.type !== "NOT_FOUND");
366
- if (!failed) lookups.set(id, result?.[alias] ?? null);
367
- });
368
- } catch (error) {
369
- console.error("Couldn't look up who changed my work:", (error as Error).message);
370
- }
371
- }
372
- const reopens = await this.reopenLookups(reopenCandidates(ledger, data));
373
- const keepDays = Math.max(this.config.mentionDays, this.config.historyWeeks * 7 + 7);
374
- // A Got it tapped, or an archive acknowledging, while this refresh ran still counts.
375
- // Got its tapped while the lookups ran decide too, so a handover cleared meanwhile survives its work coming back.
376
- const current = { ...ledger, gotIt: this.state.changes.gotIt };
377
- this.state.changes = withGotIt(nextLedger(current, data, me, lookups, now, this.config.mentionDays, keepDays, reopens), this.state.changes.gotIt);
378
- }
379
-
380
- // PRs Attention Span saw closed, asked about a batch per request so a reopen by someone else is noticed [HIS-07, GH-01].
381
- // A batch that fails leaves its PRs tracked for the next refresh; one GitHub can't find is gone.
382
- private async reopenLookups(candidates: string[]): Promise<ReopenLookups> {
383
- const lookups: ReopenLookups = new Map();
384
- for (let at = 0; at < candidates.length; at += ASSIGNMENT_BATCH) {
385
- const batch = candidates.slice(at, at + ASSIGNMENT_BATCH);
386
- try {
387
- const { data, failures } = await graphqlResult<Record<string, ReopenSubject | null>>(reopenQuery(batch));
388
- batch.forEach((id, index) => {
389
- const alias = `a${index}`;
390
- const failed = failures.some((failure) => failure.path?.[0] === alias && failure.type !== "NOT_FOUND");
391
- if (!failed) lookups.set(id, data?.[alias] ?? null);
392
- });
393
- } catch (error) {
394
- console.error("Couldn't check whether a closed PR reopened:", (error as Error).message);
395
- }
396
- }
397
- return lookups;
398
- }
399
-
400
378
  // The account gh is signed in as, for My repos [NXT-04]. Asked once, unless the last fetch already says.
401
379
  private async login(): Promise<string> {
402
- return (this.state.live?.attention.login || (await graphql<{ viewer: { login: string } }>("{ viewer { login } }")).viewer.login);
380
+ return this.state.live?.attention.login || (await this.port.github.login());
403
381
  }
404
382
 
405
383
  // My Paseo projects' GitHub repos, where Next up looks when no repos are chosen [NXT-08].
@@ -407,8 +385,7 @@ export class AttentionService {
407
385
  private async projectRepos(): Promise<string[]> {
408
386
  if (this.paseo) {
409
387
  try {
410
- const { projects } = await this.paseo.projects.list();
411
- this.state.projectRepos = [...new Set(projects.map((project) => githubRepoOf(project.projectKey)).filter((repo): repo is string => !!repo))].sort();
388
+ this.state.projectRepos = await this.port.paseo.projectRepos(this.paseo);
412
389
  } catch (error) {
413
390
  console.error("Couldn't list Paseo projects:", error);
414
391
  }
@@ -417,8 +394,7 @@ export class AttentionService {
417
394
  }
418
395
 
419
396
  private async fetchHistory(now: Date): Promise<Item[]> {
420
- if (FIXTURE) return classifyHistory(fixtureNow(now).data);
421
- return classifyHistory(await graphql<HistoryResult>(searchQuery(HISTORY_SEARCHES, true), this.variables(HISTORY_SEARCHES, now)));
397
+ return classifyHistory(await this.port.github.history(this.config, now, this.timeZone));
422
398
  }
423
399
 
424
400
  // Whether the gh login may read projects, asked at most hourly, or now when Settings asks [NXT-12]. On only when GitHub
@@ -428,149 +404,42 @@ export class AttentionService {
428
404
  // What went wrong reading projects on the last refresh, while they're on, like boards an org's SSO hides, rides along for
429
405
  // Settings; a later probe that works doesn't clear it, only a refresh that reads them cleanly.
430
406
  async projectsAccess(force = false): Promise<ProjectsAccess> {
431
- if (FIXTURE) return { state: "on", token: "gh" };
432
407
  const access = await this.probeProjects(force);
433
408
  return this.projectsWarning ? { ...access, warning: this.projectsWarning } : access;
434
409
  }
435
410
 
436
411
  private async probeProjects(force: boolean): Promise<ProjectsAccess> {
437
412
  if (this.projectsProbe) return this.projectsProbe;
438
- if (!force && Date.now() - this.projects.checkedAt < PROJECTS_CHECK_MS) return this.projects.access;
413
+ if (!force && this.port.now() - this.projects.checkedAt < PROJECTS_CHECK_MS) return this.projects.access;
439
414
  this.projectsProbe = (async () => {
440
- const result = await graphqlResult<{ viewer: { projectsV2: unknown } | null }>(PROJECTS_PROBE, {}, { timeoutMs: PROBE_TIMEOUT_MS }).catch((error: Error) => error);
441
- const answer = probeAnswer(result, this.projects.access.state);
415
+ const answer = probeAnswer(await this.port.github.probeProjects(), this.projects.access.state);
442
416
  if (answer.error) console.error("Couldn't read projects:", answer.error);
443
- this.projects = { access: { ...answer, token: tokenSource() }, checkedAt: Date.now() };
417
+ this.projects = { access: { ...answer, token: tokenSource() }, checkedAt: this.port.now() };
444
418
  return this.projects.access;
445
419
  })().finally(() => (this.projectsProbe = null));
446
420
  return this.projectsProbe;
447
421
  }
448
422
 
449
- // One request per search, in parallel. The details request starts once the searches it needs are back [GH-01].
423
+ // The live searches, reading projects when they can, and what went wrong with them for Settings [NXT-12].
450
424
  private async searchLive(now: Date, unclaimed: UnclaimedSearch[]): Promise<{ data: LiveResult; details: Details }> {
451
- const all = searchVariables(this.config, now);
452
- // Next up's searches read projects too, when they can [NXT-12]. Projects are extra, so they can never cost the search:
453
- // whatever goes wrong with them (the scope gone since the check, an org's SSO, no results at all), the search runs again
454
- // without them and Settings says why. Boards the token can't see come back empty and are left out.
455
- const projects = (await this.probeProjects(false)).state === "on";
456
- // What goes wrong reading projects this refresh, for Settings.
425
+ const on = (await this.probeProjects(false)).state === "on";
426
+ // What goes wrong reading projects this refresh.
457
427
  const problems: string[] = [];
458
- const pickable = async <K extends "assigned" | "unclaimed">(name: K, query: string): Promise<Pick<LiveResult, K>> => {
459
- const plain = () => graphql<Pick<LiveResult, K>>(searchQuery([name]), { [name]: query });
460
- if (!projects) return plain();
461
- // Bounded, so a stuck request falls back rather than hold up the refresh.
462
- const withProjects = () => graphqlResult<Pick<LiveResult, K>>(searchQuery([name], false, { projects }), { [name]: query }, { timeoutMs: PROJECTS_SEARCH_TIMEOUT_MS });
463
- const { data, failure, partly } = await searchWithProjects(withProjects, plain, (result) => !!result[name]);
464
- for (const problem of [partly, failure]) if (problem) (problems.push(problem), console.error(`Next up's ${name} search with projects:`, problem));
465
- if (failure) this.projects = { access: { ...projectsFailure(failure), token: tokenSource() }, checkedAt: Date.now() };
466
- return data;
467
- };
468
- const search = (name: keyof typeof all): Promise<Partial<LiveResult>> =>
469
- name === "assigned" ? pickable(name, all[name]) : graphql<Partial<LiveResult>>(searchQuery([name], name === "mine"), { [name]: all[name] });
470
- // One per Next up source [NXT-09].
471
- const searchUnclaimed = async (): Promise<Partial<LiveResult>> => {
472
- const results = await Promise.all(unclaimed.map(async ({ source, query }) => ({ source, nodes: (await pickable("unclaimed", query)).unclaimed.nodes })));
473
- return { unclaimed: { nodes: mergeUnclaimed(results) } };
474
- };
475
- const merge = (parts: Partial<LiveResult>[]) => Object.assign({}, ...parts) as LiveResult;
476
- const forDetails = Promise.all([search("mine"), search("assigned"), searchUnclaimed()]);
477
- const others = Promise.all([search("reviews"), search("mentions"), search("involved"), search("asked"), search("ended"), search("closedIssues")]);
478
- const afterThem = forDetails.then((parts) => this.details(merge(parts), projects, problems));
428
+ const failed = (failure: string) => (this.projects = { access: { ...projectsFailure(failure), token: tokenSource() }, checkedAt: this.port.now() });
479
429
  try {
480
- const [first, rest, details] = await Promise.all([forDetails, others, afterThem]);
481
- if (projects) this.projectsWarning = projectsWarning(problems);
482
- return { data: merge([...first, ...rest]), details };
430
+ const found = await this.port.github.live(this.config, now, unclaimed, { on, problems, failed });
431
+ if (on) this.projectsWarning = projectsWarning(problems);
432
+ return found;
483
433
  } catch (error) {
484
434
  // Another search failing doesn't lose what went wrong with projects so far; it can't say they went well either.
485
- if (projects && problems.length) this.projectsWarning = projectsWarning(problems);
435
+ if (on && problems.length) this.projectsWarning = projectsWarning(problems);
486
436
  throw error;
487
437
  }
488
438
  }
489
439
 
490
- private variables(names: readonly Exclude<SearchName, "unclaimed">[], now: Date): Record<string, string> {
491
- const all = searchVariables(this.config, now);
492
- return Object.fromEntries(names.map((name) => [name, all[name]]));
493
- }
494
-
495
- // Behind counts [UPS-07], required checks [PRS-14], issue field option order [NXT-02] and colors [NXT-10], and the Status
496
- // options of the boards Next up's issues are on [NXT-03].
497
- private async details(data: Pick<LiveResult, "mine" | "assigned" | "unclaimed">, projects: boolean, problems: string[]): Promise<Details> {
498
- const prs = data.mine.nodes.filter((pr) => pr?.headRefName && !pr.isCrossRepository);
499
- // Priority's colors tint its pill, so its options are asked for even when the config orders it.
500
- const effort = nextUpField(this.config, "effort");
501
- const needsOptions = !!nextUpField(this.config, "priority") || (!!effort && !effort.order);
502
- const issues = [...data.unclaimed.nodes, ...data.assigned.nodes];
503
- const orgs = needsOptions ? [...new Set(issues.map((issue) => issue?.repository?.nameWithOwner.split("/")[0]).filter(Boolean))] : [];
504
- const refs = toLookUp(data.mine.nodes.filter((pr) => pr?.repository));
505
- const mergeStates = this.mergeStates(data.mine.nodes.filter((pr) => pr?.repository));
506
- const statuses = projects ? this.projectStatuses(issueBoardIds(issues), problems) : Promise.resolve({});
507
- const details: Details = { behind: {}, fieldOptions: {}, fieldColors: {}, projectStatuses: {}, issues: {}, checks: {}, mergeState: {} };
508
- if (prs.length === 0 && orgs.length === 0 && refs.length === 0) return { ...details, mergeState: await mergeStates, projectStatuses: await statuses };
509
- const { query, compares } = detailsQuery(prs, orgs as string[], refs);
510
- type Result = {
511
- ref?: { compare: { behindBy: number } | null } | null;
512
- issueFields?: { nodes: { name?: string; options?: { name: string; color?: GithubColor }[] }[] };
513
- issueOrPullRequest?: (LinkedIssue & { state?: string }) | null;
514
- pullRequest?: { commits: { nodes: { commit: { statusCheckRollup: { contexts: { nodes: CheckContext[] } } | null } }[] } } | null;
515
- } | null;
516
- // A reference to a repo I can't see fails only its own field.
517
- const result = await graphql<Record<string, Result>>(query);
518
- for (const [alias, value] of Object.entries(result)) {
519
- // Org fields come back as o0, o1, … in the order the orgs were asked for.
520
- const org = /^o\d+$/.test(alias) ? (orgs[Number(alias.slice(1))] as string).toLowerCase() : null;
521
- const behindBy = value?.ref?.compare?.behindBy;
522
- if (typeof behindBy === "number") details.behind[compares[alias]] = behindBy;
523
- const contexts = value?.pullRequest?.commits.nodes[0]?.commit.statusCheckRollup?.contexts.nodes;
524
- if (contexts) details.checks[compares[alias]] = requiredChecks(contexts);
525
- for (const field of value?.issueFields?.nodes ?? []) {
526
- if (!org || !field.name || !field.options) continue;
527
- (details.fieldOptions[org] ??= {})[field.name] = field.options.map((o) => o.name);
528
- (details.fieldColors[org] ??= {})[field.name] = Object.fromEntries(field.options.flatMap((o) => (o.color ? [[o.name, o.color]] : [])));
529
- }
530
- const issue = value?.issueOrPullRequest; // empty for a PR
531
- if (issue?.state === "OPEN") details.issues[prKey(issue)] = { number: issue.number, title: issue.title, url: issue.url, repository: issue.repository };
532
- }
533
- return { ...details, mergeState: await mergeStates, projectStatuses: await statuses };
534
- }
535
-
536
- // Each board's Status options, once per board [NXT-03, GH-01]. A board that can't be read lists no statuses; the whole
537
- // request failing costs only the filter's statuses, never the refresh.
538
- // Bounded in time, so it can't hold up the refresh, in size, a batch of boards per request, and in how many go at once.
539
- private async projectStatuses(ids: string[], problems: string[]): Promise<Details["projectStatuses"]> {
540
- const batches = Array.from({ length: Math.ceil(ids.length / BOARDS_PER_REQUEST) }, (_, i) => ids.slice(i * BOARDS_PER_REQUEST, (i + 1) * BOARDS_PER_REQUEST));
541
- const read = async (batch: string[]) => {
542
- try {
543
- const { data, errors } = await graphqlResult<ProjectStatusesResult>(projectStatusesQuery(batch), {}, { timeoutMs: PROJECTS_SEARCH_TIMEOUT_MS });
544
- if (errors.length) problems.push(errors.join("; "));
545
- return batch.flatMap((id, index) => (data?.[`b${index}`]?.field?.options ? [[id, data[`b${index}`]!.field!.options!] as const] : []));
546
- } catch (error) {
547
- problems.push((error as Error).message);
548
- return [];
549
- }
550
- };
551
- const results: Awaited<ReturnType<typeof read>>[] = [];
552
- for (let at = 0; at < batches.length; at += BOARD_BATCHES_AT_ONCE) results.push(...(await Promise.all(batches.slice(at, at + BOARD_BATCHES_AT_ONCE).map(read))));
553
- if (problems.length) console.error("Reading projects:", problems.join("; "));
554
- return Object.fromEntries(results.flat());
555
- }
556
-
557
- // My PRs' merge state, a few per request in parallel, as GitHub only works it out for a few at a time; search's answer
558
- // for more is BLOCKED for all [PRS-13]. A request that fails leaves its PRs to search's answer.
559
- private async mergeStates(prs: PullRequestNode[]): Promise<Details["mergeState"]> {
560
- const batches = Array.from({ length: Math.ceil(prs.length / MERGE_STATE_BATCH) }, (_, i) => prs.slice(i * MERGE_STATE_BATCH, (i + 1) * MERGE_STATE_BATCH));
561
- const results = await Promise.all(
562
- batches.map(async (batch) => {
563
- const { query, keys } = mergeStateQuery(batch);
564
- const result = await graphql<Record<string, { pullRequest: { mergeStateStatus?: MergeStateStatus } | null } | null>>(query).catch(() => ({}) as Record<string, never>);
565
- return Object.entries(result).flatMap(([alias, value]) => (value?.pullRequest?.mergeStateStatus ? [[keys[alias], value.pullRequest.mergeStateStatus] as const] : []));
566
- }),
567
- );
568
- return Object.fromEntries(results.flat());
569
- }
570
-
571
440
  private async reloadConfig(): Promise<void> {
572
441
  try {
573
- this.config = await loadConfig();
442
+ this.config = await this.port.store.loadConfig();
574
443
  this.configError = null;
575
444
  } catch (error) {
576
445
  this.configError = (error as Error).message;
@@ -579,21 +448,25 @@ export class AttentionService {
579
448
  if (this.timer && this.intervalMinutes !== this.config.refreshMinutes) this.schedule();
580
449
  }
581
450
 
451
+ // A new refreshMinutes restarts the schedule; follow-ups already waiting still run.
582
452
  private schedule(): void {
583
- this.stop();
453
+ this.timer?.();
584
454
  this.intervalMinutes = this.config.refreshMinutes;
585
- this.timer = setInterval(() => {
455
+ const tick = () => {
456
+ this.timer = this.port.setTimer(tick, this.intervalMinutes * 60_000);
586
457
  void this.refresh("live").catch(() => {});
587
458
  if (this.isStale("history")) void this.refresh("history").catch(() => {});
588
- }, this.intervalMinutes * 60_000);
459
+ };
460
+ this.timer = this.port.setTimer(tick, this.intervalMinutes * 60_000);
589
461
  }
590
462
 
591
463
  // Older than the feed's schedule, and not failed within the last few minutes.
592
464
  private isStale(id: FeedId): boolean {
593
465
  const maxAgeSeconds = id === "live" ? this.config.refreshMinutes * 60 : HISTORY_MAX_AGE_SECONDS;
594
466
  const fetchedAt = this.state[id]?.fetchedAt;
595
- const old = !fetchedAt || Date.now() - new Date(fetchedAt).getTime() >= maxAgeSeconds * 1000;
596
- return old && Date.now() - this.feeds[id].lastAttemptAt >= RETRY_MS;
467
+ const now = this.port.now();
468
+ const old = !fetchedAt || now - new Date(fetchedAt).getTime() >= maxAgeSeconds * 1000;
469
+ return old && now - this.feeds[id].lastAttemptAt >= RETRY_MS;
597
470
  }
598
471
 
599
472
  private items(): Item[] {
@@ -602,7 +475,7 @@ export class AttentionService {
602
475
 
603
476
  // Feeds finish independently; saves go one at a time so an older snapshot never lands last.
604
477
  private save(): Promise<void> {
605
- this.saving = this.saving.catch(() => {}).then(() => saveState(this.state));
478
+ this.saving = this.saving.catch(() => {}).then(() => this.port.store.saveState(this.state));
606
479
  return this.saving;
607
480
  }
608
481
 
@@ -610,13 +483,20 @@ export class AttentionService {
610
483
  return { live: this.state.live?.fetchedAt ?? null, history: this.state.history?.fetchedAt ?? null };
611
484
  }
612
485
 
486
+ // The repositories the New issue sheet offers: the ones covered, from my projects and what's on screen [ISS-01].
487
+ private newIssueRepos(attention: Attention | null): string[] {
488
+ const shown = [...(attention?.items ?? []), ...(this.state.history?.items ?? [])].map((item) => item.repo);
489
+ const issues = [...(attention?.unclaimed ?? []), ...(attention?.assigned ?? [])].map((issue) => issue.repo);
490
+ return newIssueRepos(this.config, this.state.projectRepos, [...shown, ...issues], attention?.login ?? null);
491
+ }
492
+
613
493
  private view(): AttentionView {
614
494
  const status = (id: FeedId): FeedStatus => ({
615
495
  fetchedAt: this.state[id]?.fetchedAt ?? null,
616
496
  refreshing: this.feeds[id].inFlight !== null,
617
497
  error: this.feeds[id].error ?? this.configError,
618
498
  });
619
- const now = Date.now();
499
+ const now = this.port.now();
620
500
  const pending = Object.fromEntries(Object.entries(this.state.pending).filter(([, entry]) => isPending(entry, this.fetchedAt(), now)));
621
501
  const shown = applyPending(this.state.live?.attention ?? null, this.state.history?.items ?? [], pending);
622
502
  return buildView(
@@ -632,9 +512,12 @@ export class AttentionService {
632
512
  groups: Object.fromEntries(Object.entries(this.state.groups).map(([key, group]) => [key, group.keys])),
633
513
  config: this.config,
634
514
  pending: Object.keys(pending).length,
635
- ...(FIXTURE ? { fixtureAgents: FIXTURE_AGENTS } : {}),
515
+ newIssue: { repos: this.newIssueRepos(shown.attention), ...this.state.newIssue },
516
+ kept: this.state.kept,
636
517
  },
637
518
  this.state.changes,
519
+ new Date(now),
520
+ this.timeZone,
638
521
  );
639
522
  }
640
523
  }