@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/context.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ownStack, type StackPr, type Target } from "../shared/attention";
1
+ import { ownStack, reviewAgain, type StackPr, type Target } from "../shared/attention";
2
2
  import type { SessionKind } from "../shared/config";
3
3
  import { graphql, runGh } from "./gh";
4
4
 
@@ -49,14 +49,106 @@ export async function sessionContext(kind: SessionKind, target: Target): Promise
49
49
  if (kind === "address") return reviewFeedback(target);
50
50
 
51
51
  // Review of a stack: every branch, with a link to each PR asking for my review; the agent reads what it needs [ATT-04].
52
+ // Asked again, what I said last time and what changed since, on each PR I reviewed [REV-02].
52
53
  const stack = target.stack ?? [];
54
+ const again = kind === "review" ? reviewAgainContext(target) : Promise.resolve("");
53
55
  if (kind === "review" && stack.length > 1) {
54
56
  const lines = stack.map((pr) => `${branchLine(pr)}${pr.review ? `, review requested: https://github.com/${target.repo}/pull/${pr.number}` : ", mine"}`);
55
- return `Stack, bottom first:\n${lines.join("\n")}`;
57
+ return join(`Stack, bottom first:\n${lines.join("\n")}`, await again);
56
58
  }
57
59
 
58
60
  // review, start: the whole description and the latest comments.
59
- return conversation(ref, target);
61
+ const [talk, since] = await Promise.all([conversation(ref, target), again]);
62
+ return join(talk, since);
63
+ }
64
+
65
+ const join = (...parts: string[]) => parts.filter(Boolean).join("\n\n");
66
+
67
+ const MY_REVIEWS = 5;
68
+ const MY_THREADS = 100;
69
+
70
+ // For each PR asking for my review again: my last reviews and the threads I'm in, with what came after, and how to find
71
+ // the commits since the one I reviewed, whether the branch moved on, was rebased, or lost it [REV-02]. Empty when none
72
+ // asks again.
73
+ export async function reviewAgainContext(target: Target): Promise<string> {
74
+ const prs = reviewAgain(target);
75
+ const named = (target.stack?.length ?? 0) > 1;
76
+ const blocks = await Promise.all(prs.map((pr) => lastReview(target.repo, pr, named)));
77
+ return join(...blocks);
78
+ }
79
+
80
+ async function lastReview(repo: string, stacked: StackPr, named: boolean): Promise<string> {
81
+ type Author = { login: string } | null;
82
+ type Review = { author: Author; state: string; body: string; submittedAt: string | null; commit: { oid: string } | null };
83
+ type Thread = { isResolved: boolean; path: string; line: number | null; comments: { totalCount: number; nodes: { author: Author; body: string }[] } };
84
+ const [owner, name] = repo.split("/");
85
+ const { number } = stacked;
86
+ // My reviews only, by login, so others' reviews since can't crowd mine out; submitted ones only, as a review I've
87
+ // started and not sent isn't where I left off.
88
+ const { login } = (await graphql<{ viewer: { login: string } }>("query { viewer { login } }")).viewer;
89
+ const data = await graphql<{
90
+ repository: { pullRequest: { url: string; baseRefName: string; headRefOid: string; reviews: { nodes: Review[] }; reviewThreads: { totalCount: number; nodes: Thread[] } } };
91
+ }>(
92
+ `query($owner: String!, $name: String!, $number: Int!, $login: String!) {
93
+ repository(owner: $owner, name: $name) {
94
+ pullRequest(number: $number) {
95
+ url baseRefName headRefOid
96
+ reviews(last: ${MY_REVIEWS * 4}, author: $login, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) { nodes { author { login } state body submittedAt commit { oid } } }
97
+ reviewThreads(first: ${MY_THREADS}) { totalCount nodes { isResolved path line comments(first: ${THREAD_COMMENTS}) { totalCount nodes { author { login } body } } } }
98
+ }
99
+ }
100
+ }`,
101
+ { owner, name, number, login },
102
+ );
103
+ const me = login.toLowerCase();
104
+ const mine = (author: Author) => author?.login.toLowerCase() === me;
105
+ const pr = data.repository.pullRequest;
106
+ const reviews = pr.reviews.nodes.filter((r) => mine(r.author));
107
+ const latest = reviews.at(-1);
108
+ const title = `Your last review${named ? ` of #${number}` : ""}`;
109
+ // Where GitHub's answer has none, the list's own reading of it still says when, and on which commit.
110
+ const reviewed = latest ? latest.commit?.oid : stacked.reviewed?.oid;
111
+ const when = latest ? `${latest.state.toLowerCase()}${latest.submittedAt ? ` on ${latest.submittedAt}` : ""}` : `on ${stacked.reviewed?.at ?? "an earlier date"}`;
112
+
113
+ const who = (author: Author) => (mine(author) ? "you" : `@${author?.login ?? "ghost"}`);
114
+ const said = reviews
115
+ .filter((r) => r.body.trim())
116
+ .slice(-MY_REVIEWS)
117
+ .map((r) => `- ${r.state.toLowerCase()}${r.submittedAt ? `, ${r.submittedAt}` : ""}: ${clip(r.body, 1500)}`);
118
+ const threads = pr.reviewThreads.nodes
119
+ .filter((t) => t.comments.nodes.some((c) => mine(c.author)))
120
+ .map((t) => {
121
+ const comments = t.comments.nodes.map((c) => ` ${who(c.author)}: ${clip(c.body, 800).replace(/\n/g, "\n ")}`);
122
+ const more = notShown(t.comments.totalCount - t.comments.nodes.length, "more comments", pr.url);
123
+ return [`- ${t.path}${t.line ? `:${t.line}` : ""} (${t.isResolved ? "resolved" : "unresolved"})`, ...comments, more && ` ${more}`].filter(Boolean).join("\n");
124
+ });
125
+ // A long thread I'm not in among its first comments may still have mine further down; say how many weren't read through.
126
+ const longThreads = pr.reviewThreads.nodes.filter((t) => t.comments.totalCount > t.comments.nodes.length && !t.comments.nodes.some((c) => mine(c.author))).length;
127
+ const unread = longThreads ? `${longThreads === 1 ? "1 long review thread was" : `${longThreads} long review threads were`} read only to comment ${THREAD_COMMENTS} and may have yours further down; see ${pr.url}` : "";
128
+ const laterThreads = notShown(pr.reviewThreads.totalCount - pr.reviewThreads.nodes.length, "more review threads, some maybe yours", pr.url);
129
+
130
+ return join(
131
+ `${title}: ${when}.\n${sinceSteps(reviewed, pr.headRefOid, pr.baseRefName)}`,
132
+ said.length ? `What you wrote in your reviews:\n${said.join("\n")}` : "",
133
+ threads.length ? `Review threads you're in, with the replies:\n${threads.join("\n")}` : "",
134
+ unread,
135
+ laterThreads,
136
+ );
137
+ }
138
+
139
+ // How to find the commits since the one I reviewed: they follow it, perhaps with the base merged in, or the branch was
140
+ // rebased or force-pushed past it. The
141
+ // rebase case compares the two versions from where they meet, as the base may have moved too, a stack's parent with it.
142
+ function sinceSteps(reviewed: string | undefined, head: string, base: string): string {
143
+ if (!reviewed) return `GitHub no longer has the commit you reviewed, so review the whole diff against ${base} and say you couldn't narrow it down.`;
144
+ if (reviewed === head) return `No commits since: the head is still ${head}. What's new is in the replies below.`;
145
+ return [
146
+ `You reviewed commit ${reviewed}; the head is now ${head}.`,
147
+ `- \`git fetch origin ${reviewed} ${head}\``,
148
+ `- If \`git merge-base --is-ancestor ${reviewed} ${head}\`: the new commits are \`git log ${reviewed}..${head}\`, their changes \`git diff ${reviewed}..${head}\`. If one of them merges ${base} in, what came with it isn't the PR's: review the author's own commits (\`git log --first-parent --no-merges ${reviewed}..${head}\`, each with \`git show\`) and the merge's conflict resolutions (\`git show --remerge-diff <merge>\`) instead of the whole diff.`,
149
+ `- Otherwise the branch was rebased or force-pushed: compare the two versions with \`git range-diff ${reviewed}...${head}\`. Commits that came with ${base} or a rebased parent show up too, as added, dropped or matched; leave those out.`,
150
+ `- If ${reviewed} can't be fetched, review the whole diff against ${base} and say you couldn't narrow it down.`,
151
+ ].join("\n");
60
152
  }
61
153
 
62
154
  const branchLine = (pr: StackPr) => `- #${pr.number}: ${pr.head} (on ${pr.base})`;
@@ -10,17 +10,13 @@ const run = promisify(execFile);
10
10
  // A scratch directory for the session, where this plugin is installed and which version it is [FB-01].
11
11
  export async function feedbackInfo(): Promise<FeedbackInfo> {
12
12
  const cwd = mkdtempSync(join(tmpdir(), "attention-span-feedback-"));
13
- const source = pluginDir();
13
+ const source = ourInstall()?.path ?? null;
14
14
  return { cwd, source, version: source ? await version(source) : null };
15
15
  }
16
16
 
17
+ // The runtime ID this plugin is installed under, and its source. The update check names the ID [UPD-01].
17
18
  // Paseo evaluates the server as a bundle, so it has no file location of its own (import.meta.url is undefined).
18
19
  // Paseo's config.json records where each plugin's source is: take this plugin's, by its manifest's ID.
19
- export function pluginDir(paseoHome?: string): string | null {
20
- return ourInstall(paseoHome)?.path ?? null;
21
- }
22
-
23
- // The runtime ID this plugin is installed under, and its source. The update check names the ID [UPD-01].
24
20
  export function ourInstall(paseoHome = process.env.PASEO_HOME || join(homedir(), ".paseo")): { id: string; path: string } | null {
25
21
  try {
26
22
  const { plugins = {} } = JSON.parse(readFileSync(join(paseoHome, "config.json"), "utf8")) as { plugins?: Record<string, { path?: string }> };
@@ -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,11 +1,15 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import type { AgentSummary, GithubColor, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
3
+ import type { AgentSummary, AttentionView, GithubColor, ItemDetails, Reviewer, ReviewerChoices, Target } from "../shared/attention";
4
+ import type { KeptRow } from "../shared/archive";
4
5
  import type { OthersChange } from "../shared/changes";
5
6
  import type { SessionKind } from "../shared/config";
6
- import type { IssueField } from "../shared/setup";
7
+ import type { CoverageCheck, CoverageKind, IssueField, SetupStatus } from "../shared/setup";
8
+ import { sameName } from "../shared/names";
7
9
  import type { Actor, Comment, Details, IssueNode, MentionNode, PickableNode, PullRequestNode, SearchResult } from "./github-types";
8
- import { DIR } from "./store";
10
+ import type { Port } from "./port";
11
+ import { setTimer } from "./port";
12
+ import { State, type Store } from "./store";
9
13
 
10
14
  // Made-up GitHub data for tests and for previews without GitHub (PASEO_ATTENTION_SPAN_FIXTURE=1).
11
15
 
@@ -13,10 +17,10 @@ export const REPO = "acme/shop";
13
17
  // Issues kept apart from the code, as some orgs do; its code lives in REPO [SES-07].
14
18
  export const ISSUES_REPO = "acme/issues";
15
19
  // What the settings screen can add in previews [SRC-02]; anything else isn't found.
16
- export const FIXTURE_ORGS = ["acme"];
17
- 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"];
18
22
  // The orgs Next up's org picker offers in previews [NXT-04].
19
- export const FIXTURE_MY_ORGS = ["acme", "globex"];
23
+ const FIXTURE_MY_ORGS = ["acme", "globex"];
20
24
  // The org issue fields settings offers for Next up [NXT-04].
21
25
  export const FIXTURE_ISSUE_FIELDS: IssueField[] = [
22
26
  { name: "Effort", options: ["🐟 Tiny (< 4h)", "🐇 Small (0.5-2d)", "🐂 Medium (2-5d)", "🦑 Large (1-2w)"], orgs: ["acme"] },
@@ -219,6 +223,9 @@ export function fixture(now: Date): { data: SearchResult; details: Details } {
219
223
  // Bob's stack asking for my review: one item with one Review [ATT-04].
220
224
  pr(196, { title: "Price rules: data model", author: bob, headRefName: "rules-1", commits: commit("SUCCESS", 0.4) }),
221
225
  pr(197, { title: "Price rules: admin screen", author: bob, baseRefName: "rules-1", headRefName: "rules-2", commits: commit("SUCCESS", 0.3) }),
226
+ // Asked again after I reviewed: one with the Review session still open, one without [REV-02].
227
+ pr(198, { title: "Show shipping estimates at checkout", author: alice, latestReviews: { nodes: [{ author: me, state: "CHANGES_REQUESTED", submittedAt: daysAgo(2), commit: { oid: "oid198old" } }] }, commits: commit("SUCCESS", 0.2) }),
228
+ pr(199, { title: "Group order emails by customer", author: bob, latestReviews: { nodes: [{ author: me, state: "COMMENTED", submittedAt: daysAgo(3), commit: { oid: "oid199old" } }] }, commits: commit("SUCCESS", 0.5) }),
222
229
  ],
223
230
  mentions: [
224
231
  mention(95, [comment(bob, "@me should reminders go out on weekends too, or only on workdays?", 0.5)], { title: "Customers forget unpaid invoices", author: bob }),
@@ -327,14 +334,10 @@ export function fixture(now: Date): { data: SearchResult; details: Details } {
327
334
  };
328
335
  }
329
336
 
330
- // 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].
331
- // On while this file exists in the plugin's folder; the shooter creates it last.
332
- export const quiet = () => existsSync(join(DIR, "fixture-quiet"));
333
-
334
337
  // The fixture, or nothing in it on a quiet day.
335
- export function fixtureNow(now: Date): ReturnType<typeof fixture> {
338
+ function fixtureNow(now: Date, quiet: boolean): ReturnType<typeof fixture> {
336
339
  const { data, details } = fixture(now);
337
- if (!quiet()) return { data, details };
340
+ if (!quiet) return { data, details };
338
341
  const empty = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, key === "viewer" ? value : { nodes: [] }]));
339
342
  return { data: empty as unknown as SearchResult, details };
340
343
  }
@@ -381,6 +384,7 @@ export function fixtureGotIt(now: Date): string[] {
381
384
  // #113 waits on CI while its Fix CI session works, though Fix CI isn't one of its actions any more.
382
385
  // #120's was started outside Attention Span, in a workspace Paseo linked to the PR, so it has no kind [SES-08].
383
386
  // #197's too, so it shows on its stack, led by #196 [ATT-04].
387
+ // #198 is asked to be reviewed again while its Review session is still open: the card opens it [REV-02].
384
388
  const agent = (
385
389
  id: string,
386
390
  itemKey: string,
@@ -421,11 +425,14 @@ export const FIXTURE_AGENTS: AgentSummary[] = [
421
425
  agent("agent-113", `${REPO}#113`, "fix", "running", 2),
422
426
  agent("agent-120", `${REPO}#120`, undefined, "running", 3),
423
427
  agent("agent-197", `${REPO}#197`, undefined, "idle", 15),
428
+ agent("agent-198", `${REPO}#198`, "review", "idle", 2880, false, undefined, "Review PR 198: Show shipping estimates at checkout"),
424
429
  // Wrap up: finished work whose sessions are all idle [ATT-22].
425
430
  agent("agent-183", `${REPO}#183`, "fix", "idle", 20, false, sessionWorkspace("retry-webhooks", false, 0), "Retry webhooks"),
426
- agent("agent-186", `${REPO}#186`, "fix", "idle", 40, false, sessionWorkspace("split-invoice-pdf", true, 1, true, 2), "Split invoice PDF"),
431
+ // Its sheet counts lines and names the terminals archiving closes, as Paseo's own sheet would.
432
+ 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"),
427
433
  agent("agent-190", `${REPO}#190`, "review", "idle", 60, false, sessionWorkspace("add-vat-export", false, 0), "Review PR 190: Add the VAT export"),
428
- agent("agent-172", `${REPO}#172`, "fix", "idle", 240, false, sessionWorkspace("fix-vat-credit-notes", false, 0), "Fix VAT on credit notes"),
434
+ // With a review sub-agent it started, archived along with it.
435
+ { ...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 } },
429
436
  agent("agent-172b", `${REPO}#172`, "address", "idle", 250, false, sessionWorkspace("credit-note-tests", undefined, undefined), "Credit note tests"),
430
437
  ];
431
438
 
@@ -465,3 +472,70 @@ export function fixtureDetails(subject: { kind: "pr" | "issue"; repo: string; nu
465
472
  : [],
466
473
  };
467
474
  }
475
+
476
+ // What the service sees in previews: this made-up GitHub, no Paseo projects or sessions to archive, and state kept in
477
+ // memory. config.json is still the file in `dir`, as the shooter edits it.
478
+ export function fixturePort(store: Store, dir: string): Port {
479
+ // 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].
480
+ // On while this file exists in the plugin's folder; the shooter creates it last.
481
+ const quiet = () => existsSync(join(dir, "fixture-quiet"));
482
+ return {
483
+ github: {
484
+ login: async () => "me",
485
+ // Previews can always read projects [NXT-12].
486
+ probeProjects: async () => ({ data: { viewer: { projectsV2: { nodes: [] } } }, errors: [], failures: [] }),
487
+ live: async (_config, now) => (dismissedKept.clear(), fixtureNow(now, quiet())),
488
+ // Previews start each layout with a refresh, which brings the notes back: Got it would otherwise outlive a layout.
489
+ changes: async (ledger, _data, now) => ({ ...ledger, events: quiet() ? [] : fixtureChanges(now), gotIt: fixtureGotIt(now) }),
490
+ history: async (_config, now) => fixtureNow(now, quiet()).data,
491
+ issueFields: async () => FIXTURE_ISSUE_FIELDS,
492
+ },
493
+ // Previews have no Paseo agents, but archiving still acknowledges, so their screenshots can show the cleanup.
494
+ paseo: { projectRepos: async () => [], archive: async () => ({ ok: true, kept: [] }) },
495
+ store: { ...store, loadState: async () => State.parse({}), saveState: async () => {} },
496
+ now: Date.now,
497
+ setTimer,
498
+ };
499
+ }
500
+
501
+ // Wrap up rows whose worktree stayed, one for each reason [ATT-22].
502
+ const keptRow = (number: number, title: string, fields: Pick<KeptRow, "name" | "reason" | "detail" | "agentId">): KeptRow => ({
503
+ workspaceId: `WS_kept_${number}`,
504
+ ...fields,
505
+ itemKey: `${REPO}#${number}`,
506
+ title,
507
+ repo: REPO,
508
+ number,
509
+ kind: "pr",
510
+ at: new Date().toISOString(),
511
+ });
512
+ export const FIXTURE_KEPT: KeptRow[] = [
513
+ keptRow(176, "Round prices per currency", { name: "Round prices per currency", reason: "session", detail: "Fix flaky price test", agentId: "agent-101" }),
514
+ keptRow(178, "Cache the tax tables", { name: "cache-tax-tables", reason: "terminal", detail: "dev server" }),
515
+ keptRow(179, "Drop the legacy exporter", { name: "Drop the legacy exporter", reason: "refused", detail: "worktree is locked" }),
516
+ ];
517
+
518
+ // Made-up kept rows dismissed in this layout; each layout's first refresh brings them back, like the notes.
519
+ const dismissedKept = new Set<string>();
520
+ export const fixtureDismissKept = (workspaceId: string) => void dismissedKept.add(workspaceId);
521
+
522
+ // A view with the made-up sessions, as the preview daemon has no agents, and kept worktrees for it to show [ATT-22].
523
+ export const fixtureView = (view: AttentionView): AttentionView => ({
524
+ ...view,
525
+ fixtureAgents: FIXTURE_AGENTS,
526
+ kept: [...(view.kept ?? []), ...FIXTURE_KEPT.filter((row) => !dismissedKept.has(row.workspaceId))],
527
+ });
528
+
529
+ // The sheet's, picker's, session's and setup's asks, answered from made-up data; gh counts as signed in.
530
+ export const fixtureAnswers = {
531
+ ghStatus: async (): Promise<SetupStatus["gh"]> => ({ found: true, login: "me", error: null }),
532
+ myOrgs: async () => FIXTURE_MY_ORGS,
533
+ coverageOnGitHub: async (kind: CoverageKind, name: string): Promise<CoverageCheck> => {
534
+ const known = (kind === "org" ? FIXTURE_ORGS : FIXTURE_REPOS).find((candidate) => sameName(candidate, name));
535
+ return known ? { name: known, error: null } : { name: null, error: `${name} wasn't found on GitHub` };
536
+ },
537
+ reviewerChoices: async (_target: Target, recent: Reviewer[]) => fixtureReviewerChoices(recent),
538
+ itemDetails: async (subject: { kind: "pr" | "issue"; repo: string; number: number }, target: Target | undefined, checks: boolean) => fixtureDetails(subject, target, checks),
539
+ defaultBranch: async () => "main",
540
+ sessionContext: async () => FIXTURE_CONTEXT,
541
+ };
@@ -61,7 +61,8 @@ export interface PullRequestNode {
61
61
  commits: Nodes<{ commit: { committedDate: string; statusCheckRollup: { state: string } | null } }>;
62
62
  // A person, or a team by its "org/slug"; null when it can't be seen.
63
63
  reviewRequests: Nodes<{ requestedReviewer: RequestedReviewer | null }>;
64
- latestReviews: Nodes<{ author: Actor | null; state: string; submittedAt: string | null }>;
64
+ // The commit each review was made on, so a review asked for again can start from it [REV-02].
65
+ latestReviews: Nodes<{ author: Actor | null; state: string; submittedAt: string | null; commit?: { oid: string } | null }>;
65
66
  reviewThreads: Nodes<ReviewThread>;
66
67
  comments: Nodes<Comment>;
67
68
  }
@@ -163,6 +164,8 @@ export interface EndedPullRequest {
163
164
  number: number;
164
165
  title: string;
165
166
  url: string;
167
+ // Missing in older fixtures and caches.
168
+ headRefName?: string;
166
169
  merged: boolean;
167
170
  mergedAt: string | null;
168
171
  closedAt: string;
@@ -199,7 +202,7 @@ type Labels = { labels?: Nodes<{ name: string }> };
199
202
  export interface HistoryResult {
200
203
  // Who I am, to tell a merge by someone else [HIS-05]; missing in older fixtures.
201
204
  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>;
205
+ 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
206
  reviewed: Nodes<{ number: number; title: string; url: string; mergedAt: string; mergedBy?: { login: string } | null; repository: Repo; author: Actor | null } & Labels>;
204
207
  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
208
  }
@@ -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
+ }