@andrioid/paseo-attention-span 0.4.13 → 0.5.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 (54) hide show
  1. package/OVERVIEW.md +10 -4
  2. package/README.md +2 -2
  3. package/client/attention-screen.tsx +142 -123
  4. package/client/card.tsx +4 -2
  5. package/client/history.tsx +184 -0
  6. package/client/icons.ts +7 -0
  7. package/client/mark.ts +19 -0
  8. package/client/sessions.ts +50 -3
  9. package/client/ui.tsx +18 -3
  10. package/client/wrap-up.tsx +197 -0
  11. package/docs/architecture.md +19 -7
  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-wrap-dirty.png +0 -0
  18. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  19. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  20. package/docs/screenshots/desktop-dark-doing.png +0 -0
  21. package/docs/screenshots/desktop-dark-history-filtered.png +0 -0
  22. package/docs/screenshots/desktop-dark-history-groups.png +0 -0
  23. package/docs/screenshots/desktop-dark-history.png +0 -0
  24. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  25. package/docs/screenshots/desktop-dark-settings.png +0 -0
  26. package/docs/screenshots/desktop-dark-setup.png +0 -0
  27. package/docs/screenshots/desktop-dark-waiting.png +0 -0
  28. package/docs/screenshots/phone-dark-doing.png +0 -0
  29. package/docs/screenshots/phone-dark-history.png +0 -0
  30. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  31. package/index.client.tsx +6 -1
  32. package/index.server.ts +21 -1
  33. package/package.json +8 -3
  34. package/requirements.yaml +11 -7
  35. package/server/archive.ts +132 -0
  36. package/server/archived.ts +120 -0
  37. package/server/changes.ts +355 -0
  38. package/server/classify.ts +15 -4
  39. package/server/fixture.ts +85 -8
  40. package/server/gh.ts +16 -4
  41. package/server/github-types.ts +67 -3
  42. package/server/queries.ts +62 -8
  43. package/server/service.ts +131 -11
  44. package/server/store.ts +20 -1
  45. package/server/view.ts +25 -6
  46. package/shared/archive.ts +37 -0
  47. package/shared/attention.ts +93 -3
  48. package/shared/changes.ts +66 -0
  49. package/shared/got-it.ts +23 -0
  50. package/shared/history-report.ts +61 -0
  51. package/shared/rpc.ts +23 -2
  52. package/shared/still.ts +4 -3
  53. package/shared/wrap-up.ts +126 -0
  54. package/docs/screenshots/desktop-dark-history-reviewed.png +0 -0
@@ -96,6 +96,8 @@ export interface IssueNode {
96
96
  }
97
97
 
98
98
  export interface PickableNode {
99
+ // The issue's node id, which a transfer keeps [HIS-07].
100
+ id?: string;
99
101
  number: number;
100
102
  title: string;
101
103
  url: string;
@@ -128,6 +130,66 @@ export interface LiveResult {
128
130
  asked: Nodes<IssueNode>;
129
131
  assigned: Nodes<PickableNode>;
130
132
  unclaimed: Nodes<PickableNode>;
133
+ // My PRs closed lately [HIS-07].
134
+ ended: Nodes<EndedPullRequest>;
135
+ // Issues assigned to me closed lately, for a change by others [HIS-07].
136
+ closedIssues: Nodes<ClosedIssue>;
137
+ }
138
+
139
+ export interface ClosedIssue {
140
+ id: string;
141
+ number: number;
142
+ title: string;
143
+ url: string;
144
+ closedAt: string;
145
+ stateReason: string | null;
146
+ repository: Repo;
147
+ timelineItems: Nodes<{ createdAt?: string; actor?: { login: string } | null }>;
148
+ }
149
+
150
+ // A PR of mine known to have been closed, as it is now [HIS-07].
151
+ export interface ReopenSubject {
152
+ id: string;
153
+ number: number;
154
+ title: string;
155
+ url: string;
156
+ state: "OPEN" | "CLOSED" | "MERGED";
157
+ repository: Repo;
158
+ timelineItems: Nodes<{ createdAt?: string; actor?: { login: string } | null }>;
159
+ }
160
+
161
+ export interface EndedPullRequest {
162
+ id: string;
163
+ number: number;
164
+ title: string;
165
+ url: string;
166
+ merged: boolean;
167
+ mergedAt: string | null;
168
+ closedAt: string;
169
+ repository: Repo;
170
+ mergedBy: { login: string } | null;
171
+ assignees: Nodes<{ login: string }>;
172
+ timelineItems: Nodes<{ createdAt?: string; actor?: { login: string } | null }>;
173
+ }
174
+
175
+ // Who assigned or unassigned whom; actor and assignee are null for a deleted account [HIS-07].
176
+ export interface AssignmentEvent {
177
+ __typename: "AssignedEvent" | "UnassignedEvent";
178
+ createdAt: string;
179
+ actor: { login: string } | null;
180
+ assignee: { login?: string } | null;
181
+ }
182
+
183
+ export interface AssignmentSubject {
184
+ __typename: "PullRequest" | "Issue";
185
+ id: string;
186
+ number: number;
187
+ title: string;
188
+ url: string;
189
+ state: "OPEN" | "CLOSED" | "MERGED";
190
+ repository: Repo;
191
+ assignees: Nodes<{ login: string }>;
192
+ timelineItems: Nodes<AssignmentEvent | Record<string, never>>;
131
193
  }
132
194
 
133
195
  // One request for all three [HIS-01, HIS-02].
@@ -135,9 +197,11 @@ export interface LiveResult {
135
197
  type Labels = { labels?: Nodes<{ name: string }> };
136
198
 
137
199
  export interface HistoryResult {
138
- merged: Nodes<{ number: number; title: string; url: string; body?: string; mergedAt: string; repository: Repo; closingIssuesReferences: Nodes<{ number: number; repository: Repo }> } & Labels>;
139
- reviewed: Nodes<{ number: number; title: string; url: string; mergedAt: string; repository: Repo; author: Actor | null } & Labels>;
140
- closed: Nodes<{ number: number; title: string; url: string; closedAt: string; stateReason: string | null; repository: Repo; issueType?: { name: string } | null } & Labels>;
200
+ // Who I am, to tell a merge by someone else [HIS-05]; missing in older fixtures.
201
+ viewer?: { login: string; id: string };
202
+ merged: Nodes<{ number: number; title: string; url: string; body?: string; mergedAt: string; mergedBy?: { login: string } | null; repository: Repo; closingIssuesReferences: Nodes<{ number: number; repository: Repo }> } & Labels>;
203
+ reviewed: Nodes<{ number: number; title: string; url: string; mergedAt: string; mergedBy?: { login: string } | null; repository: Repo; author: Actor | null } & Labels>;
204
+ closed: Nodes<{ number: number; title: string; url: string; closedAt: string; stateReason: string | null; repository: Repo; issueType?: { name: string } | null; timelineItems?: Nodes<{ actor?: { login: string } | null }> } & Labels>;
141
205
  }
142
206
 
143
207
  export type SearchResult = LiveResult & HistoryResult;
package/server/queries.ts CHANGED
@@ -28,18 +28,41 @@ const SEARCHES = {
28
28
  asked: { first: 50, nodes: THREAD },
29
29
  assigned: { first: 50, nodes: "...pickable" },
30
30
  unclaimed: { first: 100, nodes: "...pickable" },
31
+ // My PRs closed lately, with who merged or closed them, for Changed by others [HIS-07]. Who closed one comes from its last
32
+ // close event; assignees tell a PR handed over before it closed [PRS-08].
33
+ ended: {
34
+ first: 50,
35
+ nodes: `... on PullRequest {
36
+ id number title url merged mergedAt closedAt repository { nameWithOwner } mergedBy { login }
37
+ assignees(first: 10) { nodes { login } }
38
+ timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { createdAt actor { login } } } }
39
+ }`,
40
+ },
41
+ // Issues assigned to me closed lately, so someone else's close is a change too [HIS-07]. Bounded like `ended`.
42
+ closedIssues: {
43
+ first: 50,
44
+ nodes: `... on Issue {
45
+ id number title url closedAt stateReason repository { nameWithOwner }
46
+ timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { createdAt actor { login } } } }
47
+ }`,
48
+ },
49
+ // Who merged it, when it wasn't me [HIS-05].
31
50
  merged: {
32
51
  first: 100,
33
- nodes: "... on PullRequest { number title url body mergedAt repository { nameWithOwner } labels(first: 20) { nodes { name } } closingIssuesReferences(first: 3) { nodes { number repository { nameWithOwner } } } }",
52
+ nodes: "... on PullRequest { number title url body mergedAt mergedBy { login } repository { nameWithOwner } labels(first: 20) { nodes { name } } closingIssuesReferences(first: 3) { nodes { number repository { nameWithOwner } } } }",
53
+ },
54
+ // Who merged someone else's PR I reviewed, for the week's Changed by others copy and Wrap up [HIS-02, ATT-22].
55
+ reviewed: { first: 100, nodes: "... on PullRequest { number title url mergedAt mergedBy { login } repository { nameWithOwner } author { ...author } labels(first: 20) { nodes { name } } }" },
56
+ // Labels and type say what kind of work each was [HIS-04]; the close event's actor says who closed it [HIS-07].
57
+ closed: {
58
+ first: 100,
59
+ nodes: "... on Issue { number title url closedAt stateReason repository { nameWithOwner } issueType { name } labels(first: 20) { nodes { name } } timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { actor { login } } } } }",
34
60
  },
35
- reviewed: { first: 100, nodes: "... on PullRequest { number title url mergedAt repository { nameWithOwner } author { ...author } labels(first: 20) { nodes { name } } }" },
36
- // Labels and type say what kind of work each was [HIS-04].
37
- closed: { first: 100, nodes: "... on Issue { number title url closedAt stateReason repository { nameWithOwner } issueType { name } labels(first: 20) { nodes { name } } }" },
38
61
  };
39
62
  export type SearchName = keyof typeof SEARCHES;
40
63
 
41
64
  // Doing, Waiting and Next up. History has its own, slower schedule.
42
- export const LIVE_SEARCHES = ["mine", "reviews", "mentions", "involved", "asked", "assigned", "unclaimed"] as const;
65
+ export const LIVE_SEARCHES = ["mine", "reviews", "mentions", "involved", "asked", "assigned", "unclaimed", "ended", "closedIssues"] as const;
43
66
  export const HISTORY_SEARCHES = ["merged", "reviewed", "closed"] as const;
44
67
 
45
68
  const FRAGMENTS: Record<string, string> = {
@@ -51,7 +74,7 @@ const FRAGMENTS: Record<string, string> = {
51
74
  ... on PullRequestReviewComment { id url reactionGroups { viewerHasReacted } }
52
75
  }`,
53
76
  pickable: `fragment pickable on Issue {
54
- number title url createdAt
77
+ id number title url createdAt
55
78
  repository { nameWithOwner isFork defaultBranchRef { name } }
56
79
  issueType { name }
57
80
  issueFieldValues(first: 20) { nodes { ... on IssueFieldSingleSelectValue { name field { ... on IssueFieldCommon { name } } } } }
@@ -125,6 +148,11 @@ function startOfWeek(now: Date): Date {
125
148
  return monday;
126
149
  }
127
150
 
151
+ // Where History starts: whole weeks, from a Monday, so the oldest week isn't cut short [HIS-01].
152
+ export function historySince(now: Date, weeks: number): string {
153
+ return new Date(startOfWeek(now).getTime() - (weeks - 1) * 7 * 86_400_000).toISOString();
154
+ }
155
+
128
156
  // Where Next up looks for unclaimed issues [NXT-04, NXT-08]: one search per chosen source, so each issue says which
129
157
  // sources found it and no query outgrows GitHub's limit [NXT-09]. Without sources, the configured orgs and repos,
130
158
  // else my Paseo projects' repos. Never all of GitHub: unlike the other searches, this one isn't about me.
@@ -170,14 +198,17 @@ export function mergeUnclaimed(results: { source: string | null; nodes: (Pickabl
170
198
  export function searchVariables(config: AttentionConfig, now: Date): Record<Exclude<SearchName, "unclaimed">, string> {
171
199
  const scope = where(config.orgs, config.repos);
172
200
  const since = isoDate(new Date(now.getTime() - config.mentionDays * 86_400_000));
173
- // Whole weeks, from a Monday, so the oldest week isn't cut short.
174
- const history = isoDate(new Date(startOfWeek(now).getTime() - (config.historyWeeks - 1) * 7 * 86_400_000));
201
+ const history = isoDate(new Date(historySince(now, config.historyWeeks)));
175
202
  return {
176
203
  mine: `is:pr is:open author:@me ${scope}`,
177
204
  // By name only, not via a team [REV-01].
178
205
  reviews: `is:pr is:open user-review-requested:@me ${scope}`,
179
206
  mentions: `is:open mentions:@me updated:>=${since} ${scope}`,
180
207
  assigned: `is:issue is:open assignee:@me ${scope}`,
208
+ // Within the window Changed by others catches up over [HIS-07].
209
+ ended: `is:pr is:closed author:@me closed:>=${since} sort:updated-desc ${scope}`,
210
+ // Issues assigned to me that closed lately: someone else's close is a change too [HIS-07].
211
+ closedIssues: `is:issue is:closed assignee:@me closed:>=${since} sort:updated-desc ${scope}`,
181
212
  // Threads I opened, commented on, was assigned or mentioned in, active lately: answers, and fresh questions [ATT-16].
182
213
  involved: `is:open involves:@me updated:>=${since} sort:updated-desc ${scope}`,
183
214
  // On my own issues a question nobody answered stays however old [ATT-11]. Newest first, so old ones go last.
@@ -189,6 +220,29 @@ export function searchVariables(config: AttentionConfig, now: Date): Record<Excl
189
220
  };
190
221
  }
191
222
 
223
+ // Who assigned and unassigned whom on PRs and issues that may have left my hands, by node id, a batch per request [HIS-07, GH-01].
224
+ // The last events are enough: a handover is the latest change of hands.
225
+ export const ASSIGNMENT_BATCH = 20;
226
+ const ASSIGNMENT_EVENT = "createdAt actor { login } assignee { ... on User { login } ... on Bot { login } ... on Mannequin { login } }";
227
+ export function assignmentsQuery(ids: string[]): string {
228
+ const subject = `id number title url state repository { nameWithOwner } assignees(first: 10) { nodes { login } }
229
+ timelineItems(itemTypes: [ASSIGNED_EVENT, UNASSIGNED_EVENT], last: 30) { nodes { __typename ... on AssignedEvent { ${ASSIGNMENT_EVENT} } ... on UnassignedEvent { ${ASSIGNMENT_EVENT} } } }`;
230
+ const fields = ids.map((id, index) => `a${index}: node(id: ${JSON.stringify(id)}) { __typename ... on PullRequest { ${subject} } ... on Issue { ${subject} } }`);
231
+ return `query Assignments {\n${fields.join("\n")}\n}`;
232
+ }
233
+
234
+ // PRs Attention Span saw closed, by node id, a batch per request: only a state and a reopen event [HIS-07, GH-01].
235
+ export function reopenQuery(ids: string[]): string {
236
+ const fields = ids.map(
237
+ (id, index) => `a${index}: node(id: ${JSON.stringify(id)}) {
238
+ ... on PullRequest { id number title url state repository { nameWithOwner }
239
+ timelineItems(itemTypes: [REOPENED_EVENT], last: 1) { nodes { ... on ReopenedEvent { createdAt actor { login } } } }
240
+ }
241
+ }`,
242
+ );
243
+ return `query Reopened {\n${fields.join("\n")}\n}`;
244
+ }
245
+
192
246
  export function prKey(node: { repository: { nameWithOwner: string }; number: number }): string {
193
247
  return `${node.repository.nameWithOwner}#${node.number}`;
194
248
  }
package/server/service.ts CHANGED
@@ -1,13 +1,19 @@
1
- import type { Attention, AttentionView, FeedId, FeedStatus, GithubColor, Item, ProjectsAccess, Reviewer } from "../shared/attention";
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";
2
2
  import type { PluginHandlerContext } from "@getpaseo/plugin/server";
3
3
  import { AttentionConfig, type FieldRole, githubRepoOf, nextUpField } from "../shared/config";
4
4
  import type { IssueField } from "../shared/setup";
5
+ import type { ArchiveOutcome, ArchiveTarget } from "../shared/archive";
6
+ import { archiveSessions } from "./archive";
7
+ import { rememberGroups } from "../shared/wrap-up";
8
+ import { acknowledge, changeCandidates, ownClosed, nextLedger, type Lookups, type ReopenLookups, reopenCandidates, withGotIt } from "./changes";
5
9
  import { classify, classifyHistory, issueBoardIds } from "./classify";
6
10
  import { probeAnswer, projectsFailure, projectsWarning, searchWithProjects } from "./projects";
7
11
  import { FIXTURE, graphql, graphqlResult } from "./gh";
8
- import { fixture, FIXTURE_AGENTS, FIXTURE_ISSUE_FIELDS } from "./fixture";
9
- import type { Details, HistoryResult, LinkedIssue, LiveResult, MergeStateStatus, PullRequestNode } from "./github-types";
12
+ import { fixture, FIXTURE_AGENTS, FIXTURE_ISSUE_FIELDS, fixtureChanges, fixtureGotIt } from "./fixture";
13
+ import type { AssignmentSubject, Details, HistoryResult, LinkedIssue, LiveResult, MergeStateStatus, PullRequestNode, ReopenSubject } from "./github-types";
10
14
  import {
15
+ ASSIGNMENT_BATCH,
16
+ assignmentsQuery,
11
17
  type CheckContext,
12
18
  detailsQuery,
13
19
  HISTORY_SEARCHES,
@@ -20,6 +26,7 @@ import {
20
26
  PROJECTS_PROBE,
21
27
  projectStatusesQuery,
22
28
  type ProjectStatusesResult,
29
+ reopenQuery,
23
30
  requiredChecks,
24
31
  type SearchName,
25
32
  searchQuery,
@@ -97,9 +104,10 @@ export class AttentionService {
97
104
  }
98
105
 
99
106
  // ⟳ fetches its tab's feed now; otherwise feeds older than their schedule are fetched first.
100
- async get(refresh?: FeedId): Promise<AttentionView> {
107
+ // `cached` answers from memory, with no GitHub refresh first.
108
+ async get(refresh?: FeedId, cached?: boolean): Promise<AttentionView> {
101
109
  if (refresh) await this.refresh(refresh).catch(() => {});
102
- else await this.refreshStale();
110
+ else if (!cached) await this.refreshStale();
103
111
  return this.view();
104
112
  }
105
113
 
@@ -118,12 +126,57 @@ export class AttentionService {
118
126
  return this.view();
119
127
  }
120
128
 
129
+ // Clears Changed by others notes, or brings them back for Undo; nothing changes on GitHub [HIS-07].
130
+ async gotIt(ids: string[], on: boolean): Promise<AttentionView> {
131
+ const gotIt = this.state.changes.gotIt.filter((other) => !ids.includes(other));
132
+ const known = ids.filter((id) => this.state.changes.events.some((event) => event.id === id));
133
+ this.state.changes.gotIt = on ? [...gotIt, ...known] : gotIt;
134
+ await this.save();
135
+ return this.view();
136
+ }
137
+
121
138
  async restoreDismissed(): Promise<AttentionView> {
122
139
  this.state.dismissed = {};
123
140
  await this.save();
124
141
  return this.view();
125
142
  }
126
143
 
144
+ // Reviewed and Changed by others in each of History's weeks [HIS-07].
145
+ async setHistoryFilter(filter: HistoryFilter[]): Promise<AttentionView> {
146
+ this.state.historyFilter = [...new Set(filter)];
147
+ await this.save();
148
+ return this.view();
149
+ }
150
+
151
+ // Archive acknowledges exactly the events on the work at that moment, including ones a refresh added meanwhile; `upTo`
152
+ // leaves out what came after then [HIS-07, ATT-22].
153
+ async acknowledge(keys: string[], upTo?: string): Promise<AttentionView> {
154
+ this.state.changes = acknowledge(this.state.changes, keys, upTo);
155
+ await this.save();
156
+ return this.view();
157
+ }
158
+
159
+ // The keys of the item's whole stack or issue group: its own members, as GitHub spells them, since Paseo's labels match
160
+ // exactly, plus what was remembered while it was open [ATT-22, ATT-04].
161
+ groupKeysOf(itemKey: string): string[] {
162
+ const wanted = itemKey.toLowerCase();
163
+ const view = this.view();
164
+ const items = [...view.history, ...(view.ownClosed ?? []), ...view.doing.flatMap((section) => section.items), ...view.waiting.flatMap((group) => group.items)];
165
+ const found = items.map(memberKeys).filter((keys) => keySet(keys).has(wanted)).flat();
166
+ return uniqueKeys([itemKey, ...found, ...(this.state.groups[wanted]?.keys ?? [])]);
167
+ }
168
+
169
+ // Archive a Wrap up row's sessions; success acknowledges the events on that work, so they go to their week as cleared, not
170
+ // 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);
175
+ if (!answer.ok) return { ...answer, view: this.view() };
176
+ const view = await this.acknowledge(targets.flatMap((target) => target.keys));
177
+ return answer.warning ? { ok: true, view, warning: answer.warning } : { ok: true, view };
178
+ }
179
+
127
180
  // Remember where an issue repo's code lives [SES-07].
128
181
  async setCodeRepo(issueRepo: string, codeRepo: string): Promise<AttentionView> {
129
182
  this.config = await saveCodeRepo(issueRepo, codeRepo);
@@ -261,7 +314,10 @@ export class AttentionService {
261
314
  await this.reloadConfig();
262
315
  const now = new Date();
263
316
  const fetchedAt = now.toISOString();
264
- if (id === "live") this.state.live = { fetchedAt, attention: await this.fetchLive(now) };
317
+ if (id === "live") {
318
+ this.state.live = { fetchedAt, attention: await this.fetchLive(now) };
319
+ this.state.groups = rememberGroups(this.state.groups, this.state.live.attention.items, now, Math.max(this.config.mentionDays, this.config.historyWeeks * 7 + 7));
320
+ }
265
321
  else this.state.history = { fetchedAt, items: await this.fetchHistory(now) };
266
322
  // Forget dismissals of items that are gone.
267
323
  const keys = new Set(this.items().map((item) => item.key));
@@ -282,7 +338,63 @@ export class AttentionService {
282
338
  const login = FIXTURE ? "me" : this.config.nextUp.mine ? await this.login() : null;
283
339
  const unclaimed = unclaimedSearches(this.config, projectRepos, login);
284
340
  const { data, details } = FIXTURE ? fixture(now) : await this.searchLive(now, unclaimed.searches);
285
- return { ...classify({ data, details, config: this.config, now }), unclaimedFrom: unclaimed.from };
341
+ await this.trackChanges(data, now);
342
+ const own = FIXTURE ? [] : ownClosed(data, data.viewer.login);
343
+ return { ...classify({ data, details, config: this.config, now }), unclaimedFrom: unclaimed.from, ...(own.length ? { ownClosed: own } : {}) };
344
+ }
345
+
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: 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;
286
398
  }
287
399
 
288
400
  // The account gh is signed in as, for My repos [NXT-04]. Asked once, unless the last fetch already says.
@@ -306,7 +418,7 @@ export class AttentionService {
306
418
 
307
419
  private async fetchHistory(now: Date): Promise<Item[]> {
308
420
  if (FIXTURE) return classifyHistory(fixture(now).data);
309
- return classifyHistory(await graphql<HistoryResult>(searchQuery(HISTORY_SEARCHES), this.variables(HISTORY_SEARCHES, now)));
421
+ return classifyHistory(await graphql<HistoryResult>(searchQuery(HISTORY_SEARCHES, true), this.variables(HISTORY_SEARCHES, now)));
310
422
  }
311
423
 
312
424
  // Whether the gh login may read projects, asked at most hourly, or now when Settings asks [NXT-12]. On only when GitHub
@@ -362,7 +474,7 @@ export class AttentionService {
362
474
  };
363
475
  const merge = (parts: Partial<LiveResult>[]) => Object.assign({}, ...parts) as LiveResult;
364
476
  const forDetails = Promise.all([search("mine"), search("assigned"), searchUnclaimed()]);
365
- const others = Promise.all([search("reviews"), search("mentions"), search("involved"), search("asked")]);
477
+ const others = Promise.all([search("reviews"), search("mentions"), search("involved"), search("asked"), search("ended"), search("closedIssues")]);
366
478
  const afterThem = forDetails.then((parts) => this.details(merge(parts), projects, problems));
367
479
  try {
368
480
  const [first, rest, details] = await Promise.all([forDetails, others, afterThem]);
@@ -507,14 +619,22 @@ export class AttentionService {
507
619
  const now = Date.now();
508
620
  const pending = Object.fromEntries(Object.entries(this.state.pending).filter(([, entry]) => isPending(entry, this.fetchedAt(), now)));
509
621
  const shown = applyPending(this.state.live?.attention ?? null, this.state.history?.items ?? [], pending);
510
- return buildView(shown.attention, shown.history, this.state.dismissed, {
622
+ return buildView(
623
+ shown.attention,
624
+ shown.history,
625
+ this.state.dismissed,
626
+ {
511
627
  feeds: { live: status("live"), history: status("history") },
512
628
  scopes: this.state.scopes,
513
629
  sources: this.state.sources,
514
630
  projectFilter: this.state.projectFilter,
631
+ historyFilter: this.state.historyFilter,
632
+ groups: Object.fromEntries(Object.entries(this.state.groups).map(([key, group]) => [key, group.keys])),
515
633
  config: this.config,
516
634
  pending: Object.keys(pending).length,
517
635
  ...(FIXTURE ? { fixtureAgents: FIXTURE_AGENTS } : {}),
518
- });
636
+ },
637
+ this.state.changes,
638
+ );
519
639
  }
520
640
  }
package/server/store.ts CHANGED
@@ -2,8 +2,10 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { z } from "zod";
5
- import { type Attention, type Item, type SectionId, SECTIONS } from "../shared/attention";
5
+ import { type Attention, type HistoryFilter, type Item, type RememberedGroups, type SectionId, SECTIONS } from "../shared/attention";
6
6
  import { AttentionConfig, FIELD_ROLES, type FieldRole, sameField } from "../shared/config";
7
+ import type { OthersChange } from "../shared/changes";
8
+ import { type ChangeLedger, EMPTY_LEDGER } from "./changes";
7
9
  import type { Pending } from "./view";
8
10
 
9
11
  // Local files in ~/.config/paseo-attention-span/ [PRIV-01].
@@ -27,8 +29,25 @@ export const State = z.object({
27
29
  sources: z.array(z.string()).default([]),
28
30
  // Project statuses ticked in Next up's filter; none means all [NXT-03].
29
31
  projectFilter: z.array(z.string()).default([]),
32
+ // Reviewed and Changed by others shown in each of History's weeks; none means finished only [HIS-07].
33
+ historyFilter: z.array(z.enum(["reviewed", "changed"])).default([]).catch([] as HistoryFilter[]),
30
34
  // The update notice put off with Not now, by the version it offered [UPD-01].
31
35
  skippedUpdate: z.string().nullable().default(null).catch(null),
36
+ // What others did to my work, kept until Got it or an archive and for History [HIS-06, HIS-07, ATT-22].
37
+ changes: z
38
+ .object({
39
+ events: z.array(z.custom<OthersChange>((value) => typeof (value as OthersChange)?.id === "string" && typeof (value as OthersChange)?.at === "string")),
40
+ gotIt: z.array(z.string()),
41
+ assigned: z.record(z.string(), z.string()).nullable(),
42
+ handed: z.record(z.string(), z.string()),
43
+ // PRs seen closed, to notice a reopen by someone else [HIS-07].
44
+ tracked: z.record(z.string(), z.custom<ChangeLedger["tracked"][string]>((value) => typeof (value as { key?: string })?.key === "string")).default({}),
45
+ })
46
+ .default(EMPTY_LEDGER)
47
+ .catch(EMPTY_LEDGER),
48
+ // Key -> the keys of the stack or issue group it was last seen in, and when, so Wrap up still knows a merged PR's open
49
+ // siblings after History lists it on its own [ATT-22, ATT-04].
50
+ groups: z.record(z.string(), z.object({ keys: z.array(z.string()), at: z.string() })).default({}).catch({}) satisfies z.ZodType<RememberedGroups>,
32
51
  // My Paseo projects' GitHub repos when last listed, for refreshes before the app has connected [NXT-08].
33
52
  projectRepos: z.array(z.string()).default([]),
34
53
  // The last fetch of each feed. A cache from an older version is dropped rather than shown wrong, like one with an item in a
package/server/view.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { type Attention, type AttentionView, type Chip, type FeedId, type FeedStatus, type Item, type NextUpIssue, type Section, SECTION_ORDER, SECTIONS, type TabId, type WaitingGroup } from "../shared/attention";
1
+ import { type Attention, type AttentionView, type Chip, type FeedId, type FeedStatus, type HistoryFilter, type Item, type NextUpIssue, type Section, SECTION_ORDER, SECTIONS, type TabId, type WaitingGroup } from "../shared/attention";
2
2
  import type { AttentionConfig } from "../shared/config";
3
3
  import { workChip, workKind } from "../shared/work";
4
+ import { type ChangeLedger, changeItems, EMPTY_LEDGER, handedKeys } from "./changes";
5
+ import { historySince } from "./queries";
4
6
  import type { State } from "./store";
5
7
 
6
8
  export interface ViewMeta {
@@ -8,6 +10,8 @@ export interface ViewMeta {
8
10
  scopes: string[];
9
11
  sources: string[];
10
12
  projectFilter: string[];
13
+ historyFilter: HistoryFilter[];
14
+ groups?: Record<string, string[]>;
11
15
  config: AttentionConfig;
12
16
  pending: number;
13
17
  }
@@ -126,25 +130,40 @@ export function waitingGroups(items: Item[]): WaitingGroup[] {
126
130
  // Waiting's work: its own sections, and my PRs in Doing while they wait on someone I asked [WAI-01, PRS-15].
127
131
  const inWaiting = (item: Item) => SECTIONS[item.section].tab === "waiting" || (SECTIONS[item.section].tab === "doing" && !!item.wait && !!item.waitingOn?.length);
128
132
 
129
- export function buildView(attention: Attention | null, history: Item[], dismissed: State["dismissed"], meta: ViewMeta): AttentionView {
133
+ export function buildView(attention: Attention | null, history: Item[], dismissed: State["dismissed"], meta: ViewMeta, ledger: ChangeLedger = EMPTY_LEDGER, now = new Date()): AttentionView {
130
134
  const items = [...(attention?.items ?? []), ...history];
131
- const visible = items.filter((item) => !isDismissed(item, dismissed));
135
+ // A PR that left my hands isn't my finished work, even once its new owner merges it [HIS-06].
136
+ const handed = handedKeys(ledger);
137
+ const visible = items
138
+ .filter((item) => !isDismissed(item, dismissed) && !(item.section === "done" && handed.has(item.key)))
139
+ .map((item) => (item.section === "done" && item.children.some((child) => handed.has(child.key)) ? { ...item, children: item.children.filter((child) => !handed.has(child.key)) } : item));
140
+ // Notes on what others did, what was cleared into a week, and finished work a live refresh saw first; never dismissed,
141
+ // only cleared with Got it or an archive [HIS-06, HIS-07, ATT-22].
142
+ const changes = changeItems(ledger, now, meta.config.mentionDays, historySince(now, meta.config.historyWeeks));
143
+ // History's daily fetch has the richer item; one seen live fills in until then, so a merge or close shows in its week now.
144
+ const knownDone = new Set(visible.filter((item) => SECTIONS[item.section].tab === "history" && item.section === "done").flatMap((item) => [item.key, ...item.children.map((child) => child.key)]));
145
+ const liveFinished = changes.finished.filter((item) => !knownDone.has(item.key));
146
+ const shown = [...visible, ...liveFinished, ...changes.notes, ...changes.history];
132
147
  const sections = (tab: TabId): Section[] =>
133
148
  SECTION_ORDER.filter((id) => SECTIONS[id].tab === tab)
134
- .map((id) => ({ id, title: SECTIONS[id].title, items: visible.filter((item) => item.section === id) }))
149
+ .map((id) => ({ id, title: SECTIONS[id].title, items: shown.filter((item) => item.section === id) }))
135
150
  .filter((section) => section.items.length > 0);
136
151
  const doing = sections("doing");
137
152
  return {
138
153
  ...meta,
139
154
  login: attention?.login ?? null,
155
+ // What needs me; Wrap up's cleanup rows are added client-side, where the sessions are [ATT-09, ATT-22].
140
156
  count: doing.reduce((sum, section) => sum + section.items.length, 0),
141
157
  doing,
142
158
  waiting: waitingGroups(visible.filter(inWaiting)),
143
- history: visible.filter((item) => SECTIONS[item.section].tab === "history"),
159
+ history: shown.filter((item) => SECTIONS[item.section].tab === "history"),
160
+ // Dismissed or not, these are still open; Wrap up must not call their sessions finished [ATT-22].
161
+ ownClosed: attention?.ownClosed ?? [],
162
+ activeKeys: (attention?.items ?? []).flatMap((item) => [item.key, ...item.children.map((child) => child.key)]),
144
163
  assigned: attention?.assigned ?? [],
145
164
  unclaimed: attention?.unclaimed ?? [],
146
165
  unclaimedFrom: attention?.unclaimedFrom ?? "config",
147
166
  projects: attention?.projects ?? [],
148
- dismissedCount: items.length - visible.length,
167
+ dismissedCount: items.filter((item) => isDismissed(item, dismissed)).length,
149
168
  };
150
169
  }
@@ -0,0 +1,37 @@
1
+ import type { AttentionView, WrapItem } from "./attention";
2
+
3
+ // Archiving a Wrap up row's sessions [ATT-22]. The screen names the row; the server checks, archives and acknowledges.
4
+
5
+ // A session with work archiving could lose, as the confirm sheet names it: "2 uncommitted files and 1 unpushed commit on
6
+ // branch". `unknown` when git and Paseo couldn't both say; the sheet says so instead.
7
+ export interface UnsavedSession {
8
+ agentId: string;
9
+ title: string | null;
10
+ branch?: string;
11
+ files?: number;
12
+ commits?: number;
13
+ unknown?: true;
14
+ }
15
+
16
+ // What an archive request names: the row's item, its sessions, and the keys whose changes success acknowledges.
17
+ export interface ArchiveTarget {
18
+ itemKey: string;
19
+ agentIds: string[];
20
+ keys: string[];
21
+ }
22
+
23
+ export const archiveTarget = (item: WrapItem): ArchiveTarget => ({
24
+ itemKey: item.wrap.itemKey,
25
+ agentIds: item.wrap.sessions.map((session) => session.id),
26
+ keys: item.wrap.keys,
27
+ });
28
+
29
+ // What archiving answers. A refusal keeps the row and says why, or names the unsaved work to confirm. `warning`: the
30
+ // sessions were archived, but a worktree that should have gone stayed, and why.
31
+ export type ArchiveResult =
32
+ | { ok: true; warning?: string }
33
+ | { ok: false; reason: "working"; message: string }
34
+ | { ok: false; reason: "unsaved"; sessions: UnsavedSession[] };
35
+
36
+ // The answer the screen gets: the result, with the list after it.
37
+ export type ArchiveOutcome = ArchiveResult & { view: AttentionView };