@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
@@ -1,4 +1,8 @@
1
+ import { z } from "zod";
1
2
  import type { OthersChange } from "./changes";
3
+ import { keySet, uniqueKeys } from "./names";
4
+ import type { KeptRow } from "./archive";
5
+ import type { NewIssueInfo } from "./new-issue";
2
6
  import type { AttentionConfig, MergeMethod, SessionKind } from "./config";
3
7
  import type { WorkKind } from "./work";
4
8
 
@@ -6,7 +10,8 @@ import type { WorkKind } from "./work";
6
10
  export type TabId = "history" | "doing" | "waiting" | "next";
7
11
 
8
12
  // Each tab's data comes from one feed, fetched from GitHub on its own schedule. History changes only when I finish something.
9
- export type FeedId = "live" | "history";
13
+ export const FeedId = z.enum(["live", "history"]);
14
+ export type FeedId = z.infer<typeof FeedId>;
10
15
  export const TAB_FEED: Record<TabId, FeedId> = { history: "history", doing: "live", waiting: "live", next: "live" };
11
16
 
12
17
  // Within a tab, top to bottom. The order is also the priority: an item appears once, under the first section whose rule
@@ -62,7 +67,8 @@ export type ActionId =
62
67
  | "got_it";
63
68
 
64
69
  // What History's filter can add to each week, both off at first [HIS-07].
65
- export type HistoryFilter = "reviewed" | "changed";
70
+ export const HistoryFilter = z.enum(["reviewed", "changed"]);
71
+ export type HistoryFilter = z.infer<typeof HistoryFilter>;
66
72
 
67
73
  // A short state label on a row [ATT-05]; tone picks its color.
68
74
  export interface Chip {
@@ -148,7 +154,8 @@ export interface ReviewerChoices {
148
154
  }
149
155
 
150
156
  // GitHub's reasons for closing an issue that Next up offers [NXT-11].
151
- export type IssueCloseReason = "completed" | "not_planned";
157
+ export const IssueCloseReason = z.enum(["completed", "not_planned"]);
158
+ export type IssueCloseReason = z.infer<typeof IssueCloseReason>;
152
159
 
153
160
  // What a session or GitHub action works on.
154
161
  export interface Target {
@@ -204,6 +211,9 @@ export interface SubRow {
204
211
  attention: boolean;
205
212
  // History only: who merged it, when it wasn't me [HIS-05].
206
213
  mergedBy?: string;
214
+ // History only: the branch it merged from, and when, so a session left on it finds its row in Wrap up [ATT-22].
215
+ headRefName?: string;
216
+ mergedAt?: string;
207
217
  }
208
218
 
209
219
  export interface Item {
@@ -244,6 +254,11 @@ export interface Item {
244
254
  wrap?: WrapInfo;
245
255
  }
246
256
 
257
+ // An item with nothing on it yet: no chips, actions or sub-rows, and no one else's activity unless given. Callers add the rest.
258
+ export function baseItem({ key, section, kind, repo, number, title, url }: Pick<Item, "key" | "section" | "kind" | "repo" | "number" | "title" | "url">, othersActivityAt = "1970-01-01T00:00:00Z"): Item {
259
+ return { key, section, kind, draft: false, repo, number, title, url, chips: [], actions: [], children: [], target: { kind, repo, number, title, url }, othersActivityAt };
260
+ }
261
+
247
262
  // A Wrap up row's sessions: all idle, or it wouldn't be there [ATT-22].
248
263
  export interface WrapInfo {
249
264
  sessions: AgentSummary[];
@@ -266,16 +281,6 @@ export function memberKeys(item: Pick<Item, "key" | "children"> & { change?: Pic
266
281
  return uniqueKeys([item.key, ...(item.change ? [item.change.key] : []), ...item.children.map((child) => child.key)]);
267
282
  }
268
283
 
269
- // Each key once, ignoring case, in the first spelling seen.
270
- export function uniqueKeys(keys: string[]): string[] {
271
- const unique = new Map<string, string>();
272
- for (const key of keys) if (!unique.has(key.toLowerCase())) unique.set(key.toLowerCase(), key);
273
- return [...unique.values()];
274
- }
275
-
276
- // Keys for comparing: GitHub's owner and repo names ignore case.
277
- export const keySet = (keys: Iterable<string>): Set<string> => new Set([...keys].map((key) => key.toLowerCase()));
278
-
279
284
  // Each open stack's and issue group's member keys, lower case, under every member, and when it was last seen open; so a
280
285
  // member that merges still knows its open siblings [ATT-04, ATT-22].
281
286
  export type RememberedGroups = Record<string, { keys: string[]; at: string }>;
@@ -368,7 +373,8 @@ export interface Attention {
368
373
  projects?: ProjectInfo[];
369
374
  // Repo -> who reviewed or was asked on my PRs there, latest first, for the reviewer picker [PRS-12].
370
375
  reviewers?: Record<string, Reviewer[]>;
371
- // My PRs I closed without merging lately: finished work for Wrap up, never shown in History [ATT-22].
376
+ // My PRs that ended lately, closed by me unmerged or merged: finished work for Wrap up, never shown in History; a merged
377
+ // one stands in until History has it [ATT-22, FRESH-03].
372
378
  ownClosed?: Item[];
373
379
  }
374
380
 
@@ -392,6 +398,8 @@ export interface AgentSummary {
392
398
  lastActivityAt: string | null;
393
399
  // Its workspace, for Wrap up: whether its worktree holds unsaved work, and whether it's Paseo's own worktree [ATT-22].
394
400
  workspace?: SessionWorkspace;
401
+ // The sub-agents it started, and theirs, unarchived: archived with it, and while one works its row stays out [ATT-22].
402
+ subAgents?: { count: number; working: boolean };
395
403
  }
396
404
 
397
405
  export interface SessionWorkspace {
@@ -403,8 +411,11 @@ export interface SessionWorkspace {
403
411
  dirty?: boolean;
404
412
  // Commits not on the upstream branch, from Paseo; missing when it couldn't tell.
405
413
  ahead?: number;
406
- // Previews only, where Paseo has no worktree: how many files are uncommitted, for the confirm sheet's words.
414
+ // Previews only, where Paseo has no worktree: how many files and lines are uncommitted, and the terminals open, for the
415
+ // confirm sheet's words.
407
416
  dirtyFiles?: number;
417
+ dirtyLines?: { added: number; deleted: number };
418
+ terminals?: string[];
408
419
  }
409
420
 
410
421
  // An item's open sessions: started on it or on any PR under it, until it's merged or closed.
@@ -414,9 +425,26 @@ export function itemSessions(agents: AgentSummary[], item: Pick<Item, "key" | "c
414
425
  return matchSessions(agents, [item.key, ...item.children.map((child) => child.key)]);
415
426
  }
416
427
 
428
+ // A session working on its turn, or starting up [ATT-07].
429
+ export const isWorking = (agent: { status: string }): boolean => agent.status === "running" || agent.status === "initializing";
430
+
431
+ // A sub-agent holds its session back while it runs or needs me, as for a permission. Finished or failed, it stays flagged
432
+ // for attention nobody gives it, as reporting back is its parent's job, so those two don't count; any other flag, or one
433
+ // with no reason, does [ATT-22].
434
+ export function subAgentBusy(agent: { status: string; requiresAttention?: boolean; attentionReason?: string | null }): boolean {
435
+ return isWorking(agent) || (!!agent.requiresAttention && agent.attentionReason !== "finished" && agent.attentionReason !== "error");
436
+ }
437
+
438
+ // What holds a session back, in words: "Review PR 46 is still working", or "… is waiting on a permission" [ATT-22].
439
+ export function busyWords(agent: { title?: string | null; requiresAttention?: boolean; attentionReason?: string | null }, again = false): string {
440
+ const who = agent.title ?? "A session";
441
+ if (agent.requiresAttention && agent.attentionReason === "permission") return `${who} is waiting on a permission`;
442
+ return `${who} is ${again ? "working again" : "still working"}`;
443
+ }
444
+
417
445
  // A session is idle when it isn't working and doesn't need me; Wrap up and archiving both ask [ATT-22].
418
446
  export function isIdle(agent: { status: string; requiresAttention?: boolean }): boolean {
419
- return !agent.requiresAttention && agent.status !== "running" && agent.status !== "initializing";
447
+ return !agent.requiresAttention && !isWorking(agent);
420
448
  }
421
449
 
422
450
  export function matchSessions(agents: AgentSummary[], keys: string[]): AgentSummary[] {
@@ -432,7 +460,7 @@ export function liftActive(items: Item[], agents: AgentSummary[]): Item[] {
432
460
  const rank = (item: Item) => {
433
461
  const agent = itemSessions(agents, item)[0];
434
462
  if (agent?.requiresAttention) return 0;
435
- return agent?.status === "running" || agent?.status === "initializing" ? 1 : 2;
463
+ return agent && isWorking(agent) ? 1 : 2;
436
464
  };
437
465
  return items.map((item) => ({ item, rank: rank(item) })).sort((a, b) => a.rank - b.rank).map(({ item }) => item);
438
466
  }
@@ -460,7 +488,7 @@ export interface AttentionView {
460
488
  history: Item[];
461
489
  // Every item key on Doing, Waiting or Next up before dismissals, so Wrap up knows what still isn't done [ATT-22].
462
490
  activeKeys?: string[];
463
- // My PRs I closed without merging, for Wrap up only [ATT-22].
491
+ // My PRs I closed without merging, and merged ones History may not have yet, for Wrap up only [ATT-22, FRESH-03].
464
492
  ownClosed?: Item[];
465
493
  // Key -> the keys of the stack or issue group it was last seen open in, lower case [ATT-22, ATT-04].
466
494
  groups?: Record<string, string[]>;
@@ -479,10 +507,14 @@ export interface AttentionView {
479
507
  // Reviewed and Changed by others shown in each of History's weeks; none means finished only [HIS-07].
480
508
  historyFilter: HistoryFilter[];
481
509
  config: AttentionConfig;
510
+ // Where the New issue sheet can file, and what it started with last time [ISS-01].
511
+ newIssue: NewIssueInfo;
482
512
  // Changes I just made that GitHub's search hasn't caught up with; the app checks back sooner while there are any [FRESH-02].
483
513
  pending: number;
484
514
  // Fixture mode only: made-up sessions, since the preview daemon has no agents.
485
515
  fixtureAgents?: AgentSummary[];
516
+ // Wrap up rows whose sessions are archived but whose worktree stayed, until it's gone or dismissed [ATT-22].
517
+ kept?: KeptRow[];
486
518
  }
487
519
 
488
520
  // What a tick in Next up's project filter stands for: one status of one project, a project's issues without a status, or
package/shared/changes.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ago } from "./format";
2
+ import type { IssueCloseReason } from "./attention";
2
3
 
3
4
  // What someone else did to my work without asking me: merged or closed my PR, closed an issue assigned to me, reopened a PR
4
5
  // of mine that was closed, took work over or handed it on, or unassigned me from an issue [HIS-07]. Others' pushes and my
@@ -29,7 +30,7 @@ export interface OthersChange {
29
30
  // The new assignee, for took_over and handed.
30
31
  to?: string;
31
32
  // An issue closed as completed or not planned, for issue_closed [HIS-07].
32
- reason?: "completed" | "not_planned";
33
+ reason?: IssueCloseReason;
33
34
  // A cleared handover whose work came back to me: it stays in its week, but my later work on it is mine again [HIS-06].
34
35
  returned?: true;
35
36
  at: string;
package/shared/config.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { sameName } from "./names";
2
3
 
3
4
  // Session types, each with its own prompt template and profile lookup.
4
5
  export const SessionKind = z.enum(["review", "fix", "address", "rebase", "refresh", "start"]);
@@ -84,11 +85,6 @@ export function nextUpField({ nextUp }: Pick<AttentionConfig, "nextUp">, role: F
84
85
  return chosen === undefined ? { field: DEFAULT_FIELD[role] } : (chosen ?? undefined);
85
86
  }
86
87
 
87
- // Org issue field names compare without case, as people type them in config.json.
88
- export function sameField(a: string | undefined, b: string | undefined): boolean {
89
- return !!a && !!b && a.toLowerCase() === b.toLowerCase();
90
- }
91
-
92
88
  // "owner/name" of a Paseo project with a GitHub remote, from its project key.
93
89
  export function githubRepoOf(projectKey: string | null | undefined): string | null {
94
90
  return /^remote:github\.com\/(.+)$/i.exec(projectKey ?? "")?.[1] ?? null;
@@ -96,6 +92,6 @@ export function githubRepoOf(projectKey: string | null | undefined): string | nu
96
92
 
97
93
  // The repository whose checkout a session on an issue from `repo` works in [SES-07].
98
94
  export function codeRepoFor(config: Pick<AttentionConfig, "codeRepos">, repo: string): string {
99
- const mapped = Object.entries(config.codeRepos).find(([issues]) => issues.toLowerCase() === repo.toLowerCase());
95
+ const mapped = Object.entries(config.codeRepos).find(([issues]) => sameName(issues, repo));
100
96
  return mapped?.[1] ?? repo;
101
97
  }
@@ -0,0 +1,17 @@
1
+ // What every post an agent drafts for me has in common, for feedback and new issues alike [FB-01, ISS-01]:
2
+ // ask until it's clear, keep it skimmable, and post nothing until I approve the whole draft [SAFE-01].
3
+
4
+ // One question at a time, only what `needs` still lacks, and a draft after about five either way.
5
+ export const askUntilClear = (needs: string) =>
6
+ `Ask one question at a time, and only what ${needs} still needs. Offer likely answers when you can. After about five questions, draft with what you have and say what's missing.`;
7
+
8
+ export const SKIMMABLE =
9
+ "Keep posts skimmable: a few short lines up front, and anything longer (environment, logs, error text, likely cause, background) in a collapsed `<details><summary>…</summary>` block.";
10
+
11
+ export const APPROVE =
12
+ 'Show the whole draft, title included, then ask with your question tool: Post it / Change something / Cancel. Without a question tool, ask in plain text and post only after they reply "post".';
13
+
14
+ // Their own words, quoted, so the agent's first message is already a follow-up.
15
+ export const quote = (message: string) => message.trim().replace(/\n/g, "\n> ");
16
+
17
+ export const fill = (template: string, values: Record<string, string>) => template.replace(/\{\{(\w+)\}\}/g, (match, name: string) => values[name] ?? match);
@@ -2,6 +2,8 @@
2
2
  // Built in on purpose: these prompts carry the rules about privacy, where it's filed and approval,
3
3
  // so config.json can't replace them the way it can the session templates.
4
4
 
5
+ import { APPROVE, askUntilClear, fill, quote, SKIMMABLE } from "./drafting";
6
+
5
7
  export const FEEDBACK_REPO = "andrioid/paseo-attention-span";
6
8
 
7
9
  export interface FeedbackInfo {
@@ -40,16 +42,16 @@ Context: {{context}}
40
42
  How to work:
41
43
  - You are in an empty scratch directory made for this session: put temporary files here. {{where}}
42
44
  - Reply in the language they write in. Write the post in English, in their voice ("I …").
43
- - Ask one question at a time, and only what the checklist below still needs. Offer likely answers when you can. After about five questions, draft with what you have and say what's missing.
45
+ - ${askUntilClear("the checklist below")}
44
46
  - Read requirements.yaml, docs/architecture.md and the code to understand what they describe. Find the Paseo version with \`paseo --version\`.
45
47
  - You may read ~/.config/paseo-attention-span/config.json and state.json, and look items up with gh, to diagnose. Nothing from them goes in the post: no repository names, titles or logins they didn't write themselves.
46
48
  - Search open issues and discussions in ${FEEDBACK_REPO} (\`gh issue list --repo ${FEEDBACK_REPO} --search …\`, and \`gh api graphql\` with \`search(type: DISCUSSION, query: "repo:${FEEDBACK_REPO} …")\`). If one matches, give its link and stop. Don't comment or react on it.
47
49
 
48
50
  Where it goes: an issue if a maintainer could finish it and close it. Otherwise a discussion: Q&A for questions and for bugs nobody can reproduce yet, Ideas for broad or contested ideas. Say which and why; they may override it.
49
51
 
50
- Keep posts skimmable: a few short lines up front, and anything longer (environment, logs, error text, likely cause, background) in a collapsed \`<details><summary>…</summary>\` block.
52
+ ${SKIMMABLE}
51
53
 
52
- Show the whole draft, title included, then ask with your question tool: Post it / Change something / Cancel. Without a question tool, ask in plain text and post only after they reply "post".
54
+ ${APPROVE}
53
55
  - Issue: \`gh issue create --repo ${FEEDBACK_REPO} --title … --body-file …\`, with the body in a file in the scratch directory.
54
56
  - Discussion: look up the repository ID and the category by its slug (\`ideas\` or \`q-a\`) with \`gh api graphql\` (\`repository { id discussionCategories { nodes { id slug } } }\`), then call the \`createDiscussion\` mutation.
55
57
 
@@ -78,8 +80,7 @@ export function feedbackPrompt(kind: FeedbackKind, input: FeedbackContext): stri
78
80
  const where = input.dir
79
81
  ? `The plugin's installed source is at ${input.dir}: read it there, and don't change anything in it.`
80
82
  : `The plugin's source isn't on this host: read it from GitHub with \`gh api repos/${FEEDBACK_REPO}/contents/<path>\`.`;
81
- const values: Record<string, string> = { message: input.message.trim().replace(/\n/g, "\n> "), context: `${facts.join(", ")}.`, where };
82
- const shared = SHARED.replace(/\{\{(\w+)\}\}/g, (match, name: string) => values[name] ?? match);
83
+ const shared = fill(SHARED, { message: quote(input.message), context: `${facts.join(", ")}.`, where });
83
84
  return `${shared}\n\n${kind === "problem" ? PROBLEM : IDEA}`;
84
85
  }
85
86
 
package/shared/format.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { sameName } from "./names";
1
2
  // "5m", "3h", "4d", "2 months": how long ago an ISO timestamp was.
2
3
  export function ago(iso: string, now: Date = new Date()): string {
3
4
  const minutes = Math.max(0, Math.floor((now.getTime() - new Date(iso).getTime()) / 60_000));
@@ -27,7 +28,7 @@ export function linkList(items: { title: string; url: string; lead?: string; mar
27
28
  // 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].
28
29
  export function repoLabel(repo: string, login: string | null): string {
29
30
  const [owner, name] = repo.split("/");
30
- return name && login && owner.toLowerCase() === login.toLowerCase() ? name : repo;
31
+ return name && sameName(owner, login) ? name : repo;
31
32
  }
32
33
 
33
34
  // An issue field value for a card: "🐟 Tiny (< 4h)" -> "Tiny", "🏕P2 Medium" -> "P2 Medium" [NXT-10]. The sheet keeps the full value.
@@ -28,7 +28,8 @@ export function weekOf(iso: string): Date {
28
28
  const newestFirst = (a: Item, b: Item) => b.closedAt!.localeCompare(a.closedAt!);
29
29
 
30
30
  // The weeks with anything shown, newest first, and whether any week holds anything at all, even only what the filter
31
- // hides: then the Filter button stays, so it can be turned on. Unread notes aren't in weeks; they sit above them.
31
+ // hides: then the Filter button stays, so it can be turned on. Unread notes aren't in weeks; they sit above them. The server
32
+ // sends only History's weeks, in the device's time zone [HIS-01].
32
33
  export function historyWeeks(items: Item[], filter: HistoryFilter[]): { weeks: HistoryWeek[]; anything: boolean } {
33
34
  const byWeek = new Map<number, Item[]>();
34
35
  for (const item of items) {
@@ -0,0 +1,76 @@
1
+ import { type AgentSummary, type SessionWorkspace, subAgentBusy } from "./attention";
2
+ import { SessionKind } from "./config";
3
+ import { linkedSessions, type PaseoAgentEntry, type PaseoWorkspaceEntry, subAgentsOf } from "./linked-sessions";
4
+
5
+ // The sessions on items, as the screen and the sidebar's count see them, from Paseo's lists [SES-03, SES-08, ATT-22].
6
+ // Pure, so the rules test in node; the client fetches every page and hands them over.
7
+
8
+ // Labels tie an agent to the item it works on [ATT-07, SES-03].
9
+ export const LABEL = "attention-span";
10
+ export const ITEM_LABEL = "attention-span-item";
11
+ // The action it was started for, so the sheet shows it in that action's line.
12
+ export const KIND_LABEL = "attention-span-kind";
13
+ // Sessions started under the plugin's earlier names, "GitHub attention" and "GitHub inbox", count too.
14
+ export const SESSION_LABELS = [LABEL, "github-attention", "github-inbox"];
15
+
16
+ // A workspace as Paseo lists it, as far as Wrap up reads it.
17
+ export type SessionWorkspaceEntry = PaseoWorkspaceEntry & {
18
+ workspaceKind: SessionWorkspace["kind"];
19
+ title?: string | null;
20
+ name: string;
21
+ workspaceDirectory?: string | null;
22
+ projectRootPath?: string | null;
23
+ gitRuntime?: { currentBranch?: string | null; remoteUrl?: string | null; isDirty?: boolean | null; aheadOfOrigin?: number | null } | null;
24
+ };
25
+
26
+ // What Paseo knows about the workspace a session runs in, for Wrap up's unsaved-work check [ATT-22].
27
+ function sessionWorkspace(workspace: SessionWorkspaceEntry): SessionWorkspace {
28
+ const git = workspace.gitRuntime;
29
+ const directory = workspace.workspaceDirectory ?? workspace.projectRootPath;
30
+ return {
31
+ kind: workspace.workspaceKind,
32
+ name: workspace.title ?? workspace.name,
33
+ ...(directory ? { directory } : {}),
34
+ ...(git?.currentBranch ? { branch: git.currentBranch } : {}),
35
+ ...(typeof git?.isDirty === "boolean" ? { dirty: git.isDirty } : {}),
36
+ ...(typeof git?.aheadOfOrigin === "number" ? { ahead: git.aheadOfOrigin } : {}),
37
+ };
38
+ }
39
+
40
+ // Agents started from Attention Span (`labelled`, listed by SESSION_LABELS), each with the item it was started on, and the
41
+ // agents started outside it (from `all`) in a workspace that belongs to an item. Each with its workspace, and the sub-agents
42
+ // that go with it: one still busy keeps its Wrap up row out [SES-08, ATT-22]. `branches` are closedBranches.
43
+ export function sessionsFrom(
44
+ labelled: PaseoAgentEntry[],
45
+ all: PaseoAgentEntry[],
46
+ workspaces: SessionWorkspaceEntry[],
47
+ branches = new Map<string, string>(),
48
+ ): AgentSummary[] {
49
+ const byId = new Map<string, AgentSummary>();
50
+ for (const agent of labelled) {
51
+ const itemKey = SESSION_LABELS.map((label) => agent.labels?.[`${label}-item`]).find(Boolean);
52
+ if (!itemKey || agent.archivedAt) continue;
53
+ byId.set(agent.id, {
54
+ id: agent.id,
55
+ itemKey,
56
+ kind: SessionKind.safeParse(agent.labels?.[KIND_LABEL]).data,
57
+ status: agent.status,
58
+ requiresAttention: !!agent.requiresAttention,
59
+ title: agent.title ?? null,
60
+ workspaceId: agent.workspaceId ?? null,
61
+ lastActivityAt: agent.updatedAt ?? null,
62
+ });
63
+ }
64
+ const started = [...byId.values()];
65
+ const unlabelled = all.filter((agent) => !SESSION_LABELS.some((label) => agent.labels?.[label]));
66
+ const byWorkspace = new Map(workspaces.map((workspace) => [workspace.id, sessionWorkspace(workspace)]));
67
+ return [...started, ...linkedSessions(started, unlabelled, workspaces, branches)].map((agent) => {
68
+ const workspace = agent.workspaceId ? byWorkspace.get(agent.workspaceId) : undefined;
69
+ const subAgents = subAgentsOf(all, [agent.id]);
70
+ return {
71
+ ...agent,
72
+ ...(workspace ? { workspace } : {}),
73
+ ...(subAgents.length ? { subAgents: { count: subAgents.length, working: subAgents.some(subAgentBusy) } } : {}),
74
+ };
75
+ });
76
+ }
@@ -0,0 +1,223 @@
1
+ // What an item's card and sheet say and offer, as plain data: client/attention-screen.tsx draws it and wires the presses
2
+ // [ATT-05, ATT-06].
3
+ import { type ActionId, type AgentSummary, type AttentionView, type Chip, type FailingChecks, isWorking, type Item, looseSessions, ownStack, SECTIONS, type SubRow, type TabId, type WaitingOn, type WrapItem } from "./attention";
4
+ import { summarizeRerun } from "./checks";
5
+ import type { SessionKind } from "./config";
6
+ import { ago } from "./format";
7
+ import { sameName } from "./names";
8
+ import { ACTION_SESSION } from "./prompts";
9
+ import { doingCount, finishText } from "./wrap-up";
10
+
11
+ // A session's state, as a chip on its card: needing me beats working [ATT-07].
12
+ export function sessionSignal(agent: AgentSummary): Chip {
13
+ if (agent.requiresAttention) return { text: "agent needs you", tone: "warn" };
14
+ if (isWorking(agent)) return { text: "agent working", tone: "good" };
15
+ if (agent.status === "error") return { text: "agent failed", tone: "bad" };
16
+ return { text: "agent idle", tone: "neutral" };
17
+ }
18
+
19
+ // The same state as a badge on the session's line in a sheet, where the line already says it's a session [SES-03, ATT-07].
20
+ export function sessionBadge(agent: AgentSummary): Chip {
21
+ const signal = sessionSignal(agent);
22
+ return { ...signal, text: signal.text.replace(/^agent /, "") };
23
+ }
24
+
25
+ export function actionLabel(action: ActionId, item: Item): string {
26
+ // Review takes the whole stack; Rebase, my PRs in it [ATT-04].
27
+ const stacked = ownStack(item.target).length > 1;
28
+ return {
29
+ reply: "Reply ↗",
30
+ acknowledge: "Acknowledge",
31
+ review: (item.target.stack?.length ?? 0) > 1 ? "Review stack" : "Review",
32
+ fix: "Fix CI",
33
+ rerun: "Rerun failed jobs",
34
+ address: "Address comments",
35
+ update: "Update branch",
36
+ rebase: stacked ? "Rebase stack" : "Rebase",
37
+ refresh: "Refresh draft",
38
+ ready: "Ready for review",
39
+ request_review: "Request review",
40
+ automerge: "Auto-merge",
41
+ merge: "Merge",
42
+ close: "Close draft",
43
+ start: "Start",
44
+ got_it: "Got it",
45
+ }[action];
46
+ }
47
+
48
+ // What an action will do, in the sheet, so pressing it makes sense [ATT-06]. Rerun's comes from the fetched checks.
49
+ export function actionDetail(action: Exclude<ActionId, "rerun">, item: Item): string {
50
+ const { target } = item;
51
+ const pr = `#${target.number}`;
52
+ const base = target.baseRefName ?? target.defaultBranch ?? "its base";
53
+ const stacked = ownStack(target).length > 1;
54
+ const asking = (target.stack ?? []).filter((p) => p.review);
55
+ const comments = item.person?.comments ?? [];
56
+ return {
57
+ reply: item.person ? `Opens ${item.person.login}'s comment on GitHub` : "Opens it on GitHub",
58
+ acknowledge:
59
+ comments.length === 1 ? `Reacts to ${comments[0].author}'s comment, which clears it` : `Pick which of the ${comments.length} waiting comments to react to`,
60
+ review:
61
+ (target.stack?.length ?? 0) > 1
62
+ ? `An agent reviews ${asking.map((p) => `#${p.number}`).join(", ") || "the stack"} in a checkout of the stack's top and reports back. Nothing is posted`
63
+ : "An agent reviews the PR in a checkout and reports back. Nothing is posted",
64
+ fix: "An agent reads the failing logs and commits a fix, without pushing",
65
+ address: "An agent works through the unresolved comments and applies the trivial ones, without pushing",
66
+ update: `GitHub rebases ${pr} onto ${base}`,
67
+ rebase: `An agent rebases ${stacked ? "the stack" : pr} onto ${base}. It pushes only if there were no conflicts`,
68
+ refresh: `An agent rebases the draft onto ${base} and says what it still needs`,
69
+ ready: `Takes ${pr} out of draft, then asks who should review it`,
70
+ request_review: `Pick people or teams to review ${pr}`,
71
+ automerge: `GitHub merges ${pr} into ${base} (${target.mergeMethod}) once checks pass`,
72
+ merge: `Merges ${pr} into ${base} (${target.mergeMethod}) now`,
73
+ close: `Closes ${pr}. A comment is posted only if you write one`,
74
+ start: "An agent reads the issue and proposes a plan",
75
+ got_it: "Clears this note. Nothing changes on GitHub",
76
+ }[action];
77
+ }
78
+
79
+ // A session is named for what started it; one of no kind, or a Start's, just continues.
80
+ export const sessionLabel = (kind: SessionKind | undefined, item: Item) => (kind && kind !== "start" ? actionLabel(kind, item) : "Continue session");
81
+
82
+ // A session on an item that has no session action of its own starts with this prompt; it's editable first.
83
+ export const fallbackKind = (item: Item): SessionKind => (item.target.kind === "issue" ? "start" : "review");
84
+
85
+ // One line of an item's sheet, top to bottom; the client draws each and wires its press [ATT-06].
86
+ export type SheetStep =
87
+ // A running session, in the line of what started it: it opens it [SES-03, ATT-07].
88
+ | { kind: "session"; agent: AgentSummary; label: string }
89
+ // A session action that asks first, with "…": the card's button is the one-tap start [SES-01, SES-02].
90
+ | { kind: "ask"; action: ActionId; session: SessionKind; label: string; detail: string }
91
+ // Rerun failed jobs, whose line comes from the fetched checks [PRS-09].
92
+ | { kind: "rerun"; label: string }
93
+ // A change on GitHub; closing it sits apart, below the work [ATT-06].
94
+ | { kind: "action"; action: Exclude<ActionId, "rerun">; label: string; detail: string; housekeeping: boolean }
95
+ // Open on GitHub, with an issue's PR beside it [ATT-12].
96
+ | { kind: "github"; pr?: { number: number; url: string; stack?: { number: number }[] } }
97
+ // Another session only on purpose: quiet, near the end [SES-02, SES-03].
98
+ | { kind: "start"; any: boolean; session: SessionKind }
99
+ | { kind: "dismiss" };
100
+
101
+ // Everything an item's sheet offers [ATT-06].
102
+ export function sheetPlan(item: Item, sessions: AgentSummary[]): SheetStep[] {
103
+ // Sessions none of its actions would start lead, needs me first [SES-03].
104
+ const kinds = item.actions.flatMap((action) => ACTION_SESSION[action] ?? []);
105
+ const steps: SheetStep[] = looseSessions(sessions, kinds).map((agent) => ({ kind: "session", agent, label: sessionLabel(agent.kind, item) }));
106
+ for (const action of item.actions) {
107
+ const session = ACTION_SESSION[action];
108
+ const label = actionLabel(action, item);
109
+ if (session) {
110
+ // An action's session takes its line once it runs, so work on it stays in one place [SES-03].
111
+ const running = sessions.filter((agent) => agent.kind === session);
112
+ if (running.length) steps.push(...running.map((agent) => ({ kind: "session" as const, agent, label: sessionLabel(session, item) })));
113
+ else steps.push({ kind: "ask", action, session, label, detail: actionDetail(action as Exclude<ActionId, "rerun">, item) });
114
+ } else if (action === "rerun") {
115
+ steps.push({ kind: "rerun", label });
116
+ } else {
117
+ steps.push({ kind: "action", action, label, detail: actionDetail(action, item), housekeeping: action === "close" });
118
+ }
119
+ }
120
+ // Anything Attention Span doesn't cover [ATT-12], with an issue's PR beside it: the one its actions apply to, or in
121
+ // History, where an issue is its own target, the first of the PRs that closed it.
122
+ const pr = targetUrl(item) && item.target.kind === "pr" ? item.target : item.kind === "issue" && item.children[0] ? item.children[0] : undefined;
123
+ steps.push({ kind: "github", ...(pr ? { pr } : {}) });
124
+ // Nothing's left to start on once it's merged or closed, or out of my hands; a note is cleared with Got it, not dismissed [HIS-07].
125
+ if (!item.closedAt && !item.change) steps.push({ kind: "start", any: sessions.length > 0, session: fallbackKind(item) });
126
+ if (SECTIONS[item.section].tab === "doing" && !item.change) steps.push({ kind: "dismiss" });
127
+ return steps;
128
+ }
129
+
130
+ // A sheet with one action is a wasted tap: the card shows that action instead of ›. Starting another session is quiet, so
131
+ // it doesn't count [ATT-06].
132
+ export function soleStep(steps: SheetStep[]): SheetStep | undefined {
133
+ const loud = steps.filter((step) => step.kind !== "start");
134
+ return loud.length === 1 ? loud[0] : undefined;
135
+ }
136
+
137
+ // Rerun's line before it's pressed: still checking, nothing it can rerun and why, or the runs to rerun [PRS-09].
138
+ // Checking can be pressed: the sheet closes, and the rerun goes ahead once the checks are in.
139
+ export type RerunState =
140
+ | { state: "checking" | "unknown" | "none"; detail: string }
141
+ | { state: "elsewhere"; detail: string; failing: FailingChecks[] }
142
+ | { state: "ready"; failing: FailingChecks[]; runIds: number[] };
143
+
144
+ export function rerunState(details: { data?: { failing: FailingChecks[] }; isLoading: boolean } | undefined): RerunState {
145
+ if (!details || details.isLoading) return { state: "checking", detail: "Checking which checks failed…" };
146
+ const failing = details.data?.failing;
147
+ if (!failing) return { state: "unknown", detail: "Couldn't find the failing checks" };
148
+ const summary = summarizeRerun(failing);
149
+ if (summary.failed === 0) return { state: "none", detail: "No failed checks on the latest commit" };
150
+ if (summary.runIds.length === 0) return { state: "elsewhere", detail: `${summary.failed} failed, none in GitHub Actions, so none can be rerun here`, failing };
151
+ return { state: "ready", failing, runIds: summary.runIds };
152
+ }
153
+
154
+ // Why it waits and how long, in Waiting only; Doing says what's mine to do. Once it has waited too long, where nudging is
155
+ // fair, the age itself turns amber with ⌛ and says so in words [WAI-01, ATT-11].
156
+ export function waitChips(item: Item, inWaiting: boolean, tooLongDays: number, now = new Date()): Chip[] {
157
+ const { wait } = item;
158
+ if (!wait || !inWaiting) return [];
159
+ const age = ago(wait.since, now);
160
+ const reason: Chip[] = wait.reason ? [{ text: wait.reason, tone: "neutral" }] : [];
161
+ if (!wait.tooLong) return [...reason, { text: age, tone: "neutral" }];
162
+ const since = wait.reason === "question" ? "you asked" : "your last push or reply";
163
+ const limit = `${tooLongDays} day${tooLongDays === 1 ? "" : "s"}`;
164
+ return [...reason, { text: age, tone: "warn", icon: "hourglass", hint: `Waited too long: ${age} since ${since}, more than ${limit}` }];
165
+ }
166
+
167
+ // "Review 2h", "Question 3d": why and how long, to lead a line in a nudge [WAI-03].
168
+ export function nudgeLead(item: Item, now = new Date()): string | undefined {
169
+ if (!item.wait) return undefined;
170
+ const { reason, since } = item.wait;
171
+ return reason ? `${reason[0].toUpperCase()}${reason.slice(1)} ${ago(since, now)}` : ago(since, now);
172
+ }
173
+
174
+ // In a Waiting group, the card names whom else it waits on; the group names one [WAI-02].
175
+ export function alsoWaitingOn(item: Item, groupWho: WaitingOn | undefined): string[] {
176
+ if (!groupWho) return [];
177
+ return (item.waitingOn ?? []).filter((who) => !(who.team === groupWho.team && sameName(who.login, groupWho.login))).map((who) => who.login);
178
+ }
179
+
180
+ // The card's "when": a note's change, or how it finished, in the words Wrap up uses [HIS-05, HIS-07].
181
+ export function cardWhen(item: Item, now = new Date()): string | undefined {
182
+ return item.change || item.closedAt ? finishText(item, now) : undefined;
183
+ }
184
+
185
+ // History is where I report from, so its cards copy their link in one tap; unread notes are not report rows [ATT-15].
186
+ export const copiesLink = (item: Item) => SECTIONS[item.section].tab === "history" && item.section !== "changed";
187
+
188
+ // The PR an item's actions apply to, where that isn't the item itself, like an issue's PR.
189
+ export const targetUrl = (item: Item) => (item.target.number !== item.number || item.target.kind !== item.kind ? item.target.url : undefined);
190
+
191
+ const isRed = (chips: Chip[]) => chips.some((chip) => chip.tone === "bad");
192
+
193
+ // The full stack is in the sheet; the card shows the PRs that need attention [ATT-04]. Once it shows any, it shows the PR an
194
+ // issue's actions apply to as well, tinted, and says that PR's facts there rather than in its meta, as the sheet does [ATT-06].
195
+ export function cardStack(item: Item): { rows: SubRow[]; target?: SubRow } {
196
+ const target = targetUrl(item);
197
+ const needing = item.children.some((child) => child.attention || isRed(child.chips));
198
+ const rows = needing ? item.children.filter((child) => child.attention || isRed(child.chips) || child.url === target) : [];
199
+ return { rows, target: rows.find((child) => child.url === target) };
200
+ }
201
+
202
+ // An issue's chips are about the PR its actions apply to. Where its stack line shows that PR, each is said once, on that PR's
203
+ // row, and the meta keeps only what the row doesn't say; "PR #103" and "stack of 2" are the stack line itself. The sheet always
204
+ // shows the row; a card only when a PR in the stack needs attention [ATT-04, ATT-06].
205
+ export function stackMetaChips(item: Item, targetRow: SubRow | undefined): Chip[] {
206
+ if (!targetRow) return item.chips;
207
+ const onRow = new Set(targetRow.chips.map((chip) => chip.text));
208
+ return item.chips.filter((chip) => !/^PR #\d+$/.test(chip.text) && !/^stack of \d+$/.test(chip.text) && !onRow.has(chip.text));
209
+ }
210
+
211
+ // Each tab's count: History's finished work in the weeks it shows [HIS-01], Doing with Wrap up's rows [ATT-09, ATT-22], work
212
+ // waiting on several people once, and every issue in Next up.
213
+ export function tabCounts(
214
+ view: Pick<AttentionView, "history" | "count" | "waiting" | "assigned" | "unclaimed">,
215
+ wrap: WrapItem[],
216
+ ): Record<TabId, number> {
217
+ return {
218
+ history: view.history.filter((item) => item.section === "done" && !!item.closedAt).length,
219
+ doing: doingCount(view, wrap),
220
+ waiting: new Set(view.waiting.flatMap((group) => group.items.map((item) => item.key))).size,
221
+ next: view.assigned.length + view.unclaimed.length,
222
+ };
223
+ }