@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
@@ -1,178 +1,32 @@
1
- import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
2
- import { openExternalUrl, type PluginScreenProps, usePaseo, useRpc } from "@getpaseo/plugin/client";
3
- import { Markdown, TextInput, useToast } from "@getpaseo/plugin/client/ui";
4
- import { useQuery, useQueryClient } from "@tanstack/react-query";
5
- import { type ReactNode, useState } from "react";
1
+ import { type PluginScreenProps, useRpc } from "@getpaseo/plugin/client";
2
+ import { useToast } from "@getpaseo/plugin/client/ui";
3
+ import { useQuery } from "@tanstack/react-query";
4
+ import { useEffect, useState } from "react";
6
5
  import { Pressable, ScrollView, Text, View } from "react-native";
7
- import { type ActionId, type AgentSummary, type AttentionView, type Chip, checkoutPr, type FailingChecks, type Item, itemSessions, liftActive, looseSessions, type NextUpIssue, ownStack, type PersonRole, type Reviewer, type Section, type SectionId, SECTIONS, type SubRow, TAB_FEED, type TabId, type Target, type WaitingGroup, type WaitingOn, type WrapItem } from "../shared/attention";
8
- import { type AttentionConfig, nextUpSources, type SessionKind } from "../shared/config";
9
- import { failingList, groupLabel, rerunHistory, summarizeRerun } from "../shared/checks";
10
- import { changeText } from "../shared/changes";
6
+ import { liftActive, type Section, type SectionId, TAB_FEED, type TabId, type WaitingGroup } from "../shared/attention";
7
+ import { nextUpSources } from "../shared/config";
11
8
  import { ago, linkList } from "../shared/format";
12
9
  import { historyClear, isClear, nextUpClear, waitingClear } from "../shared/still";
13
- import { ACTION_SESSION, renderPrompt } from "../shared/prompts";
14
10
  import * as rpc from "../shared/rpc";
15
11
  import { type FeedbackKind, themeName } from "../shared/feedback";
16
12
  import { blocks } from "../shared/setup";
13
+ import { cleanSingle, unreadChanges, wrapItems } from "../shared/wrap-up";
14
+ import { nudgeLead, tabCounts } from "../shared/item-view";
17
15
  import { useAttention } from "./data";
18
- import { CardList, CardRow } from "./card";
19
16
  import type { IconName } from "./icons";
20
- import { NumberText, PlaceText } from "./entity";
17
+ import { type Actions, useItemActions } from "./item-actions";
18
+ import { Card } from "./item-row";
21
19
  import { NextUpList } from "./next-up";
20
+ import { CodeRepoPicker, SessionOptions } from "./pickers";
22
21
  import { Still } from "./still";
23
- import { agentSignal, sessionEntry, startAnotherEntry } from "./session-menu";
24
- import { ActionSheet, DETAILS_STALE_MS, DetailLines, type DetailsQuery, detailsKey, FadeIn, githubEntry, Modal, type SheetEntry, useArrived, usePrefetchOnRest } from "./sheet";
25
22
  import { FeedbackAsk, FeedbackLine, type FeedbackScreen, FeedbackSheet } from "./feedback";
26
- import { AGENTS_QUERY_KEY, branchWorkspaces, type FetchProviders, findCheckout, githubProjects, listProfiles, noProjectMessage, resolveAgentConfig, startSession, useItemAgents } from "./sessions";
27
- import { ALL_NOTES, ALL_WRAP, noteBusy } from "../shared/got-it";
28
- import { cleanSingle, doingCount, unreadChanges, wrapItems } from "../shared/wrap-up";
29
- import { type ArchiveOutcome, archiveTarget } from "../shared/archive";
23
+ import { NewIssueSheet, type NewIssueRequest, takeNewIssueRequest } from "./new-issue";
24
+ import { useItemAgents } from "./sessions";
30
25
  import { History } from "./history";
31
- import { stateMark } from "./mark";
32
26
  import { WrapUp } from "./wrap-up";
33
27
  import { SetupChecklist } from "./setup";
34
28
  import { UpdateNotice } from "./update";
35
- import { Avatar, Button, Hint, KeepStyles, LINE_HEIGHT, Loading, Meta, mix, SectionHeader, SpinningIcon, StylesProvider, TablerIcon, Toggle, useCopy, useHover, useStrongText, useStyles } from "./ui";
36
-
37
- // The agent icon marks every action that starts an agent session; the rest act on GitHub right away [ATT-13].
38
- const ACTION_ICONS: Record<ActionId, IconName> = {
39
- reply: "replyArrow",
40
- acknowledge: "thumbUp",
41
- review: "agent",
42
- fix: "agent",
43
- rerun: "reload",
44
- address: "agent",
45
- update: "update",
46
- rebase: "agent",
47
- refresh: "agent",
48
- ready: "pr",
49
- request_review: "claim",
50
- automerge: "clock",
51
- merge: "merge",
52
- close: "close",
53
- start: "agent",
54
- got_it: "check",
55
- };
56
-
57
- function actionLabel(action: ActionId, item: Item): string {
58
- // Review takes the whole stack; Rebase, my PRs in it [ATT-04].
59
- const stacked = ownStack(item.target).length > 1;
60
- return {
61
- reply: "Reply ↗",
62
- acknowledge: "Acknowledge",
63
- review: (item.target.stack?.length ?? 0) > 1 ? "Review stack" : "Review",
64
- fix: "Fix CI",
65
- rerun: "Rerun failed jobs",
66
- address: "Address comments",
67
- update: "Update branch",
68
- rebase: stacked ? "Rebase stack" : "Rebase",
69
- refresh: "Refresh draft",
70
- ready: "Ready for review",
71
- request_review: "Request review",
72
- automerge: "Auto-merge",
73
- merge: "Merge",
74
- close: "Close draft",
75
- start: "Start",
76
- got_it: "Got it",
77
- }[action];
78
- }
79
-
80
- // What an action will do, in the sheet, so pressing it makes sense [ATT-06]. Rerun's comes from the fetched checks.
81
- function actionDetail(action: Exclude<ActionId, "rerun">, item: Item): string {
82
- const { target } = item;
83
- const pr = `#${target.number}`;
84
- const base = target.baseRefName ?? target.defaultBranch ?? "its base";
85
- const stacked = ownStack(target).length > 1;
86
- const asking = (target.stack ?? []).filter((p) => p.review);
87
- const comments = item.person?.comments ?? [];
88
- return {
89
- reply: item.person ? `Opens ${item.person.login}'s comment on GitHub` : "Opens it on GitHub",
90
- acknowledge:
91
- comments.length === 1 ? `Reacts to ${comments[0].author}'s comment, which clears it` : `Pick which of the ${comments.length} waiting comments to react to`,
92
- review:
93
- (target.stack?.length ?? 0) > 1
94
- ? `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`
95
- : "An agent reviews the PR in a checkout and reports back. Nothing is posted",
96
- fix: "An agent reads the failing logs and commits a fix, without pushing",
97
- address: "An agent works through the unresolved comments and applies the trivial ones, without pushing",
98
- update: `GitHub rebases ${pr} onto ${base}`,
99
- rebase: `An agent rebases ${stacked ? "the stack" : pr} onto ${base}. It pushes only if there were no conflicts`,
100
- refresh: `An agent rebases the draft onto ${base} and says what it still needs`,
101
- ready: `Takes ${pr} out of draft, then asks who should review it`,
102
- request_review: `Pick people or teams to review ${pr}`,
103
- automerge: `GitHub merges ${pr} into ${base} (${target.mergeMethod}) once checks pass`,
104
- merge: `Merges ${pr} into ${base} (${target.mergeMethod}) now`,
105
- close: `Closes ${pr}. A comment is posted only if you write one`,
106
- start: "An agent reads the issue and proposes a plan",
107
- got_it: "Clears this note. Nothing changes on GitHub",
108
- }[action];
109
- }
110
-
111
- // Rerun failed jobs as a sheet line: which checks failed and whether they were rerun before, flaky or real? [PRS-09]
112
- // It can be pressed before the checks are in: the sheet closes, and the rerun goes ahead once they are.
113
- function rerunEntry(label: string, details: SheetDetails | undefined, rerun: (runIds?: number[]) => void): SheetEntry {
114
- const base = { key: "rerun", icon: ACTION_ICONS.rerun, label, live: true };
115
- if (!details || details.isLoading) return { ...base, detail: "Checking which checks failed…", onPress: () => rerun() };
116
- const failing = details.data?.failing;
117
- if (!failing) return { ...base, detail: "Couldn't find the failing checks", disabled: true, onPress: () => {} };
118
- const summary = summarizeRerun(failing);
119
- if (summary.failed === 0) return { ...base, detail: "No failed checks on the latest commit", disabled: true, onPress: () => {} };
120
- if (summary.runIds.length === 0)
121
- return { ...base, detail: `${summary.failed} failed, none in GitHub Actions, so none can be rerun here`, hint: failingList(failing), disabled: true, onPress: () => {} };
122
- return { ...base, detailNode: <RerunDetail failing={failing} arrived={!!details.arrived} />, hint: failingList(failing), onPress: () => rerun(summary.runIds) };
123
- }
124
-
125
- // What an item's sheet has fetched, as its lines need it; `arrived` once it came in while the sheet was open.
126
- interface SheetDetails {
127
- data?: { failing: FailingChecks[] };
128
- isLoading: boolean;
129
- arrived?: boolean;
130
- }
131
-
132
- // "7 failed · lint, e2e ×3, unit ×2 · ↻ rerun once": the count and names quiet, as the card's red already says CI failed; checks
133
- // that can't rerun dimmer; the history amber once rerun, a hint it may not be flaky. One line on desktop, where the names give way
134
- // and the hint has them all; two on phones, which can't point at a hint [PRS-09].
135
- function RerunDetail({ failing, arrived }: { failing: FailingChecks[]; arrived: boolean }) {
136
- const styles = useStyles();
137
- const summary = summarizeRerun(failing);
138
- const strong = useStrongText();
139
- // Dimmer than the quiet text, on the line's own background, so it reads in any theme.
140
- const dimmer = { color: mix(styles.c.foregroundMuted, styles.c.surface2, 0.55) };
141
- const stack = summary.prs.length > 1;
142
- const names = summary.prs.map(({ pr, groups }, index) => (
143
- <Text key={pr}>
144
- {index > 0 ? " · " : null}
145
- {stack ? <Text style={strong}>#{pr} </Text> : null}
146
- {groups.map((group, at) => (
147
- <Text key={`${group.name}-${group.rerunnable}`} style={group.rerunnable ? null : dimmer}>
148
- {at > 0 ? ", " : null}
149
- {groupLabel(group)}
150
- </Text>
151
- ))}
152
- </Text>
153
- ));
154
- const history = (
155
- <Text style={summary.reruns ? { color: styles.c.statusWarning, fontWeight: "500" } : null}>{summary.reruns ? `↻ ${rerunHistory(summary.reruns)}` : rerunHistory(0)}</Text>
156
- );
157
- const line = [styles.muted, { lineHeight: LINE_HEIGHT }];
158
- return (
159
- <FadeIn active={arrived}>
160
- {styles.compact ? (
161
- <Text style={line} numberOfLines={2}>
162
- {summary.failed} failed · {names} · {history}
163
- </Text>
164
- ) : (
165
- <View style={{ flexDirection: "row", minWidth: 0 }}>
166
- <Text style={line}>{summary.failed} failed · </Text>
167
- <Text style={[line, { flexShrink: 1 }]} numberOfLines={1}>
168
- {names}
169
- </Text>
170
- <Text style={line}> · {history}</Text>
171
- </View>
172
- )}
173
- </FadeIn>
174
- );
175
- }
29
+ import { Avatar, Button, Loading, SectionHeader, SpinningIcon, StylesProvider, TablerIcon, tint, useCopy, useStyles } from "./ui";
176
30
 
177
31
  const SECTION_ICONS: Record<SectionId, IconName> = {
178
32
  reply: "reply",
@@ -202,164 +56,44 @@ const TABS: { id: TabId; label: string; icon: IconName }[] = [
202
56
  { id: "next", label: "Next up", icon: "nextUp" },
203
57
  ];
204
58
 
205
- type FetchContext = (input: RpcInput<typeof rpc.sessionContext>) => Promise<RpcOutput<typeof rpc.sessionContext>>;
206
- export type FetchDetails = (input: RpcInput<typeof rpc.itemDetails>) => Promise<RpcOutput<typeof rpc.itemDetails>>;
207
- type DefaultBranch = (repo: string) => Promise<string | null>;
208
- type FetchReviewers = (input: RpcInput<typeof rpc.reviewerChoices>) => Promise<RpcOutput<typeof rpc.reviewerChoices>>;
209
-
210
- // A start held back until I say where the issue's code lives [SES-07].
211
- interface Placing {
212
- itemKey: string;
213
- kind: SessionKind;
214
- target: Target;
215
- missing: string;
216
- before?: () => Promise<unknown>;
217
- }
218
-
219
- // Session options, before it starts [SES-02].
220
- export interface OptionsSpec {
221
- itemKey: string;
222
- title: string;
223
- kind: SessionKind;
224
- target: Target;
225
- // Claims an issue first [NXT-05].
226
- before?: () => Promise<unknown>;
227
- }
228
-
229
- // Something I just did, offered for undo until the tab changes [ATT-08, ATT-14].
230
- interface Undoable {
231
- id: number;
232
- text: string;
233
- dismissal?: boolean;
234
- undo: () => Promise<unknown>;
235
- }
236
-
237
59
  // `openSettings` opens the orgs and repos settings [SRC-02].
238
- export function AttentionScreen({ theme, layout, navigation, openSettings }: PluginScreenProps & { openSettings?: () => void }) {
60
+ export function AttentionScreen({ theme, layout, navigation, params, openSettings }: PluginScreenProps & { openSettings?: () => void }) {
239
61
  return (
240
62
  <StylesProvider theme={theme} compact={layout.compact}>
241
- <AttentionList navigation={navigation} openSettings={openSettings} device={{ device: layout.compact ? "phone" : "desktop", platform: layout.platform, theme: themeName(theme.colors.surface0) }} />
63
+ <AttentionList navigation={navigation} params={params} openSettings={openSettings} device={{ device: layout.compact ? "phone" : "desktop", platform: layout.platform, theme: themeName(theme.colors.surface0) }} />
242
64
  </StylesProvider>
243
65
  );
244
66
  }
245
67
 
246
68
  function AttentionList({
247
69
  navigation,
70
+ params,
248
71
  openSettings,
249
72
  device,
250
- }: Pick<PluginScreenProps, "navigation"> & { openSettings?: () => void; device: Omit<FeedbackScreen, "tab" | "refreshError"> }) {
73
+ }: Pick<PluginScreenProps, "navigation" | "params"> & { openSettings?: () => void; device: Omit<FeedbackScreen, "tab" | "refreshError"> }) {
251
74
  const styles = useStyles();
252
- const paseo = usePaseo();
253
75
  const toast = useToast();
254
- const queryClient = useQueryClient();
255
76
  const attention = useAttention();
256
77
  const agents = useItemAgents();
257
- const fetchContext = useRpc(rpc.sessionContext);
258
- const dismiss = useRpc(rpc.dismissItem);
259
- const undismiss = useRpc(rpc.undismissItem);
260
- const restore = useRpc(rpc.restoreDismissed);
261
- const gotIt = useRpc(rpc.gotIt);
262
- const saveHistoryFilter = useRpc(rpc.setHistoryFilter);
263
- const archiveSessions = useRpc(rpc.archiveSessions);
264
- const saveScopes = useRpc(rpc.setScopes);
265
- const saveSources = useRpc(rpc.setSources);
266
- const saveProjects = useRpc(rpc.setProjectFilter);
267
- const closeIssue = useRpc(rpc.closeIssue);
268
- const reopenIssue = useRpc(rpc.reopenIssue);
269
- const update = useRpc(rpc.updateBranch);
270
- const merge = useRpc(rpc.mergePullRequest);
271
- const close = useRpc(rpc.closePullRequest);
272
- const claim = useRpc(rpc.claimIssue);
273
- const unclaim = useRpc(rpc.unclaimIssue);
274
- const setReady = useRpc(rpc.setReady);
275
- const setAutoMerge = useRpc(rpc.setAutoMerge);
276
- const react = useRpc(rpc.react);
277
- const requestReviewers = useRpc(rpc.requestReviewers);
278
- const fetchReviewers = useRpc(rpc.reviewerChoices);
279
- const rerunFailed = useRpc(rpc.rerunFailed);
280
- const fetchDetails = useRpc(rpc.itemDetails);
281
- const setCodeRepo = useRpc(rpc.setCodeRepo);
282
- const fetchDefaultBranch = useRpc(rpc.defaultBranch);
283
- const fetchReadyProviders = useRpc(rpc.readyProviders);
284
- const fetchProviders: FetchProviders = () => fetchReadyProviders({}).then((result) => result.providers);
285
- const defaultBranch: DefaultBranch = async (repo) => (await fetchDefaultBranch({ repo })).name;
78
+ const act = useItemActions(attention, navigation);
286
79
  const [tab, setTab] = useState<TabId>("doing");
287
- // Every card with a change still running: each runs on its own.
288
- const [busy, setBusy] = useState<ReadonlySet<string>>(new Set());
289
- // Sessions archived here, hidden before Paseo's list catches up; in previews, where nothing really archives, this is what
290
- // makes a Wrap up row go away after its screenshot [ATT-22].
291
- const [archivedSessions, setArchivedSessions] = useState<ReadonlySet<string>>(new Set());
292
- const [undoable, setUndoable] = useState<Undoable[]>([]);
293
- const [placing, setPlacing] = useState<Placing | null>(null);
294
- const [options, setOptions] = useState<OptionsSpec | null>(null);
295
80
  // History's Filter sheet: Reviewed and Changed by others per week [HIS-07].
296
81
  const [filtering, setFiltering] = useState(false);
297
82
  // The feedback sheet, then the first words for the kind picked in it [FB-01].
298
83
  const [feedback, setFeedback] = useState<"sheet" | FeedbackKind | null>(null);
84
+ // The New issue sheet, from ⌘K by the screen's params or from Next up [ISS-01].
85
+ const [newIssue, setNewIssue] = useState<Omit<NewIssueRequest, "at"> | null>(null);
86
+ const newIssueAt = params?.newIssue;
87
+ useEffect(() => {
88
+ const request = takeNewIssueRequest(params);
89
+ if (request) setNewIssue(request);
90
+ }, [newIssueAt]);
299
91
  const view = attention.data;
300
92
  // Only when something fails: is it setup, and what's missing [SET-01]?
301
93
  const fetchSetup = useRpc(rpc.setupStatus);
302
94
  const failing = !!attention.error || !!view?.feeds.live.error;
303
95
  const setup = useQuery({ queryKey: ["attention-span", "setup"], queryFn: () => fetchSetup({}), enabled: failing });
304
96
  const [checking, setChecking] = useState(false);
305
- async function run(key: string, label: string, work: () => Promise<unknown>) {
306
- setBusy((keys) => new Set(keys).add(key));
307
- try {
308
- await work();
309
- } catch (error) {
310
- toast.error(`${label} failed: ${(error as Error).message}`);
311
- } finally {
312
- setBusy((keys) => new Set([...keys].filter((other) => other !== key)));
313
- }
314
- }
315
-
316
- // A change from one tap, without confirming: Undo instead, where it can be taken back [SAFE-01, ATT-08, ATT-14].
317
- // The server answers each with the list after it, so nothing needs a refresh.
318
- function change(key: string, label: string, work: () => Promise<AttentionView>, done: string, undo?: () => Promise<AttentionView>, dismissal?: boolean) {
319
- void run(key, label, async () => {
320
- attention.setView(await work());
321
- if (!undo) return toast.show(done, { variant: "success" });
322
- const id = Date.now() + Math.random();
323
- setUndoable((rows) => [...rows, { id, text: done, undo: async () => attention.setView(await undo()), dismissal }]);
324
- });
325
- }
326
-
327
- function openAgent(agentId: string) {
328
- if (navigation?.openAgent) navigation.openAgent({ agentId });
329
- else toast.show("Session started. Open it from the sidebar.", { variant: "success" });
330
- }
331
-
332
- async function started(agentId: string) {
333
- await queryClient.invalidateQueries({ queryKey: AGENTS_QUERY_KEY });
334
- openAgent(agentId);
335
- }
336
-
337
- // One tap: start a session with defaults [SES-01]. An open one is offered first, by the card [SES-03].
338
- async function startWithDefaults(itemKey: string, kind: SessionKind, target: Target, before?: () => Promise<unknown>) {
339
- if (!view) return;
340
- await run(itemKey, "Starting the session", () => startNow(itemKey, kind, target, view.config, before));
341
- }
342
-
343
- async function startNow(itemKey: string, kind: SessionKind, target: Target, config: AttentionConfig, before?: () => Promise<unknown>) {
344
- const checkout = await findCheckout(paseo, config, target, defaultBranch);
345
- // Ask where an issue's code lives before claiming it, so a failed start doesn't leave it taken [SES-07].
346
- if (!checkout.project && target.kind === "issue") return setPlacing({ itemKey, kind, target, missing: checkout.repo, before });
347
- await before?.();
348
- const { context } = await fetchContext({ kind, target });
349
- const prompt = renderPrompt(kind, target, context, config);
350
- await started(await startSession(paseo, { itemKey, kind, target, prompt, config, fetchProviders, checkout }));
351
- }
352
-
353
- function place(codeRepo: string) {
354
- if (!placing) return;
355
- const { itemKey, kind, target, before } = placing;
356
- setPlacing(null);
357
- void run(itemKey, "Starting the session", async () => {
358
- const next = await setCodeRepo({ issueRepo: target.repo, codeRepo });
359
- attention.setView(next);
360
- await startNow(itemKey, kind, target, next.config, before);
361
- });
362
- }
363
97
 
364
98
  if (failing && setup.data && blocks(setup.data)) {
365
99
  const check = async () => {
@@ -386,14 +120,16 @@ function AttentionList({
386
120
  // Each tab shows how fresh its own feed is.
387
121
  const feed = view.feeds[TAB_FEED[tab]];
388
122
  // Wrap up is made here from the sessions the screen and sidebar already poll; the server archives and acknowledges [ATT-22].
389
- const agentsNow = (view.fixtureAgents ?? agents.data ?? []).filter((agent) => !archivedSessions.has(agent.id));
123
+ const agentsNow = (view.fixtureAgents ?? agents.data ?? []).filter((agent) => !act.archivedSessions.has(agent.id));
390
124
  const wrap = wrapItems(view, agentsNow);
391
125
  // Notes about work Already in Wrap up wait there; archiving acknowledges them [HIS-07, ATT-22].
392
126
  const notes = unreadChanges(view.history.filter((item) => item.section === "changed"), wrap);
393
127
  // Calm only once a refresh that worked says Doing is empty, Wrap up included [ATT-18, ATT-22].
394
128
  // Sessions not known yet, or failing to load, leave Wrap up unknown: no calm on that [ATT-18, ATT-22].
395
129
  const sessionsKnown = !!view.fixtureAgents || (agents.isSuccess && !agents.isError);
396
- const clear = sessionsKnown && isClear(view, !!attention.error, wrap.length);
130
+ // A worktree that stayed after its sessions were archived lingers in Wrap up, uncounted, but keeps the calm away [ATT-22].
131
+ const kept = view.kept ?? [];
132
+ const clear = sessionsKnown && isClear(view, !!attention.error, wrap.length + kept.length);
397
133
  // The other tabs' scenes, on the same terms [HIS-08, WAI-04, NXT-13].
398
134
  const calm = {
399
135
  history: historyClear(view, notes.length, !!attention.error),
@@ -403,115 +139,13 @@ function AttentionList({
403
139
  // ⟳ turns for any refresh of this tab's feed, but only my own press locks it: the cached view can still say a background one runs after it's done.
404
140
  const pressed = attention.isRefreshing(TAB_FEED[tab]);
405
141
  const refreshing = feed.refreshing || attention.isFetching || pressed;
406
- const counts: Record<TabId, number> = {
407
- history: view.history.filter((item) => item.section === "done").length,
408
- doing: doingCount(view, wrap),
409
- // Work waiting on several people counts once.
410
- waiting: new Set(view.waiting.flatMap((group) => group.items.map((item) => item.key))).size,
411
- next: view.assigned.length + view.unclaimed.length,
412
- };
142
+ const counts = tabCounts(view, wrap);
413
143
 
414
- const actions: Actions = {
415
- agents: agentsNow,
416
- fixture: !!view.fixtureAgents,
417
- startWithOptions: setOptions,
418
- busy,
419
- config: view.config,
420
- login: view.login,
421
- fetchContext,
422
- fetchDetails,
423
- fetchReviewers,
424
- defaultBranch,
425
- fetchProviders,
426
- openAgent,
427
- started,
428
- act: (item, action) => {
429
- const session = ACTION_SESSION[action];
430
- const { target } = item;
431
- if (action === "reply") return void openExternalUrl(item.person?.url ?? item.url);
432
- // [HIS-07]
433
- if (action === "got_it" && item.change) {
434
- const { id } = item.change;
435
- return change(item.key, "Got it", () => gotIt({ ids: [id], on: true }), `Cleared the note on “${item.title}”`, () => gotIt({ ids: [id], on: false }));
436
- }
437
- if (session) return void startWithDefaults(item.key, session, target);
438
- if (action === "update") change(item.key, "Update", () => update({ key: item.key, target }), `Updating PR ${target.number} with ${target.baseRefName}`);
439
- // [PRS-11]
440
- if (action === "ready")
441
- change(item.key, "Ready for review", () => setReady({ key: item.key, target, ready: true }), `PR ${target.number} is ready for review`, () => setReady({ key: item.key, target, ready: false }));
442
- // [PRS-10]
443
- if (action === "automerge")
444
- change(item.key, "Auto-merge", () => setAutoMerge({ key: item.key, target, on: true }), `PR ${target.number} merges once checks pass`, () => setAutoMerge({ key: item.key, target, on: false }));
445
- },
446
- // [PRS-09]
447
- rerun: (item, known) => {
448
- if (!known) toast.show("Finding the failed jobs to rerun…");
449
- change(
450
- item.key,
451
- "Rerun",
452
- async () => {
453
- const runIds = known ?? summarizeRerun((await queryClient.fetchQuery({ ...itemDetailsQuery(item, fetchDetails), staleTime: DETAILS_STALE_MS })).failing).runIds;
454
- if (runIds.length === 0) throw new Error("no failed GitHub Actions jobs to rerun");
455
- return rerunFailed({ key: item.key, repo: item.target.repo, runIds });
456
- },
457
- `Rerunning the failed jobs of PR ${item.target.number}`,
458
- );
459
- },
460
- // [PRS-12]
461
- requestReviewers: (item, reviewers) => {
462
- const { target } = item;
463
- const names = reviewers.length === 1 ? reviewers[0] : `${reviewers.length} reviewers`;
464
- change(item.key, "Request review", () => requestReviewers({ key: item.key, target, reviewers, on: true }), `Asked ${names} to review PR ${target.number}`, () =>
465
- requestReviewers({ key: item.key, target, reviewers, on: false }),
466
- );
467
- },
468
- // [MEN-07]
469
- acknowledge: (item, ids) =>
470
- change(item.key, "Acknowledge", () => react({ key: item.key, subjectIds: ids, on: true }), `Acknowledged ${ids.length === 1 ? "a comment" : `${ids.length} comments`} on #${item.number}`, () =>
471
- react({ key: item.key, subjectIds: ids, on: false }),
472
- ),
473
- confirm: (item, action, comment) =>
474
- action === "merge"
475
- ? change(item.key, "Merge", () => merge({ key: item.key, target: item.target }), `PR ${item.target.number} merged`)
476
- : change(item.key, "Close", () => close({ key: item.key, target: item.target, comment }), `PR ${item.target.number} closed`),
477
- // Got it on every Changed by others note at once; one Undo brings them all back [HIS-07].
478
- gotItAll: (items) => {
479
- const ids = items.flatMap((item) => (item.change ? [item.change.id] : []));
480
- const notes = `${ids.length} note${ids.length === 1 ? "" : "s"}`;
481
- change(ALL_NOTES, "Mark all as read", () => gotIt({ ids, on: true }), `Cleared ${notes} on changes by others`, () => gotIt({ ids, on: false }));
482
- },
483
- dismiss: (item) => change(item.key, "Dismiss", () => dismiss({ key: item.key }), `Dismissed “${item.title}”`, () => undismiss({ key: item.key }), true),
484
- };
485
-
486
- // Archive sessions, with the busy key that makes it wait for Archive all clean and the other way round [ATT-22].
487
- // No Undo: Paseo's SDK can't restore a workspace and its agents, so the sheet is the safeguard instead.
488
- async function archiveRows(items: WrapItem[], confirm: boolean, key = ALL_WRAP): Promise<ArchiveOutcome | null> {
489
- if (items.length === 0) return null;
490
- setBusy((keys) => new Set(keys).add(key));
491
- try {
492
- const outcome = await archiveSessions({ targets: items.map(archiveTarget), confirm });
493
- attention.setView(outcome.view);
494
- if (outcome.ok) {
495
- const archived = new Set(items.flatMap((item) => item.wrap.sessions.map((session) => session.id)));
496
- setArchivedSessions((known) => new Set([...known, ...archived]));
497
- const sessions = archived.size;
498
- if (outcome.warning) toast.error(outcome.warning);
499
- else toast.show(sessions === 1 ? `Archived the session on #${items[0].number}` : `Archived ${sessions} sessions`, { variant: "success" });
500
- } else if (outcome.reason === "working") {
501
- toast.error(`Couldn't archive: ${outcome.message}`);
502
- }
503
- return outcome;
504
- } catch (error) {
505
- toast.error(`Archive failed: ${(error as Error).message}`);
506
- return null;
507
- } finally {
508
- setBusy((keys) => new Set([...keys].filter((other) => other !== key)));
509
- }
510
- }
144
+ const actions = act.itemActions(view, agentsNow);
511
145
 
512
146
  const switchTab = (id: TabId) => {
513
147
  setTab(id);
514
- setUndoable([]);
148
+ act.clearUndo();
515
149
  };
516
150
 
517
151
  return (
@@ -545,21 +179,12 @@ function AttentionList({
545
179
  {feed.error ? <Text style={styles.danger}>{feed.error}</Text> : null}
546
180
  <UpdateNotice />
547
181
 
548
- {undoable.map((row) => (
182
+ {act.undoable.map((row) => (
549
183
  <View key={row.id} style={[styles.panel, styles.row, { justifyContent: "space-between" }]}>
550
184
  <Text style={[styles.muted, { flexShrink: 1 }]} numberOfLines={1}>
551
185
  {row.text}
552
186
  </Text>
553
- <Button
554
- label="Undo"
555
- variant="calm"
556
- onPress={() =>
557
- void run(String(row.id), "Undo", async () => {
558
- await row.undo();
559
- setUndoable((rows) => rows.filter((other) => other.id !== row.id));
560
- })
561
- }
562
- />
187
+ <Button label="Undo" variant="calm" onPress={() => act.undo(row)} />
563
188
  </View>
564
189
  ))}
565
190
  {tab === "history" ? (
@@ -570,35 +195,32 @@ function AttentionList({
570
195
  filter={view.historyFilter ?? []}
571
196
  filtering={filtering}
572
197
  onFiltering={setFiltering}
573
- onFilter={(next) => {
574
- // Ticks apply right away, like Next up's; the server remembers them [HIS-07].
575
- attention.setView({ ...view, historyFilter: next });
576
- saveHistoryFilter({ filter: next })
577
- .then((saved) => attention.setView(saved))
578
- .catch((error: Error) => toast.error(`Saving the filter failed: ${error.message}`));
579
- }}
580
- busy={busy}
198
+ onFilter={(next) => act.filterHistory(view, next)}
199
+ busy={act.busy}
581
200
  onMarkAllRead={actions.gotItAll}
582
201
  card={(items) => <Card items={items} actions={actions} />}
583
202
  />
584
203
  ) : null}
585
204
  {tab === "doing" ? (
586
205
  <>
587
- {clear ? <Still /> : wrap.length || view.doing.length ? (
206
+ {clear ? <Still /> : wrap.length || kept.length || view.doing.length ? (
588
207
  <>
589
- {wrap.length > 0 ? (
208
+ {wrap.length + kept.length > 0 ? (
590
209
  <WrapUp
591
210
  items={wrap}
592
- busy={busy}
211
+ kept={kept}
212
+ onArchiveWorktree={act.archiveWorktree}
213
+ onDismissKept={act.dismissKept}
214
+ busy={act.busy}
593
215
  login={view.login}
594
216
  fixture={!!view.fixtureAgents}
595
- openAgent={openAgent}
596
- onArchive={(item, confirm) => archiveRows([item], confirm, item.key)}
217
+ openAgent={act.openAgent}
218
+ onArchive={(item, confirm, terminals) => act.archiveRows([item], confirm, item.key, terminals)}
597
219
  onArchiveAll={async () => {
598
220
  const clean = wrap.filter(cleanSingle);
599
221
  if (clean.length === 0) return;
600
- const outcome = await archiveRows(clean, false);
601
- if (outcome && !outcome.ok && outcome.reason === "unsaved") toast.error("Some sessions have unsaved changes. Archive them one by one.");
222
+ const outcome = await act.archiveRows(clean, false);
223
+ if (outcome && !outcome.ok && outcome.reason === "unsaved") toast.error("Some sessions have unsaved changes or open terminals. Archive them one by one.");
602
224
  }}
603
225
  />
604
226
  ) : null}
@@ -611,11 +233,11 @@ function AttentionList({
611
233
  ) : !sessionsKnown ? (
612
234
  <Loading text="Checking your sessions…" />
613
235
  ) : null}
614
- {view.dismissedCount > undoable.filter((row) => row.dismissal).length ? (
236
+ {view.dismissedCount > act.undoable.filter((row) => row.dismissal).length ? (
615
237
  <Pressable
616
238
  accessibilityRole="button"
617
239
  style={clear ? { alignSelf: "center", opacity: 0.7 } : undefined}
618
- onPress={() => void run("restore", "Restore", async () => (attention.setView(await restore({})), setUndoable([])))}
240
+ onPress={act.restoreDismissed}
619
241
  >
620
242
  <Text style={styles.muted}>{view.dismissedCount} dismissed · show them again</Text>
621
243
  </Pressable>
@@ -637,55 +259,32 @@ function AttentionList({
637
259
  selectedSources={view.sources}
638
260
  projects={view.projects}
639
261
  selectedProjects={view.projectFilter}
640
- // One setView for all, so clearing them together can't put any back.
641
- onFilter={(change) => {
642
- attention.setView({ ...view, ...change });
643
- const failed = (error: Error) => toast.error(`Saving the filter failed: ${error.message}`);
644
- if (change.scopes) saveScopes({ scopes: change.scopes }).catch(failed);
645
- if (change.sources) saveSources({ sources: change.sources }).catch(failed);
646
- if (change.projectFilter) saveProjects({ projects: change.projectFilter }).catch(failed);
647
- }}
262
+ onFilter={(change) => act.filterNextUp(view, change)}
263
+ // Narrowed to one repository, a new issue starts there [ISS-01].
264
+ onNewIssue={() => setNewIssue({ nextUp: view.sources.length === 1 && view.sources[0].startsWith("repo:") ? view.sources[0].slice(5) : undefined })}
648
265
  agents={actions.agents}
649
266
  login={view.login}
650
- busy={busy}
651
- fetchDetails={fetchDetails}
652
- onOpenAgent={openAgent}
653
- onStart={(issue, claimFirst) => {
654
- const target = issueTarget(issue);
655
- void startWithDefaults(issue.key, "start", target, claimFirst ? async () => attention.setView(await claim({ key: issue.key, target })) : undefined);
656
- }}
657
- onOptions={(issue, claimFirst, label) => {
658
- const target = issueTarget(issue);
659
- setOptions({ itemKey: issue.key, title: `${label}: ${issue.title}`, kind: "start", target, before: claimFirst ? async () => attention.setView(await claim({ key: issue.key, target })) : undefined });
660
- }}
661
- // Claim without starting, or give it back; each undoes the other [NXT-07].
662
- onClaim={(issue, on) => {
663
- const target = issueTarget(issue);
664
- const [take, giveBack] = [() => claim({ key: issue.key, target }), () => unclaim({ key: issue.key, target })];
665
- change(issue.key, on ? "Claim" : "Unclaim", on ? take : giveBack, `${on ? "Claimed" : "Unclaimed"} #${issue.number}`, on ? giveBack : take);
666
- }}
667
- // Undo reopens; a comment already posted stays [NXT-11].
668
- onCloseIssue={(issue, reason, comment) => {
669
- const target = issueTarget(issue);
670
- const done = `Closed #${issue.number} as ${reason === "completed" ? "completed" : "not planned"}`;
671
- change(issue.key, "Close", () => closeIssue({ key: issue.key, target, reason, comment: comment || undefined }), done, () => reopenIssue({ key: issue.key, target }));
672
- }}
267
+ busy={act.busy}
268
+ fetchDetails={act.fetchDetails}
269
+ onOpenAgent={act.openAgent}
270
+ {...act.issueActions}
673
271
  />
674
272
  ) : null}
675
273
  <FeedbackLine onPress={() => setFeedback("sheet")} />
676
- {feedback === "sheet" ? <FeedbackSheet agents={actions.agents} onOpenAgent={openAgent} onAsk={setFeedback} onClose={() => setFeedback(null)} /> : null}
274
+ {feedback === "sheet" ? <FeedbackSheet agents={actions.agents} onOpenAgent={act.openAgent} onAsk={setFeedback} onClose={() => setFeedback(null)} /> : null}
677
275
  {feedback && feedback !== "sheet" ? (
678
276
  <FeedbackAsk
679
277
  kind={feedback}
680
278
  config={view.config}
681
279
  screen={{ ...device, tab, refreshError: feed.error ?? null }}
682
- onStarted={started}
280
+ onStarted={act.started}
683
281
  onBack={() => setFeedback("sheet")}
684
282
  onClose={() => setFeedback(null)}
685
283
  />
686
284
  ) : null}
687
- {options ? <SessionOptions spec={options} actions={actions} onClose={() => setOptions(null)} /> : null}
688
- {placing ? <CodeRepoPicker issueRepo={placing.target.repo} missing={placing.missing} onPick={place} onClose={() => setPlacing(null)} /> : null}
285
+ {newIssue ? <NewIssueSheet request={newIssue} view={view} onView={attention.setView} onStarted={act.started} onClose={() => setNewIssue(null)} /> : null}
286
+ {act.options ? <SessionOptions spec={act.options} config={view.config} started={act.startedOn} onClose={act.closeOptions} /> : null}
287
+ {act.placing ? <CodeRepoPicker issueRepo={act.placing.target.repo} missing={act.placing.missing} onPick={act.place} onClose={act.cancelPlacing} /> : null}
689
288
  </ScrollView>
690
289
  );
691
290
  }
@@ -714,547 +313,6 @@ function Tab({ icon, label, count, active, dot, onPress }: { icon: IconName; lab
714
313
  );
715
314
  }
716
315
 
717
- // A theme colour, see-through, so a badge reads on any surface; colours that aren't #rrggbb fall back to none.
718
- function tint(color: string, alpha: number): string {
719
- const hex = /^#([0-9a-f]{6})/i.exec(color)?.[1];
720
- if (!hex) return "transparent";
721
- const [r, g, b] = [0, 2, 4].map((at) => parseInt(hex.slice(at, at + 2), 16));
722
- return `rgba(${r}, ${g}, ${b}, ${alpha})`;
723
- }
724
-
725
- interface Actions {
726
- agents: AgentSummary[];
727
- // Previews have made-up sessions: show their sheets locally instead of asking a daemon that has none.
728
- fixture: boolean;
729
- startWithOptions: (spec: OptionsSpec) => void;
730
- busy: ReadonlySet<string>;
731
- config: AttentionConfig;
732
- login: string | null;
733
- fetchContext: FetchContext;
734
- fetchDetails: FetchDetails;
735
- fetchReviewers: FetchReviewers;
736
- defaultBranch: DefaultBranch;
737
- fetchProviders: FetchProviders;
738
- act: (item: Item, action: ActionId) => void;
739
- requestReviewers: (item: Item, reviewers: string[]) => void;
740
- // Without run ids, it finds them first: Rerun pressed before the sheet had the failing checks.
741
- rerun: (item: Item, runIds?: number[]) => void;
742
- acknowledge: (item: Item, commentIds: string[]) => void;
743
- confirm: (item: Item, action: "merge" | "close", comment?: string) => void;
744
- dismiss: (item: Item) => void;
745
- gotItAll: (items: Item[]) => void;
746
- openAgent: (agentId: string) => void;
747
- started: (agentId: string) => Promise<void>;
748
- }
749
-
750
- // A card that works collapsed: its main action and ›. Tapping it opens the sheet with everything else [ATT-05, ATT-06].
751
- const isRed = (chips: Chip[]) => chips.some((chip) => chip.tone === "bad");
752
-
753
- // The sheet, Acknowledge, or the reviewer picker (after Ready for review, or on its own).
754
- type Sheet = "item" | "acknowledge" | "reviewers" | "reviewers-after-ready" | null;
755
-
756
- // A session on an item that has no session action of its own starts with this prompt; it's editable first.
757
- const fallbackKind = (item: Item): SessionKind => (item.target.kind === "issue" ? "start" : "review");
758
-
759
- // 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
760
- // fair, the age itself turns amber with ⌛ and says so in words [WAI-01, ATT-11].
761
- function waitChips(item: Item, inWaiting: boolean, tooLongDays: number): Chip[] {
762
- const { wait } = item;
763
- if (!wait || !inWaiting) return [];
764
- const age = ago(wait.since);
765
- const reason: Chip[] = wait.reason ? [{ text: wait.reason, tone: "neutral" }] : [];
766
- if (!wait.tooLong) return [...reason, { text: age, tone: "neutral" }];
767
- const since = wait.reason === "question" ? "you asked" : "your last push or reply";
768
- const limit = `${tooLongDays} day${tooLongDays === 1 ? "" : "s"}`;
769
- return [...reason, { text: age, tone: "warn", icon: "hourglass", hint: `Waited too long: ${age} since ${since}, more than ${limit}` }];
770
- }
771
-
772
- // "Review 2h", "Question 3d": why and how long, to lead a line in a nudge [WAI-03].
773
- function nudgeLead(item: Item): string | undefined {
774
- if (!item.wait) return undefined;
775
- const { reason, since } = item.wait;
776
- return reason ? `${reason[0].toUpperCase()}${reason.slice(1)} ${ago(since)}` : ago(since);
777
- }
778
-
779
- const samePerson = (a: WaitingOn, b: WaitingOn) => a.team === b.team && a.login.toLowerCase() === b.login.toLowerCase();
780
-
781
- // In Waiting, a card sits under one of whom it waits on: its group.
782
- function ItemRow({ item, first, actions, group }: { item: Item; first: boolean; actions: Actions; group?: WaitingGroup }) {
783
- const styles = useStyles();
784
- // An open session leads; without one, the item's own action does [SES-03].
785
- const sessions = itemSessions(actions.agents, item);
786
- const waits = waitChips(item, !!group, actions.config.waitingTooLongDays);
787
- // The group names one; the card names the rest [WAI-01].
788
- const others = group?.who ? (item.waitingOn ?? []).filter((who) => !samePerson(who, group.who!)) : [];
789
- const waitingOn = group ? null : item.waitingOn ? <WaitingOnLine people={item.waitingOn} asked={item.wait?.reason === "question"} expanded={false} /> : null;
790
- const alsoOn = others.length ? <Text style={styles.muted}>also waiting on {others.map((who) => who.login).join(", ")}</Text> : null;
791
- const [sheet, setSheet] = useState<Sheet>(null);
792
- const [confirm, setConfirm] = useState<"merge" | "close" | null>(null);
793
- const main = item.actions[0];
794
- // 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
795
- // 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].
796
- const target = targetUrl(item);
797
- const needing = item.children.some((child) => child.attention || isRed(child.chips));
798
- const children = needing ? item.children.filter((child) => child.attention || isRed(child.chips) || child.url === target) : [];
799
- const targetRow = children.find((child) => child.url === target);
800
- const shown = [...waits, ...stackMetaChips(item, targetRow)];
801
- const chips = sessions[0] ? [...shown, agentSignal(sessions[0])] : shown;
802
- // The sheet opens at once; what it fetches fills in [ATT-06].
803
- const open = () => setSheet("item");
804
- const prefetch = usePrefetchOnRest(itemDetailsQuery(item, actions.fetchDetails));
805
- const copy = useCopy();
806
- const history = SECTIONS[item.section].tab === "history";
807
-
808
- function perform(action: ActionId) {
809
- setSheet(null);
810
- if (action === "merge" || action === "close") setConfirm(action);
811
- else if (action === "acknowledge") setSheet("acknowledge");
812
- else if (action === "request_review") setSheet("reviewers");
813
- // A draft made ready goes straight on to who should review it [PRS-11].
814
- else if (action === "ready") (actions.act(item, action), setSheet("reviewers-after-ready"));
815
- else actions.act(item, action);
816
- }
817
- const handlers: SheetHandlers = { onPerform: perform, onClose: () => setSheet(null) };
818
- // A sheet with one action is a wasted tap: show that action instead of ›. The card still opens the sheet, quiet lines and all [ATT-06].
819
- const loud = sheetEntries(item, sessions, actions, handlers).filter((entry) => !entry.quiet);
820
- const only = loud.length === 1 ? loud[0] : undefined;
821
- const confirmed = (action: "merge" | "close") => (comment: string) => (setConfirm(null), actions.confirm(item, action, comment));
822
-
823
- return (
824
- <CardRow
825
- first={first}
826
- mark={stateMark(item)}
827
- title={item.title}
828
- meta={{
829
- place: { repo: item.repo, number: item.number, login: actions.login },
830
- when: item.change
831
- ? changeText(item.change)
832
- : item.closedAt
833
- ? `${item.kind === "pr" ? "merged" : "closed"} ${ago(item.closedAt)} ago${(item.kind === "pr" ? item.mergedBy : item.closedBy) ? ` by ${item.kind === "pr" ? item.mergedBy : item.closedBy}` : ""}${item.notPlanned ? " as not planned" : ""}`
834
- : undefined,
835
- signals: chips,
836
- }}
837
- extra={
838
- item.person || waitingOn || alsoOn || children.length > 0 ? (
839
- <>
840
- {item.person ? <PersonQuote person={item.person} expanded={false} /> : null}
841
- {waitingOn}
842
- {alsoOn}
843
- {children.length > 0 ? <StackLine rows={children} merged={!!item.closedAt} target={targetRow?.key} /> : null}
844
- </>
845
- ) : null
846
- }
847
- onOpen={open}
848
- hover={prefetch}
849
- busy={item.change ? noteBusy(actions.busy, item.key) : actions.busy.has(item.key)}
850
- primary={
851
- sessions[0]
852
- ? { label: "Open session", icon: "agent", onPress: () => actions.openAgent(sessions[0].id) }
853
- : main
854
- ? { label: actionLabel(main, item), icon: ACTION_ICONS[main], iconOnly: main === "got_it", onPress: () => perform(main) }
855
- : undefined
856
- }
857
- secondary={[
858
- only ? { label: only.label, accessibilityLabel: only.accessibilityLabel, icon: only.icon, onPress: only.onPress } : { label: `Details for #${item.number}`, icon: "chevronRight", onPress: open },
859
- // History is where I report from, so its cards copy their link in one tap [ATT-15]. Unread notes are not report rows.
860
- ...(history && item.section !== "changed" ? [{ label: `Copy link to #${item.number}`, icon: "copy" as const, onPress: () => copy(item.url, `Copied link to #${item.number}`) }] : []),
861
- ]}
862
- confirm={
863
- confirm === "merge"
864
- ? {
865
- text: `Merge PR ${item.target.number} into ${item.target.baseRefName} (${item.target.mergeMethod})?`,
866
- choices: [{ label: "Merge", icon: "merge", solid: true, onConfirm: confirmed("merge") }],
867
- onCancel: () => setConfirm(null),
868
- }
869
- : confirm === "close"
870
- ? {
871
- text: `Close PR ${item.target.number}? A comment is only posted if you write one.`,
872
- comment: true,
873
- choices: [{ label: "Close PR", icon: "close", solid: true, onConfirm: confirmed("close") }],
874
- onCancel: () => setConfirm(null),
875
- }
876
- : null
877
- }
878
- overlay={
879
- <>
880
- {sheet === "item" ? <ItemSheet item={item} waitChips={waits} sessions={sessions} actions={actions} {...handlers} /> : null}
881
- {sheet === "acknowledge" ? <AcknowledgeSheet item={item} onReact={(ids) => (setSheet(null), actions.acknowledge(item, ids))} onClose={() => setSheet(null)} /> : null}
882
- {sheet === "reviewers" || sheet === "reviewers-after-ready" ? (
883
- <ReviewerSheet
884
- item={item}
885
- afterReady={sheet === "reviewers-after-ready"}
886
- fetchReviewers={actions.fetchReviewers}
887
- onRequest={(reviewers) => (setSheet(null), actions.requestReviewers(item, reviewers))}
888
- onClose={() => setSheet(null)}
889
- />
890
- ) : null}
891
- </>
892
- }
893
- />
894
- );
895
- }
896
-
897
- interface SheetHandlers {
898
- onPerform: (action: ActionId) => void;
899
- onClose: () => void;
900
- }
901
-
902
- // What the card already knows on top, then every action, then what's fetched when it opens, so nothing jumps as it loads [ATT-06, GH-01].
903
- // What an item's sheet fetches when it opens; resting the pointer on its card fetches the same ahead. `checks` asks for
904
- // failing checks too, for Rerun.
905
- function itemDetailsQuery(item: Item, fetchDetails: FetchDetails): DetailsQuery {
906
- const checks = item.actions.includes("rerun");
907
- const subject = { kind: item.kind, repo: item.repo, number: item.number };
908
- return { queryKey: detailsKey(subject, item.target, checks), queryFn: () => fetchDetails({ subject, target: item.target, checks }) };
909
- }
910
-
911
- // The PR an item's actions apply to, where that isn't the item itself, like an issue's PR.
912
- const targetUrl = (item: Item) => (item.target.number !== item.number || item.target.kind !== item.kind ? item.target.url : undefined);
913
-
914
- // 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
915
- // 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
916
- // shows the row; a card only when a PR in the stack needs attention [ATT-04, ATT-06].
917
- function stackMetaChips(item: Item, targetRow: SubRow | undefined): Chip[] {
918
- if (!targetRow) return item.chips;
919
- const onRow = new Set(targetRow.chips.map((chip) => chip.text));
920
- return item.chips.filter((chip) => !/^PR #\d+$/.test(chip.text) && !/^stack of \d+$/.test(chip.text) && !onRow.has(chip.text));
921
- }
922
-
923
- function ItemSheet({ item, waitChips, sessions, actions, ...handlers }: { item: Item; waitChips: Chip[]; sessions: AgentSummary[]; actions: Actions } & SheetHandlers) {
924
- const details = useQuery({ ...itemDetailsQuery(item, actions.fetchDetails), staleTime: DETAILS_STALE_MS });
925
- const arrived = useArrived(details.isLoading);
926
- const elsewhere = !!targetUrl(item);
927
- // The row of the PR its actions apply to, where it's in the stack line: marked there instead of named on top.
928
- const targetRow = elsewhere ? item.children.find((child) => child.url === item.target.url) : undefined;
929
- const meta = elsewhere && !targetRow ? [`actions apply to PR #${item.target.number}`] : [];
930
- // PRs already in the stack line link from there; list only the rest, like someone else's PR closing the same issue.
931
- const shown = new Set(item.children.map((child) => child.url));
932
- const extra = details.data && { ...details.data, linked: details.data.linked.filter((link) => !shown.has(link.url)) };
933
- return (
934
- <ActionSheet
935
- title={item.title}
936
- onClose={handlers.onClose}
937
- top={
938
- <>
939
- {/* Number first, as on the card; the sheet always names the owner, even of my own repos [ATT-20]. */}
940
- <Meta lead={<PlaceText place={{ repo: item.repo, number: item.number, login: null }} />} facts={meta} chips={[...waitChips, ...stackMetaChips(item, targetRow)]} />
941
- {item.person ? <PersonQuote person={item.person} expanded /> : null}
942
- {item.waitingOn ? <WaitingOnLine people={item.waitingOn} asked={item.wait?.reason === "question"} expanded /> : null}
943
- {item.children.length > 0 ? <StackLine rows={item.children} merged={!!item.closedAt} links target={targetRow?.key} /> : null}
944
- </>
945
- }
946
- entries={sheetEntries(item, sessions, actions, handlers, { data: details.data, isLoading: details.isLoading, arrived })}
947
- // The PR its actions apply to has a size line, named where it isn't the item; an issue's PRs are in its stack line
948
- // already, so few more come [ATT-06].
949
- bottom={
950
- <DetailLines
951
- details={extra}
952
- loading={details.isLoading}
953
- error={details.error}
954
- linkedLabel={item.kind === "issue" ? "PR" : "Closes"}
955
- expected={item.target.kind === "pr" ? 1 : 0}
956
- sizeOf={elsewhere ? item.target.number : undefined}
957
- />
958
- }
959
- />
960
- );
961
- }
962
-
963
- // Everything an item's sheet offers, each saying what it will do [ATT-06]. Rerun's line says more once the checks are in.
964
- function sheetEntries(
965
- item: Item,
966
- sessions: AgentSummary[],
967
- actions: Actions,
968
- { onPerform, onClose }: SheetHandlers,
969
- details?: SheetDetails,
970
- ): SheetEntry[] {
971
- const inDoing = SECTIONS[item.section].tab === "doing";
972
- const close = (then: () => void) => () => (onClose(), then());
973
-
974
- const open = (agentId: string) => close(() => actions.openAgent(agentId))();
975
- const withOptions = (label: string, kind: SessionKind) => close(() => actions.startWithOptions({ itemKey: item.key, title: `${label}: ${item.title}`, kind, target: item.target }));
976
- // Sessions none of its actions would start lead, needs me first [SES-03].
977
- const kinds = item.actions.flatMap((action) => ACTION_SESSION[action] ?? []);
978
- const entries: SheetEntry[] = looseSessions(sessions, kinds).map((agent) => sessionEntry(agent, sessionLabel(agent.kind, item), open));
979
- for (const action of item.actions) {
980
- const kind = ACTION_SESSION[action];
981
- const label = actionLabel(action, item);
982
- if (kind) {
983
- // An action's session takes its line once it runs, so work on it stays in one place [SES-03].
984
- // Until then it asks first: the card's button is the one-tap start [SES-01, SES-02].
985
- const running = sessions.filter((agent) => agent.kind === kind);
986
- if (running.length) entries.push(...running.map((agent) => sessionEntry(agent, sessionLabel(kind, item), open)));
987
- else entries.push({ key: action, icon: "agent", label: `${label}…`, detail: actionDetail(action as Exclude<ActionId, "rerun">, item), onPress: withOptions(label, kind) });
988
- } else if (action === "rerun") {
989
- entries.push(rerunEntry(label, details, (runIds) => close(() => actions.rerun(item, runIds))()));
990
- } else {
991
- // Closing it sits apart, below the work, with Dismiss [ATT-06].
992
- entries.push({ key: action, icon: ACTION_ICONS[action], label, detail: actionDetail(action, item), housekeeping: action === "close", onPress: () => onPerform(action) });
993
- }
994
- }
995
- // Anything Attention Span doesn't cover [ATT-12], with an issue's PR beside it: the one its actions apply to, or in
996
- // History, where an issue is its own target, the first of the PRs that closed it.
997
- const pr = targetUrl(item) && item.target.kind === "pr" ? item.target : item.kind === "issue" && item.children[0] ? item.children[0] : undefined;
998
- entries.push(githubEntry(item, (url) => close(() => void openExternalUrl(url))(), pr));
999
- // 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].
1000
- if (!item.closedAt && !item.change) entries.push(startAnotherEntry(sessions.length > 0, withOptions("Start session", fallbackKind(item))));
1001
- if (inDoing && !item.change) entries.push({ key: "dismiss", icon: "dismiss", label: "Dismiss", detail: "Hides it until something new happens on it", housekeeping: true, onPress: close(() => actions.dismiss(item)) });
1002
- return entries;
1003
- }
1004
-
1005
- // A session is named for what started it; one of no kind, or a Start's, just continues.
1006
- const sessionLabel = (kind: SessionKind | undefined, item: Item) => (kind && kind !== "start" ? actionLabel(kind, item) : "Continue session");
1007
-
1008
- // Pick which waiting comments get a 👍, after reading them in full; all are picked to start [MEN-07].
1009
- function AcknowledgeSheet({ item, onReact, onClose }: { item: Item; onReact: (ids: string[]) => void; onClose: () => void }) {
1010
- const styles = useStyles();
1011
- const comments = item.person?.comments ?? [];
1012
- const [picked, setPicked] = useState(() => new Set(comments.map((c) => c.id)));
1013
- const toggle = (id: string) => setPicked((now) => (now.has(id) ? new Set([...now].filter((other) => other !== id)) : new Set([...now, id])));
1014
- return (
1015
- <Modal title={`Acknowledge: ${item.title}`} open onOpenChange={(open) => (open ? null : onClose())}>
1016
- <Modal.Content>
1017
- <KeepStyles styles={styles}>
1018
- <View style={styles.row}>
1019
- <TablerIcon name="thumbUp" size={14} />
1020
- <Text style={[styles.muted, { flexShrink: 1 }]}>Tells them you've seen it, and clears it from your list.</Text>
1021
- </View>
1022
- {comments.map((c) => (
1023
- <Pressable
1024
- key={c.id}
1025
- accessibilityRole="checkbox"
1026
- accessibilityState={{ checked: picked.has(c.id) }}
1027
- accessibilityLabel={`Comment from ${c.author}`}
1028
- onPress={() => toggle(c.id)}
1029
- style={[styles.quote, styles.row, { alignItems: "flex-start", gap: 10 }]}
1030
- >
1031
- <TablerIcon name={picked.has(c.id) ? "squareCheck" : "square"} size={18} color={picked.has(c.id) ? styles.action : styles.c.foregroundMuted} />
1032
- <View style={{ flex: 1, gap: 4 }}>
1033
- <Text style={{ color: styles.c.foreground, fontSize: 12, fontWeight: "600" }}>
1034
- {c.author} <Text style={[styles.muted, { fontWeight: "400" }]}>· {ago(c.createdAt)}</Text>
1035
- </Text>
1036
- <Markdown>{c.body}</Markdown>
1037
- </View>
1038
- </Pressable>
1039
- ))}
1040
- <View style={styles.wrap}>
1041
- <Button
1042
- label={`${picked.size} comment${picked.size === 1 ? "" : "s"}`}
1043
- icon="thumbUp"
1044
- accessibilityLabel={`Acknowledge ${picked.size} comment${picked.size === 1 ? "" : "s"}`}
1045
- variant="solid"
1046
- disabled={picked.size === 0}
1047
- onPress={() => onReact(comments.filter((c) => picked.has(c.id)).map((c) => c.id))}
1048
- />
1049
- <Button label="Cancel" onPress={onClose} />
1050
- </View>
1051
- </KeepStyles>
1052
- </Modal.Content>
1053
- </Modal>
1054
- );
1055
- }
1056
-
1057
- // Who should review a PR: GitHub's suggestions, who reviewed my other PRs in the repo, its teams, or anyone typed in.
1058
- // All start unticked; requesting keeps whoever is already asked [PRS-12].
1059
- function ReviewerSheet({
1060
- item,
1061
- afterReady,
1062
- fetchReviewers,
1063
- onRequest,
1064
- onClose,
1065
- }: {
1066
- item: Item;
1067
- afterReady: boolean;
1068
- fetchReviewers: FetchReviewers;
1069
- onRequest: (reviewers: string[]) => void;
1070
- onClose: () => void;
1071
- }) {
1072
- const styles = useStyles();
1073
- const choices = useQuery({ queryKey: ["attention-span", "reviewers", item.target.repo, item.target.number], queryFn: () => fetchReviewers({ target: item.target }), staleTime: 60_000 });
1074
- const [picked, setPicked] = useState<ReadonlySet<string>>(new Set());
1075
- const [typed, setTyped] = useState<Reviewer[]>([]);
1076
- const [text, setText] = useState("");
1077
- const toggle = (login: string) => setPicked((now) => (now.has(login) ? new Set([...now].filter((other) => other !== login)) : new Set([...now, login])));
1078
- // Each person or team once, in the first group that has them.
1079
- const seen = new Set<string>();
1080
- const once = (list: Reviewer[]) => list.filter((reviewer) => !seen.has(reviewer.login.toLowerCase()) && seen.add(reviewer.login.toLowerCase()));
1081
- const groups = [
1082
- { title: "Added", list: once(typed) },
1083
- { title: "Suggested by GitHub", list: once(choices.data?.suggested ?? []) },
1084
- { title: "Recent on your PRs here", list: once(choices.data?.recent ?? []) },
1085
- { title: "Teams", list: once(choices.data?.teams ?? []) },
1086
- ];
1087
- const add = () => {
1088
- const login = text.trim().replace(/^@/, "");
1089
- if (!login) return;
1090
- setTyped((now) => [...now, { login, team: login.includes("/") }]);
1091
- setPicked((now) => new Set([...now, login]));
1092
- setText("");
1093
- };
1094
- const count = `${picked.size} reviewer${picked.size === 1 ? "" : "s"}`;
1095
- return (
1096
- <Modal title={`${afterReady ? "Ready for review" : "Request review"}: ${item.title}`} open onOpenChange={(open) => (open ? null : onClose())}>
1097
- <Modal.Content>
1098
- <KeepStyles styles={styles}>
1099
- <Text style={styles.muted}>{afterReady ? `PR ${item.target.number} is out of draft. Who should review it?` : `Who should review PR ${item.target.number}?`}</Text>
1100
- {choices.isLoading ? <Loading text="Loading suggestions…" /> : null}
1101
- {choices.error ? <Text style={styles.danger}>Couldn't load suggestions: {(choices.error as Error).message}</Text> : null}
1102
- {groups.map(({ title, list }) =>
1103
- list.length > 0 ? (
1104
- <View key={title} style={{ gap: 4 }}>
1105
- <Text style={[styles.muted, { fontSize: 12 }]}>{title}</Text>
1106
- {list.map((reviewer) => (
1107
- <Pressable
1108
- key={reviewer.login}
1109
- accessibilityRole="checkbox"
1110
- accessibilityState={{ checked: picked.has(reviewer.login) }}
1111
- accessibilityLabel={reviewer.login}
1112
- onPress={() => toggle(reviewer.login)}
1113
- style={[styles.row, { paddingVertical: 4 }]}
1114
- >
1115
- <TablerIcon name={picked.has(reviewer.login) ? "squareCheck" : "square"} size={18} color={picked.has(reviewer.login) ? styles.action : styles.c.foregroundMuted} />
1116
- {reviewer.team ? <TablerIcon name="claim" size={18} color={styles.c.foregroundMuted} /> : <Avatar url={reviewer.avatarUrl} />}
1117
- <Text style={{ color: styles.c.foreground, fontSize: 13 }}>{reviewer.login}</Text>
1118
- </Pressable>
1119
- ))}
1120
- </View>
1121
- ) : null,
1122
- )}
1123
- {choices.data?.teamsNote ? <Text style={styles.muted}>{choices.data.teamsNote}</Text> : null}
1124
- <View style={styles.row}>
1125
- <TextInput
1126
- style={[styles.input, { flex: 1 }]}
1127
- placeholder="Login, or org/team"
1128
- placeholderTextColor={styles.c.foregroundMuted}
1129
- value={text}
1130
- onChangeText={setText}
1131
- onSubmitEditing={add}
1132
- autoCapitalize="none"
1133
- autoCorrect={false}
1134
- />
1135
- <Button label="Add" variant="calm" disabled={!text.trim()} onPress={add} />
1136
- </View>
1137
- <View style={styles.wrap}>
1138
- <Button
1139
- label={`Request ${count}`}
1140
- icon="claim"
1141
- variant="solid"
1142
- disabled={picked.size === 0}
1143
- onPress={() => onRequest([...picked])}
1144
- />
1145
- <Button label={afterReady ? "Skip" : "Cancel"} onPress={onClose} />
1146
- </View>
1147
- </KeepStyles>
1148
- </Modal.Content>
1149
- </Modal>
1150
- );
1151
- }
1152
-
1153
- // What a face on a card is to it, where no quote says it: the icon of the tab or section that means the same, so whom I wait on
1154
- // reads like Waiting, and whose comments are left like Changes requested [ATT-19].
1155
- const ROLE_ICON: Record<PersonRole | "waiting", IconName> = { waiting: "hourglass", author: "pencil", changes: "changes" };
1156
-
1157
- // The icon sits tight against the faces it explains, apart from the name and time, so they read as one.
1158
- function Badged({ role, children }: { role: keyof typeof ROLE_ICON; children: ReactNode }) {
1159
- const styles = useStyles();
1160
- return (
1161
- <View style={{ flexDirection: "row", alignItems: "center", gap: 2 }}>
1162
- <TablerIcon name={ROLE_ICON[role]} size={16} color={styles.c.foregroundMuted} />
1163
- {children}
1164
- </View>
1165
- );
1166
- }
1167
-
1168
- // Who is waiting on me, or who I'm waiting on.
1169
- function PersonQuote({ person, expanded }: { person: NonNullable<Item["person"]>; expanded: boolean }) {
1170
- const styles = useStyles();
1171
- const name = <Text style={{ color: styles.c.foreground, fontSize: 12, fontWeight: "600" }}>{person.login}</Text>;
1172
- // An author line says who, not when: its time meant something different on each tab [ATT-19].
1173
- if (!person.snippet && person.role) {
1174
- const text = person.role === "author" ? `Opened by ${person.login}` : `${person.login}'s comments are left to address, since your last push ${ago(person.since)} ago`;
1175
- return (
1176
- <Hint text={text}>
1177
- <View style={styles.row}>
1178
- <Badged role={person.role}>
1179
- <Avatar url={person.avatarUrl} bot={person.bot} />
1180
- </Badged>
1181
- {name}
1182
- {person.role === "author" ? null : <Text style={styles.muted}>· {ago(person.since)}</Text>}
1183
- </View>
1184
- </Hint>
1185
- );
1186
- }
1187
- const line = (
1188
- <View style={styles.row}>
1189
- <Avatar url={person.avatarUrl} bot={person.bot} />
1190
- {name}
1191
- <Text style={styles.muted}>· {ago(person.since)}</Text>
1192
- </View>
1193
- );
1194
- if (!person.snippet) return line;
1195
- return (
1196
- <View style={styles.quote}>
1197
- {line}
1198
- <Text style={{ color: styles.c.foreground, fontSize: 13, lineHeight: 18 }} numberOfLines={expanded ? undefined : 2}>
1199
- {person.snippet}
1200
- </Text>
1201
- </View>
1202
- );
1203
- }
1204
-
1205
- // Pictures on a card before the rest are counted, so a crowd fits a phone; the sheet names everyone.
1206
- const MAX_FACES = 5;
1207
-
1208
- // Who my work waits on: one by name, several by picture, named on hover, and each by name in the sheet [WAI-02].
1209
- // On an issue they're who my question tagged; on a PR, reviewers since my last push or reply [WAI-02, ATT-19].
1210
- function WaitingOnLine({ people, asked, expanded }: { people: WaitingOn[]; asked: boolean; expanded: boolean }) {
1211
- const styles = useStyles();
1212
- const [hovered, setHovered] = useState<string | null>(null);
1213
- const name = (login: string) => (
1214
- <Text style={{ color: styles.c.foreground, fontSize: 12, fontWeight: "600", flexShrink: 1 }} numberOfLines={1}>
1215
- {login}
1216
- </Text>
1217
- );
1218
- const since = (at: string) => <Text style={styles.muted}>· {ago(at)}</Text>;
1219
- const explain = (logins: string[], at: string) => `Waiting on ${logins.join(", ")} since ${asked ? "you asked" : "your last push or reply"}, ${ago(at)} ago`;
1220
- if (expanded || people.length === 1) {
1221
- return (
1222
- <View style={{ gap: 6 }}>
1223
- {people.map((who) => (
1224
- <Hint key={who.login} text={explain([who.login], who.since)}>
1225
- <View style={styles.row}>
1226
- <Badged role="waiting">
1227
- <Avatar url={who.avatarUrl} team={who.team} />
1228
- </Badged>
1229
- {name(who.login)}
1230
- {since(who.since)}
1231
- </View>
1232
- </Hint>
1233
- ))}
1234
- </View>
1235
- );
1236
- }
1237
- const earliest = people.map((who) => who.since).sort()[0];
1238
- return (
1239
- <Hint text={explain(people.map((who) => who.login), earliest)}>
1240
- <View style={styles.row}>
1241
- <Badged role="waiting">
1242
- <View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
1243
- {people.slice(0, MAX_FACES).map((who) => (
1244
- <View key={who.login} onPointerEnter={() => setHovered(who.login)} onPointerLeave={() => setHovered((current) => (current === who.login ? null : current))}>
1245
- <Avatar url={who.avatarUrl} team={who.team} />
1246
- </View>
1247
- ))}
1248
- {people.length > MAX_FACES ? <Text style={styles.muted}>+{people.length - MAX_FACES}</Text> : null}
1249
- </View>
1250
- </Badged>
1251
- {hovered ? name(hovered) : null}
1252
- {since(earliest)}
1253
- </View>
1254
- </Hint>
1255
- );
1256
- }
1257
-
1258
316
  function Sections({ sections, actions }: { sections: Section[]; actions: Actions }) {
1259
317
  return sections.map((section) => (
1260
318
  <View key={section.id}>
@@ -1264,16 +322,6 @@ function Sections({ sections, actions }: { sections: Section[]; actions: Actions
1264
322
  ));
1265
323
  }
1266
324
 
1267
- function Card({ items, actions, group }: { items: Item[]; actions: Actions; group?: WaitingGroup }) {
1268
- return (
1269
- <CardList>
1270
- {items.map((item, index) => (
1271
- <ItemRow key={item.key} item={item} first={index === 0} actions={actions} group={group} />
1272
- ))}
1273
- </CardList>
1274
- );
1275
- }
1276
-
1277
325
  // Waiting by who it waits on, each with a list to copy for a nudge, oldest first; a bot gets none, as there's nobody to send
1278
326
  // it to. Last, the work no person holds up. Cards with an active session lead their group [WAI-01, WAI-03].
1279
327
  function Waiting({ groups, actions }: { groups: WaitingGroup[]; actions: Actions }) {
@@ -1305,164 +353,3 @@ function Waiting({ groups, actions }: { groups: WaitingGroup[]; actions: Actions
1305
353
  });
1306
354
  }
1307
355
 
1308
- // Stacked or linked PRs as a connected line; collapsed, only those needing attention [ATT-03, ATT-04].
1309
- // In the sheet each row opens its PR on GitHub [ATT-12], and the PR an issue's actions apply to is tinted and says so [ATT-06].
1310
- function StackLine({ rows, merged, links = false, target }: { rows: SubRow[]; merged: boolean; links?: boolean; target?: string }) {
1311
- const styles = useStyles();
1312
- return (
1313
- <View>
1314
- {rows.map((row, index) => (
1315
- <StackRow key={row.key} url={row.url} number={row.number} link={links} target={row.key === target}>
1316
- <View style={{ width: 16, alignItems: "center" }}>
1317
- <View style={{ width: 2, flex: 1, backgroundColor: index === 0 ? "transparent" : styles.c.border }} />
1318
- <TablerIcon name={merged ? "merge" : row.draft ? "draft" : "pr"} size={14} color={merged ? styles.c.statusSuccess : row.draft ? styles.c.foregroundMuted : styles.c.statusSuccess} />
1319
- <View style={{ width: 2, flex: 1, backgroundColor: index === rows.length - 1 ? "transparent" : styles.c.border }} />
1320
- </View>
1321
- <View style={{ flex: 1, paddingVertical: 3, gap: 2 }}>
1322
- <Text style={{ color: styles.c.foreground, fontSize: 13 }} numberOfLines={1}>
1323
- {row.title}
1324
- </Text>
1325
- <View style={[styles.wrap, { columnGap: 10, rowGap: 2 }]}>
1326
- <Meta lead={<NumberText number={row.number} />} facts={merged && row.mergedBy ? [`merged by ${row.mergedBy}`] : []} chips={row.chips} />
1327
- {row.key === target ? <Text style={{ color: styles.action, fontSize: 12, fontWeight: "600" }}>actions apply here</Text> : null}
1328
- </View>
1329
- </View>
1330
- {links ? (
1331
- <View style={{ justifyContent: "center", paddingHorizontal: 4 }}>
1332
- <TablerIcon name="github" size={14} color={styles.c.foregroundMuted} />
1333
- </View>
1334
- ) : null}
1335
- </StackRow>
1336
- ))}
1337
- </View>
1338
- );
1339
- }
1340
-
1341
- function StackRow({ url, number, link, target = false, children }: { url: string; number: number; link: boolean; target?: boolean; children: ReactNode }) {
1342
- const styles = useStyles();
1343
- const { hovered, hover } = useHover();
1344
- const tinted = target ? { backgroundColor: tint(styles.action, 0.1), borderRadius: 6 } : null;
1345
- if (!link) return <View style={[styles.row, { alignItems: "stretch" }, tinted]}>{children}</View>;
1346
- return (
1347
- <Pressable
1348
- accessibilityRole="link"
1349
- accessibilityLabel={`Open PR #${number} on GitHub`}
1350
- onPress={() => void openExternalUrl(url)}
1351
- {...hover}
1352
- style={({ pressed }) => [styles.row, { alignItems: "stretch", borderRadius: 6, backgroundColor: pressed || hovered ? styles.c.surface2 : target ? tint(styles.action, 0.1) : "transparent" }]}
1353
- >
1354
- {children}
1355
- </Pressable>
1356
- );
1357
- }
1358
-
1359
- // Session options in a modal: a bottom sheet on phones [SES-02].
1360
- function SessionOptions({ spec, actions, onClose }: { spec: OptionsSpec; actions: Actions; onClose: () => void }) {
1361
- const styles = useStyles();
1362
- const paseo = usePaseo();
1363
- const toast = useToast();
1364
- const { itemKey, kind, target } = spec;
1365
- const options = useQuery({
1366
- queryKey: ["attention-span", "options", itemKey, kind],
1367
- queryFn: async () => {
1368
- const [{ context }, profiles, checkout, defaults] = await Promise.all([
1369
- actions.fetchContext({ kind, target }),
1370
- listProfiles(paseo),
1371
- findCheckout(paseo, actions.config, target, actions.defaultBranch),
1372
- // Without a ready provider, still show the options; starting reports the error.
1373
- resolveAgentConfig(paseo, actions.fetchProviders, kind, actions.config).catch(() => ({ label: "No agent provider is ready" })),
1374
- ]);
1375
- const workspaces = checkout.project ? await branchWorkspaces(paseo, checkout.project.projectId, checkoutPr(kind, target).head) : [];
1376
- return { prompt: renderPrompt(kind, target, context, actions.config), profiles, checkout, workspaces, defaultLabel: defaults.label };
1377
- },
1378
- staleTime: 60_000,
1379
- });
1380
- const [workspaceId, setWorkspaceId] = useState<string>();
1381
- const [profileId, setProfileId] = useState<string>();
1382
- const [prompt, setPrompt] = useState<string | null>(null);
1383
- const [starting, setStarting] = useState(false);
1384
- const data = options.data;
1385
-
1386
- async function start() {
1387
- if (!data) return;
1388
- setStarting(true);
1389
- try {
1390
- await spec.before?.();
1391
- await actions.started(await startSession(paseo, { itemKey, kind, target, prompt: prompt ?? data.prompt, config: actions.config, fetchProviders: actions.fetchProviders, checkout: data.checkout, profileId, workspaceId }));
1392
- onClose();
1393
- } catch (error) {
1394
- toast.error(`Starting the session failed: ${(error as Error).message}`);
1395
- } finally {
1396
- setStarting(false);
1397
- }
1398
- }
1399
-
1400
- return (
1401
- <Modal title={spec.title} open onOpenChange={(open) => (open ? null : onClose())}>
1402
- <Modal.Content>
1403
- <KeepStyles styles={styles}>
1404
- {options.isLoading ? <Loading text="Loading context…" /> : null}
1405
- {!options.isLoading && !data ? <Text style={styles.danger}>{(options.error as Error)?.message ?? "No options"}</Text> : null}
1406
- {data && !data.checkout.project ? <Text style={styles.danger}>{noProjectMessage(data.checkout, target)}</Text> : null}
1407
- {data?.checkout.project ? (
1408
- <View style={{ gap: 10 }}>
1409
- <Text style={styles.muted}>Workspace</Text>
1410
- <View style={styles.wrap}>
1411
- <Toggle label="New worktree" active={!workspaceId} onPress={() => setWorkspaceId(undefined)} />
1412
- {data.workspaces.map((w) => (
1413
- <Toggle key={w.id} label={w.name} active={workspaceId === w.id} onPress={() => setWorkspaceId(w.id)} />
1414
- ))}
1415
- </View>
1416
- <Text style={styles.muted}>Agent profile</Text>
1417
- <View style={styles.wrap}>
1418
- <Toggle label={data.defaultLabel} active={!profileId} onPress={() => setProfileId(undefined)} />
1419
- {data.profiles.map((p) => (
1420
- <Toggle key={p.id} label={p.name} active={profileId === p.id} onPress={() => setProfileId(p.id)} />
1421
- ))}
1422
- </View>
1423
- <Text style={styles.muted}>Prompt</Text>
1424
- <TextInput style={[styles.input, { minHeight: 180 }]} value={prompt ?? data.prompt} onChangeText={setPrompt} multiline textAlignVertical="top" />
1425
- <View style={styles.wrap}>
1426
- <Button label={starting ? "Starting…" : "Start session"} icon="agent" variant="solid" disabled={starting} onPress={() => void start()} />
1427
- <Button label="Cancel" onPress={onClose} />
1428
- </View>
1429
- </View>
1430
- ) : null}
1431
- </KeepStyles>
1432
- </Modal.Content>
1433
- </Modal>
1434
- );
1435
- }
1436
-
1437
- // Where an issue repo's code lives, picked from my Paseo projects and saved to config.json [SES-07].
1438
- function CodeRepoPicker({ issueRepo, missing, onPick, onClose }: { issueRepo: string; missing: string; onPick: (repo: string) => void; onClose: () => void }) {
1439
- const styles = useStyles();
1440
- const paseo = usePaseo();
1441
- const projects = useQuery({ queryKey: ["attention-span", "github-projects"], queryFn: () => githubProjects(paseo) });
1442
- return (
1443
- <Modal title={`Where does the code for ${issueRepo} live?`} open onOpenChange={(open) => (open ? null : onClose())}>
1444
- <Modal.Content>
1445
- <KeepStyles styles={styles}>
1446
- <View style={{ gap: 10 }}>
1447
- <Text style={styles.text}>No Paseo project has {missing} as its GitHub remote. Pick the project that holds the code for issues in {issueRepo}.</Text>
1448
- {projects.isLoading ? <Loading text="Loading projects…" /> : null}
1449
- {projects.data?.length === 0 ? <Text style={styles.danger}>No Paseo project has a GitHub remote. Add the code repository as a project first.</Text> : null}
1450
- <View style={styles.wrap}>
1451
- {projects.data?.map((project) => (
1452
- <Button key={project.projectId} label={project.repo} icon="play" variant="calm" onPress={() => onPick(project.repo)} />
1453
- ))}
1454
- </View>
1455
- <Text style={styles.muted}>Saved to codeRepos in config.json, so the next start goes straight there.</Text>
1456
- <View style={styles.wrap}>
1457
- <Button label="Cancel" onPress={onClose} />
1458
- </View>
1459
- </View>
1460
- </KeepStyles>
1461
- </Modal.Content>
1462
- </Modal>
1463
- );
1464
- }
1465
-
1466
- function issueTarget(issue: NextUpIssue): Target {
1467
- return { kind: "issue", repo: issue.repo, number: issue.number, title: issue.title, url: issue.url, defaultBranch: issue.defaultBranch };
1468
- }