@andrioid/paseo-attention-span 0.1.2 → 0.2.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.
package/server/service.ts CHANGED
@@ -5,17 +5,22 @@ import { classify, classifyHistory } from "./classify";
5
5
  import { FIXTURE, graphql } from "./gh";
6
6
  import { fixture, FIXTURE_AGENTS } from "./fixture";
7
7
  import type { Details, HistoryResult, LiveResult } from "./github-types";
8
- import { detailsQuery, HISTORY_SEARCHES, LIVE_SEARCHES, type SearchName, searchQuery, searchVariables, unclaimedScope } from "./queries";
9
- import { loadConfig, loadState, moveOldFiles, saveCodeRepo, saveCoverage, saveState, State } from "./store";
10
- import { buildView } from "./view";
8
+ import { detailsQuery, HISTORY_SEARCHES, mergeUnclaimed, type SearchName, searchQuery, searchVariables, type UnclaimedSearch, unclaimedSearches } from "./queries";
9
+ import { loadConfig, loadState, moveOldFiles, saveCodeRepo, saveCoverage, saveNextUpSources, saveState, State } from "./store";
10
+ import { applyPending, buildView, doneItem, type Effect, isPending, SETTLE_MS } from "./view";
11
11
 
12
12
  // History changes only when I finish something, so it's fetched daily, on ⟳ in its tab and after a merge.
13
13
  const HISTORY_MAX_AGE_SECONDS = 24 * 60 * 60;
14
14
  // A failed refresh is retried at most this often, except on ⟳.
15
15
  const RETRY_MS = 5 * 60_000;
16
16
 
17
+ // What a change does to the lists: an effect, Finished (merged or closed, so off the lists and maybe into History), or nothing.
18
+ export type Change = Effect | { kind: "finished"; notPlanned?: boolean } | null;
19
+
17
20
  interface Feed {
18
21
  inFlight: Promise<void> | null;
22
+ // A fetch queued to start once the one in flight is done, for callers that need data from after now.
23
+ next: Promise<void> | null;
19
24
  lastAttemptAt: number;
20
25
  error: string | null;
21
26
  }
@@ -26,11 +31,12 @@ export class AttentionService {
26
31
  private config: AttentionConfig = AttentionConfig.parse({});
27
32
  private configError: string | null = null;
28
33
  private feeds: Record<FeedId, Feed> = {
29
- live: { inFlight: null, lastAttemptAt: 0, error: null },
30
- history: { inFlight: null, lastAttemptAt: 0, error: null },
34
+ live: { inFlight: null, next: null, lastAttemptAt: 0, error: null },
35
+ history: { inFlight: null, next: null, lastAttemptAt: 0, error: null },
31
36
  };
32
37
  private saving: Promise<void> = Promise.resolve();
33
38
  private timer: ReturnType<typeof setInterval> | null = null;
39
+ private followUps: Partial<Record<FeedId, ReturnType<typeof setTimeout>>> = {};
34
40
  private intervalMinutes = 0;
35
41
  // The app's connection to Paseo, from its last request; background refreshes have none of their own.
36
42
  private paseo: PluginHandlerContext["paseo"] | null = null;
@@ -50,6 +56,7 @@ export class AttentionService {
50
56
  stop(): void {
51
57
  if (this.timer) clearInterval(this.timer);
52
58
  this.timer = null;
59
+ for (const timeout of Object.values(this.followUps)) clearTimeout(timeout);
53
60
  }
54
61
 
55
62
  // ⟳ fetches its tab's feed now; otherwise feeds older than their schedule are fetched first.
@@ -93,14 +100,57 @@ export class AttentionService {
93
100
  await this.refresh("live").catch(() => {});
94
101
  }
95
102
 
103
+ // Where Next up looks, chosen in settings [NXT-04]. Only the live feed has Next up.
104
+ async setNextUpSources(sources: Pick<AttentionConfig["nextUp"], "mine" | "orgs" | "repos">): Promise<void> {
105
+ this.config = await saveNextUpSources(sources);
106
+ await this.refresh("live").catch(() => {});
107
+ }
108
+
96
109
  async setScopes(scopes: string[]): Promise<void> {
97
110
  this.state.scopes = scopes;
98
111
  await this.save();
99
112
  }
100
113
 
101
- // Concurrent callers share one refresh per feed.
102
- refresh(id: FeedId): Promise<void> {
114
+ async setSources(sources: string[]): Promise<void> {
115
+ this.state.sources = sources;
116
+ await this.save();
117
+ }
118
+
119
+ // A change on GitHub from one tap [SAFE-01], answered with the list as it is after it.
120
+ // GitHub's search takes seconds to show it, so its effect shows until a fetch can [FRESH-02]; no change (Undo) clears it.
121
+ async act(key: string, work: () => Promise<void>, change: Change): Promise<AttentionView> {
122
+ await work();
123
+ const before = this.state.pending[key];
124
+ const at = new Date().toISOString();
125
+ if (change) this.state.pending[key] = { at, effect: change.kind === "finished" ? this.finished(key, at, change.notPlanned) : change };
126
+ else delete this.state.pending[key];
127
+ await this.save();
128
+ const history = change?.kind === "finished" || before?.effect.kind === "done";
129
+ this.followUp("live");
130
+ if (history) this.followUp("history");
131
+ return this.view();
132
+ }
133
+
134
+ // Into History if it's mine: a PR in my lists, or an issue assigned to me [HIS-01]. Else just off the lists.
135
+ private finished(key: string, at: string, notPlanned?: boolean): Effect {
136
+ const live = this.state.live?.attention;
137
+ const source = live?.items.find((item) => item.key === key) ?? live?.assigned.find((issue) => issue.key === key);
138
+ return source ? { kind: "done", item: doneItem(source, at, notPlanned) } : { kind: "gone" };
139
+ }
140
+
141
+ // One fetch once GitHub's search has caught up with the latest change, which ends what's pending.
142
+ private followUp(id: FeedId): void {
143
+ clearTimeout(this.followUps[id]);
144
+ this.followUps[id] = setTimeout(() => void this.refresh(id, true).catch(() => {}), SETTLE_MS);
145
+ }
146
+
147
+ // Concurrent callers share one refresh per feed. `fresh` won't share one that began before the call, which can't show a change just made.
148
+ refresh(id: FeedId, fresh = false): Promise<void> {
103
149
  const feed = this.feeds[id];
150
+ if (fresh && feed.inFlight) {
151
+ feed.next ??= feed.inFlight.catch(() => {}).then(() => ((feed.next = null), this.refresh(id)));
152
+ return feed.next;
153
+ }
104
154
  feed.inFlight ??= this.fetch(id).finally(() => (feed.inFlight = null));
105
155
  return feed.inFlight;
106
156
  }
@@ -122,6 +172,8 @@ export class AttentionService {
122
172
  // Forget dismissals of items that are gone.
123
173
  const keys = new Set(this.items().map((item) => item.key));
124
174
  for (const key of Object.keys(this.state.dismissed)) if (!keys.has(key)) delete this.state.dismissed[key];
175
+ // And changes GitHub now shows for itself.
176
+ for (const [key, pending] of Object.entries(this.state.pending)) if (!isPending(pending, this.fetchedAt(), Date.now())) delete this.state.pending[key];
125
177
  feed.error = null;
126
178
  await this.save();
127
179
  } catch (error) {
@@ -133,8 +185,15 @@ export class AttentionService {
133
185
 
134
186
  private async fetchLive(now: Date): Promise<Attention> {
135
187
  const projectRepos = FIXTURE ? [] : await this.projectRepos();
136
- const { data, details } = FIXTURE ? fixture(now) : await this.searchLive(now, projectRepos);
137
- return { ...classify({ data, details, config: this.config, now }), unclaimedFrom: unclaimedScope(this.config, projectRepos).from };
188
+ const login = FIXTURE ? "me" : this.config.nextUp.mine ? await this.login() : null;
189
+ const unclaimed = unclaimedSearches(this.config, projectRepos, login);
190
+ const { data, details } = FIXTURE ? fixture(now) : await this.searchLive(now, unclaimed.searches);
191
+ return { ...classify({ data, details, config: this.config, now }), unclaimedFrom: unclaimed.from };
192
+ }
193
+
194
+ // The account gh is signed in as, for My repos [NXT-04]. Asked once, unless the last fetch already says.
195
+ private async login(): Promise<string> {
196
+ return (this.state.live?.attention.login || (await graphql<{ viewer: { login: string } }>("{ viewer { login } }")).viewer.login);
138
197
  }
139
198
 
140
199
  // My Paseo projects' GitHub repos, where Next up looks when no repos are chosen [NXT-08].
@@ -157,19 +216,25 @@ export class AttentionService {
157
216
  }
158
217
 
159
218
  // One request per search, in parallel. The details request starts once the searches it needs are back [GH-01].
160
- private async searchLive(now: Date, projectRepos: string[]): Promise<{ data: LiveResult; details: Details }> {
161
- const all = searchVariables(this.config, now, projectRepos);
162
- const search = async (name: (typeof LIVE_SEARCHES)[number]): Promise<Partial<LiveResult>> =>
163
- all[name] === null ? { [name]: { nodes: [] } } : graphql<Partial<LiveResult>>(searchQuery([name], name === "mine"), { [name]: all[name] });
219
+ private async searchLive(now: Date, unclaimed: UnclaimedSearch[]): Promise<{ data: LiveResult; details: Details }> {
220
+ const all = searchVariables(this.config, now);
221
+ const search = (name: keyof typeof all): Promise<Partial<LiveResult>> => graphql<Partial<LiveResult>>(searchQuery([name], name === "mine"), { [name]: all[name] });
222
+ // One per Next up source [NXT-09].
223
+ const searchUnclaimed = async (): Promise<Partial<LiveResult>> => {
224
+ const results = await Promise.all(
225
+ unclaimed.map(async ({ source, query }) => ({ source, nodes: (await graphql<Pick<LiveResult, "unclaimed">>(searchQuery(["unclaimed"]), { unclaimed: query })).unclaimed.nodes })),
226
+ );
227
+ return { unclaimed: { nodes: mergeUnclaimed(results) } };
228
+ };
164
229
  const merge = (parts: Partial<LiveResult>[]) => Object.assign({}, ...parts) as LiveResult;
165
- const forDetails = Promise.all([search("mine"), search("assigned"), search("unclaimed")]);
230
+ const forDetails = Promise.all([search("mine"), search("assigned"), searchUnclaimed()]);
166
231
  const others = Promise.all([search("reviews"), search("mentions"), search("commented")]);
167
232
  const afterThem = forDetails.then((parts) => this.details(merge(parts)));
168
233
  const [first, rest, details] = await Promise.all([forDetails, others, afterThem]);
169
234
  return { data: merge([...first, ...rest]), details };
170
235
  }
171
236
 
172
- private variables(names: readonly SearchName[], now: Date): Record<string, string | null> {
237
+ private variables(names: readonly Exclude<SearchName, "unclaimed">[], now: Date): Record<string, string> {
173
238
  const all = searchVariables(this.config, now);
174
239
  return Object.fromEntries(names.map((name) => [name, all[name]]));
175
240
  }
@@ -232,16 +297,25 @@ export class AttentionService {
232
297
  return this.saving;
233
298
  }
234
299
 
300
+ private fetchedAt(): Record<FeedId, string | null> {
301
+ return { live: this.state.live?.fetchedAt ?? null, history: this.state.history?.fetchedAt ?? null };
302
+ }
303
+
235
304
  private view(): AttentionView {
236
305
  const status = (id: FeedId): FeedStatus => ({
237
306
  fetchedAt: this.state[id]?.fetchedAt ?? null,
238
307
  refreshing: this.feeds[id].inFlight !== null,
239
308
  error: this.feeds[id].error ?? this.configError,
240
309
  });
241
- return buildView(this.state.live?.attention ?? null, this.state.history?.items ?? [], this.state.dismissed, {
310
+ const now = Date.now();
311
+ const pending = Object.fromEntries(Object.entries(this.state.pending).filter(([, entry]) => isPending(entry, this.fetchedAt(), now)));
312
+ const shown = applyPending(this.state.live?.attention ?? null, this.state.history?.items ?? [], pending);
313
+ return buildView(shown.attention, shown.history, this.state.dismissed, {
242
314
  feeds: { live: status("live"), history: status("history") },
243
315
  scopes: this.state.scopes,
316
+ sources: this.state.sources,
244
317
  config: this.config,
318
+ pending: Object.keys(pending).length,
245
319
  ...(FIXTURE ? { fixtureAgents: FIXTURE_AGENTS } : {}),
246
320
  });
247
321
  }
package/server/setup.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ConfigStatus, CoverageCheck, CoverageKind, SetupStatus } from "../shared/setup";
2
- import { FIXTURE_ORGS, FIXTURE_REPOS } from "./fixture";
3
- import { FIXTURE, runGh } from "./gh";
2
+ import { FIXTURE_MY_ORGS, FIXTURE_ORGS, FIXTURE_REPOS } from "./fixture";
3
+ import { FIXTURE, graphql, runGh } from "./gh";
4
4
  import { loadConfig } from "./store";
5
5
 
6
6
  // What the setup checklist needs [SET-01]. Asked only when Attention Span can't load.
@@ -21,13 +21,20 @@ async function ghStatus(): Promise<SetupStatus["gh"]> {
21
21
 
22
22
  export async function configStatus(): Promise<ConfigStatus> {
23
23
  try {
24
- const { orgs, repos } = await loadConfig();
25
- return { error: null, orgs, repos };
24
+ const { orgs, repos, nextUp } = await loadConfig();
25
+ return { error: null, orgs, repos, nextUp: { mine: nextUp.mine, orgs: nextUp.orgs, repos: nextUp.repos } };
26
26
  } catch (error) {
27
- return { error: (error as Error).message, orgs: [], repos: [] };
27
+ return { error: (error as Error).message, orgs: [], repos: [], nextUp: { mine: false, orgs: [], repos: [] } };
28
28
  }
29
29
  }
30
30
 
31
+ // The orgs I belong to, for Next up's org picker [NXT-04]. Only these can be picked.
32
+ export async function myOrgs(): Promise<string[]> {
33
+ if (FIXTURE) return FIXTURE_MY_ORGS;
34
+ const { viewer } = await graphql<{ viewer: { organizations: { nodes: { login: string }[] } } }>("{ viewer { organizations(first: 100) { nodes { login } } } }");
35
+ return viewer.organizations.nodes.map((org) => org.login).sort((a, b) => a.localeCompare(b));
36
+ }
37
+
31
38
  // An org or repo is checked on GitHub before it's saved, so a typo shows right away [SRC-02].
32
39
  // Pasted GitHub URLs are accepted. The exact name GitHub returns is what gets saved.
33
40
  export async function checkCoverage(kind: CoverageKind, input: string): Promise<CoverageCheck> {
package/server/store.ts CHANGED
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  import { z } from "zod";
5
5
  import type { Attention, Item, SectionId } from "../shared/attention";
6
6
  import { AttentionConfig } from "../shared/config";
7
+ import type { Pending } from "./view";
7
8
 
8
9
  // Local files in ~/.config/paseo-attention-span/ [PRIV-01].
9
10
  const CHOSEN_DIR = process.env.PASEO_ATTENTION_SPAN_DIR ?? process.env.PASEO_GITHUB_ATTENTION_DIR;
@@ -16,12 +17,19 @@ const STATE = join(DIR, "state.json");
16
17
  export const State = z.object({
17
18
  // Item key -> others' activity and section when dismissed [ATT-08].
18
19
  dismissed: z.record(z.string(), z.object({ at: z.string(), section: z.custom<SectionId>() })).default({}),
19
- // Scope chips picked on Next up; none means all [NXT-03].
20
+ // Item key -> what I just changed on GitHub, until a fetch shows it [FRESH-02].
21
+ pending: z.record(z.string(), z.custom<Pending>((value) => typeof (value as Pending)?.at === "string" && !!(value as Pending)?.effect)).default({}).catch({}),
22
+ // Scopes ticked in Next up's filter; none means all [NXT-03].
20
23
  scopes: z.array(z.string()).default([]),
24
+ // Sources ticked in Next up's filter; none means all [NXT-09].
25
+ sources: z.array(z.string()).default([]),
21
26
  // My Paseo projects' GitHub repos when last listed, for refreshes before the app has connected [NXT-08].
22
27
  projectRepos: z.array(z.string()).default([]),
23
28
  // The last fetch of each feed. A cache from an older version is dropped rather than shown wrong.
24
- live: z.object({ fetchedAt: z.string(), attention: z.custom<Attention>((value) => Array.isArray((value as Attention)?.unclaimed)) }).nullable().catch(null),
29
+ live: z
30
+ .object({ fetchedAt: z.string(), attention: z.custom<Attention>((value) => (value as Attention)?.unclaimed?.every?.((issue) => Array.isArray(issue.sources) && Array.isArray(issue.openPrs))) })
31
+ .nullable()
32
+ .catch(null),
25
33
  history: z.object({ fetchedAt: z.string(), items: z.custom<Item[]>(Array.isArray) }).nullable().catch(null),
26
34
  });
27
35
  export type State = z.infer<typeof State>;
@@ -68,6 +76,14 @@ export function saveCoverage(orgs: string[], repos: string[]): Promise<Attention
68
76
  return updateConfig((file) => ({ ...file, orgs, repos }));
69
77
  }
70
78
 
79
+ // Where Next up looks, chosen in settings [NXT-04]. The fields and the rest of nextUp are kept.
80
+ export function saveNextUpSources(sources: Pick<AttentionConfig["nextUp"], "mine" | "orgs" | "repos">): Promise<AttentionConfig> {
81
+ return updateConfig((file) => {
82
+ const nextUp = file.nextUp && typeof file.nextUp === "object" ? (file.nextUp as Record<string, unknown>) : {};
83
+ return { ...file, nextUp: { ...nextUp, ...sources } };
84
+ });
85
+ }
86
+
71
87
  // What the screen writes changes only its own keys; everything else in the file is kept as it is.
72
88
  // A file that doesn't read or parse is left alone.
73
89
  async function updateConfig(change: (file: Record<string, unknown>) => Record<string, unknown>): Promise<AttentionConfig> {
package/server/view.ts CHANGED
@@ -1,11 +1,82 @@
1
- import { type Attention, type AttentionView, type FeedId, type FeedStatus, type Item, type Section, SECTION_ORDER, SECTIONS, type TabId } from "../shared/attention";
1
+ import { type Attention, type AttentionView, type Chip, type FeedId, type FeedStatus, type Item, type NextUpIssue, type Section, SECTION_ORDER, SECTIONS, type TabId } from "../shared/attention";
2
2
  import type { AttentionConfig } from "../shared/config";
3
3
  import type { State } from "./store";
4
4
 
5
5
  export interface ViewMeta {
6
6
  feeds: Record<FeedId, FeedStatus>;
7
7
  scopes: string[];
8
+ sources: string[];
8
9
  config: AttentionConfig;
10
+ pending: number;
11
+ }
12
+
13
+ // What a tap on GitHub changed, shown until a fetch can show it for itself [FRESH-02].
14
+ // Only where the outcome is certain does a card move; otherwise it stays, with a chip saying what's under way.
15
+ export type Effect =
16
+ | { kind: "gone" }
17
+ // Merged, or an issue of mine closed: off the lists, and into History as it will be fetched.
18
+ | { kind: "done"; item: Item }
19
+ | { kind: "claimed" }
20
+ | { kind: "unclaimed" }
21
+ | { kind: "chip"; chip: Chip };
22
+
23
+ export interface Pending {
24
+ at: string;
25
+ effect: Effect;
26
+ }
27
+
28
+ // GitHub's search shows a change within seconds (3s, measured), so a fetch begun this long after it shows it.
29
+ export const SETTLE_MS = 30_000;
30
+ // While fetches keep failing, a change stops being shown after this.
31
+ const GIVE_UP_MS = 10 * 60_000;
32
+
33
+ // Shown until every feed it touches has been fetched from after GitHub caught up.
34
+ export function isPending({ at, effect }: Pending, fetchedAt: Record<FeedId, string | null>, now: number): boolean {
35
+ const time = new Date(at).getTime();
36
+ if (now - time >= GIVE_UP_MS) return false;
37
+ const feeds: FeedId[] = effect.kind === "done" ? ["live", "history"] : ["live"];
38
+ return feeds.some((id) => !fetchedAt[id] || new Date(fetchedAt[id]).getTime() < time + SETTLE_MS);
39
+ }
40
+
41
+ // The History entry a merge or close will be, as classifyHistory makes it [HIS-01].
42
+ export function doneItem(source: Item | NextUpIssue, closedAt: string, notPlanned = false): Item {
43
+ const { key, repo, number, title, url } = source;
44
+ const kind = "kind" in source ? source.kind : "issue";
45
+ return {
46
+ key,
47
+ section: "done",
48
+ kind,
49
+ draft: false,
50
+ repo,
51
+ number,
52
+ title,
53
+ url,
54
+ chips: notPlanned ? [{ text: "not planned", tone: "neutral" }] : [],
55
+ actions: [],
56
+ children: "children" in source ? source.children.map((child) => ({ ...child, draft: false, chips: [], attention: false })) : [],
57
+ target: { kind, repo, number, title, url },
58
+ othersActivityAt: "1970-01-01T00:00:00Z",
59
+ closedAt,
60
+ };
61
+ }
62
+
63
+ // The fetched lists with what's pending applied on top.
64
+ export function applyPending(attention: Attention | null, history: Item[], pending: Record<string, Pending>): { attention: Attention | null; history: Item[] } {
65
+ if (!attention || Object.keys(pending).length === 0) return { attention, history };
66
+ const effect = (key: string) => pending[key]?.effect.kind;
67
+ const off = (key: string) => effect(key) === "gone" || effect(key) === "done";
68
+ const items = attention.items
69
+ .filter((item) => !off(item.key))
70
+ .map((item) => {
71
+ const now = pending[item.key]?.effect;
72
+ return now?.kind === "chip" && !item.chips.some((chip) => chip.text === now.chip.text) ? { ...item, chips: [...item.chips, now.chip] } : item;
73
+ });
74
+ const assigned = [...attention.assigned.filter((issue) => !off(issue.key) && effect(issue.key) !== "unclaimed"), ...attention.unclaimed.filter((issue) => effect(issue.key) === "claimed")];
75
+ const unclaimed = [...attention.unclaimed.filter((issue) => !off(issue.key) && effect(issue.key) !== "claimed"), ...attention.assigned.filter((issue) => effect(issue.key) === "unclaimed")];
76
+ const known = new Set(history.map((item) => item.key));
77
+ const done = Object.values(pending).flatMap(({ effect }) => (effect.kind === "done" && !known.has(effect.item.key) ? [effect.item] : []));
78
+ // History is newest first; what I just finished is newest of all.
79
+ return { attention: { ...attention, items, assigned, unclaimed }, history: [...done, ...history] };
9
80
  }
10
81
 
11
82
  // A dismissed item stays hidden until someone else does something on it or its reason changes [ATT-08].
@@ -50,6 +50,8 @@ export type ActionId =
50
50
  export interface Chip {
51
51
  text: string;
52
52
  tone: "good" | "bad" | "warn" | "neutral";
53
+ // In place of the dot, where a picture says it better.
54
+ icon?: "thumbUp";
53
55
  }
54
56
 
55
57
  // The person (or bot) I'm waiting on, or who is waiting on me.
@@ -73,6 +75,9 @@ export interface WaitingComment {
73
75
  url?: string;
74
76
  }
75
77
 
78
+ // GitHub's reasons for closing an issue that Next up offers [NXT-11].
79
+ export type IssueCloseReason = "completed" | "not_planned";
80
+
76
81
  // What a session or GitHub action works on.
77
82
  export interface Target {
78
83
  kind: "pr" | "issue";
@@ -136,6 +141,12 @@ export interface NextUpIssue {
136
141
  effort?: string;
137
142
  scope?: string;
138
143
  defaultBranch?: string;
144
+ // Ids of the Next up sources that found it; empty without sources of its own [NXT-09].
145
+ sources: string[];
146
+ // Its priority's place in the field's order, 0 first; missing when unknown [NXT-02].
147
+ priorityRank?: number;
148
+ // Open PRs that close it: someone may already be on it [NXT-10].
149
+ openPrs: { number: number; url: string; author: string | null }[];
139
150
  }
140
151
 
141
152
  // More about an item, fetched when its sheet opens rather than in every refresh [GH-01].
@@ -175,10 +186,27 @@ export interface Section {
175
186
  // A Paseo session started from an item [ATT-07].
176
187
  export interface AgentSummary {
177
188
  id: string;
189
+ // The item it was started on: an issue or a PR.
190
+ itemKey: string;
178
191
  status: string;
179
192
  requiresAttention: boolean;
180
193
  title: string | null;
181
194
  workspaceId: string | null;
195
+ lastActivityAt: string | null;
196
+ }
197
+
198
+ // An item's open sessions: started on it or on any PR under it, until it's merged or closed.
199
+ // One that needs me comes first, then the most recent [SES-03].
200
+ export function itemSessions(agents: AgentSummary[], item: Pick<Item, "key" | "closedAt" | "children">): AgentSummary[] {
201
+ if (item.closedAt) return [];
202
+ return matchSessions(agents, [item.key, ...item.children.map((child) => child.key)]);
203
+ }
204
+
205
+ export function matchSessions(agents: AgentSummary[], keys: string[]): AgentSummary[] {
206
+ const wanted = new Set(keys.map((key) => key.toLowerCase()));
207
+ return agents
208
+ .filter((agent) => wanted.has(agent.itemKey.toLowerCase()))
209
+ .sort((a, b) => Number(b.requiresAttention) - Number(a.requiresAttention) || (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? ""));
182
210
  }
183
211
 
184
212
  export interface FeedStatus {
@@ -200,9 +228,13 @@ export interface AttentionView {
200
228
  unclaimed: NextUpIssue[];
201
229
  unclaimedFrom: UnclaimedSource;
202
230
  dismissedCount: number;
203
- // Scope chips picked on Next up; none means all [NXT-03].
231
+ // Scopes ticked in Next up's filter; none means all [NXT-03].
204
232
  scopes: string[];
233
+ // Sources ticked in Next up's filter; none means all [NXT-09].
234
+ sources: string[];
205
235
  config: AttentionConfig;
236
+ // Changes I just made that GitHub's search hasn't caught up with; the app checks back sooner while there are any [FRESH-02].
237
+ pending: number;
206
238
  // Fixture mode only: made-up sessions, since the preview daemon has no agents.
207
- fixtureAgents?: Record<string, AgentSummary>;
239
+ fixtureAgents?: AgentSummary[];
208
240
  }
package/shared/config.ts CHANGED
@@ -38,18 +38,35 @@ export const AttentionConfig = z.object({
38
38
  mentionDays: z.number().positive().default(30),
39
39
  // How many weeks History shows [HIS-01].
40
40
  historyWeeks: z.number().int().positive().default(4),
41
- // Unclaimed issues to pick from [NXT-04]. Repos default to `orgs` and `repos`.
41
+ // Unclaimed issues to pick from [NXT-04]. With no sources chosen, Next up looks in `orgs` and `repos` [NXT-08].
42
42
  nextUp: z
43
43
  .object({
44
- repos: z.array(z.string()).optional(),
44
+ // Sources: my own repos (not forks), whole orgs, and single "owner/name" repos.
45
+ mine: z.boolean().default(false),
46
+ orgs: z.array(z.string()).default([]),
47
+ repos: z.array(z.string()).default([]),
45
48
  priority: RankedField.optional(),
46
49
  effort: RankedField.optional(),
47
50
  scope: z.object({ field: z.string() }).optional(),
48
51
  })
49
- .default({}),
52
+ .default({ mine: false, orgs: [], repos: [] }),
50
53
  });
51
54
  export type AttentionConfig = z.infer<typeof AttentionConfig>;
52
55
 
56
+ // Where Next up looks, one search each; `id` is what the chips I pick remember [NXT-09].
57
+ export interface NextUpSource {
58
+ id: string;
59
+ label: string;
60
+ }
61
+
62
+ export function nextUpSources({ nextUp }: Pick<AttentionConfig, "nextUp">): NextUpSource[] {
63
+ return [
64
+ ...(nextUp.mine ? [{ id: "mine", label: "My repos" }] : []),
65
+ ...nextUp.orgs.map((org) => ({ id: `org:${org}`, label: org })),
66
+ ...nextUp.repos.map((repo) => ({ id: `repo:${repo}`, label: repo })),
67
+ ];
68
+ }
69
+
53
70
  // "owner/name" of a Paseo project with a GitHub remote, from its project key.
54
71
  export function githubRepoOf(projectKey: string | null | undefined): string | null {
55
72
  return /^remote:github\.com\/(.+)$/i.exec(projectKey ?? "")?.[1] ?? null;
package/shared/format.ts CHANGED
@@ -19,3 +19,19 @@ export function daysSince(iso: string, now: Date): number {
19
19
  export function linkList(items: { title: string; url: string }[]): string {
20
20
  return items.map(({ title, url }) => `- [${title.replace(/[[\]\\]/g, "\\$&")}](${url})`).join("\n");
21
21
  }
22
+
23
+ // Where a card's item lives: "app" for my own repos, "acme/app" for anyone else's, so same-named repos don't blur [ATT-05, NXT-10].
24
+ export function repoLabel(repo: string, login: string | null): string {
25
+ const [owner, name] = repo.split("/");
26
+ return name && login && owner.toLowerCase() === login.toLowerCase() ? name : repo;
27
+ }
28
+
29
+ // An issue field value for a card: "🐟 Tiny (< 4h)" -> "Tiny", "🏕P2 Medium" -> "P2 Medium" [NXT-10]. The sheet keeps the full value.
30
+ export function shortValue(value: string): string {
31
+ return (
32
+ value
33
+ .replace(/^[^\p{L}\p{N}]+/u, "")
34
+ .replace(/\s*\([^)]*\)\s*$/, "")
35
+ .trim() || value
36
+ );
37
+ }
package/shared/rpc.ts CHANGED
@@ -23,20 +23,28 @@ export const setupStatus = defineRpc({ name: "setup.status", input: z.object({})
23
23
  export const getCoverage = defineRpc({ name: "config.coverage", input: z.object({}), output: z.custom<ConfigStatus>() });
24
24
  export const checkCoverage = defineRpc({ name: "config.check-coverage", input: z.object({ kind: z.enum(["org", "repo"]), name: z.string() }), output: z.custom<CoverageCheck>() });
25
25
  export const setCoverage = defineRpc({ name: "config.set-coverage", input: z.object({ orgs: z.array(z.string()), repos: z.array(z.string()) }), output: done });
26
- // Remember the scope chips picked on Next up [NXT-03].
26
+ // Where Next up looks, chosen in settings [NXT-04]; orgs are picked from the ones I belong to.
27
+ export const setNextUpSources = defineRpc({ name: "config.set-next-up", input: z.object({ mine: z.boolean(), orgs: z.array(z.string()), repos: z.array(z.string()) }), output: done });
28
+ export const myOrgs = defineRpc({ name: "config.my-orgs", input: z.object({}), output: z.object({ orgs: z.array(z.string()) }) });
29
+ // Remember the scopes and sources ticked in Next up's filter [NXT-03, NXT-09].
27
30
  export const setScopes = defineRpc({ name: "next-up.scopes", input: z.object({ scopes: z.array(z.string()) }), output: done });
31
+ export const setSources = defineRpc({ name: "next-up.sources", input: z.object({ sources: z.array(z.string()) }), output: done });
28
32
 
29
- // GitHub changes, each from an explicit tap [SAFE-01].
30
- export const updateBranch = defineRpc({ name: "pr.update-branch", input: z.object({ target }), output: done });
31
- export const mergePullRequest = defineRpc({ name: "pr.merge", input: z.object({ target }), output: done });
32
- export const closePullRequest = defineRpc({ name: "pr.close", input: z.object({ target, comment: z.string().optional() }), output: done });
33
- export const claimIssue = defineRpc({ name: "issue.claim", input: z.object({ target }), output: done });
34
- export const unclaimIssue = defineRpc({ name: "issue.unclaim", input: z.object({ target }), output: done });
33
+ // GitHub changes, each from an explicit tap [SAFE-01], answered with the list after it.
34
+ // `key` is the card it was done from, which shows the change until GitHub's search does [FRESH-02].
35
+ export const updateBranch = defineRpc({ name: "pr.update-branch", input: z.object({ key: z.string(), target }), output: view });
36
+ export const mergePullRequest = defineRpc({ name: "pr.merge", input: z.object({ key: z.string(), target }), output: view });
37
+ export const closePullRequest = defineRpc({ name: "pr.close", input: z.object({ key: z.string(), target, comment: z.string().optional() }), output: view });
38
+ export const claimIssue = defineRpc({ name: "issue.claim", input: z.object({ key: z.string(), target }), output: view });
39
+ export const unclaimIssue = defineRpc({ name: "issue.unclaim", input: z.object({ key: z.string(), target }), output: view });
40
+ // Close an issue from Next up; reopen is its Undo [NXT-11].
41
+ export const closeIssue = defineRpc({ name: "issue.close", input: z.object({ key: z.string(), target, reason: z.enum(["completed", "not_planned"]), comment: z.string().optional() }), output: view });
42
+ export const reopenIssue = defineRpc({ name: "issue.reopen", input: z.object({ key: z.string(), target }), output: view });
35
43
  // `ready: false` and `on: false` are the Undo of each.
36
- export const setReady = defineRpc({ name: "pr.ready", input: z.object({ target, ready: z.boolean() }), output: done });
37
- export const setAutoMerge = defineRpc({ name: "pr.auto-merge", input: z.object({ target, on: z.boolean() }), output: done });
38
- export const react = defineRpc({ name: "comment.react", input: z.object({ subjectIds: z.array(z.string()), on: z.boolean() }), output: done });
39
- export const rerunFailed = defineRpc({ name: "checks.rerun", input: z.object({ repo: z.string(), runIds: z.array(z.number()) }), output: done });
44
+ export const setReady = defineRpc({ name: "pr.ready", input: z.object({ key: z.string(), target, ready: z.boolean() }), output: view });
45
+ export const setAutoMerge = defineRpc({ name: "pr.auto-merge", input: z.object({ key: z.string(), target, on: z.boolean() }), output: view });
46
+ export const react = defineRpc({ name: "comment.react", input: z.object({ key: z.string(), subjectIds: z.array(z.string()), on: z.boolean() }), output: view });
47
+ export const rerunFailed = defineRpc({ name: "checks.rerun", input: z.object({ key: z.string(), repo: z.string(), runIds: z.array(z.number()) }), output: view });
40
48
 
41
49
  // What an item's sheet shows beyond the card [ATT-06]. `checks` asks for failing checks too, for Rerun.
42
50
  export const itemDetails = defineRpc({
package/shared/setup.ts CHANGED
@@ -5,6 +5,8 @@ export interface ConfigStatus {
5
5
  error: string | null;
6
6
  orgs: string[];
7
7
  repos: string[];
8
+ // Where Next up looks; none chosen falls back to `orgs` and `repos`, then my Paseo projects [NXT-04, NXT-08].
9
+ nextUp: { mine: boolean; orgs: string[]; repos: string[] };
8
10
  }
9
11
 
10
12
  export interface SetupStatus {