paseo-follow-up 2.4.0-beta.0 → 2.4.0-beta.2

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 (65) hide show
  1. package/client/brief.tsx +27 -14
  2. package/client/header.tsx +9 -4
  3. package/client/home-list.tsx +8 -7
  4. package/client/home-view.ts +11 -2
  5. package/client/home.tsx +30 -9
  6. package/client/inbox.tsx +5 -5
  7. package/client/merge-button.tsx +1 -1
  8. package/client/morning-brief-settings.tsx +266 -0
  9. package/client/needs-you.tsx +4 -3
  10. package/client/pr-stats-settings.tsx +228 -0
  11. package/client/pr-stats.tsx +360 -0
  12. package/client/questions.tsx +34 -19
  13. package/client/settings.tsx +7 -0
  14. package/index.client.tsx +7 -1
  15. package/index.server.ts +247 -11
  16. package/package.json +2 -1
  17. package/server/agent-actions.ts +34 -2
  18. package/server/agent-hook.mjs +35 -6
  19. package/server/agent-parity.ts +37 -0
  20. package/server/check-watches.ts +145 -0
  21. package/server/dispatch.ts +420 -0
  22. package/server/engine.ts +13 -2
  23. package/server/github.ts +15 -2
  24. package/server/hook-source.ts +35 -6
  25. package/server/linear-issues.ts +121 -0
  26. package/server/linear-queue.ts +224 -0
  27. package/server/mcp-source.ts +34 -10
  28. package/server/mcp.mjs +34 -10
  29. package/server/morning-brief.ts +233 -0
  30. package/server/obligations.ts +25 -3
  31. package/server/overseer-prompt-source.ts +1 -1
  32. package/server/overseer-prompt.md +1 -1
  33. package/server/overseer.ts +46 -2
  34. package/server/pr-stats-gate.ts +102 -0
  35. package/server/pr-stats-store.ts +196 -0
  36. package/server/pr-stats-sync.ts +228 -0
  37. package/server/pr-stats.ts +309 -0
  38. package/server/questions.ts +57 -12
  39. package/server/ranker.ts +33 -69
  40. package/server/wait-for-checks.ts +108 -0
  41. package/shared/attention.ts +6 -5
  42. package/shared/brief.ts +1 -1
  43. package/shared/chat.ts +3 -2
  44. package/shared/check-watch.ts +129 -0
  45. package/shared/contracts.ts +56 -2
  46. package/shared/dispatch.ts +429 -0
  47. package/shared/home.ts +28 -10
  48. package/shared/inbox.ts +38 -3
  49. package/shared/linear-issues.ts +137 -0
  50. package/shared/linear-queue.ts +315 -0
  51. package/shared/list-entries.ts +5 -0
  52. package/shared/model.ts +22 -2
  53. package/shared/morning-brief.ts +346 -0
  54. package/shared/poll.ts +9 -2
  55. package/shared/pr-stats-page.ts +110 -0
  56. package/shared/pr-stats-records.ts +169 -0
  57. package/shared/pr-stats-settings.ts +217 -0
  58. package/shared/pr-stats.ts +377 -0
  59. package/shared/questions.ts +136 -1
  60. package/shared/queue.ts +1 -1
  61. package/shared/ranker.ts +32 -25
  62. package/shared/settings-nav.ts +2 -1
  63. package/shared/status-invariants.ts +69 -3
  64. package/shared/task-status.ts +10 -3
  65. package/shared/workweek.ts +24 -0
@@ -0,0 +1,266 @@
1
+ import { useEffect, useState } from "react";
2
+ import { ActivityIndicator, TextInput, View } from "react-native";
3
+ import { openExternalUrl, useRpc } from "@getpaseo/plugin/client";
4
+ import { Icon, SettingsAction, SettingsCard, SettingsSection, SettingsSelect, SettingsSwitch, useToast } from "@getpaseo/plugin/client/ui";
5
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
6
+ import { Pressable, Text } from "./text";
7
+ import { Button, errorText, text, type Theme } from "./kit";
8
+ import { tint, withAlpha } from "./theme";
9
+ import { briefChatSearchRpc, briefSettingsRpc, setBriefPlanRpc, setBriefSettingsRpc } from "../shared/contracts";
10
+ import { QUEUE_STATE_TYPES, WEEKDAYS, defaultWorkdays, isZone, type Weekday } from "../shared/linear-queue";
11
+ import {
12
+ PLAN_MODES, planCard, queueStateLabel, type BriefSettingsView, type ChatRef, type PlanChange, type PlanMode, type PlanView, type QueueChange,
13
+ } from "../shared/morning-brief";
14
+
15
+ export const briefSettingsKey = ["follow-up", "brief-settings"];
16
+ const MODE_LABEL: Record<PlanMode, string> = { auto: "Find it for me", link: "Use a link", off: "Off" };
17
+
18
+ /**
19
+ * Settings → Morning brief (docs/morning-brief.md#settings): this week's plan link and the Linear queue's settings.
20
+ * Every change goes through the same RPCs the agent tools run (set_brief_plan, set_brief_settings).
21
+ */
22
+ export function MorningBriefCategory({ theme, compact }: { theme: Theme; compact: boolean }) {
23
+ const c = theme.colors;
24
+ const read = useRpc(briefSettingsRpc);
25
+ const query = useQuery({ queryKey: briefSettingsKey, queryFn: async () => await read({}) as BriefSettingsView, refetchInterval: 15_000 });
26
+ if (query.isPending) return <ActivityIndicator accessibilityLabel="Loading Morning brief settings" color={c.foregroundMuted} style={{ alignSelf: "flex-start", marginVertical: 8 }} />;
27
+ if (query.error || !query.data) return <SettingsCard><SettingsAction label="Couldn't load Morning brief settings" hint={query.error ? errorText(query.error) : undefined} actionLabel="Retry" onPress={() => void query.refetch()} /></SettingsCard>;
28
+ return <>
29
+ <PlanSection view={query.data} theme={theme} compact={compact} />
30
+ <QueueSection view={query.data} theme={theme} compact={compact} />
31
+ </>;
32
+ }
33
+
34
+ function usePlanChange() {
35
+ const write = useRpc(setBriefPlanRpc); const cache = useQueryClient(); const toast = useToast();
36
+ return useMutation({
37
+ mutationFn: async (input: PlanChange) => await write(input) as PlanView,
38
+ onSuccess: plan => { cache.setQueryData<BriefSettingsView>(briefSettingsKey, v => v ? { ...v, plan } : v); void cache.invalidateQueries({ queryKey: briefSettingsKey }); },
39
+ onError: error => toast.error(errorText(error)),
40
+ });
41
+ }
42
+
43
+ function PlanSection({ view, theme, compact }: { view: BriefSettingsView; theme: Theme; compact: boolean }) {
44
+ const c = theme.colors; const t = text(c, compact);
45
+ const plan = view.plan;
46
+ const change = usePlanChange();
47
+ // "Use a link" with nothing pasted yet shows the field without saving a mode that has no link.
48
+ const [picked, setPicked] = useState<PlanMode | null>(null);
49
+ const mode = picked ?? plan.mode;
50
+ useEffect(() => { if (picked && picked === plan.mode) setPicked(null); }, [picked, plan.mode]);
51
+ const env = plan.source === "env";
52
+ const choose = (m: PlanMode) => {
53
+ if (m === "link" && !plan.link) { setPicked("link"); return; }
54
+ setPicked(null);
55
+ if (m !== plan.mode) change.mutate({ mode: m });
56
+ };
57
+ const reading = !!plan.url && !plan.read && change.isSuccess;
58
+ const card = planCard({ ...plan, mode }, Date.now(), view.clock.timeZone, reading);
59
+ return <SettingsSection title="This week's plan" info="The brief reads it once a day and AI priority uses it to rank your work. Agents can set it too.">
60
+ {env
61
+ ? <Text style={t.meta}>Set by the environment (FOLLOW_UP_PLAN_URL), which wins over these settings. Unset it to choose here.</Text>
62
+ : <Segmented<PlanMode> label="Where the plan comes from" value={mode} options={PLAN_MODES.map(m => ({ value: m, label: MODE_LABEL[m] }))} onChange={choose} disabled={change.isPending} theme={theme} compact={compact} />}
63
+ {!env && mode === "auto" && <WhoWhere plan={plan} busy={change.isPending} onChange={input => change.mutate(input)} theme={theme} compact={compact} />}
64
+ {!env && mode === "link" && <LinkField initial={plan.link ?? ""} busy={change.isPending} onUse={link => change.mutate({ link, mode: "link" })} theme={theme} compact={compact} />}
65
+ {card && <PlanCardView card={card} busy={change.isPending} theme={theme} compact={compact}
66
+ onAnother={() => setPicked("link")} onRetry={() => change.mutate({ find: true })} onPaste={link => change.mutate({ link, mode: "link" })} />}
67
+ {!env && mode === "link" && plan.person && plan.channels.length > 0 && <SettingsCard>
68
+ <SettingsSwitch label="Replace when a newer one is found" hint={`Find it for me still looks in ${plan.channels.map(ch => `#${ch.name}`).join(", ")}.`} value={plan.replaceWhenNewer} disabled={change.isPending}
69
+ onValueChange={value => change.mutate({ replaceWhenNewer: value })} />
70
+ </SettingsCard>}
71
+ </SettingsSection>;
72
+ }
73
+
74
+ /** Three choices in one row: 44 px tall on a phone. */
75
+ function Segmented<V extends string>({ label, value, options, onChange, disabled, theme, compact }: { label: string; value: V; options: { value: V; label: string }[]; onChange: (v: V) => void; disabled?: boolean; theme: Theme; compact: boolean }) {
76
+ const c = theme.colors;
77
+ return <View accessibilityRole="radiogroup" accessibilityLabel={label} style={{ flexDirection: "row", alignSelf: compact ? "stretch" : "flex-start", backgroundColor: c.surface2, borderRadius: 8, padding: 2, gap: 2 }}>
78
+ {options.map(choice => {
79
+ const on = choice.value === value;
80
+ return <Pressable key={choice.value} accessibilityRole="radio" accessibilityState={{ checked: on, disabled }} disabled={disabled} onPress={() => onChange(choice.value)}
81
+ style={state => ({ flexGrow: compact ? 1 : 0, flexBasis: compact ? 0 : "auto", minHeight: compact ? 44 : 30, paddingHorizontal: 12, borderRadius: 6, alignItems: "center", justifyContent: "center",
82
+ backgroundColor: on ? c.surface0 : (state as { hovered?: boolean }).hovered ? tint(c.foreground, c) : "transparent", ...(on ? { boxShadow: "0px 0px 0px 1px rgba(127,127,127,0.18)" } : {}) })}>
83
+ <Text style={{ color: on ? c.foreground : c.foregroundMuted, fontSize: compact ? 14 : 13, fontWeight: "500" }}>{choice.label}</Text>
84
+ </Pressable>;
85
+ })}
86
+ </View>;
87
+ }
88
+
89
+ /** A text field; `mono` sets the typed value in monospace (a link), never the placeholder. */
90
+ function field(theme: Theme, compact: boolean, mono = false) {
91
+ const c = theme.colors;
92
+ return { flex: 1, minWidth: 0, minHeight: compact ? 44 : 32, paddingHorizontal: 10, borderRadius: 6, borderWidth: 1, borderColor: c.border, color: c.foreground, fontSize: 13, backgroundColor: c.surface0, ...(mono ? { fontFamily: "ui-monospace, Menlo, monospace" } : {}) } as const;
93
+ }
94
+
95
+ function LinkField({ initial, busy, onUse, theme, compact, placeholder = "https://claude.ai/artifact/…" }: { initial: string; busy: boolean; onUse: (link: string) => void; theme: Theme; compact: boolean; placeholder?: string }) {
96
+ const c = theme.colors;
97
+ const [value, setValue] = useState(initial);
98
+ useEffect(() => setValue(initial), [initial]);
99
+ const dirty = value.trim() !== initial && value.trim().length > 0;
100
+ return <View style={{ flexDirection: "row", gap: 8, alignItems: "center" }}>
101
+ <TextInput accessibilityLabel="The plan's link" value={value} onChangeText={setValue} placeholder={placeholder} placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false}
102
+ onSubmitEditing={() => dirty && onUse(value.trim())} style={field(theme, compact, value.length > 0)} />
103
+ {/* Shown once there's something new to use: then it's the screen's one primary action. */}
104
+ {dirty && <Button title="Use it" kind="primary" theme={theme} compact={compact} loading={busy} onPress={() => onUse(value.trim())} />}
105
+ </View>;
106
+ }
107
+
108
+ /** "Posted by [person] in [channels]": each picked from the chat source's own search, or typed as a name. */
109
+ function WhoWhere({ plan, busy, onChange, theme, compact }: { plan: PlanView; busy: boolean; onChange: (c: PlanChange) => void; theme: Theme; compact: boolean }) {
110
+ const c = theme.colors; const t = text(c, compact);
111
+ const [open, setOpen] = useState<"people" | "channels" | null>(null);
112
+ const chips = (refs: ChatRef[], prefix: string, remove?: (r: ChatRef) => void) => refs.map(r => <View key={r.id ?? r.name} style={{ flexDirection: "row", alignItems: "center", gap: 4, minHeight: compact ? 44 : 28, paddingLeft: 10, paddingRight: remove ? 4 : 10, borderRadius: 6, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface1 }}>
113
+ <Text style={t.body}>{`${prefix}${r.name}`}</Text>
114
+ {remove && <Pressable accessibilityRole="button" accessibilityLabel={`Remove ${prefix}${r.name}`} onPress={() => remove(r)} hitSlop={6} style={{ minWidth: compact ? 36 : 22, minHeight: compact ? 36 : 22, alignItems: "center", justifyContent: "center" }}>
115
+ <Icon name="X" size={12} color={c.foregroundMuted} />
116
+ </Pressable>}
117
+ </View>);
118
+ const personChip = (r: ChatRef) => <Pressable accessibilityRole="button" accessibilityLabel={`Posted by @${r.name}. Change`} disabled={busy} onPress={() => setOpen(open === "people" ? null : "people")}
119
+ style={state => ({ flexDirection: "row", alignItems: "center", gap: 6, minHeight: compact ? 44 : 28, paddingHorizontal: 10, borderRadius: 6, borderWidth: 1, borderColor: c.border,
120
+ backgroundColor: state.pressed || (state as { hovered?: boolean }).hovered ? c.surface2 : c.surface1 })}>
121
+ <Text style={t.body}>{`@${r.name}`}</Text>
122
+ <Icon name="ChevronDown" size={12} color={c.foregroundMuted} />
123
+ </Pressable>;
124
+ const label = (s: string) => <Text style={[t.meta, { width: compact ? undefined : 72, minWidth: compact ? 64 : undefined }]}>{s}</Text>;
125
+ const rowStyle = { flexDirection: "row", flexWrap: "wrap", alignItems: "center", gap: 8 } as const;
126
+ return <View style={{ gap: 8 }}>
127
+ <View style={rowStyle}>
128
+ {label("Posted by")}
129
+ {plan.person ? personChip(plan.person)
130
+ : <Button title="Pick a person" icon="Plus" theme={theme} compact={compact} disabled={busy} onPress={() => setOpen(open === "people" ? null : "people")} />}
131
+ </View>
132
+ {open === "people" && <ChatPicker kind="people" exclude={plan.person ? [plan.person] : []} theme={theme} compact={compact} onCancel={() => setOpen(null)}
133
+ onPick={ref => { setOpen(null); onChange({ person: ref }); }} />}
134
+ <View style={rowStyle}>
135
+ {label("In")}
136
+ {chips(plan.channels, "#", r => onChange({ channels: plan.channels.filter(x => x !== r) }))}
137
+ {plan.channels.length < 5 && <Button title={plan.channels.length ? "Add" : "Pick channels"} icon="Plus" kind={plan.channels.length ? "ghost" : "secondary"} theme={theme} compact={compact} disabled={busy} onPress={() => setOpen(open === "channels" ? null : "channels")} />}
138
+ </View>
139
+ {open === "channels" && <ChatPicker kind="channels" exclude={plan.channels} theme={theme} compact={compact} onCancel={() => setOpen(null)}
140
+ onPick={ref => { setOpen(null); onChange({ channels: [...plan.channels, ref] }); }} />}
141
+ </View>;
142
+ }
143
+
144
+ function ChatPicker({ kind, exclude, onPick, onCancel, theme, compact }: { kind: "people" | "channels"; exclude: ChatRef[]; onPick: (r: ChatRef) => void; onCancel: () => void; theme: Theme; compact: boolean }) {
145
+ const taken = (r: ChatRef) => exclude.some(x => (x.id && x.id === r.id) || x.name.toLowerCase() === r.name.toLowerCase());
146
+ const c = theme.colors; const t = text(c, compact);
147
+ const search = useRpc(briefChatSearchRpc);
148
+ const [q, setQ] = useState("");
149
+ const [debounced, setDebounced] = useState("");
150
+ useEffect(() => { const id = setTimeout(() => setDebounced(q.trim()), 350); return () => clearTimeout(id); }, [q]);
151
+ const results = useQuery({ queryKey: ["follow-up", "brief-chat", kind, debounced], enabled: debounced.length >= 2, staleTime: 60_000,
152
+ queryFn: async () => await search({ kind, query: debounced }) as { results: ChatRef[]; error: string | null } });
153
+ const prefix = kind === "people" ? "@" : "#";
154
+ const typed = q.trim().replace(/^[#@]/, "");
155
+ const row = (label: string, hint: string | null, onPress: () => void, key: string) => <Pressable key={key} accessibilityRole="button" onPress={onPress}
156
+ style={state => ({ minHeight: compact ? 44 : 34, paddingHorizontal: 12, paddingVertical: 8, justifyContent: "center", borderTopWidth: 1, borderTopColor: c.border, backgroundColor: state.pressed || (state as { hovered?: boolean }).hovered ? c.surface2 : "transparent" })}>
157
+ <Text style={t.body}>{label}</Text>{hint && <Text style={t.meta}>{hint}</Text>}
158
+ </Pressable>;
159
+ return <View style={{ borderWidth: 1, borderColor: c.border, borderRadius: 8, backgroundColor: c.surface1, overflow: "hidden" }}>
160
+ <View style={{ flexDirection: "row", gap: 8, padding: 8, alignItems: "center" }}>
161
+ <TextInput autoFocus accessibilityLabel={kind === "people" ? "Search people" : "Search channels"} value={q} onChangeText={setQ} placeholder={kind === "people" ? "Pick who posts it: search by name" : "Add a channel: search by name"}
162
+ placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false} style={field(theme, compact)} />
163
+ <Button title="Cancel" kind="ghost" theme={theme} compact={compact} onPress={onCancel} />
164
+ </View>
165
+ {results.isFetching && <Text style={[t.meta, { paddingHorizontal: 12, paddingBottom: 8 }]}>Searching…</Text>}
166
+ {results.data?.error && <Text style={[t.meta, { paddingHorizontal: 12, paddingBottom: 8, color: c.statusWarning }]}>{results.data.error}</Text>}
167
+ {(results.data?.results ?? []).filter(r => !taken(r)).map(r => row(`${prefix}${r.name}`, null, () => onPick(r), r.id ?? r.name))}
168
+ {debounced.length >= 2 && !results.isFetching && !results.data?.results.length && !results.data?.error && <Text style={[t.meta, { paddingHorizontal: 12, paddingBottom: 8 }]}>{`Nothing matches "${debounced}".`}</Text>}
169
+ {typed.length >= 2 && !taken({ id: null, name: typed }) && !(results.data?.results ?? []).some(r => r.name.toLowerCase() === typed.toLowerCase()) && row(`Use "${prefix}${typed}" as typed`, null, () => onPick({ id: null, name: typed }), "typed")}
170
+ </View>;
171
+ }
172
+
173
+ function PlanCardView({ card, busy, onAnother, onRetry, onPaste, theme, compact }: { card: NonNullable<ReturnType<typeof planCard>>; busy: boolean; onAnother: () => void; onRetry: () => void; onPaste: (link: string) => void; theme: Theme; compact: boolean }) {
174
+ const c = theme.colors; const t = text(c, compact);
175
+ const warn = card.tone === "warn"; const error = card.tone === "error";
176
+ const icon = card.tone === "ok" ? "Check" : warn ? "TriangleAlert" : error ? "CircleAlert" : "Info";
177
+ const iconColor = card.tone === "ok" ? c.statusSuccess : warn ? c.statusWarning : error ? c.statusDanger : c.foregroundMuted;
178
+ return <View accessibilityRole={warn || error ? "alert" : undefined} style={{ flexDirection: "row", gap: 10, padding: compact ? 14 : 12, borderRadius: 8, borderWidth: 1, borderColor: warn ? withAlpha(c.statusWarning, 0.4) : c.border, backgroundColor: warn ? withAlpha(c.statusWarning, 0.14) : c.surface1 }}>
179
+ <View style={{ paddingTop: 2 }}><Icon name={icon} size={14} color={iconColor} /></View>
180
+ <View style={{ flex: 1, minWidth: 0, gap: 6 }}>
181
+ <Text style={t.label}>{card.title}</Text>
182
+ <Text style={t.meta}>{card.line}</Text>
183
+ {(warn || error) && card.inUse && <View style={{ flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 4 }}>
184
+ <Text style={t.meta}>{card.inUse.line}</Text>
185
+ <Button title="Open" kind="ghost" icon="ExternalLink" theme={theme} compact={compact} onPress={() => void openExternalUrl(card.inUse!.url).catch(() => undefined)} />
186
+ </View>}
187
+ {card.tone === "ok" && <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
188
+ {card.actions.includes("open") && <Button title="Open" icon="ExternalLink" grow={compact} theme={theme} compact={compact} onPress={() => void openExternalUrl(card.url).catch(() => undefined)} />}
189
+ {card.actions.includes("another") && <Button title="Use another link" grow={compact} theme={theme} compact={compact} onPress={onAnother} />}
190
+ </View>}
191
+ {(warn || error) && card.paste && <LinkField initial="" busy={busy} onUse={onPaste} theme={theme} compact={compact} placeholder={error ? "Or paste this week's link" : "Paste this week's link"} />}
192
+ {error && card.retry && <Button title="Look again" icon="RotateCcw" theme={theme} compact={compact} loading={busy} onPress={onRetry} />}
193
+ </View>
194
+ </View>;
195
+ }
196
+
197
+ const SWEEP_TIMES = ["05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00"];
198
+
199
+ function QueueSection({ view, theme, compact }: { view: BriefSettingsView; theme: Theme; compact: boolean }) {
200
+ const c = theme.colors; const t = text(c, compact);
201
+ const write = useRpc(setBriefSettingsRpc); const cache = useQueryClient(); const toast = useToast();
202
+ const change = useMutation({
203
+ mutationFn: async (input: QueueChange) => await write(input) as BriefSettingsView,
204
+ onSuccess: value => cache.setQueryData(briefSettingsKey, value),
205
+ onError: error => toast.error(errorText(error)),
206
+ });
207
+ const q = view.queue;
208
+ const times = [...new Set([...SWEEP_TIMES, q.sweepAt])].sort();
209
+ const zoneFrom = view.clock.zoneFrom === "setting" ? "set here" : view.clock.zoneFrom === "device" ? "this device's" : "the host's";
210
+ const usual = defaultWorkdays(view.clock.timeZone);
211
+ return <SettingsSection title="Linear queue" info="What the morning sweep reads, when, and what the brief's changes are counted from. The sweep reads every issue assigned to you in these states.">
212
+ <ChipGroup label="Counts as the queue" hint="Issues assigned to you in these states. At least one."
213
+ options={QUEUE_STATE_TYPES.map(st => ({ value: st, label: queueStateLabel(st) }))} value={q.states} disabled={change.isPending}
214
+ onChange={states => change.mutate({ states: states as typeof q.states })} theme={theme} compact={compact} />
215
+ <SettingsCard>
216
+ <SettingsSelect label="Sweep at" hint={`On workdays, in ${view.clock.timeZone}.`} value={q.sweepAt} disabled={change.isPending}
217
+ options={times.map(v => ({ value: v, label: v }))} onValueChange={sweepAt => change.mutate({ sweepAt })} />
218
+ <SettingsSelect label="Changes since" hint={q.since === "read" ? "What moved since you last read the brief; before your first read, since the last workday's sweep." : "What moved since the last workday's sweep, however often you look."}
219
+ value={q.since} disabled={change.isPending} options={[{ value: "read", label: "Your last read" }, { value: "workday", label: "Your last workday" }]} onValueChange={since => change.mutate({ since })} />
220
+ </SettingsCard>
221
+ <ZoneField view={view} zoneFrom={zoneFrom} busy={change.isPending} onChange={timeZone => change.mutate({ timeZone })} theme={theme} compact={compact} />
222
+ <ChipGroup label="Workdays" hint={q.workdays ? "Set here." : "The zone's usual week."} options={WEEKDAYS.map(d => ({ value: d, label: d }))} value={q.workdays ?? usual} disabled={change.isPending}
223
+ onChange={days => change.mutate({ workdays: sameDays(days, usual) ? null : days as Weekday[] })} theme={theme} compact={compact} />
224
+ </SettingsSection>;
225
+ }
226
+ const sameDays = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every(d => b.includes(d));
227
+
228
+ /** A labelled row of on/off chips (checkboxes): at least one stays on. 44 px on a phone. */
229
+ function ChipGroup({ label, hint, options, value, onChange, disabled, theme, compact }: { label: string; hint?: string; options: { value: string; label: string }[]; value: readonly string[]; onChange: (v: string[]) => void; disabled?: boolean; theme: Theme; compact: boolean }) {
230
+ const c = theme.colors; const t = text(c, compact);
231
+ return <View style={{ gap: 6 }}>
232
+ <Text style={t.label}>{label}</Text>
233
+ {hint && <Text style={t.meta}>{hint}</Text>}
234
+ <View role="group" aria-label={label} style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
235
+ {options.map(choice => {
236
+ const on = value.includes(choice.value);
237
+ const last = on && value.length === 1;
238
+ return <Pressable key={choice.value} accessibilityRole="checkbox" accessibilityState={{ checked: on, disabled: disabled || last }} accessibilityLabel={choice.label} disabled={disabled || last}
239
+ onPress={() => onChange(on ? value.filter(x => x !== choice.value) : options.map(x => x.value).filter(x => x === choice.value || value.includes(x)))}
240
+ style={state => ({ minWidth: compact ? 44 : 40, minHeight: compact ? 44 : 30, paddingHorizontal: 10, borderRadius: 6, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 5, borderWidth: 1,
241
+ borderColor: on ? withAlpha(c.accent, 0.55) : c.border, backgroundColor: on ? withAlpha(c.accent, 0.1) : (state as { hovered?: boolean }).hovered ? c.surface1 : "transparent" })}>
242
+ {on && <Icon name="Check" size={12} color={c.foreground} />}
243
+ <Text style={{ color: on ? c.foreground : c.foregroundMuted, fontSize: 13, fontWeight: "500" }}>{choice.label}</Text>
244
+ </Pressable>;
245
+ })}
246
+ </View>
247
+ </View>;
248
+ }
249
+
250
+ function ZoneField({ view, zoneFrom, busy, onChange, theme, compact }: { view: BriefSettingsView; zoneFrom: string; busy: boolean; onChange: (z: string | null) => void; theme: Theme; compact: boolean }) {
251
+ const c = theme.colors; const t = text(c, compact);
252
+ const [value, setValue] = useState(view.queue.timeZone ?? "");
253
+ useEffect(() => setValue(view.queue.timeZone ?? ""), [view.queue.timeZone]);
254
+ const v = value.trim();
255
+ const valid = !v || isZone(v);
256
+ const dirty = v !== (view.queue.timeZone ?? "");
257
+ return <View style={{ gap: 6 }}>
258
+ <Text style={t.meta}>{`Time zone: ${view.clock.timeZone} (${zoneFrom})`}</Text>
259
+ <View style={{ flexDirection: "row", gap: 8, alignItems: "center" }}>
260
+ <TextInput accessibilityLabel="Time zone" value={value} onChangeText={setValue} placeholder="Automatic: this device's zone" placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false}
261
+ onSubmitEditing={() => valid && dirty && onChange(v || null)} style={field(theme, compact)} />
262
+ {dirty && <Button title={v ? "Save" : "Use automatic"} theme={theme} compact={compact} disabled={!valid} loading={busy} onPress={() => onChange(v || null)} />}
263
+ </View>
264
+ {!valid && <Text accessibilityRole="alert" style={[t.meta, { color: c.statusDanger }]}>Use an IANA time zone, like Europe/Paris.</Text>}
265
+ </View>;
266
+ }
@@ -14,7 +14,7 @@ import type { Colors } from "./theme";
14
14
  import { QuestionBody, QuestionDismissX, meanwhile } from "./questions";
15
15
  import { needsYouBlock } from "../shared/needs-block";
16
16
  import { age } from "../shared/inbox";
17
- import { questionState } from "../shared/questions";
17
+ import { isDoneOnly, questionState } from "../shared/questions";
18
18
  import type { Brief } from "../shared/brief";
19
19
  import { useState, type ReactNode } from "react";
20
20
  import { usePendingAnswer } from "./pending-answers";
@@ -261,8 +261,9 @@ function QuestionAsk({ workspace: w, questionId, context, theme, compact, now, o
261
261
  const state = meanwhile(w, q, pending);
262
262
  // "Q1 · title" (DESIGN.md): the chip leads so a long title wraps under itself, and the age stays on the right.
263
263
  const header = <View style={{ flexDirection: "row", alignItems: "flex-start", gap: 8 }}>
264
- <View style={{ paddingTop: 2 }}><Icon name={questionState(q) === "stopped" ? "CirclePause" : "MessageCircleQuestion"} size={compact ? 16 : 14} color={c.statusWarning} /></View>
265
- <View style={{ paddingTop: 1 }}><Chip theme={theme} label={q.id} color={c.foregroundMuted} /></View>
264
+ <View style={{ paddingTop: 2 }}><Icon name={questionState(q) === "stopped" ? "CirclePause" : q.need === "action" ? "Hand" : "MessageCircleQuestion"} size={compact ? 16 : 14} color={c.statusWarning} /></View>
265
+ {/* An action card carries no Q chip (one-done-button): there is nothing to cite, only something to do. */}
266
+ {!isDoneOnly(q) && <View style={{ paddingTop: 1 }}><Chip theme={theme} label={q.id} color={c.foregroundMuted} /></View>}
266
267
  <RichText accessibilityRole="header" numberOfLines={open ? undefined : 1} style={[open ? t.ask : t.label, { flex: 1, minWidth: 0 }]}>{q.title}</RichText>
267
268
  <Text style={[t.meta, { paddingTop: 1 }]}>{age(q.askedAt, now)}</Text>
268
269
  <View style={{ paddingTop: 1 }}><Icon name={open ? "ChevronUp" : "ChevronDown"} size={14} color={c.foregroundMuted} /></View>
@@ -0,0 +1,228 @@
1
+ import { useState, type ReactNode } from "react";
2
+ import { ActivityIndicator, TextInput, View } from "react-native";
3
+ import { Text } from "./text";
4
+ import { useRpc } from "@getpaseo/plugin/client";
5
+ import { Icon, Modal, SettingsAction, SettingsCard, SettingsSection, SettingsSelect, SettingsSwitch, useToast } from "@getpaseo/plugin/client/ui";
6
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
7
+ import { prStatsSettingsRpc, setPrStatsRpc } from "../shared/contracts";
8
+ import { estimateLines, sizeWords, statsRepoLine, statsRepoWait, statsRepoWaitTone, type SetPrStatsInput, type StatsSettingsView, type StatsTeam } from "../shared/pr-stats-settings";
9
+ import { Button, errorText, SubmitScope, text, type Theme } from "./kit";
10
+ import { Pressable } from "./text";
11
+
12
+ export const prStatsSettingsKey = ["follow-up", "pr-stats-settings"];
13
+ type Row = StatsSettingsView["repos"][number];
14
+ const REPO = /^[\w.-]+\/[\w.-]+$/;
15
+ export const PR_STATS_INFO = "PR statistics show who opens PRs and whose PRs wait longest for a first review, from each repository's own GitHub data. Turn them on per repository. They read GitHub slowly in the background, stop whenever GitHub's limit drops under 40% so your agents and PR checks come first, and stay on this machine.";
16
+
17
+ /**
18
+ * Settings → Following → PR statistics: one switch per repository Follow-up knows. Turning one on opens the opt-in
19
+ * sheet (the estimate first, `OptInSheet`); turning one off asks in place, with keeping the data as the default and
20
+ * deleting it as the quiet extra. Options per repository (window, team, hidden people) fold under it; the clock and
21
+ * GitHub share are host-wide.
22
+ */
23
+ let openStatsPage: (() => void) | null = null;
24
+ /** index.client.tsx: how Settings opens the PR stats page ("Open PR stats"). */
25
+ export function setOpenStats(open: () => void): void { openStatsPage = open; }
26
+
27
+ export function PrStatsSettings({ theme, compact, onPage = false }: { theme: Theme; compact: boolean; /** Drawn on the page itself (no "Open PR stats"). */ onPage?: boolean }) {
28
+ const c = theme.colors; const t = text(c, compact);
29
+ const read = useRpc(prStatsSettingsRpc); const write = useRpc(setPrStatsRpc); const cache = useQueryClient(); const toast = useToast();
30
+ const query = useQuery({ queryKey: prStatsSettingsKey, queryFn: () => read({}), staleTime: 30_000, refetchInterval: 60_000 });
31
+ const change = useMutation({
32
+ mutationFn: (input: SetPrStatsInput & { toast?: string }) => { const { toast: _, ...rest } = input; return write(rest); },
33
+ onSuccess: (v, input) => { cache.setQueryData(prStatsSettingsKey, v); if (input.toast) toast.show(input.toast, { variant: "success" }); },
34
+ onError: e => toast.error(errorText(e)),
35
+ });
36
+ const [optIn, setOptIn] = useState<string | null>(null);
37
+ const [confirmOff, setConfirmOff] = useState<string | null>(null);
38
+ const [adding, setAdding] = useState("");
39
+ const data = query.data;
40
+ const withStats = data?.repos.filter(r => r.state !== "off") ?? [];
41
+ const alreadyOn = data?.repos.find(r => r.repo === adding.trim() && r.state !== "off") ?? null;
42
+ const addValid = REPO.test(adding.trim()) && !alreadyOn;
43
+ return <SettingsSection title="PR statistics" info={PR_STATS_INFO}>
44
+ {query.isPending && <ActivityIndicator accessibilityLabel="Loading PR statistics settings" color={c.foregroundMuted} style={{ alignSelf: "flex-start", marginVertical: 8 }} />}
45
+ {query.error && <SettingsCard><SettingsAction label="Couldn't load PR statistics" hint={errorText(query.error)} actionLabel="Retry" onPress={() => void query.refetch()} /></SettingsCard>}
46
+ {data && <>
47
+ <SettingsCard>
48
+ {data.repos.map(row => <View key={row.repo}>
49
+ <SettingsSwitch label={row.repo} hint={statsRepoLine(row, data.timeZone)} value={row.state === "on"} disabled={change.isPending}
50
+ onValueChange={on => {
51
+ if (on && row.state === "paused") change.mutate({ repo: row.repo, enable: true, toast: `${row.repo}: PR statistics on` });
52
+ else if (on) setOptIn(row.repo);
53
+ else setConfirmOff(row.repo);
54
+ }} />
55
+ {confirmOff === row.repo && <TurnOffConfirm row={row} theme={theme} compact={compact} busy={change.isPending}
56
+ onKeep={() => { setConfirmOff(null); change.mutate({ repo: row.repo, enable: false, toast: `${row.repo}: paused, data kept` }); }}
57
+ onDelete={() => { setConfirmOff(null); change.mutate({ repo: row.repo, enable: false, delete: true, toast: `${row.repo}: off, data deleted` }); }}
58
+ onCancel={() => setConfirmOff(null)} />}
59
+ <RepoWait row={row} theme={theme} compact={compact} />
60
+ {row.state === "on" && <OptionsFold row={row} theme={theme} compact={compact}>
61
+ <RepoOptions row={row} theme={theme} compact={compact} busy={change.isPending} set={(input, label) => change.mutate({ repo: row.repo, ...input, toast: `${row.repo}: ${label}` })} />
62
+ </OptionsFold>}
63
+ </View>)}
64
+ {/* A repository Follow-up hasn't seen yet. */}
65
+ <SubmitScope enabled={addValid} onSubmit={() => setOptIn(adding.trim())} style={{ flexDirection: compact ? "column" : "row", alignItems: compact ? "stretch" : "center", gap: 8, paddingHorizontal: compact ? 16 : 14, paddingVertical: 10, borderTopWidth: data.repos.length ? 1 : 0, borderTopColor: c.border }}>
66
+ <TextInput accessibilityLabel="Another repository, owner/repo" value={adding} onChangeText={setAdding} placeholder="Another repository: owner/repo" placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false}
67
+ style={{ flex: compact ? undefined : 1, minWidth: 0, minHeight: compact ? 44 : 32, paddingHorizontal: 10, borderRadius: 6, borderWidth: 1, borderColor: c.border, color: c.foreground, fontSize: compact ? 15 : 13, backgroundColor: c.surface0 }} />
68
+ {!!adding.trim() && <Button theme={theme} compact={compact} grow={compact} icon="Plus" title="Add" disabled={!addValid} onPress={() => setOptIn(adding.trim())} />}
69
+ </SubmitScope>
70
+ {!!adding.trim() && !alreadyOn && !REPO.test(adding.trim()) && <Text style={[t.meta, { paddingHorizontal: compact ? 16 : 14, paddingBottom: 10, marginTop: -4 }]}>Use owner/repo, like example/app.</Text>}
71
+ {alreadyOn && <Text style={[t.meta, { paddingHorizontal: compact ? 16 : 14, paddingBottom: 10, marginTop: -4 }]}>{`${alreadyOn.repo} is already ${alreadyOn.state === "on" ? "on" : "listed above (paused): turn its switch on"}.`}</Text>}
72
+ </SettingsCard>
73
+ {!data.repos.length && <Text style={t.meta}>Repositories show here once Follow-up sees a PR in them or a project with a GitHub remote, or add one above.</Text>}
74
+ {withStats.length > 0 && !onPage && openStatsPage && <SettingsCard><SettingsAction label="PR stats" hint="Who opens PRs and whose PRs wait longest, per repository." actionLabel="Open PR stats" onPress={() => openStatsPage?.()} /></SettingsCard>}
75
+ {withStats.length > 0 && <Text style={[t.meta, { marginTop: 4, paddingHorizontal: compact ? 6 : 5 }]}>All repositories</Text>}
76
+ {withStats.length > 0 && <SettingsCard>
77
+ <SettingsSelect label="GitHub share for stats" hint="At most this much of GitHub's hourly limit in any hour; stats always stop under 40% left." value={String(Math.round(data.settings.slice * 100))} disabled={change.isPending}
78
+ options={["1", "2", "5", "10"].map(v => ({ value: v, label: `${v}%` }))} onValueChange={v => change.mutate({ slice: Number(v) / 100, toast: `Stats may use ${v}% of GitHub's limit` })} />
79
+ <SettingsSelect<"calendar" | "working"> label="Clock" hint={`Working hours use one schedule for everyone: ${hoursWords(data.hours)}, ${data.timeZone}.`} value={data.settings.clock} disabled={change.isPending}
80
+ options={[{ value: "calendar", label: "Calendar time" }, { value: "working", label: "Working hours" }]} onValueChange={v => change.mutate({ clock: v, toast: v === "working" ? "Stats count working hours" : "Stats count calendar time" })} />
81
+ <SettingsSwitch label="Count stacks fairly" hint="A stacked PR's review clock starts when its parent got a first review or merged, not while it waits its turn." value={data.settings.enable_stack_aware} disabled={change.isPending}
82
+ onValueChange={v => change.mutate({ enable_stack_aware: v, toast: v ? "Stacked PRs start their clocks when reached" : "Stacked PRs start their clocks when asked" })} />
83
+ </SettingsCard>}
84
+ </>}
85
+ {optIn && <OptInSheet repo={optIn} theme={theme} compact={compact} onClose={() => setOptIn(null)}
86
+ onTurnOn={() => { const repo = optIn; setOptIn(null); setAdding(""); change.mutate({ repo, enable: true, toast: `${repo}: PR statistics on. The first read runs in the background.` }); }} />}
87
+ </SettingsSection>;
88
+ }
89
+
90
+ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
91
+ const hhmm = (m: number) => `${Math.floor(m / 60)}${m % 60 ? `:${String(m % 60).padStart(2, "0")}` : ""}`;
92
+ export function hoursWords(h: { days: number[]; from: number; to: number }): string {
93
+ const days = [...h.days].sort((a, b) => a - b);
94
+ const run = days.length > 1 && days.every((d, i) => i === 0 || d === days[i - 1]! + 1);
95
+ return `${run ? `${DAYS[days[0]!]}–${DAYS[days.at(-1)!]}` : days.map(d => DAYS[d]).join(", ")} ${hhmm(h.from)}–${hhmm(h.to)}`;
96
+ }
97
+ const teamWords = (team: StatsTeam) => team.kind === "everyone" ? "everyone" : team.kind === "people" ? `${team.logins.length} ${team.logins.length === 1 ? "person" : "people"}` : `@${team.team}`;
98
+ function repoOptionsSummary(row: Row): string {
99
+ const s = row.settings!;
100
+ return [`${s.windowDays} days`, teamWords(s.team), s.ignore.length ? `${s.ignore.length} hidden` : null].filter(Boolean).join(" · ");
101
+ }
102
+
103
+ /** A repository's options, folded under its own row at the row's left edge: "Options · 90 days · 4 people ›". */
104
+ function OptionsFold({ row, theme, compact, children }: { row: Row; theme: Theme; compact: boolean; children: ReactNode }) {
105
+ const c = theme.colors; const t = text(c, compact);
106
+ const [open, setOpen] = useState(false);
107
+ const summary = repoOptionsSummary(row);
108
+ return <View>
109
+ <Pressable accessibilityRole="button" accessibilityState={{ expanded: open }} aria-expanded={open} accessibilityLabel={`${row.repo} options, ${summary}`} accessibilityHint={open ? "Collapses" : "Expands"} onPress={() => setOpen(!open)}
110
+ style={state => ({ flexDirection: "row", alignItems: "center", gap: 6, minHeight: compact ? 44 : 28, paddingHorizontal: compact ? 16 : 14, marginTop: -6, paddingBottom: compact ? 4 : 8,
111
+ backgroundColor: state.pressed ? c.surface2 : "transparent" })}>
112
+ <Text numberOfLines={1} style={[t.meta, { flexShrink: 1 }]}>{`Options · ${summary}`}</Text>
113
+ <Icon name={open ? "ChevronDown" : "ChevronRight"} size={13} color={c.foregroundMuted} />
114
+ </Pressable>
115
+ {open && <View style={{ borderTopWidth: 1, borderTopColor: c.border }}>{children}</View>}
116
+ </View>;
117
+ }
118
+
119
+ /**
120
+ * Why a repository on isn't reading, on its own line under its row: red with a next step when GitHub refused it,
121
+ * amber while it waits for GitHub's limit or its share, muted while this machine is busy.
122
+ */
123
+ function RepoWait({ row, theme, compact }: { row: Row; theme: Theme; compact: boolean }) {
124
+ const c = theme.colors; const t = text(c, compact);
125
+ const words = statsRepoWait(row); const tone = statsRepoWaitTone(row);
126
+ if (!words || !tone) return null;
127
+ const color = tone === "danger" ? c.statusDanger : tone === "warning" ? c.statusWarning : c.foregroundMuted;
128
+ const next = tone === "danger" ? " Check this GitHub account can read it, or turn it off." : "";
129
+ return <View style={{ flexDirection: "row", gap: 6, paddingHorizontal: compact ? 16 : 14, paddingBottom: 10, marginTop: -4 }}>
130
+ <View style={{ paddingTop: compact ? 3 : 2 }}><Icon name={tone === "danger" ? "CircleAlert" : "Clock"} size={13} color={color} /></View>
131
+ <Text style={[t.meta, { flex: 1, color }]}>{`${words}${next}`}</Text>
132
+ </View>;
133
+ }
134
+
135
+ /** The quiet two-choice confirm in place (Q123's pattern): keep the data is the bordered default; delete is quiet red text. */
136
+ function TurnOffConfirm({ row, theme, compact, busy, onKeep, onDelete, onCancel }: { row: Row; theme: Theme; compact: boolean; busy: boolean; onKeep: () => void; onDelete: () => void; onCancel: () => void }) {
137
+ const c = theme.colors; const t = text(c, compact);
138
+ const n = row.settings?.status?.records ?? 0;
139
+ return <View accessibilityRole="alert" style={{ flexDirection: compact ? "column" : "row", alignItems: compact ? "stretch" : "center", gap: compact ? 10 : 16, paddingHorizontal: compact ? 16 : 14, paddingVertical: 12, borderTopWidth: 1, borderTopColor: c.border, borderStyle: "dashed" }}>
140
+ <Text style={[t.body, { flex: compact ? undefined : 1 }]}>{`Stop reading ${row.repo}? Its stored PRs stay readable unless you delete them.`}</Text>
141
+ <View style={{ flexDirection: compact ? "column-reverse" : "row", alignItems: compact ? "stretch" : "center", gap: 8 }}>
142
+ {n > 0 && <Button theme={theme} compact={compact} kind="danger" title={`Also delete the ${n.toLocaleString("en-US")} PRs`} disabled={busy} onPress={onDelete} accessibilityHint="Turns stats off and deletes what was read. This can't be undone." />}
143
+ {!compact && <Button theme={theme} compact={compact} kind="ghost" title="Cancel" onPress={onCancel} />}
144
+ <Button theme={theme} compact={compact} kind="secondary" title="Turn off, keep data" disabled={busy} onPress={onKeep} />
145
+ {compact && <Button theme={theme} compact={compact} kind="ghost" title="Cancel" onPress={onCancel} />}
146
+ </View>
147
+ </View>;
148
+ }
149
+
150
+ /** Window, team filter and hidden people for one repository. */
151
+ function RepoOptions({ row, theme, compact, busy, set }: { row: Row; theme: Theme; compact: boolean; busy: boolean; set: (input: Omit<SetPrStatsInput, "repo">, label: string) => void }) {
152
+ const c = theme.colors; const t = text(c, compact);
153
+ const s = row.settings!;
154
+ const [teamDraft, setTeamDraft] = useState(s.team.kind === "people" ? s.team.logins.join(", ") : s.team.kind === "github" ? s.team.team : "");
155
+ const [teamKind, setTeamKind] = useState<StatsTeam["kind"]>(s.team.kind);
156
+ const [hidden, setHidden] = useState(s.ignore.join(", "));
157
+ const members = s.status?.teamMembers;
158
+ const teamHint = s.team.kind === "github" && members?.team === s.team.team && members.error ? `Can't read the team @${s.team.team} with this GitHub account, so stats show everyone. Pick people instead, or give gh read:org.`
159
+ : teamKind === "people" ? "Logins, separated by commas." : teamKind === "github" ? "org/team-slug, read once a day." : "Everyone who opened or reviewed a PR here, minus bots and hidden people.";
160
+ const logins = (v: string) => [...new Set(v.split(/[\s,]+/).map(x => x.trim().replace(/^@/, "")).filter(Boolean))];
161
+ const field = { flex: 1, minWidth: 0, minHeight: compact ? 44 : 32, paddingHorizontal: 10, borderRadius: 6, borderWidth: 1, borderColor: c.border, color: c.foreground, fontSize: compact ? 15 : 13, backgroundColor: c.surface0 } as const;
162
+ const slug = teamDraft.trim().replace(/^@/, "");
163
+ const draftTeam: StatsTeam | null = teamKind === "people" ? (logins(teamDraft).length ? { kind: "people", logins: logins(teamDraft) } : null)
164
+ : teamKind === "github" ? (/^[\w.-]+\/[\w.-]+$/.test(slug) ? { kind: "github", team: slug } : null) : { kind: "everyone" };
165
+ const teamProblem = teamDraft.trim() && !draftTeam ? (teamKind === "people" ? "Add at least one login." : "Use org/team-slug, like example/backend.") : null;
166
+ const teamChanged = !!draftTeam && JSON.stringify(draftTeam) !== JSON.stringify(s.team);
167
+ const saveTeam = () => { if (draftTeam && teamChanged) set({ team: draftTeam }, draftTeam.kind === "people" ? `team: ${draftTeam.logins.length} people` : draftTeam.kind === "github" ? `team: @${draftTeam.team}` : "team: everyone"); };
168
+ const hiddenChanged = logins(hidden).join(",") !== s.ignore.join(",");
169
+ const pad = { paddingHorizontal: compact ? 16 : 14, paddingBottom: 10 };
170
+ return <View style={{ paddingBottom: 6 }}>
171
+ <SettingsSelect label="History" hint="How far back stats read. Longer reads more once, then costs the same to keep current." value={String(s.windowDays)} disabled={busy}
172
+ options={[30, 90, 180].map(d => ({ value: String(d), label: `${d} days` }))} onValueChange={v => set({ windowDays: Number(v) as 30 | 90 | 180 }, `${v} days of history`)} />
173
+ <SettingsSelect<StatsTeam["kind"]> label="Team" hint={teamHint} value={teamKind} disabled={busy}
174
+ options={[{ value: "everyone", label: "Everyone" }, { value: "people", label: "Picked people" }, { value: "github", label: "A GitHub team" }]}
175
+ onValueChange={v => { setTeamKind(v); setTeamDraft(v === s.team.kind ? (s.team.kind === "people" ? s.team.logins.join(", ") : s.team.kind === "github" ? s.team.team : "") : ""); if (v === "everyone") set({ team: { kind: "everyone" } }, "team: everyone"); }} />
176
+ {teamKind !== "everyone" && <SubmitScope enabled={!busy && teamChanged} onSubmit={saveTeam} style={[pad, { flexDirection: "row", alignItems: "center", gap: 8 }]}>
177
+ <TextInput accessibilityLabel={teamKind === "people" ? "Team logins" : "GitHub team, org/slug"} value={teamDraft} onChangeText={setTeamDraft} placeholder={teamKind === "people" ? "alice, bob, carol" : "example/backend"} placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false} style={field} />
178
+ <Button theme={theme} compact={compact} title="Save" disabled={busy || !teamChanged} onPress={saveTeam} />
179
+ </SubmitScope>}
180
+ {teamKind !== "everyone" && (teamProblem || teamKind !== s.team.kind) && <Text style={[t.meta, { paddingHorizontal: compact ? 16 : 14, paddingBottom: 10, marginTop: -4, color: teamProblem ? c.statusDanger : c.foregroundMuted }]}>{teamProblem ?? "Not saved yet: stats show the saved team until you Save."}</Text>}
181
+ <View style={{ height: 1, backgroundColor: c.border }} />
182
+ <View style={{ paddingHorizontal: compact ? 16 : 14, paddingTop: 10, gap: 4 }}>
183
+ <Text style={t.body}>Hidden from stats</Text>
184
+ <Text style={t.meta}>Bots are always hidden. Add service accounts that look like people; * matches anything.</Text>
185
+ </View>
186
+ <SubmitScope enabled={!busy && hiddenChanged} onSubmit={() => set({ ignore: logins(hidden) }, logins(hidden).length ? `${logins(hidden).length} hidden` : "nobody hidden")} style={[pad, { paddingTop: 8, flexDirection: "row", alignItems: "center", gap: 8 }]}>
187
+ <TextInput accessibilityLabel="Hidden from stats, logins" value={hidden} onChangeText={setHidden} placeholder="deploy-robot, release-*" placeholderTextColor={c.foregroundMuted} autoCapitalize="none" autoCorrect={false} style={field} />
188
+ <Button theme={theme} compact={compact} title="Save" disabled={busy || !hiddenChanged} onPress={() => set({ ignore: logins(hidden) }, logins(hidden).length ? `${logins(hidden).length} hidden` : "nobody hidden")} />
189
+ </SubmitScope>
190
+ </View>;
191
+ }
192
+
193
+ /**
194
+ * The opt-in sheet: what turning stats on reads, costs and stores, from the repository's own count (1 GitHub point),
195
+ * before anything is read. The switch turns on only from its Turn on; a repository the token can't read is refused here.
196
+ */
197
+ export function OptInSheet({ repo, theme, compact, onClose, onTurnOn }: { repo: string; theme: Theme; compact: boolean; onClose: () => void; onTurnOn: () => void }) {
198
+ const c = theme.colors; const t = text(c, compact);
199
+ const read = useRpc(prStatsSettingsRpc);
200
+ const query = useQuery({ queryKey: [...prStatsSettingsKey, "estimate", repo], queryFn: () => read({ repo, estimate: true }), staleTime: 5 * 60_000, retry: false });
201
+ const e = query.data?.estimate ?? null;
202
+ const slice = query.data?.settings.slice ?? 0.05;
203
+ const lines = e ? estimateLines(e, slice) : null;
204
+ const point = (icon: string, main: ReactNode, sub?: string) => <View style={{ flexDirection: "row", gap: 10 }}>
205
+ <View style={{ paddingTop: compact ? 2 : 1 }}><Icon name={icon} size={16} color={c.foregroundMuted} /></View>
206
+ <View style={{ flex: 1, gap: 2 }}><Text style={t.body}>{main}</Text>{sub && <Text style={t.meta}>{sub}</Text>}</View>
207
+ </View>;
208
+ return <Modal title={`Turn on PR stats for ${repo}?`} open onOpenChange={next => { if (!next) onClose(); }}>
209
+ <Modal.Content contentContainerStyle={{ padding: compact ? 16 : 20 }}>
210
+ <SubmitScope enabled={!!lines} onSubmit={onTurnOn} style={{ gap: compact ? 16 : 14, maxWidth: 560 }}>
211
+ {query.isPending && <View style={{ flexDirection: "row", gap: 8, alignItems: "center" }}><ActivityIndicator color={c.foregroundMuted} /><Text style={t.meta}>Counting PRs changed in the last 90 days…</Text></View>}
212
+ {(query.error || e?.error) && <Text accessibilityRole="alert" style={[t.body, { color: c.statusDanger }]}>{e?.error ?? errorText(query.error)}</Text>}
213
+ {lines && e && <>
214
+ <Text style={[t.body, { color: c.foregroundMuted }]}>About <Text style={[t.body, { fontWeight: "600" }]}>{`${e.prs!.toLocaleString("en-US")} PRs`}</Text> changed in the last 90 days.</Text>
215
+ {point("Gauge", <>Reading them costs about <Text style={[t.body, { fontWeight: "600" }]}>{`${e.points!.toLocaleString("en-US")} GitHub points`}</Text>{`, ${lines.time.charAt(0).toLowerCase()}${lines.time.slice(1)}`}</>,
216
+ `Never more than ${Math.round(slice * 100)}% of your hourly limit (${e.slicePoints.toLocaleString("en-US")} points). Staying current: about 1–15 points an hour.`)}
217
+ {point("CirclePause", "Stats pause whenever GitHub's limit drops under 40%, so your agents and PR checks always come first.")}
218
+ {point("Lock", `Stored on this machine only, about ${sizeWords(e.bytes ?? 0)}: numbers, times, logins and PR titles.`, "No code and no comment text. Bots are left out.")}
219
+ <Text style={t.meta}>90 days · everyone · calendar time. Change these in the repository's options.</Text>
220
+ </>}
221
+ <View style={{ flexDirection: "row", justifyContent: "flex-end", gap: 8, flexWrap: "wrap" }}>
222
+ <Button theme={theme} compact={compact} grow={compact} kind="ghost" title="Cancel" onPress={onClose} />
223
+ <Button shortcut theme={theme} compact={compact} grow={compact} kind="primary" title="Turn on" disabled={!lines} onPress={onTurnOn} />
224
+ </View>
225
+ </SubmitScope>
226
+ </Modal.Content>
227
+ </Modal>;
228
+ }