@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
@@ -4,10 +4,11 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  import { useState } from "react";
5
5
  import { Text, View } from "react-native";
6
6
  import * as rpc from "../shared/rpc";
7
- import { DEFAULT_FIELD, FIELD_ROLES, type FieldRole, sameField } from "../shared/config";
7
+ import { DEFAULT_FIELD, FIELD_ROLES, type FieldRole } from "../shared/config";
8
8
  import type { ConfigStatus, CoverageKind, IssueField } from "../shared/setup";
9
9
  import { VIEW_QUERY_KEY } from "./data";
10
10
  import { Button, StylesProvider, useCopy, useStyles } from "./ui";
11
+ import { sameName } from "../shared/names";
11
12
 
12
13
  const COVERAGE_QUERY_KEY = ["attention-span", "coverage"] as const;
13
14
  const MY_ORGS_QUERY_KEY = ["attention-span", "my-orgs"] as const;
@@ -143,7 +144,7 @@ function Coverage() {
143
144
  function NextUpSources({ value, disabled, onChange }: { value: ConfigStatus["nextUp"]; disabled: boolean; onChange: (next: ConfigStatus["nextUp"]) => Promise<void> }) {
144
145
  const fetchOrgs = useRpc(rpc.myOrgs);
145
146
  const myOrgs = useQuery({ queryKey: MY_ORGS_QUERY_KEY, queryFn: () => fetchOrgs({}) });
146
- const choosable = (myOrgs.data?.orgs ?? []).filter((org) => !value.orgs.some((added) => added.toLowerCase() === org.toLowerCase()));
147
+ const choosable = (myOrgs.data?.orgs ?? []).filter((org) => !value.orgs.some((added) => sameName(added, org)));
147
148
  return (
148
149
  <SettingsSection title="Next up">
149
150
  <SettingsCard>
@@ -186,7 +187,7 @@ function NextUpFields({ value, disabled, onChange }: { value: ConfigStatus["fiel
186
187
  const fetchFields = useRpc(rpc.issueFields);
187
188
  const available = useQuery({ queryKey: FIELDS_QUERY_KEY, queryFn: () => fetchFields({}) });
188
189
  const fields: IssueField[] = available.data?.fields ?? [];
189
- const find = (name: string | null | undefined) => fields.find((field) => sameField(field.name, name ?? undefined));
190
+ const find = (name: string | null | undefined) => fields.find((field) => sameName(field.name, name ?? undefined));
190
191
  // What each role uses now: the chosen field, or the one named after it if an org has it. Names match without case,
191
192
  // so a field typed "priority" shows as GitHub's "Priority".
192
193
  const current = (role: FieldRole): string | null => {
@@ -278,7 +279,7 @@ function AddRow({ kind, placeholder, existing, disabled, onAdd }: { kind: Covera
278
279
  try {
279
280
  const result = await check({ kind, name: text });
280
281
  if (result.error !== null) return setError(result.error);
281
- if (existing.some((name) => name.toLowerCase() === result.name.toLowerCase())) return setError(`${result.name} is already in the list`);
282
+ if (existing.some((name) => sameName(name, result.name))) return setError(`${result.name} is already in the list`);
282
283
  await onAdd(result.name);
283
284
  setText("");
284
285
  } catch (failure) {
package/client/data.ts CHANGED
@@ -6,6 +6,8 @@ import { getAttention } from "../shared/rpc";
6
6
 
7
7
  export const VIEW_QUERY_KEY = ["attention-span", "view"] as const;
8
8
  const REFRESH_KEY = ["attention-span", "refresh"] as const;
9
+ // History's weeks are the device's, so the server is told its time zone [HIS-01].
10
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
9
11
 
10
12
  // The server owns the GitHub refresh schedule; the app only reads its cache [FRESH-01, GH-01].
11
13
  export function useAttention() {
@@ -13,13 +15,13 @@ export function useAttention() {
13
15
  const queryClient = useQueryClient();
14
16
  const query = useQuery({
15
17
  queryKey: VIEW_QUERY_KEY,
16
- queryFn: () => fetchAttention({}),
18
+ queryFn: () => fetchAttention({ timeZone }),
17
19
  // Sooner while a change waits on GitHub, so the list shows GitHub's own word on it soon after [FRESH-02].
18
20
  refetchInterval: (query) => (query.state.data?.pending ? 10_000 : 60_000),
19
21
  });
20
22
  const setView = useCallback((view: AttentionView) => queryClient.setQueryData(VIEW_QUERY_KEY, view), [queryClient]);
21
23
  // ⟳ fetches only the feed behind the tab I'm on.
22
- const refresh = useMutation({ mutationKey: REFRESH_KEY, mutationFn: (feed: FeedId) => fetchAttention({ refresh: feed }), onSuccess: setView });
24
+ const refresh = useMutation({ mutationKey: REFRESH_KEY, mutationFn: (feed: FeedId) => fetchAttention({ refresh: feed, timeZone }), onSuccess: setView });
23
25
  const refreshNow = refresh.mutateAsync;
24
26
  // The server answers ⟳ only once its refresh is done, so the view can't say it's running; the pending call does.
25
27
  // Kept in the query client, so it still shows after leaving the screen and coming back mid-refresh.
@@ -6,10 +6,10 @@ import type { AgentSummary } from "../shared/attention";
6
6
  import type { AttentionConfig } from "../shared/config";
7
7
  import { FEEDBACK_REPO, type FeedbackContext, type FeedbackKind, feedbackItemKey, feedbackPrompt } from "../shared/feedback";
8
8
  import * as rpc from "../shared/rpc";
9
- import { ActionSheet, Modal, type SheetEntry } from "./sheet";
9
+ import { ActionSheet, Dialog, type SheetEntry } from "./sheet";
10
10
  import { sessionEntry } from "./session-menu";
11
11
  import { ITEM_LABEL, KIND_LABEL, LABEL, resolveAgentConfig } from "./sessions";
12
- import { Button, KeepStyles, TablerIcon, useStyles } from "./ui";
12
+ import { Button, TablerIcon, useStyles } from "./ui";
13
13
 
14
14
  // Feedback to the Attention Span project from the bottom of every tab [FB-01].
15
15
  // Problem and Idea start an agent that asks until it's clear and posts only once I approve; Like opens the repo to star it.
@@ -117,29 +117,25 @@ export function FeedbackAsk({
117
117
  }
118
118
 
119
119
  return (
120
- <Modal title={KINDS[kind].label} open onOpenChange={(open) => (open ? null : onClose())}>
121
- <Modal.Content>
122
- <KeepStyles styles={styles}>
123
- <View style={{ gap: 10 }}>
124
- <Text style={styles.muted}>{KINDS[kind].ask}</Text>
125
- <TextInput
126
- style={[styles.input, { minHeight: 110 }]}
127
- value={message}
128
- onChangeText={setMessage}
129
- placeholder={KINDS[kind].placeholder}
130
- multiline
131
- textAlignVertical="top"
132
- autoFocus
133
- />
134
- <Text style={styles.muted}>An agent asks what else it needs and shows you the post before anything goes to GitHub.</Text>
135
- <View style={styles.wrap}>
136
- <Button label={starting ? "Starting…" : "Start"} icon="agent" variant="solid" disabled={starting || !message.trim()} onPress={() => void start()} />
137
- <Button label="Back" onPress={onBack} />
138
- </View>
139
- </View>
140
- </KeepStyles>
141
- </Modal.Content>
142
- </Modal>
120
+ <Dialog title={KINDS[kind].label} onClose={onClose}>
121
+ <View style={{ gap: 10 }}>
122
+ <Text style={styles.muted}>{KINDS[kind].ask}</Text>
123
+ <TextInput
124
+ style={[styles.input, { minHeight: 110 }]}
125
+ value={message}
126
+ onChangeText={setMessage}
127
+ placeholder={KINDS[kind].placeholder}
128
+ multiline
129
+ textAlignVertical="top"
130
+ autoFocus
131
+ />
132
+ <Text style={styles.muted}>An agent asks what else it needs and shows you the post before anything goes to GitHub.</Text>
133
+ <View style={styles.wrap}>
134
+ <Button label={starting ? "Starting…" : "Start"} icon="agent" variant="solid" disabled={starting || !message.trim()} onPress={() => void start()} />
135
+ <Button label="Back" onPress={onBack} />
136
+ </View>
137
+ </View>
138
+ </Dialog>
143
139
  );
144
140
  }
145
141
 
@@ -1,11 +1,12 @@
1
1
  import type { ReactNode } from "react";
2
- import { Pressable, Text, View } from "react-native";
2
+ import { Text, View } from "react-native";
3
3
  import type { HistoryFilter, Item } from "../shared/attention";
4
4
  import { allNotesBusy } from "../shared/got-it";
5
5
  import { historyWeeks, weekOf } from "../shared/history-report";
6
6
  import type { IconName } from "./icons";
7
- import { Modal } from "./sheet";
8
- import { Button, KeepStyles, SectionHeader, TablerIcon, useCopy, useStyles } from "./ui";
7
+ import { FilterSheet } from "./sheet";
8
+ import { Still } from "./still";
9
+ import { Button, FilterButton, SectionHeader, TablerIcon, useCopy, useStyles } from "./ui";
9
10
 
10
11
  // History: what others did to my work, unread, on top until Got it or an archive; then what I finished, by week, with
11
12
  // Reviewed and cleared changes when the filter shows them [HIS-01, HIS-02, HIS-06, HIS-07]. A week copies what's shown as
@@ -22,6 +23,7 @@ function weekLabel(monday: Date): string {
22
23
 
23
24
  export function History({
24
25
  notes,
26
+ calm,
25
27
  items,
26
28
  filter,
27
29
  filtering,
@@ -31,6 +33,8 @@ export function History({
31
33
  onMarkAllRead,
32
34
  card,
33
35
  }: {
36
+ // Nothing finished and nothing unread, after a refresh that worked [HIS-08].
37
+ calm: boolean;
34
38
  notes: Item[];
35
39
  items: Item[];
36
40
  filter: HistoryFilter[];
@@ -45,6 +49,7 @@ export function History({
45
49
  const styles = useStyles();
46
50
  const copy = useCopy();
47
51
  const { weeks, anything } = historyWeeks(items, filter);
52
+ if (calm) return <Still shore="bench" title="Nothing finished yet." line="Your accomplishments will show up here." />;
48
53
  if (notes.length === 0 && !anything) return <Text style={styles.text}>Nothing finished in this period.</Text>;
49
54
  return (
50
55
  <>
@@ -74,13 +79,7 @@ export function History({
74
79
  {/* Filter shows whenever a week holds anything, even only what the filter hides, so it can be turned on [HIS-07]. */}
75
80
  {anything ? (
76
81
  <View style={[styles.row, { justifyContent: "flex-end" }]}>
77
- <Button
78
- label={filter.length ? `Filter · ${filter.length}` : "Filter"}
79
- accessibilityLabel={filter.length ? `Filter, ${filter.length} on` : "Filter"}
80
- icon="filter"
81
- variant={filter.length ? "calm" : "ghost"}
82
- onPress={() => onFiltering(true)}
83
- />
82
+ <FilterButton count={filter.length} onPress={() => onFiltering(true)} />
84
83
  </View>
85
84
  ) : null}
86
85
  {anything && weeks.length === 0 ? <Text style={styles.text}>Nothing finished in this period.</Text> : null}
@@ -140,45 +139,13 @@ function Subgroup({ icon, label, count }: { icon: IconName; label: string; count
140
139
  );
141
140
  }
142
141
 
143
- // History's filter: Finished always, plus Reviewed and cleared Changed by others per week [HIS-07]. Ticks apply right away.
142
+ // History's filter: Finished always, plus Reviewed and cleared Changed by others per week [HIS-07].
144
143
  function HistoryFilterSheet({ filter, onChange, onClose }: { filter: HistoryFilter[]; onChange: (filter: HistoryFilter[]) => void; onClose: () => void }) {
145
- const styles = useStyles();
146
- const flip = (id: HistoryFilter) => onChange(filter.includes(id) ? filter.filter((other) => other !== id) : [...filter, id]);
147
- const row = (id: HistoryFilter | null, label: string, note?: string) => {
148
- const on = id === null || filter.includes(id);
149
- return (
150
- <Pressable
151
- accessibilityRole="checkbox"
152
- accessibilityState={{ checked: on, disabled: id === null }}
153
- disabled={id === null}
154
- accessibilityLabel={label}
155
- onPress={() => id && flip(id)}
156
- style={[styles.row, { paddingVertical: 11, paddingHorizontal: 14, opacity: id === null ? 0.65 : 1 }]}
157
- >
158
- <TablerIcon name={on ? "squareCheck" : "square"} size={18} color={on ? styles.action : styles.c.foregroundMuted} />
159
- <Text style={[styles.text, { flex: 1 }]}>{label}</Text>
160
- {note ? <Text style={styles.muted}>{note}</Text> : null}
161
- </Pressable>
162
- );
163
- };
164
- return (
165
- <Modal title="Filter" open onOpenChange={(open) => (open ? null : onClose())}>
166
- <Modal.Content>
167
- <KeepStyles styles={styles}>
168
- <Text style={styles.muted}>Show in each week</Text>
169
- <View style={[styles.card, { backgroundColor: styles.c.surface2 }]}>
170
- {row(null, "Finished", "always")}
171
- <View style={{ height: 1, backgroundColor: styles.c.surface1 }} />
172
- {row("reviewed", "Reviewed")}
173
- <View style={{ height: 1, backgroundColor: styles.c.surface1 }} />
174
- {row("changed", "Changed by others")}
175
- </View>
176
- <View style={[styles.row, { justifyContent: "flex-end" }]}>
177
- <Button label="Clear" variant="ghost" disabled={filter.length === 0} onPress={() => onChange([])} />
178
- <Button label="Done" variant="solid" onPress={onClose} />
179
- </View>
180
- </KeepStyles>
181
- </Modal.Content>
182
- </Modal>
183
- );
144
+ const flip = (id: string) => onChange(filter.includes(id as HistoryFilter) ? filter.filter((other) => other !== id) : [...filter, id as HistoryFilter]);
145
+ const options = [
146
+ { id: "finished", label: "Finished", state: "on" as const, disabled: true, note: "always" },
147
+ { id: "reviewed", label: "Reviewed" },
148
+ { id: "changed", label: "Changed by others" },
149
+ ];
150
+ return <FilterSheet groups={[{ kind: "history", title: "Show in each week", options, active: filter }]} onToggle={(_, id) => flip(id)} onClear={() => onChange([])} onClose={onClose} />;
184
151
  }
@@ -0,0 +1,363 @@
1
+ import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
2
+ import { openExternalUrl, type PluginScreenProps, usePaseo, useRpc } from "@getpaseo/plugin/client";
3
+ import { useToast } from "@getpaseo/plugin/client/ui";
4
+ import { useQueryClient } from "@tanstack/react-query";
5
+ import { useState } from "react";
6
+ import type { ActionId, AgentSummary, AttentionView, HistoryFilter, IssueCloseReason, Item, NextUpIssue, Target, WrapItem } from "../shared/attention";
7
+ import type { AttentionConfig, SessionKind } from "../shared/config";
8
+ import { summarizeRerun } from "../shared/checks";
9
+ import { ALL_NOTES, ALL_WRAP } from "../shared/got-it";
10
+ import { type ArchiveOutcome, archiveTarget, type KeptRow } from "../shared/archive";
11
+ import type { FilterChange } from "../shared/next-up-filter";
12
+ import { ACTION_SESSION, renderPrompt } from "../shared/prompts";
13
+ import * as rpc from "../shared/rpc";
14
+ import type { useAttention } from "./data";
15
+ import { DETAILS_STALE_MS, type DetailsQuery, detailsKey } from "./sheet";
16
+ import { AGENTS_QUERY_KEY, findCheckout, startSession, useStartRpcs } from "./sessions";
17
+
18
+ export type FetchDetails = (input: RpcInput<typeof rpc.itemDetails>) => Promise<RpcOutput<typeof rpc.itemDetails>>;
19
+
20
+ // What an item's sheet fetches when it opens; resting the pointer on its card fetches the same ahead. `checks` asks for
21
+ // failing checks too, for Rerun.
22
+ export function itemDetailsQuery(item: Item, fetchDetails: FetchDetails): DetailsQuery {
23
+ const checks = item.actions.includes("rerun");
24
+ const subject = { kind: item.kind, repo: item.repo, number: item.number };
25
+ return { queryKey: detailsKey(subject, item.target, checks), queryFn: () => fetchDetails({ subject, target: item.target, checks }) };
26
+ }
27
+
28
+ // A start held back until I say where the issue's code lives [SES-07].
29
+ interface Placing {
30
+ itemKey: string;
31
+ kind: SessionKind;
32
+ target: Target;
33
+ missing: string;
34
+ before?: () => Promise<unknown>;
35
+ }
36
+
37
+ // Session options, before it starts [SES-02].
38
+ export interface OptionsSpec {
39
+ itemKey: string;
40
+ title: string;
41
+ kind: SessionKind;
42
+ target: Target;
43
+ // Claims an issue first [NXT-05].
44
+ before?: () => Promise<unknown>;
45
+ }
46
+
47
+ // Something I just did, offered for undo until the tab changes [ATT-08, ATT-14].
48
+ export interface Undoable {
49
+ id: number;
50
+ text: string;
51
+ dismissal?: boolean;
52
+ undo: () => Promise<unknown>;
53
+ }
54
+
55
+ // What a card and its sheet can do.
56
+ export interface Actions {
57
+ agents: AgentSummary[];
58
+ startWithOptions: (spec: OptionsSpec) => void;
59
+ busy: ReadonlySet<string>;
60
+ config: AttentionConfig;
61
+ login: string | null;
62
+ fetchDetails: FetchDetails;
63
+ act: (item: Item, action: ActionId) => void;
64
+ requestReviewers: (item: Item, reviewers: string[]) => void;
65
+ // Without run ids, it finds them first: Rerun pressed before the sheet had the failing checks.
66
+ rerun: (item: Item, runIds?: number[]) => void;
67
+ acknowledge: (item: Item, commentIds: string[]) => void;
68
+ confirm: (item: Item, action: "merge" | "close", comment?: string) => void;
69
+ dismiss: (item: Item) => void;
70
+ gotItAll: (items: Item[]) => void;
71
+ openAgent: (agentId: string) => void;
72
+ started: (agentId: string) => Promise<void>;
73
+ }
74
+
75
+ function issueTarget(issue: NextUpIssue): Target {
76
+ return { kind: "issue", repo: issue.repo, number: issue.number, title: issue.title, url: issue.url, defaultBranch: issue.defaultBranch };
77
+ }
78
+
79
+ // Everything the screen does on GitHub and in Paseo: each card's change runs on its own, with Undo where it can be taken
80
+ // back; sessions start here, and Wrap up archives here.
81
+ export function useItemActions(attention: ReturnType<typeof useAttention>, navigation: PluginScreenProps["navigation"]) {
82
+ const paseo = usePaseo();
83
+ const toast = useToast();
84
+ const queryClient = useQueryClient();
85
+ const { fetchContext, defaultBranch, fetchProviders } = useStartRpcs();
86
+ const dismiss = useRpc(rpc.dismissItem);
87
+ const undismiss = useRpc(rpc.undismissItem);
88
+ const restore = useRpc(rpc.restoreDismissed);
89
+ const gotIt = useRpc(rpc.gotIt);
90
+ const saveHistoryFilter = useRpc(rpc.setHistoryFilter);
91
+ const archiveSessions = useRpc(rpc.archiveSessions);
92
+ const archiveWorktreeRpc = useRpc(rpc.archiveWorktree);
93
+ const dismissKept = useRpc(rpc.dismissKept);
94
+ const saveScopes = useRpc(rpc.setScopes);
95
+ const saveSources = useRpc(rpc.setSources);
96
+ const saveProjects = useRpc(rpc.setProjectFilter);
97
+ const closeIssue = useRpc(rpc.closeIssue);
98
+ const reopenIssue = useRpc(rpc.reopenIssue);
99
+ const update = useRpc(rpc.updateBranch);
100
+ const merge = useRpc(rpc.mergePullRequest);
101
+ const close = useRpc(rpc.closePullRequest);
102
+ const claim = useRpc(rpc.claimIssue);
103
+ const unclaim = useRpc(rpc.unclaimIssue);
104
+ const setReady = useRpc(rpc.setReady);
105
+ const setAutoMerge = useRpc(rpc.setAutoMerge);
106
+ const react = useRpc(rpc.react);
107
+ const requestReviewers = useRpc(rpc.requestReviewers);
108
+ const rerunFailed = useRpc(rpc.rerunFailed);
109
+ const fetchDetails = useRpc(rpc.itemDetails);
110
+ const setCodeRepo = useRpc(rpc.setCodeRepo);
111
+ // Every card with a change still running: each runs on its own.
112
+ const [busy, setBusy] = useState<ReadonlySet<string>>(new Set());
113
+ // Sessions archived here, hidden before Paseo's list catches up; in previews, where nothing really archives, this is what
114
+ // makes a Wrap up row go away after its screenshot [ATT-22].
115
+ const [archivedSessions, setArchivedSessions] = useState<ReadonlySet<string>>(new Set());
116
+ const [undoable, setUndoable] = useState<Undoable[]>([]);
117
+ const [placing, setPlacing] = useState<Placing | null>(null);
118
+ const [options, setOptions] = useState<OptionsSpec | null>(null);
119
+ const view = attention.data;
120
+
121
+ async function run(key: string, label: string, work: () => Promise<unknown>) {
122
+ setBusy((keys) => new Set(keys).add(key));
123
+ try {
124
+ await work();
125
+ } catch (error) {
126
+ toast.error(`${label} failed: ${(error as Error).message}`);
127
+ } finally {
128
+ setBusy((keys) => new Set([...keys].filter((other) => other !== key)));
129
+ }
130
+ }
131
+
132
+ // A change from one tap, without confirming: Undo instead, where it can be taken back [SAFE-01, ATT-08, ATT-14].
133
+ // The server answers each with the list after it, so nothing needs a refresh.
134
+ function change(key: string, label: string, work: () => Promise<AttentionView>, done: string, undo?: () => Promise<AttentionView>, dismissal?: boolean) {
135
+ void run(key, label, async () => {
136
+ attention.setView(await work());
137
+ if (!undo) return toast.show(done, { variant: "success" });
138
+ const id = Date.now() + Math.random();
139
+ setUndoable((rows) => [...rows, { id, text: done, undo: async () => attention.setView(await undo()), dismissal }]);
140
+ });
141
+ }
142
+
143
+ function openAgent(agentId: string) {
144
+ if (navigation?.openAgent) navigation.openAgent({ agentId });
145
+ else toast.show("Session started. Open it from the sidebar.", { variant: "success" });
146
+ }
147
+
148
+ async function started(agentId: string) {
149
+ await queryClient.invalidateQueries({ queryKey: AGENTS_QUERY_KEY });
150
+ openAgent(agentId);
151
+ }
152
+
153
+ // One tap: start a session with defaults [SES-01]. An open one is offered first, by the card [SES-03].
154
+ async function startWithDefaults(itemKey: string, kind: SessionKind, target: Target, before?: () => Promise<unknown>) {
155
+ if (!view) return;
156
+ await run(itemKey, "Starting the session", () => startNow(itemKey, kind, target, view.config, before));
157
+ }
158
+
159
+ async function startNow(itemKey: string, kind: SessionKind, target: Target, config: AttentionConfig, before?: () => Promise<unknown>) {
160
+ const checkout = await findCheckout(paseo, config, target, defaultBranch);
161
+ // Ask where an issue's code lives before claiming it, so a failed start doesn't leave it taken [SES-07].
162
+ if (!checkout.project && target.kind === "issue") return setPlacing({ itemKey, kind, target, missing: checkout.repo, before });
163
+ await before?.();
164
+ const { context } = await fetchContext({ kind, target });
165
+ const prompt = renderPrompt(kind, target, context, config);
166
+ await started(await startSession(paseo, { itemKey, kind, target, prompt, config, fetchProviders, checkout }));
167
+ }
168
+
169
+ function place(codeRepo: string) {
170
+ if (!placing) return;
171
+ const { itemKey, kind, target, before } = placing;
172
+ setPlacing(null);
173
+ void run(itemKey, "Starting the session", async () => {
174
+ const next = await setCodeRepo({ issueRepo: target.repo, codeRepo });
175
+ attention.setView(next);
176
+ await startNow(itemKey, kind, target, next.config, before);
177
+ });
178
+ }
179
+
180
+ // Archive sessions, with the busy key that makes it wait for Archive all clean and the other way round [ATT-22].
181
+ // No Undo: Paseo's SDK can't restore a workspace and its agents, so the sheet is the safeguard instead.
182
+ // `terminals` are the ones the confirm sheet named; archiving closes no other.
183
+ async function archiveRows(items: WrapItem[], confirm: boolean, key = ALL_WRAP, terminals: string[] = []): Promise<ArchiveOutcome | null> {
184
+ if (items.length === 0) return null;
185
+ setBusy((keys) => new Set(keys).add(key));
186
+ try {
187
+ const outcome = await archiveSessions({ targets: items.map(archiveTarget), confirm, terminals });
188
+ attention.setView(outcome.view);
189
+ if (outcome.ok) {
190
+ const archived = new Set(items.flatMap((item) => item.wrap.sessions.map((session) => session.id)));
191
+ setArchivedSessions((known) => new Set([...known, ...archived]));
192
+ const sessions = archived.size;
193
+ // A worktree that stayed lingers as a row saying why; the toast only confirms [ATT-22].
194
+ const kept = outcome.kept.length ? ` · ${outcome.kept.length === 1 ? "worktree" : "worktrees"} kept` : "";
195
+ toast.show(`${sessions === 1 ? `Archived the session on #${items[0].number}` : `Archived ${sessions} sessions`}${kept}`, { variant: "success" });
196
+ } else if (outcome.reason === "working") {
197
+ toast.error(`Couldn't archive: ${outcome.message}`);
198
+ }
199
+ return outcome;
200
+ } catch (error) {
201
+ toast.error(`Archive failed: ${(error as Error).message}`);
202
+ return null;
203
+ } finally {
204
+ setBusy((keys) => new Set([...keys].filter((other) => other !== key)));
205
+ }
206
+ }
207
+
208
+ // A kept worktree tried again on its own: Archive worktree, or Try again [ATT-22].
209
+ async function archiveWorktree(row: KeptRow, confirm: boolean, terminals: string[] = []): Promise<ArchiveOutcome | null> {
210
+ const key = `kept:${row.workspaceId}`;
211
+ setBusy((keys) => new Set(keys).add(key));
212
+ try {
213
+ const outcome = await archiveWorktreeRpc({ workspaceId: row.workspaceId, confirm, terminals });
214
+ attention.setView(outcome.view);
215
+ if (outcome.ok && !outcome.kept.length) toast.show(`Archived ${row.name}`, { variant: "success" });
216
+ else if (!outcome.ok && outcome.reason === "working") toast.error(`Couldn't archive: ${outcome.message}`);
217
+ return outcome;
218
+ } catch (error) {
219
+ toast.error(`Archive failed: ${(error as Error).message}`);
220
+ return null;
221
+ } finally {
222
+ setBusy((keys) => new Set([...keys].filter((other) => other !== key)));
223
+ }
224
+ }
225
+
226
+ function itemActions(view: AttentionView, agents: AgentSummary[]): Actions {
227
+ return {
228
+ agents,
229
+ startWithOptions: setOptions,
230
+ busy,
231
+ config: view.config,
232
+ login: view.login,
233
+ fetchDetails,
234
+ openAgent,
235
+ started,
236
+ act: (item, action) => {
237
+ const session = ACTION_SESSION[action];
238
+ const { target } = item;
239
+ if (action === "reply") return void openExternalUrl(item.person?.url ?? item.url);
240
+ // [HIS-07]
241
+ if (action === "got_it" && item.change) {
242
+ const { id } = item.change;
243
+ return change(item.key, "Got it", () => gotIt({ ids: [id], on: true }), `Cleared the note on “${item.title}”`, () => gotIt({ ids: [id], on: false }));
244
+ }
245
+ if (session) return void startWithDefaults(item.key, session, target);
246
+ if (action === "update") change(item.key, "Update", () => update({ key: item.key, target }), `Updating PR ${target.number} with ${target.baseRefName}`);
247
+ // [PRS-11]
248
+ if (action === "ready")
249
+ 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 }));
250
+ // [PRS-10]
251
+ if (action === "automerge")
252
+ 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 }));
253
+ },
254
+ // [PRS-09]
255
+ rerun: (item, known) => {
256
+ if (!known) toast.show("Finding the failed jobs to rerun…");
257
+ change(
258
+ item.key,
259
+ "Rerun",
260
+ async () => {
261
+ const runIds = known ?? summarizeRerun((await queryClient.fetchQuery({ ...itemDetailsQuery(item, fetchDetails), staleTime: DETAILS_STALE_MS })).failing).runIds;
262
+ if (runIds.length === 0) throw new Error("no failed GitHub Actions jobs to rerun");
263
+ return rerunFailed({ key: item.key, repo: item.target.repo, runIds });
264
+ },
265
+ `Rerunning the failed jobs of PR ${item.target.number}`,
266
+ );
267
+ },
268
+ // [PRS-12]
269
+ requestReviewers: (item, reviewers) => {
270
+ const { target } = item;
271
+ const names = reviewers.length === 1 ? reviewers[0] : `${reviewers.length} reviewers`;
272
+ change(item.key, "Request review", () => requestReviewers({ key: item.key, target, reviewers, on: true }), `Asked ${names} to review PR ${target.number}`, () =>
273
+ requestReviewers({ key: item.key, target, reviewers, on: false }),
274
+ );
275
+ },
276
+ // [MEN-07]
277
+ acknowledge: (item, ids) =>
278
+ change(item.key, "Acknowledge", () => react({ key: item.key, subjectIds: ids, on: true }), `Acknowledged ${ids.length === 1 ? "a comment" : `${ids.length} comments`} on #${item.number}`, () =>
279
+ react({ key: item.key, subjectIds: ids, on: false }),
280
+ ),
281
+ confirm: (item, action, comment) =>
282
+ action === "merge"
283
+ ? change(item.key, "Merge", () => merge({ key: item.key, target: item.target }), `PR ${item.target.number} merged`)
284
+ : change(item.key, "Close", () => close({ key: item.key, target: item.target, comment }), `PR ${item.target.number} closed`),
285
+ // Got it on every Changed by others note at once; one Undo brings them all back [HIS-07].
286
+ gotItAll: (items) => {
287
+ const ids = items.flatMap((item) => (item.change ? [item.change.id] : []));
288
+ const notes = `${ids.length} note${ids.length === 1 ? "" : "s"}`;
289
+ change(ALL_NOTES, "Mark all as read", () => gotIt({ ids, on: true }), `Cleared ${notes} on changes by others`, () => gotIt({ ids, on: false }));
290
+ },
291
+ dismiss: (item) => change(item.key, "Dismiss", () => dismiss({ key: item.key }), `Dismissed “${item.title}”`, () => undismiss({ key: item.key }), true),
292
+ };
293
+ }
294
+
295
+ // Next up's issues: start, with options, claim or give back, close [NXT-05, NXT-07, NXT-11].
296
+ const claimFirst = (issue: NextUpIssue, target: Target) => async () => attention.setView(await claim({ key: issue.key, target }));
297
+ const issueActions = {
298
+ onStart: (issue: NextUpIssue, claiming: boolean) => {
299
+ const target = issueTarget(issue);
300
+ void startWithDefaults(issue.key, "start", target, claiming ? claimFirst(issue, target) : undefined);
301
+ },
302
+ onOptions: (issue: NextUpIssue, claiming: boolean, label: string) => {
303
+ const target = issueTarget(issue);
304
+ setOptions({ itemKey: issue.key, title: `${label}: ${issue.title}`, kind: "start", target, before: claiming ? claimFirst(issue, target) : undefined });
305
+ },
306
+ // Claim without starting, or give it back; each undoes the other [NXT-07].
307
+ onClaim: (issue: NextUpIssue, on: boolean) => {
308
+ const target = issueTarget(issue);
309
+ const [take, giveBack] = [() => claim({ key: issue.key, target }), () => unclaim({ key: issue.key, target })];
310
+ change(issue.key, on ? "Claim" : "Unclaim", on ? take : giveBack, `${on ? "Claimed" : "Unclaimed"} #${issue.number}`, on ? giveBack : take);
311
+ },
312
+ // Undo reopens; a comment already posted stays [NXT-11].
313
+ onCloseIssue: (issue: NextUpIssue, reason: IssueCloseReason, comment: string) => {
314
+ const target = issueTarget(issue);
315
+ const done = `Closed #${issue.number} as ${reason === "completed" ? "completed" : "not planned"}`;
316
+ change(issue.key, "Close", () => closeIssue({ key: issue.key, target, reason, comment: comment || undefined }), done, () => reopenIssue({ key: issue.key, target }));
317
+ },
318
+ };
319
+
320
+ const failedSaving = (error: Error) => toast.error(`Saving the filter failed: ${error.message}`);
321
+ // Ticks apply right away, like Next up's; the server remembers them [HIS-07].
322
+ function filterHistory(view: AttentionView, next: HistoryFilter[]) {
323
+ attention.setView({ ...view, historyFilter: next });
324
+ saveHistoryFilter({ filter: next })
325
+ .then((saved) => attention.setView(saved))
326
+ .catch(failedSaving);
327
+ }
328
+ // One setView for all, so clearing them together can't put any back.
329
+ function filterNextUp(view: AttentionView, change: FilterChange) {
330
+ attention.setView({ ...view, ...change });
331
+ if (change.scopes) saveScopes({ scopes: change.scopes }).catch(failedSaving);
332
+ if (change.sources) saveSources({ sources: change.sources }).catch(failedSaving);
333
+ if (change.projectFilter) saveProjects({ projects: change.projectFilter }).catch(failedSaving);
334
+ }
335
+
336
+ return {
337
+ busy,
338
+ archivedSessions,
339
+ undoable,
340
+ clearUndo: () => setUndoable([]),
341
+ undo: (row: Undoable) =>
342
+ void run(String(row.id), "Undo", async () => {
343
+ await row.undo();
344
+ setUndoable((rows) => rows.filter((other) => other.id !== row.id));
345
+ }),
346
+ restoreDismissed: () => void run("restore", "Restore", async () => (attention.setView(await restore({})), setUndoable([]))),
347
+ placing,
348
+ place,
349
+ cancelPlacing: () => setPlacing(null),
350
+ options,
351
+ closeOptions: () => setOptions(null),
352
+ fetchDetails,
353
+ openAgent,
354
+ started,
355
+ archiveRows,
356
+ archiveWorktree,
357
+ dismissKept: (row: KeptRow) => void run(`kept:${row.workspaceId}`, "Dismiss", async () => attention.setView(await dismissKept({ workspaceId: row.workspaceId }))),
358
+ itemActions,
359
+ issueActions,
360
+ filterHistory,
361
+ filterNextUp,
362
+ };
363
+ }