@andrioid/paseo-attention-span 0.5.0 → 0.6.1

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 (73) hide show
  1. package/OVERVIEW.md +7 -1
  2. package/client/attention-screen.tsx +74 -1176
  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 +17 -50
  7. package/client/item-actions.ts +363 -0
  8. package/client/item-row.tsx +450 -0
  9. package/client/new-issue.tsx +244 -0
  10. package/client/next-up.tsx +36 -183
  11. package/client/pickers.tsx +237 -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/still.tsx +70 -27
  17. package/client/ui.tsx +23 -14
  18. package/client/wrap-up.tsx +151 -85
  19. package/docs/architecture.md +22 -11
  20. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  21. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  22. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  23. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  24. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  25. package/docs/screenshots/desktop-dark-doing-wrap-dirty.png +0 -0
  26. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  27. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  28. package/docs/screenshots/desktop-dark-doing.png +0 -0
  29. package/docs/screenshots/desktop-dark-next-up-setup.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/phone-dark-doing.png +0 -0
  33. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  34. package/index.client.tsx +19 -0
  35. package/index.server.ts +43 -26
  36. package/package.json +3 -1
  37. package/requirements.yaml +11 -3
  38. package/server/actions.ts +2 -1
  39. package/server/archive.ts +146 -67
  40. package/server/archived.ts +12 -16
  41. package/server/changes.ts +34 -54
  42. package/server/classify.ts +142 -136
  43. package/server/feedback.ts +2 -6
  44. package/server/fetch.ts +262 -0
  45. package/server/fixture.ts +91 -7
  46. package/server/github-types.ts +3 -1
  47. package/server/markdown.ts +3 -1
  48. package/server/port.ts +46 -0
  49. package/server/queries.ts +33 -23
  50. package/server/service.ts +155 -272
  51. package/server/setup.ts +15 -14
  52. package/server/store.ts +94 -80
  53. package/server/update.ts +34 -13
  54. package/server/view.ts +16 -15
  55. package/shared/archive.ts +116 -13
  56. package/shared/attention.ts +50 -18
  57. package/shared/changes.ts +2 -1
  58. package/shared/config.ts +2 -6
  59. package/shared/drafting.ts +17 -0
  60. package/shared/feedback.ts +6 -5
  61. package/shared/format.ts +2 -1
  62. package/shared/history-report.ts +2 -1
  63. package/shared/item-sessions.ts +76 -0
  64. package/shared/item-view.ts +223 -0
  65. package/shared/linked-sessions.ts +59 -8
  66. package/shared/names.ts +17 -0
  67. package/shared/new-issue.ts +129 -0
  68. package/shared/next-up-filter.ts +137 -0
  69. package/shared/paging.ts +16 -0
  70. package/shared/rpc.ts +23 -10
  71. package/shared/setup.ts +3 -1
  72. package/shared/still.ts +28 -7
  73. package/shared/wrap-up.ts +20 -23
@@ -0,0 +1,262 @@
1
+ import type { GithubColor } from "../shared/attention";
2
+ import { type AttentionConfig, nextUpField } from "../shared/config";
3
+ import type { IssueField } from "../shared/setup";
4
+ import { type ChangeLedger, changeCandidates, nextLedger, reopenCandidates, withGotIt } from "./changes";
5
+ import { issueBoardIds } from "./classify";
6
+ import type { graphql, graphqlResult } from "./gh";
7
+ import type { AssignmentSubject, Details, HistoryResult, LinkedIssue, LiveResult, MergeStateStatus, PullRequestNode, ReopenSubject } from "./github-types";
8
+ import { searchWithProjects } from "./projects";
9
+ import {
10
+ ASSIGNMENT_BATCH,
11
+ assignmentsQuery,
12
+ type CheckContext,
13
+ detailsQuery,
14
+ HISTORY_SEARCHES,
15
+ issueFieldsQuery,
16
+ MERGE_STATE_BATCH,
17
+ mergeStateQuery,
18
+ mergeUnclaimed,
19
+ type OrgFields,
20
+ prKey,
21
+ PROJECTS_PROBE,
22
+ projectStatusesQuery,
23
+ type ProjectStatusesResult,
24
+ reopenQuery,
25
+ requiredChecks,
26
+ type SearchName,
27
+ searchQuery,
28
+ searchVariables,
29
+ type UnclaimedSearch,
30
+ } from "./queries";
31
+ import { toLookUp } from "./references";
32
+
33
+ // What the service asks GitHub, one request shape each [GH-01]. Previews answer from made-up data instead (fixture.ts).
34
+
35
+ export interface Gh {
36
+ graphql: typeof graphql;
37
+ graphqlResult: typeof graphqlResult;
38
+ }
39
+
40
+ export type ProbeResult = Awaited<ReturnType<typeof graphqlResult<{ viewer: { projectsV2: unknown } | null }>>> | Error;
41
+
42
+ // What a refresh learns about reading projects [NXT-12]: whether to, what went wrong, and a search that had to go without.
43
+ export interface ProjectsReport {
44
+ on: boolean;
45
+ problems: string[];
46
+ failed(message: string): void;
47
+ }
48
+
49
+ export interface GitHub {
50
+ // The account gh is signed in as, for My repos [NXT-04].
51
+ login(): Promise<string>;
52
+ // Whether the gh login may read projects [NXT-12].
53
+ probeProjects(): Promise<ProbeResult>;
54
+ live(config: AttentionConfig, now: Date, unclaimed: UnclaimedSearch[], projects: ProjectsReport): Promise<{ data: LiveResult; details: Details }>;
55
+ // The ledger after what others did to my work since the last refresh [HIS-07]. `gotIt` is read once the lookups are back.
56
+ changes(ledger: ChangeLedger, data: LiveResult, now: Date, config: AttentionConfig, gotIt: () => string[]): Promise<ChangeLedger>;
57
+ // From the oldest week's Monday in the device's `timeZone` [HIS-01].
58
+ history(config: AttentionConfig, now: Date, timeZone: string): Promise<HistoryResult>;
59
+ // The single-select fields of these orgs, merged by name [NXT-04].
60
+ issueFields(owners: string[]): Promise<IssueField[]>;
61
+ }
62
+
63
+ // The check waits this long at most, as the refresh waits on it.
64
+ const PROBE_TIMEOUT_MS = 10_000;
65
+ // A search with projects, or a batch of boards' statuses, waits this long at most before the refresh goes on without them.
66
+ const PROJECTS_SEARCH_TIMEOUT_MS = 20_000;
67
+ const BOARDS_PER_REQUEST = 50;
68
+ // Batches of boards asked at once, so many boards don't burst requests [GH-01].
69
+ const BOARD_BATCHES_AT_ONCE = 2;
70
+
71
+ export function gitHub(gh: Gh): GitHub {
72
+ return {
73
+ login: async () => (await gh.graphql<{ viewer: { login: string } }>("{ viewer { login } }")).viewer.login,
74
+ // Given PROBE_TIMEOUT_MS, so a stuck gh can't hold up the refresh waiting on it.
75
+ probeProjects: () => gh.graphqlResult<{ viewer: { projectsV2: unknown } | null }>(PROJECTS_PROBE, {}, { timeoutMs: PROBE_TIMEOUT_MS }).catch((error: Error) => error),
76
+ live: (config, now, unclaimed, projects) => searchLive(gh, config, now, unclaimed, projects),
77
+ changes: (ledger, data, now, config, gotIt) => trackChanges(gh, ledger, data, now, config, gotIt),
78
+ history: (config, now, timeZone) => gh.graphql<HistoryResult>(searchQuery(HISTORY_SEARCHES, true), variables(config, HISTORY_SEARCHES, now, timeZone)),
79
+ issueFields: (owners) => issueFields(gh, owners),
80
+ };
81
+ }
82
+
83
+ // One request per search, in parallel. The details request starts once the searches it needs are back [GH-01].
84
+ export async function searchLive(gh: Gh, config: AttentionConfig, now: Date, unclaimed: UnclaimedSearch[], projects: ProjectsReport): Promise<{ data: LiveResult; details: Details }> {
85
+ const all = searchVariables(config, now);
86
+ // Next up's searches read projects too, when they can [NXT-12]. Projects are extra, so they can never cost the search:
87
+ // whatever goes wrong with them (the scope gone since the check, an org's SSO, no results at all), the search runs again
88
+ // without them and Settings says why. Boards the token can't see come back empty and are left out.
89
+ const pickable = async <K extends "assigned" | "unclaimed">(name: K, query: string): Promise<Pick<LiveResult, K>> => {
90
+ const plain = () => gh.graphql<Pick<LiveResult, K>>(searchQuery([name]), { [name]: query });
91
+ if (!projects.on) return plain();
92
+ // Bounded, so a stuck request falls back rather than hold up the refresh.
93
+ const withProjects = () => gh.graphqlResult<Pick<LiveResult, K>>(searchQuery([name], false, { projects: true }), { [name]: query }, { timeoutMs: PROJECTS_SEARCH_TIMEOUT_MS });
94
+ const { data, failure, partly } = await searchWithProjects(withProjects, plain, (result) => !!result[name]);
95
+ for (const problem of [partly, failure]) if (problem) (projects.problems.push(problem), console.error(`Next up's ${name} search with projects:`, problem));
96
+ if (failure) projects.failed(failure);
97
+ return data;
98
+ };
99
+ const search = (name: keyof typeof all): Promise<Partial<LiveResult>> =>
100
+ name === "assigned" ? pickable(name, all[name]) : gh.graphql<Partial<LiveResult>>(searchQuery([name], name === "mine"), { [name]: all[name] });
101
+ // One per Next up source [NXT-09].
102
+ const searchUnclaimed = async (): Promise<Partial<LiveResult>> => {
103
+ const results = await Promise.all(unclaimed.map(async ({ source, query }) => ({ source, nodes: (await pickable("unclaimed", query)).unclaimed.nodes })));
104
+ return { unclaimed: { nodes: mergeUnclaimed(results) } };
105
+ };
106
+ const merge = (parts: Partial<LiveResult>[]) => Object.assign({}, ...parts) as LiveResult;
107
+ const forDetails = Promise.all([search("mine"), search("assigned"), searchUnclaimed()]);
108
+ const others = Promise.all([search("reviews"), search("mentions"), search("involved"), search("asked"), search("ended"), search("closedIssues")]);
109
+ const afterThem = forDetails.then((parts) => details(gh, config, merge(parts), projects.on, projects.problems));
110
+ const [first, rest, found] = await Promise.all([forDetails, others, afterThem]);
111
+ return { data: merge([...first, ...rest]), details: found };
112
+ }
113
+
114
+ function variables(config: AttentionConfig, names: readonly Exclude<SearchName, "unclaimed">[], now: Date, timeZone: string): Record<string, string> {
115
+ const all = searchVariables(config, now, timeZone);
116
+ return Object.fromEntries(names.map((name) => [name, all[name]]));
117
+ }
118
+
119
+ // Behind counts [UPS-07], required checks [PRS-14], issue field option order [NXT-02] and colors [NXT-10], and the Status
120
+ // options of the boards Next up's issues are on [NXT-03].
121
+ async function details(gh: Gh, config: AttentionConfig, data: Pick<LiveResult, "mine" | "assigned" | "unclaimed">, projects: boolean, problems: string[]): Promise<Details> {
122
+ const prs = data.mine.nodes.filter((pr) => pr?.headRefName && !pr.isCrossRepository);
123
+ // Priority's colors tint its pill, so its options are asked for even when the config orders it.
124
+ const effort = nextUpField(config, "effort");
125
+ const needsOptions = !!nextUpField(config, "priority") || (!!effort && !effort.order);
126
+ const issues = [...data.unclaimed.nodes, ...data.assigned.nodes];
127
+ const orgs = needsOptions ? [...new Set(issues.map((issue) => issue?.repository?.nameWithOwner.split("/")[0]).filter(Boolean))] : [];
128
+ const refs = toLookUp(data.mine.nodes.filter((pr) => pr?.repository));
129
+ const mergeState = mergeStates(gh, data.mine.nodes.filter((pr) => pr?.repository));
130
+ const statuses = projects ? projectStatuses(gh, issueBoardIds(issues), problems) : Promise.resolve({});
131
+ if (prs.length === 0 && orgs.length === 0 && refs.length === 0) return { ...readDetails({}, [], {}), mergeState: await mergeState, projectStatuses: await statuses };
132
+ const { query, compares } = detailsQuery(prs, orgs as string[], refs);
133
+ // A reference to a repo I can't see fails only its own field.
134
+ const result = await gh.graphql<Record<string, DetailsField>>(query);
135
+ return { ...readDetails(result, orgs as string[], compares), mergeState: await mergeState, projectStatuses: await statuses };
136
+ }
137
+
138
+ type DetailsField = {
139
+ ref?: { compare: { behindBy: number } | null } | null;
140
+ issueFields?: { nodes: { name?: string; options?: { name: string; color?: GithubColor }[] }[] };
141
+ issueOrPullRequest?: (LinkedIssue & { state?: string }) | null;
142
+ pullRequest?: { commits: { nodes: { commit: { statusCheckRollup: { contexts: { nodes: CheckContext[] } } | null } }[] } } | null;
143
+ } | null;
144
+
145
+ // The details request's answer, by alias: `compares` maps a PR's aliases to its key, and org fields come back as o0, o1,
146
+ // … in the order `orgs` were asked for.
147
+ export function readDetails(result: Record<string, DetailsField>, orgs: string[], compares: Record<string, string>): Omit<Details, "mergeState" | "projectStatuses"> {
148
+ const found: Omit<Details, "mergeState" | "projectStatuses"> = { behind: {}, fieldOptions: {}, fieldColors: {}, issues: {}, checks: {} };
149
+ for (const [alias, value] of Object.entries(result)) {
150
+ const org = /^o\d+$/.test(alias) ? orgs[Number(alias.slice(1))].toLowerCase() : null;
151
+ const behindBy = value?.ref?.compare?.behindBy;
152
+ if (typeof behindBy === "number") found.behind[compares[alias]] = behindBy;
153
+ const contexts = value?.pullRequest?.commits.nodes[0]?.commit.statusCheckRollup?.contexts.nodes;
154
+ if (contexts) found.checks[compares[alias]] = requiredChecks(contexts);
155
+ for (const field of value?.issueFields?.nodes ?? []) {
156
+ if (!org || !field.name || !field.options) continue;
157
+ (found.fieldOptions[org] ??= {})[field.name] = field.options.map((o) => o.name);
158
+ (found.fieldColors[org] ??= {})[field.name] = Object.fromEntries(field.options.flatMap((o) => (o.color ? [[o.name, o.color]] : [])));
159
+ }
160
+ const issue = value?.issueOrPullRequest; // empty for a PR
161
+ if (issue?.state === "OPEN") found.issues[prKey(issue)] = { number: issue.number, title: issue.title, url: issue.url, repository: issue.repository };
162
+ }
163
+ return found;
164
+ }
165
+
166
+ // Each board's Status options, once per board [NXT-03, GH-01]. A board that can't be read lists no statuses; the whole
167
+ // request failing costs only the filter's statuses, never the refresh.
168
+ // 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.
169
+ export async function projectStatuses(gh: Gh, ids: string[], problems: string[]): Promise<Details["projectStatuses"]> {
170
+ const found = await lookupBatches<string, NonNullable<ProjectStatusesResult[string]>>(gh, ids, "b", projectStatusesQuery, {
171
+ size: BOARDS_PER_REQUEST,
172
+ atOnce: BOARD_BATCHES_AT_ONCE,
173
+ timeoutMs: PROJECTS_SEARCH_TIMEOUT_MS,
174
+ problem: (message) => problems.push(message),
175
+ });
176
+ if (problems.length) console.error("Reading projects:", problems.join("; "));
177
+ return Object.fromEntries([...found].flatMap(([id, board]) => (board?.field?.options ? [[id, board.field.options]] : [])));
178
+ }
179
+
180
+ // 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
181
+ // for more is BLOCKED for all [PRS-13]. A request that fails leaves its PRs to search's answer.
182
+ async function mergeStates(gh: Gh, prs: PullRequestNode[]): Promise<Details["mergeState"]> {
183
+ const found = await lookupBatches<PullRequestNode, { pullRequest: { mergeStateStatus?: MergeStateStatus } | null }>(gh, prs, "m", mergeStateQuery, {
184
+ size: MERGE_STATE_BATCH,
185
+ atOnce: Infinity,
186
+ });
187
+ return Object.fromEntries([...found].flatMap(([pr, node]) => (node?.pullRequest?.mergeStateStatus ? [[prKey(pr), node.pullRequest.mergeStateStatus]] : [])));
188
+ }
189
+
190
+ // Nodes asked for `size` to a request, `atOnce` requests at a time, each aliased `prefix` and its index in the batch
191
+ // [GH-01]. Answers each item's node, or null when GitHub can't find it, as that one is gone for good. An item whose
192
+ // request, or own field, failed is left out, to be asked again next refresh. `problem` hears what went wrong.
193
+ export async function lookupBatches<T, N>(
194
+ gh: Gh,
195
+ items: T[],
196
+ prefix: string,
197
+ query: (batch: T[]) => string,
198
+ { size, atOnce = 1, timeoutMs, problem }: { size: number; atOnce?: number; timeoutMs?: number; problem?: (message: string) => void },
199
+ ): Promise<Map<T, N | null>> {
200
+ const batches = Array.from({ length: Math.ceil(items.length / size) }, (_, i) => items.slice(i * size, (i + 1) * size));
201
+ const read = async (batch: T[]): Promise<[T, N | null][]> => {
202
+ try {
203
+ const { data, errors, failures } = await gh.graphqlResult<Record<string, N | null>>(query(batch), {}, timeoutMs ? { timeoutMs } : {});
204
+ if (errors.length) problem?.(errors.join("; "));
205
+ return batch.flatMap((item, index) => {
206
+ const alias = `${prefix}${index}`;
207
+ const failed = failures.some((failure) => failure.path?.[0] === alias && failure.type !== "NOT_FOUND");
208
+ return failed ? [] : [[item, data?.[alias] ?? null]];
209
+ });
210
+ } catch (error) {
211
+ problem?.((error as Error).message);
212
+ return [];
213
+ }
214
+ };
215
+ const found: [T, N | null][] = [];
216
+ for (let at = 0; at < batches.length; at += atOnce) for (const answer of await Promise.all(batches.slice(at, at + atOnce).map(read))) found.push(...answer);
217
+ return new Map(found);
218
+ }
219
+
220
+ // What others did to my work since the last refresh [HIS-07]. Only PRs whose hands changed and issues that left my assigned
221
+ // search are looked up, a batch per request; a failed batch is asked again next time [GH-01]. Kept long enough for History.
222
+ export async function trackChanges(gh: Gh, ledger: ChangeLedger, data: LiveResult, now: Date, config: AttentionConfig, gotIt: () => string[]): Promise<ChangeLedger> {
223
+ const me = data.viewer.login;
224
+ // The two don't depend on each other, so they run together, each with its own batches.
225
+ const [lookups, reopens] = await Promise.all([
226
+ lookupBatches<string, AssignmentSubject>(gh, changeCandidates(ledger, data, me), "a", assignmentsQuery, {
227
+ size: ASSIGNMENT_BATCH,
228
+ problem: (message) => console.error("Couldn't look up who changed my work:", message),
229
+ }),
230
+ // PRs Attention Span saw closed, so a reopen by someone else is noticed.
231
+ lookupBatches<string, ReopenSubject>(gh, reopenCandidates(ledger, data), "a", reopenQuery, {
232
+ size: ASSIGNMENT_BATCH,
233
+ problem: (message) => console.error("Couldn't check whether a closed PR reopened:", message),
234
+ }),
235
+ ]);
236
+ const keepDays = Math.max(config.mentionDays, config.historyWeeks * 7 + 7);
237
+ // A Got it tapped, or an archive acknowledging, while this refresh ran still counts.
238
+ // Got its tapped while the lookups ran decide too, so a handover cleared meanwhile survives its work coming back.
239
+ const current = { ...ledger, gotIt: gotIt() };
240
+ return withGotIt(nextLedger(current, data, me, lookups, now, config.mentionDays, keepDays, reopens), gotIt());
241
+ }
242
+
243
+ // The fields settings offers for Next up, merged by name across orgs [NXT-04]. No orgs, no request.
244
+ async function issueFields(gh: Gh, owners: string[]): Promise<IssueField[]> {
245
+ if (owners.length === 0) return [];
246
+ return mergeIssueFields(owners, await gh.graphql<Record<string, OrgFields>>(issueFieldsQuery(owners)));
247
+ }
248
+
249
+ // Each org's fields as o0, o1, … in the order of `owners`, merged by name, case aside; a field without options isn't one.
250
+ export function mergeIssueFields(owners: string[], result: Record<string, OrgFields>): IssueField[] {
251
+ const merged = new Map<string, IssueField>();
252
+ owners.forEach((org, index) => {
253
+ for (const field of result[`o${index}`]?.issueFields?.nodes ?? []) {
254
+ if (!field.name || !field.options) continue;
255
+ const known = merged.get(field.name.toLowerCase());
256
+ if (known) known.orgs.push(org);
257
+ else merged.set(field.name.toLowerCase(), { name: field.name, options: field.options.map((option) => option.name), orgs: [org] });
258
+ }
259
+ });
260
+ return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
261
+ }
262
+
package/server/fixture.ts CHANGED
@@ -1,8 +1,15 @@
1
- import type { AgentSummary, GithubColor, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { AgentSummary, AttentionView, GithubColor, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
4
+ import type { KeptRow } from "../shared/archive";
2
5
  import type { OthersChange } from "../shared/changes";
3
6
  import type { SessionKind } from "../shared/config";
4
- import type { IssueField } from "../shared/setup";
7
+ import type { CoverageCheck, CoverageKind, IssueField, SetupStatus } from "../shared/setup";
8
+ import { sameName } from "../shared/names";
5
9
  import type { Actor, Comment, Details, IssueNode, MentionNode, PickableNode, PullRequestNode, SearchResult } from "./github-types";
10
+ import type { Port } from "./port";
11
+ import { setTimer } from "./port";
12
+ import { State, type Store } from "./store";
6
13
 
7
14
  // Made-up GitHub data for tests and for previews without GitHub (PASEO_ATTENTION_SPAN_FIXTURE=1).
8
15
 
@@ -10,10 +17,10 @@ export const REPO = "acme/shop";
10
17
  // Issues kept apart from the code, as some orgs do; its code lives in REPO [SES-07].
11
18
  export const ISSUES_REPO = "acme/issues";
12
19
  // What the settings screen can add in previews [SRC-02]; anything else isn't found.
13
- export const FIXTURE_ORGS = ["acme"];
14
- export const FIXTURE_REPOS = [REPO, ISSUES_REPO, "acme/web", "me/tool"];
20
+ const FIXTURE_ORGS = ["acme"];
21
+ const FIXTURE_REPOS = [REPO, ISSUES_REPO, "acme/web", "me/tool"];
15
22
  // The orgs Next up's org picker offers in previews [NXT-04].
16
- export const FIXTURE_MY_ORGS = ["acme", "globex"];
23
+ const FIXTURE_MY_ORGS = ["acme", "globex"];
17
24
  // The org issue fields settings offers for Next up [NXT-04].
18
25
  export const FIXTURE_ISSUE_FIELDS: IssueField[] = [
19
26
  { name: "Effort", options: ["🐟 Tiny (< 4h)", "🐇 Small (0.5-2d)", "🐂 Medium (2-5d)", "🦑 Large (1-2w)"], orgs: ["acme"] },
@@ -324,6 +331,14 @@ export function fixture(now: Date): { data: SearchResult; details: Details } {
324
331
  };
325
332
  }
326
333
 
334
+ // The fixture, or nothing in it on a quiet day.
335
+ function fixtureNow(now: Date, quiet: boolean): ReturnType<typeof fixture> {
336
+ const { data, details } = fixture(now);
337
+ if (!quiet) return { data, details };
338
+ const empty = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, key === "viewer" ? value : { nodes: [] }]));
339
+ return { data: empty as unknown as SearchResult, details };
340
+ }
341
+
327
342
  // What others did to my work, one of each kind, as the ledger keeps them [HIS-07, HIS-06]. #179 was handed over, then merged
328
343
  // by its new owner, so History doesn't count it as mine.
329
344
  export function fixtureChanges(now: Date): OthersChange[] {
@@ -408,9 +423,11 @@ export const FIXTURE_AGENTS: AgentSummary[] = [
408
423
  agent("agent-197", `${REPO}#197`, undefined, "idle", 15),
409
424
  // Wrap up: finished work whose sessions are all idle [ATT-22].
410
425
  agent("agent-183", `${REPO}#183`, "fix", "idle", 20, false, sessionWorkspace("retry-webhooks", false, 0), "Retry webhooks"),
411
- agent("agent-186", `${REPO}#186`, "fix", "idle", 40, false, sessionWorkspace("split-invoice-pdf", true, 1, true, 2), "Split invoice PDF"),
426
+ // Its sheet counts lines and names the terminals archiving closes, as Paseo's own sheet would.
427
+ agent("agent-186", `${REPO}#186`, "fix", "idle", 40, false, { ...sessionWorkspace("split-invoice-pdf", true, 1, true, 2)!, dirtyLines: { added: 12, deleted: 3 }, terminals: ["dev", "shell"] }, "Split invoice PDF"),
412
428
  agent("agent-190", `${REPO}#190`, "review", "idle", 60, false, sessionWorkspace("add-vat-export", false, 0), "Review PR 190: Add the VAT export"),
413
- agent("agent-172", `${REPO}#172`, "fix", "idle", 240, false, sessionWorkspace("fix-vat-credit-notes", false, 0), "Fix VAT on credit notes"),
429
+ // With a review sub-agent it started, archived along with it.
430
+ { ...agent("agent-172", `${REPO}#172`, "fix", "idle", 240, false, sessionWorkspace("fix-vat-credit-notes", false, 0), "Fix VAT on credit notes"), subAgents: { count: 1, working: false } },
414
431
  agent("agent-172b", `${REPO}#172`, "address", "idle", 250, false, sessionWorkspace("credit-note-tests", undefined, undefined), "Credit note tests"),
415
432
  ];
416
433
 
@@ -450,3 +467,70 @@ export function fixtureDetails(subject: { kind: "pr" | "issue"; repo: string; nu
450
467
  : [],
451
468
  };
452
469
  }
470
+
471
+ // What the service sees in previews: this made-up GitHub, no Paseo projects or sessions to archive, and state kept in
472
+ // memory. config.json is still the file in `dir`, as the shooter edits it.
473
+ export function fixturePort(store: Store, dir: string): Port {
474
+ // A quiet day: GitHub has nothing for me, so the preview can show the empty tabs' scenes [ATT-18, HIS-08, WAI-04, NXT-13].
475
+ // On while this file exists in the plugin's folder; the shooter creates it last.
476
+ const quiet = () => existsSync(join(dir, "fixture-quiet"));
477
+ return {
478
+ github: {
479
+ login: async () => "me",
480
+ // Previews can always read projects [NXT-12].
481
+ probeProjects: async () => ({ data: { viewer: { projectsV2: { nodes: [] } } }, errors: [], failures: [] }),
482
+ live: async (_config, now) => (dismissedKept.clear(), fixtureNow(now, quiet())),
483
+ // Previews start each layout with a refresh, which brings the notes back: Got it would otherwise outlive a layout.
484
+ changes: async (ledger, _data, now) => ({ ...ledger, events: quiet() ? [] : fixtureChanges(now), gotIt: fixtureGotIt(now) }),
485
+ history: async (_config, now) => fixtureNow(now, quiet()).data,
486
+ issueFields: async () => FIXTURE_ISSUE_FIELDS,
487
+ },
488
+ // Previews have no Paseo agents, but archiving still acknowledges, so their screenshots can show the cleanup.
489
+ paseo: { projectRepos: async () => [], archive: async () => ({ ok: true, kept: [] }) },
490
+ store: { ...store, loadState: async () => State.parse({}), saveState: async () => {} },
491
+ now: Date.now,
492
+ setTimer,
493
+ };
494
+ }
495
+
496
+ // Wrap up rows whose worktree stayed, one for each reason [ATT-22].
497
+ const keptRow = (number: number, title: string, fields: Pick<KeptRow, "name" | "reason" | "detail" | "agentId">): KeptRow => ({
498
+ workspaceId: `WS_kept_${number}`,
499
+ ...fields,
500
+ itemKey: `${REPO}#${number}`,
501
+ title,
502
+ repo: REPO,
503
+ number,
504
+ kind: "pr",
505
+ at: new Date().toISOString(),
506
+ });
507
+ export const FIXTURE_KEPT: KeptRow[] = [
508
+ keptRow(176, "Round prices per currency", { name: "Round prices per currency", reason: "session", detail: "Fix flaky price test", agentId: "agent-101" }),
509
+ keptRow(178, "Cache the tax tables", { name: "cache-tax-tables", reason: "terminal", detail: "dev server" }),
510
+ keptRow(179, "Drop the legacy exporter", { name: "Drop the legacy exporter", reason: "refused", detail: "worktree is locked" }),
511
+ ];
512
+
513
+ // Made-up kept rows dismissed in this layout; each layout's first refresh brings them back, like the notes.
514
+ const dismissedKept = new Set<string>();
515
+ export const fixtureDismissKept = (workspaceId: string) => void dismissedKept.add(workspaceId);
516
+
517
+ // A view with the made-up sessions, as the preview daemon has no agents, and kept worktrees for it to show [ATT-22].
518
+ export const fixtureView = (view: AttentionView): AttentionView => ({
519
+ ...view,
520
+ fixtureAgents: FIXTURE_AGENTS,
521
+ kept: [...(view.kept ?? []), ...FIXTURE_KEPT.filter((row) => !dismissedKept.has(row.workspaceId))],
522
+ });
523
+
524
+ // The sheet's, picker's, session's and setup's asks, answered from made-up data; gh counts as signed in.
525
+ export const fixtureAnswers = {
526
+ ghStatus: async (): Promise<SetupStatus["gh"]> => ({ found: true, login: "me", error: null }),
527
+ myOrgs: async () => FIXTURE_MY_ORGS,
528
+ coverageOnGitHub: async (kind: CoverageKind, name: string): Promise<CoverageCheck> => {
529
+ const known = (kind === "org" ? FIXTURE_ORGS : FIXTURE_REPOS).find((candidate) => sameName(candidate, name));
530
+ return known ? { name: known, error: null } : { name: null, error: `${name} wasn't found on GitHub` };
531
+ },
532
+ reviewerChoices: async (_target: Target, recent: Reviewer[]) => fixtureReviewerChoices(recent),
533
+ itemDetails: async (subject: { kind: "pr" | "issue"; repo: string; number: number }, target: Target | undefined, checks: boolean) => fixtureDetails(subject, target, checks),
534
+ defaultBranch: async () => "main",
535
+ sessionContext: async () => FIXTURE_CONTEXT,
536
+ };
@@ -163,6 +163,8 @@ export interface EndedPullRequest {
163
163
  number: number;
164
164
  title: string;
165
165
  url: string;
166
+ // Missing in older fixtures and caches.
167
+ headRefName?: string;
166
168
  merged: boolean;
167
169
  mergedAt: string | null;
168
170
  closedAt: string;
@@ -199,7 +201,7 @@ type Labels = { labels?: Nodes<{ name: string }> };
199
201
  export interface HistoryResult {
200
202
  // Who I am, to tell a merge by someone else [HIS-05]; missing in older fixtures.
201
203
  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>;
204
+ merged: Nodes<{ number: number; title: string; url: string; headRefName?: string; body?: string; mergedAt: string; mergedBy?: { login: string } | null; repository: Repo; closingIssuesReferences: Nodes<{ number: number; repository: Repo }> } & Labels>;
203
205
  reviewed: Nodes<{ number: number; title: string; url: string; mergedAt: string; mergedBy?: { login: string } | null; repository: Repo; author: Actor | null } & Labels>;
204
206
  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>;
205
207
  }
@@ -1,3 +1,5 @@
1
+ import { sameName } from "../shared/names";
2
+
1
3
  // GitHub Markdown for the screen: whole comments to render in the 👍 picker, and plain text for quotes cut anywhere.
2
4
 
3
5
  const FENCE = /^\s*(```|~~~)/;
@@ -103,7 +105,7 @@ export function taggedIn(html: string | undefined): { login: string; team: boole
103
105
  const team = /^\/orgs\/([^/]+)\/teams\/([^/]+)\/?$/.exec(path);
104
106
  const user = /^\/([^/]+)\/?$/.exec(path);
105
107
  const login = kind === "team" && team ? `${team[1]}/${team[2]}` : kind === "user" && user ? user[1] : undefined;
106
- if (login && !tags.some((tag) => tag.login.toLowerCase() === login.toLowerCase())) tags.push({ login, team: kind === "team" });
108
+ if (login && !tags.some((tag) => sameName(tag.login, login))) tags.push({ login, team: kind === "team" });
107
109
  }
108
110
  return tags;
109
111
  }
package/server/port.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+ import type { ArchiveResult } from "../shared/archive";
3
+ import { githubRepoOf } from "../shared/config";
4
+ import { archiveSessions } from "./archive";
5
+ import { type GitHub, gitHub } from "./fetch";
6
+ import { graphql, graphqlResult } from "./gh";
7
+ import type { Store } from "./store";
8
+
9
+ type Paseo = PluginHandlerContext["paseo"];
10
+
11
+ // Everything the service reaches outside itself: GitHub, Paseo, its files and the clock. Real here; made up for previews
12
+ // in fixture.ts, and for tests.
13
+ export interface Port {
14
+ github: GitHub;
15
+ paseo: {
16
+ // My Paseo projects' GitHub repos [NXT-08].
17
+ projectRepos(paseo: Paseo): Promise<string[]>;
18
+ // Archives sessions, and `worktrees` kept before, tried again on their own [ATT-22].
19
+ archive(paseo: Paseo, agentIds: string[], confirm: boolean, terminals: string[], worktrees: string[]): Promise<ArchiveResult>;
20
+ };
21
+ store: Store;
22
+ now(): number;
23
+ // Runs `run` once after `ms`; calling the answer cancels it.
24
+ setTimer(run: () => void, ms: number): () => void;
25
+ }
26
+
27
+ export function setTimer(run: () => void, ms: number): () => void {
28
+ const timer = setTimeout(run, ms);
29
+ return () => clearTimeout(timer);
30
+ }
31
+
32
+ export function realPort(store: Store): Port {
33
+ return {
34
+ github: gitHub({ graphql, graphqlResult }),
35
+ paseo: {
36
+ projectRepos: async (paseo) => {
37
+ const { projects } = await paseo.projects.list();
38
+ return [...new Set(projects.map((project) => githubRepoOf(project.projectKey)).filter((repo): repo is string => !!repo))].sort();
39
+ },
40
+ archive: archiveSessions,
41
+ },
42
+ store,
43
+ now: Date.now,
44
+ setTimer,
45
+ };
46
+ }
package/server/queries.ts CHANGED
@@ -33,7 +33,7 @@ const SEARCHES = {
33
33
  ended: {
34
34
  first: 50,
35
35
  nodes: `... on PullRequest {
36
- id number title url merged mergedAt closedAt repository { nameWithOwner } mergedBy { login }
36
+ id number title url headRefName merged mergedAt closedAt repository { nameWithOwner } mergedBy { login }
37
37
  assignees(first: 10) { nodes { login } }
38
38
  timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { createdAt actor { login } } } }
39
39
  }`,
@@ -46,10 +46,10 @@ const SEARCHES = {
46
46
  timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { createdAt actor { login } } } }
47
47
  }`,
48
48
  },
49
- // Who merged it, when it wasn't me [HIS-05].
49
+ // Who merged it, when it wasn't me [HIS-05]; its branch, so a session left on it finds its way to Wrap up [ATT-22].
50
50
  merged: {
51
51
  first: 100,
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 } } } }",
52
+ nodes: "... on PullRequest { number title url headRefName body mergedAt mergedBy { login } repository { nameWithOwner } labels(first: 20) { nodes { name } } closingIssuesReferences(first: 3) { nodes { number repository { nameWithOwner } } } }",
53
53
  },
54
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
55
  reviewed: { first: 100, nodes: "... on PullRequest { number title url mergedAt mergedBy { login } repository { nameWithOwner } author { ...author } labels(first: 20) { nodes { name } } }" },
@@ -61,8 +61,7 @@ const SEARCHES = {
61
61
  };
62
62
  export type SearchName = keyof typeof SEARCHES;
63
63
 
64
- // Doing, Waiting and Next up. History has its own, slower schedule.
65
- export const LIVE_SEARCHES = ["mine", "reviews", "mentions", "involved", "asked", "assigned", "unclaimed", "ended", "closedIssues"] as const;
64
+ // History's searches, on their own, slower schedule; the live ones are sent by the service, one request each.
66
65
  export const HISTORY_SEARCHES = ["merged", "reviewed", "closed"] as const;
67
66
 
68
67
  const FRAGMENTS: Record<string, string> = {
@@ -141,16 +140,30 @@ function where(orgs: string[], repos: string[]): string {
141
140
 
142
141
  const isoDate = (date: Date) => date.toISOString().slice(0, 10);
143
142
 
144
- function startOfWeek(now: Date): Date {
145
- const monday = new Date(now);
146
- monday.setUTCHours(0, 0, 0, 0);
147
- monday.setUTCDate(monday.getUTCDate() - ((monday.getUTCDay() + 6) % 7));
148
- return monday;
143
+ // How far `timeZone`'s clock is ahead of UTC at `at`, in ms.
144
+ function zoneOffset(at: number, timeZone: string): number {
145
+ const format = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" });
146
+ const part = Object.fromEntries(format.formatToParts(at).map(({ type, value }) => [type, Number(value)]));
147
+ return Date.UTC(part.year, part.month - 1, part.day, part.hour, part.minute, part.second) - Math.floor(at / 1000) * 1000;
149
148
  }
150
149
 
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();
150
+ // Where History starts: midnight on the oldest week's Monday in the device's time zone, so the server's weeks are the
151
+ // screen's and the oldest isn't cut short [HIS-01]. UTC until a device has sent its zone.
152
+ export function historySince(now: Date, weeks: number, timeZone = "UTC"): string {
153
+ const local = new Date(now.getTime() + zoneOffset(now.getTime(), timeZone));
154
+ const monday = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() - ((local.getUTCDay() + 6) % 7) - 7 * (weeks - 1));
155
+ // The offset at that midnight, which a daylight saving change since may have moved.
156
+ return new Date(monday - zoneOffset(monday - zoneOffset(monday, timeZone), timeZone)).toISOString();
157
+ }
158
+
159
+ // A time zone this server's Intl knows [HIS-01].
160
+ export function isTimeZone(name: string): boolean {
161
+ try {
162
+ new Intl.DateTimeFormat("en-US", { timeZone: name });
163
+ return true;
164
+ } catch {
165
+ return false;
166
+ }
154
167
  }
155
168
 
156
169
  // Where Next up looks for unclaimed issues [NXT-04, NXT-08]: one search per chosen source, so each issue says which
@@ -195,10 +208,11 @@ export function mergeUnclaimed(results: { source: string | null; nodes: (Pickabl
195
208
  }
196
209
 
197
210
  // The searches about me. Next up's unclaimed issues have their own [NXT-04].
198
- export function searchVariables(config: AttentionConfig, now: Date): Record<Exclude<SearchName, "unclaimed">, string> {
211
+ export function searchVariables(config: AttentionConfig, now: Date, timeZone?: string): Record<Exclude<SearchName, "unclaimed">, string> {
199
212
  const scope = where(config.orgs, config.repos);
200
213
  const since = isoDate(new Date(now.getTime() - config.mentionDays * 86_400_000));
201
- const history = isoDate(new Date(historySince(now, config.historyWeeks)));
214
+ // To the second: GitHub reads a bare date as UTC midnight.
215
+ const history = `${historySince(now, config.historyWeeks, timeZone).slice(0, 19)}+00:00`;
202
216
  return {
203
217
  mine: `is:pr is:open author:@me ${scope}`,
204
218
  // By name only, not via a team [REV-01].
@@ -316,14 +330,10 @@ export function issueFieldsQuery(orgs: string[]): string {
316
330
  // in search and in a repo's PR list. Seen on 2026-11-04 [PRS-13].
317
331
  export const MERGE_STATE_BATCH = 5;
318
332
 
319
- // The merge state of up to MERGE_STATE_BATCH PRs, in one request; m0, m1, … map back to their keys.
320
- export function mergeStateQuery(prs: PullRequestNode[]): { query: string; keys: Record<string, string> } {
321
- const keys: Record<string, string> = {};
322
- const fields = prs.map((pr, index) => {
323
- keys[`m${index}`] = prKey(pr);
324
- return `m${index}: ${repository(pr.repository.nameWithOwner)} { pullRequest(number: ${pr.number}) { mergeStateStatus } }`;
325
- });
326
- return { query: `query MergeState {\n${fields.join("\n")}\n}`, keys };
333
+ // The merge state of up to MERGE_STATE_BATCH PRs, in one request, as m0, m1, … in the order given.
334
+ export function mergeStateQuery(prs: PullRequestNode[]): string {
335
+ const fields = prs.map((pr, index) => `m${index}: ${repository(pr.repository.nameWithOwner)} { pullRequest(number: ${pr.number}) { mergeStateStatus } }`);
336
+ return `query MergeState {\n${fields.join("\n")}\n}`;
327
337
  }
328
338
 
329
339
  export type CheckContext = { status?: string; conclusion?: string | null; state?: string; isRequired?: boolean };