paseo-follow-up 2.3.0-beta.2 → 2.3.0-beta.3

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.
@@ -3,7 +3,8 @@ import { Platform, TextInput, View } from "react-native";
3
3
  import { Pressable, Text } from "./text";
4
4
  import { Icon, ScrollView, useToast } from "@getpaseo/plugin/client/ui";
5
5
  import { homeCounts, type HomeGroupId, type HomeModel } from "../shared/home";
6
- import { filterHome, homeSearchDocs, indexDocs, defaultActive, omniboxResults, overseerProvider, workspaceProvider, type OmniboxItem, type OmniboxProvider } from "../shared/search";
6
+ import { layoutHint, filterHome, homeSearchDocs, indexDocs, defaultActive, omniboxResults, overseerProvider, workspaceProvider, type OmniboxItem, type OmniboxProvider } from "../shared/search";
7
+ import { LayoutCapture, type LayoutKey } from "../shared/layout-swap";
7
8
  import { DEFAULT_SORT, SORT_HINT, SORT_LABEL, SORT_MODES, type SortMode } from "../shared/sort";
8
9
  import { PRIORITY_SOURCE_LABEL } from "../shared/priorities";
9
10
  import { rankFooter } from "../shared/ranker";
@@ -13,7 +14,7 @@ import type { HomeSources } from "./home-data";
13
14
  import { useMinute } from "./home-data";
14
15
  import { Spinner } from "./motion";
15
16
  import { withAlpha, type Colors } from "./theme";
16
- import type { Theme } from "./kit";
17
+ import { text, type Theme } from "./kit";
17
18
  import { MenuItemContent, menuGlyph, menuItemRow } from "./menu-item";
18
19
  import { useLinkedIndex } from "./linked";
19
20
 
@@ -27,6 +28,8 @@ import { useLinkedIndex } from "./linked";
27
28
  export type Omnibox = {
28
29
  query: string;
29
30
  setQuery(q: string): void;
31
+ setPhysical?: (q: string | null) => void;
32
+ layoutHint?: string | null;
30
33
  /** null while the query is empty: the list shows its groups. */
31
34
  results: OmniboxItem[] | null;
32
35
  active: number;
@@ -42,6 +45,7 @@ export type Omnibox = {
42
45
  */
43
46
  export function useOmnibox(model: HomeModel, sources: HomeSources, extraProviders: readonly OmniboxProvider[] = []): Omnibox {
44
47
  const [query, setQueryState] = useState("");
48
+ const [physical, setPhysical] = useState<string | null>(null);
45
49
  // null: the default row. -1: none, so Enter does nothing.
46
50
  const [active, setActive] = useState<number | null>(null);
47
51
  const inputRef = useRef<TextInput | null>(null);
@@ -57,7 +61,7 @@ export function useOmnibox(model: HomeModel, sources: HomeSources, extraProvider
57
61
  const index = useMemo(() => searching ? indexDocs(homeSearchDocs({ model, paseo: sources.paseo.all(), tracked: sources.live.all(), archived: sources.live.archived(), agents: sources.extras.agents(), linked })) : null,
58
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
59
63
  [searching, model, live, paseo, extras, linked]);
60
- const providers = useMemo(() => index ? [workspaceProvider(index), ...extraProviders, overseerProvider(askOn)] : [], [index, extraProviders, askOn]);
64
+ const providers = useMemo(() => index ? [workspaceProvider(index, Date.now(), physical), ...extraProviders, overseerProvider(askOn)] : [], [index, extraProviders, askOn, physical]);
61
65
  const results = useMemo(() => searching ? omniboxResults(providers, query) : null, [providers, query, searching]);
62
66
  const setQuery = useCallback((q: string) => { setQueryState(q); setActive(null); }, []);
63
67
  const fallback = defaultActive(results);
@@ -67,7 +71,8 @@ export function useOmnibox(model: HomeModel, sources: HomeSources, extraProvider
67
71
  // A request made before this field mounted (the search key opening Home) is taken on mount.
68
72
  const token = useSyncExternalStore(sources.extras.subscribe, sources.extras.focusToken, sources.extras.focusToken);
69
73
  useEffect(() => { if (sources.extras.takeFocus()) inputRef.current?.focus(); }, [token, sources.extras]);
70
- return { query, setQuery, results, active: Math.min(current, Math.max(0, (results?.length ?? 1) - 1)), move, inputRef, askOn };
74
+ const hint = layoutHint((results ?? []).flatMap(r => r.hit ? [r.hit] : []));
75
+ return { query, setQuery, setPhysical, layoutHint: hint, results, active: Math.min(current, Math.max(0, (results?.length ?? 1) - 1)), move, inputRef, askOn };
71
76
  }
72
77
 
73
78
  type DomKey = { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; target: unknown; preventDefault(): void };
@@ -92,9 +97,10 @@ export function useSlashToFocus(omnibox: Omnibox, enabled = true) {
92
97
  * The one query field: Home's omnibox (SearchField) and the sidebar view's filter (FilterField) are this with
93
98
  * different words. `dense` is the phone layout: a 44px field with a rounder shape and body-size text.
94
99
  */
95
- export function QueryField({ theme, value, onChange, placeholder, icon, dense, inputRef, slashHint, slashTitle, onSubmit, onArrow, listKeys = false, count, autoFocus = false, onEscape }: {
100
+ export function QueryField({ theme, value, onChange, placeholder, icon, dense, inputRef, slashHint, slashTitle, onSubmit, onArrow, listKeys = false, count, autoFocus = false, onEscape, onLayoutQuery }: {
96
101
  /** Its arrows step into the list below (client/list-keys.ts): the sidebar filter, and Home's search while empty. */
97
102
  listKeys?: boolean;
103
+ onLayoutQuery?: (q: string | null) => void;
98
104
  /** "2 of 12" at the field's end (a panel section's search), in place of the field's own ✕: the section has its own. */
99
105
  count?: string;
100
106
  autoFocus?: boolean;
@@ -108,10 +114,31 @@ export function QueryField({ theme, value, onChange, placeholder, icon, dense, i
108
114
  }) {
109
115
  const c = theme.colors;
110
116
  const [focused, setFocused] = useState(false);
117
+ const capture = useRef(new LayoutCapture());
118
+ const layoutCallback = useRef(onLayoutQuery); layoutCallback.current = onLayoutQuery;
119
+ useEffect(() => {
120
+ if (Platform.OS !== "web" || !onLayoutQuery) return;
121
+ type Input = { value: string; selectionStart: number | null; selectionEnd: number | null };
122
+ type InputEvent = LayoutKey & { target: unknown };
123
+ type Listen = (name: string, listener: (e: InputEvent) => void, capture: boolean) => void;
124
+ const doc = (globalThis as unknown as { document?: { addEventListener: Listen; removeEventListener: Listen } }).document;
125
+ if (!doc) return;
126
+ const belongs = (e: InputEvent) => e.target === inputRef.current;
127
+ const key = (e: InputEvent) => {
128
+ if (!belongs(e)) return;
129
+ const input = e.target as Input;
130
+ capture.current.key(e, input.value, input.selectionStart, input.selectionEnd);
131
+ };
132
+ const reset = (e: InputEvent) => { if (belongs(e)) { capture.current.reset(); layoutCallback.current?.(null); } };
133
+ doc.addEventListener("keydown", key, true);
134
+ const resets = ["paste", "cut", "drop", "compositionstart", "compositionend", "select"];
135
+ for (const event of resets) doc.addEventListener(event, reset, true);
136
+ return () => { doc.removeEventListener("keydown", key, true); for (const event of resets) doc.removeEventListener(event, reset, true); };
137
+ }, [inputRef, !!onLayoutQuery]);
111
138
  return <View style={{ flex: 1, minWidth: 0, flexDirection: "row", alignItems: "center", gap: dense ? 8 : 6, height: dense ? 44 : 32, paddingHorizontal: dense ? 12 : 8, borderRadius: dense ? 12 : 6,
112
139
  borderWidth: 1, borderColor: focused ? withAlpha(c.foreground, 0.35) : c.border, backgroundColor: c.surface1 }}>
113
140
  <Icon name={icon as never} size={dense ? 16 : 13} color={c.foregroundMuted} />
114
- <TextInput ref={inputRef} value={value} onChangeText={onChange} placeholder={placeholder} placeholderTextColor={c.foregroundMuted}
141
+ <TextInput ref={inputRef} value={value} onChangeText={q => { onLayoutQuery?.(capture.current.change(q)); onChange(q); }} placeholder={placeholder} placeholderTextColor={c.foregroundMuted}
115
142
  accessibilityLabel={placeholder} autoFocus={autoFocus} autoCorrect={false} autoCapitalize="none" spellCheck={false} returnKeyType="go"
116
143
  {...(listKeys ? { dataSet: { listKeys: "1" } } as object : {})}
117
144
  onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
@@ -144,7 +171,7 @@ export function QueryField({ theme, value, onChange, placeholder, icon, dense, i
144
171
  export function SearchField({ theme, omnibox, dense, onEnter, anywhereKey }: { theme: Theme; omnibox: Omnibox; dense: boolean; onEnter: (item: OmniboxItem | null) => void; anywhereKey?: string | null }) {
145
172
  const { query, setQuery, results, active, move, inputRef, askOn } = omnibox;
146
173
  const placeholder = askOn ? dense ? "Search or ask the Overseer" : "Search, or ask the Overseer" : "Search workspaces, branches, PRs";
147
- return <QueryField theme={theme} value={query} onChange={setQuery} placeholder={placeholder} icon="Search" dense={dense} inputRef={inputRef} slashHint={anywhereKey || "/"}
174
+ return <QueryField theme={theme} onLayoutQuery={omnibox.setPhysical} value={query} onChange={setQuery} placeholder={placeholder} icon="Search" dense={dense} inputRef={inputRef} slashHint={anywhereKey || "/"}
148
175
  slashTitle={anywhereKey ? `${anywhereKey} from anywhere · / on Home` : "/ focuses the search"}
149
176
  onSubmit={() => { const item = results?.[active]; if (item || !query.trim()) onEnter(item ?? null); }} onArrow={move} listKeys={!query.trim()} />;
150
177
  }
@@ -153,8 +180,9 @@ export function SearchField({ theme, omnibox, dense, onEnter, anywhereKey }: { t
153
180
  * The sidebar view's filter (2.1): narrows the list in place with Home search's matcher (shared/search.ts
154
181
  * `filterHome`), keeping groups and the chosen order. Archived workspaces stay out; Home's search finds those.
155
182
  */
156
- export type ListFilter = { query: string; setQuery: (q: string) => void; model: HomeModel; hits: ReturnType<typeof filterHome>["hits"]; inputRef: { current: TextInput | null } };
183
+ export type ListFilter = { setPhysical?: (q: string | null) => void; layoutHint?: string | null; query: string; setQuery: (q: string) => void; model: HomeModel; hits: ReturnType<typeof filterHome>["hits"]; inputRef: { current: TextInput | null } };
157
184
  export function useListFilter(model: HomeModel, sources: HomeSources): ListFilter {
185
+ const [physical, setPhysical] = useState<string | null>(null);
158
186
  const [query, setQuery] = useState("");
159
187
  const inputRef = useRef<TextInput | null>(null);
160
188
  const live = useSyncExternalStore(sources.live.subscribe, sources.live.version, sources.live.version);
@@ -166,12 +194,17 @@ export function useListFilter(model: HomeModel, sources: HomeSources): ListFilte
166
194
  const index = useMemo(() => searching ? indexDocs(homeSearchDocs({ model, paseo: sources.paseo.all(), tracked: sources.live.all(), agents: sources.extras.agents(), linked })) : null,
167
195
  // eslint-disable-next-line react-hooks/exhaustive-deps
168
196
  [searching, model, live, paseo, extras, linked]);
169
- const filtered = useMemo(() => index ? filterHome(model, index, query) : { model, hits: null }, [index, model, query]);
170
- return { query, setQuery, model: filtered.model, hits: filtered.hits, inputRef };
197
+ const filtered = useMemo(() => index ? filterHome(model, index, query, Date.now(), physical) : { model, hits: null }, [index, model, query, physical]);
198
+ return { query, setQuery, setPhysical, layoutHint: layoutHint([...(filtered.hits?.values() ?? [])]), model: filtered.model, hits: filtered.hits, inputRef };
171
199
  }
172
200
  /** "Filter workspaces": a filter icon and no key binding, so it never reads as Paseo's own Search (the Command Center, ⌘K). */
173
201
  export function FilterField({ theme, filter, dense }: { theme: Theme; filter: ListFilter; dense: boolean }) {
174
- return <QueryField theme={theme} value={filter.query} onChange={filter.setQuery} placeholder="Filter workspaces" icon="ListFilter" dense={dense} inputRef={filter.inputRef} slashHint={false} listKeys />;
202
+ return <QueryField theme={theme} onLayoutQuery={filter.setPhysical} value={filter.query} onChange={filter.setQuery} placeholder="Filter workspaces" icon="ListFilter" dense={dense} inputRef={filter.inputRef} slashHint={false} listKeys />;
203
+ }
204
+
205
+ /** Kept outside the textbox: never changes the query or adds a decision to the search flow. */
206
+ export function LayoutNotice({ theme, query, dense }: { theme: Theme; query?: string | null; dense: boolean }) {
207
+ return <Text accessibilityLiveRegion="polite" numberOfLines={2} style={{ ...text(theme.colors, dense).meta, ...(query ? { paddingTop: 4 } : { height: 0 }) }}>{query ? `Showing results for “\u2068${query}\u2069”` : ""}</Text>;
175
208
  }
176
209
 
177
210
  // ---------- sort ----------
package/client/home.tsx CHANGED
@@ -27,7 +27,7 @@ import { DismissReveal } from "./dismiss";
27
27
  import { Age, BadgeView, BRIEF_KEY, glyphColor, HomeList, OVERSEER_KEY, PrChipView, PrSummaryText, type OverseerRowState } from "./home-list";
28
28
  import { answerLine, overseerRowState } from "../shared/overseer";
29
29
  import type { OmniboxItem } from "../shared/search";
30
- import { ListTop, SearchField, SortMenu, StatusStrip, UsageMeters, useOmnibox, useSlashToFocus } from "./home-chrome";
30
+ import { LayoutNotice, ListTop, SearchField, SortMenu, StatusStrip, UsageMeters, useOmnibox, useSlashToFocus } from "./home-chrome";
31
31
  import { useHomeModel, useTick, type HomeSources } from "./home-data";
32
32
  import { laterLabel, useInbox, UndoBar, useNextRelay } from "./inbox";
33
33
  import { Spinner } from "./motion";
@@ -249,6 +249,7 @@ function HomeBody(props: PluginScreenProps & { deps: HomeDeps; onboarding: Onboa
249
249
  {!(compact && nothing) && <SortMenu theme={theme} mode={model.sort} onChange={deps.sources.extras.setSort} rankedAt={model.rankedAt} touch={compact} rank={rank} onRerank={deps.sources.extras.rankNow} />}
250
250
  {compact && <IconButton theme={theme} compact icon="Settings" label="Follow-up settings" onPress={deps.openSettings} />}
251
251
  </View>
252
+ <View style={{ paddingHorizontal: 16 }}><LayoutNotice theme={theme} query={omnibox.layoutHint} dense={compact} /></View>
252
253
  {!compact && !omnibox.results && <StatusStrip theme={theme} model={model} filter={filter} onFilter={setFilter} touch={compact} dense={compact} />}
253
254
  {!compact && !omnibox.results && <UsageMeters theme={theme} sources={deps.sources} dense={compact} hold={!!model.hold} />}
254
255
  {!compact && !omnibox.results && <SetupOffer theme={theme} compact={compact} view={props.onboarding} />}
@@ -6,7 +6,7 @@ import { Text } from "./text";
6
6
  import { UndoBar, useInbox, useSidebarViewMounted } from "./inbox";
7
7
  import { HomeList, OVERSEER_KEY, type OverseerRowState } from "./home-list";
8
8
  import { sidebarSelected } from "./theme";
9
- import { FilterField, SortMenu, useListFilter } from "./home-chrome";
9
+ import { FilterField, LayoutNotice, SortMenu, useListFilter } from "./home-chrome";
10
10
  import { useHomeModel, type HomeSources } from "./home-data";
11
11
  import { useRowMenu } from "./row-actions";
12
12
  import { RenameHost } from "./rename";
@@ -90,11 +90,12 @@ export function inboxSidebarView(sources: HomeSources, openOverseerHome: () => v
90
90
  keys={{ mode: "focus", onOpen: onSelect }}
91
91
  // The open chat's row wears Paseo's own selected-item fill, so it reads like a selected native item.
92
92
  selectedBg={sidebarSelected(c)}
93
- // One row, nothing else (invariant 8): the filter takes the width, the sort is an icon. zIndex keeps the
93
+ // One control row: the filter takes the width, the sort is an icon. A layout hint may sit below. zIndex keeps the
94
94
  // sort menu above the list on web, where every View is its own stacking context.
95
- top={<View style={{ zIndex: 10, flexDirection: "row", alignItems: "center", gap: touch ? 8 : 4, paddingHorizontal: touch ? 12 : 8, paddingVertical: touch ? 8 : 6, borderBottomWidth: 1, borderBottomColor: c.border }}>
96
- <FilterField theme={view.theme} filter={filter} dense={touch} />
97
- <SortMenu theme={view.theme} mode={full.sort} onChange={sources.extras.setSort} rankedAt={full.rankedAt} touch={touch} compact rank={rank} onRerank={sources.extras.rankNow} />
95
+ top={<View style={{ zIndex: 10, paddingHorizontal: touch ? 12 : 8, paddingVertical: touch ? 8 : 6, borderBottomWidth: 1, borderBottomColor: c.border }}>
96
+ <View style={{ flexDirection: "row", alignItems: "center", gap: touch ? 8 : 4 }}><FilterField theme={view.theme} filter={filter} dense={touch} />
97
+ <SortMenu theme={view.theme} mode={full.sort} onChange={sources.extras.setSort} rankedAt={full.rankedAt} touch={touch} compact rank={rank} onRerank={sources.extras.rankNow} /></View>
98
+ <LayoutNotice theme={view.theme} query={filter.layoutHint} dense={touch} />
98
99
  </View>}
99
100
  footer={filter.hits && !touch ? <Text style={{ color: c.foregroundMuted, fontSize: 11, paddingHorizontal: 8, paddingTop: 10, paddingBottom: 32 }}>Filtering this list · Esc clears</Text> : undefined} />
100
101
  <View style={{ position: "absolute", left: 8, right: 8, bottom: 8 }}><UndoBar store={sources.inbox} theme={view.theme} touch={touch} /></View>
package/client/stacks.tsx CHANGED
@@ -2,7 +2,7 @@ import { View } from "react-native";
2
2
  import { Pressable, Text } from "./text";
3
3
  import { Icon } from "@getpaseo/plugin/client/ui";
4
4
  import type { Pr, Workspace } from "../shared/model";
5
- import { compactPrStatus, orderedStacks, settledForDisplay } from "../shared/presentation";
5
+ import { compactPrStatus, githubWaitLine, orderedStacks, settledForDisplay } from "../shared/presentation";
6
6
  import { mergeQueued, prTone, stackOrder } from "../shared/attention";
7
7
  import { reviewersMissing } from "../shared/pr-workflow";
8
8
  import { isGithubFlow } from "../shared/pr-actions";
@@ -123,6 +123,7 @@ export function StacksCard({ workspace: w, theme, compact, open, toggle, onOpen,
123
123
  const showRepo = new Set(w.prs.map(p => p.repo)).size > 1;
124
124
  const openCount = w.prs.filter(p => p.snapshot?.state === "OPEN").length;
125
125
  const inFlight = w.prActions.filter(a => a.state === "sending");
126
+ const wait = githubWaitLine(w, Date.now());
126
127
  const settledOpen = open("settled");
127
128
  const settledPrs = settled.reduce((n, s) => n + s.prs.length, 0);
128
129
  // Every PR in the order the card draws them, settled stacks included: the search's "n of N" and its filter.
@@ -135,6 +136,13 @@ export function StacksCard({ workspace: w, theme, compact, open, toggle, onOpen,
135
136
  <View style={{ paddingTop: 3 }}><Spinner color={c.accent} size={12} /></View>
136
137
  <RichText style={[t.meta, { flex: 1, color: c.foreground }]}>{a.result || (isGithubFlow(w.prs.find(p => p.key === a.prs[0])?.snapshot) ? "Sending to GitHub…" : "Submitting to Graphite…")}</RichText>
137
138
  </View>)}
139
+ {!hits && wait && <View accessible accessibilityLabel={wait.label} style={{ flexDirection: "row", gap: 8, paddingHorizontal: 12, paddingVertical: 8, borderTopWidth: 1, borderTopColor: c.border }}>
140
+ <View style={{ paddingTop: 2 }}><Icon name="CirclePause" size={13} color={c.foregroundMuted} /></View>
141
+ <View style={{ flex: 1, gap: 2 }}>
142
+ <Text style={[t.meta, { color: c.foreground, fontVariant: ["tabular-nums"] }]}>{wait.title}</Text>
143
+ <Text style={t.meta}>{wait.detail}</Text>
144
+ </View>
145
+ </View>}
138
146
  {!hits && <HeldMerges workspace={w} theme={theme} compact={compact} framed />}
139
147
  {!hits && !w.prs.length && <View style={{ paddingHorizontal: 12, paddingVertical: 10, borderTopWidth: 1, borderTopColor: c.border, gap: 4 }}>
140
148
  <Text style={t.body}>No PRs yet</Text>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "2.3.0-beta.2",
4
+ "version": "2.3.0-beta.3",
5
5
  "description": "A Paseo plugin that follows every workspace until the work is done: one Home for what needs you, questions you answer anywhere, and repairs that send themselves.",
6
6
  "type": "module",
7
7
  "files": [
@@ -1,3 +1,4 @@
1
+ import { searchRows } from "../shared/search";
1
2
  import { sendingOf } from "../shared/sending";
2
3
  import { agentActor, type Actor } from "../shared/actor";
3
4
  import { conditionId, noProgressSends } from "../shared/send-decision";
@@ -363,7 +364,10 @@ export class AgentActions {
363
364
 
364
365
  private async listPrs(args: { workspace?: string; needs_reviewers?: boolean; ready_to_merge?: boolean; include_closed?: boolean }) {
365
366
  const state = await this.d.store.snapshot();
366
- const workspaces = this.tracked(state).filter(w => !args.workspace || w.id === args.workspace || w.title === args.workspace);
367
+ const tracked = this.tracked(state);
368
+ // Stable ids remain exact identities. Text queries share Home's layout-aware matcher.
369
+ const exact = tracked.find(w => w.id === args.workspace);
370
+ const workspaces = exact ? [exact] : searchRows(tracked, w => [{ field: "name", text: w.title }], args.workspace ?? "");
367
371
  if (args.workspace && !workspaces.length) throw new Error(`No tracked workspace matches ${args.workspace}.`);
368
372
  const prs = workspaces.flatMap(w => w.prs.map(p => prRow(w, p)))
369
373
  .filter(r => args.include_closed || !["MERGED", "CLOSED"].includes(r.state))
package/server/engine.ts CHANGED
@@ -130,7 +130,7 @@ export class Engine {
130
130
  statusCheck: (w: Workspace, now: number, inputs?: string) => Promise<void> = async () => {};
131
131
  /** Background refreshes skipped while paused, for tests and the resource check. */
132
132
  skipped = 0;
133
- constructor(readonly store: Store, private github: Pick<Github, "observe">, private gateway: Gateway, private now = Date.now, private settleMs = 60_000, private nudgeMs = NUDGE_MS) {}
133
+ constructor(readonly store: Store, private github: Pick<Github, "observe"> & Partial<Pick<Github, "waitUntil">>, private gateway: Gateway, private now = Date.now, private settleMs = 60_000, private nudgeMs = NUDGE_MS) {}
134
134
  async recover(): Promise<void> {
135
135
  await this.store.mutate(state => {
136
136
  for (const w of state.workspaces) {
@@ -182,6 +182,17 @@ export class Engine {
182
182
  this.running = this.store.batch(() => this.run(o)).catch(() => { this.error = "Follow-up refresh failed. Saved work is intact; refresh will retry."; }).finally(() => { this.running = null; });
183
183
  return this.running;
184
184
  }
185
+ /**
186
+ * When Follow-up's GitHub reads resume for this workspace's open PRs, while the account's budget is under the reserve
187
+ * (`Github.waitUntil`): the earliest reset among their repositories, or null when reads run. Merged and closed PRs
188
+ * aren't read anyway, so a workspace with only those says nothing.
189
+ */
190
+ private githubWait(w: Workspace): string | null {
191
+ if (!this.github.waitUntil) return null;
192
+ const until = [...new Set(w.prs.filter(p => p.snapshot?.state !== "MERGED" && p.snapshot?.state !== "CLOSED").map(p => p.repo))]
193
+ .map(repo => this.github.waitUntil!(repo)).filter((t): t is number => t !== null && t > this.now());
194
+ return until.length ? new Date(Math.min(...until)).toISOString() : null;
195
+ }
185
196
  /** Reads one workspace's PRs fresh and records what came back, nothing else (a Refresh of a dormant workspace). */
186
197
  private async refreshPrs(w: Workspace): Promise<void> {
187
198
  const observations = await this.github.observe(w.prs, { background: true, fresh: new Set(w.prs.map(p => p.key)) });
@@ -257,15 +268,17 @@ export class Engine {
257
268
  // left, same runtime, no PR read or error it hasn't recorded, and a full pass under OBSERVE_FULL_MS ago (time-based
258
269
  // rules, like the 120 s acknowledgement, run on that pass). The checks cost a ~200-byte JSON and a shallow compare per PR.
259
270
  const runtimeKey = JSON.stringify(runtime);
271
+ const githubWait = this.githubWait(original);
260
272
  const last = this.observedPass.get(original.id);
261
273
  // A scheduled task due since the last pass makes it a full pass, so a trigger fires at its time, not up to a minute late.
262
- const untouched = !!last && last.w === original && last.runtime === runtimeKey && this.now() - last.at < OBSERVE_FULL_MS && this.now() < last.dueAt && o.workspaceId !== original.id &&
274
+ const untouched = (original.githubWait?.until ?? null) === githubWait && !!last && last.w === original && last.runtime === runtimeKey && this.now() - last.at < OBSERVE_FULL_MS && this.now() < last.dueAt && o.workspaceId !== original.id &&
263
275
  original.prs.every(p => { const seen = observations.get(p.key); return !seen || seen.error === p.error && sameSnapshot(seen.snapshot, p.snapshot, !isHot(original) && !awaitsRead(original)); });
264
276
  if (!untouched) this.observationWrites++;
265
277
  if (!untouched) await this.store.mutateWorkspace(original.id, w => {
266
278
  w.runtimeBusy = runtime.busy; w.runtimeReason = runtime.reason; w.taskAgents = runtime.taskAgents;
267
279
  w.backgroundBusy = runtime.backgroundBusy ?? false;
268
280
  w.mainBusy = repairWait(runtime);
281
+ if ((w.githubWait?.until ?? null) !== githubWait) w.githubWait = githubWait ? { until: githubWait } : null;
269
282
  if (runtime.mainTitle !== undefined && (w.mainAgentTitle ?? null) !== runtime.mainTitle) w.mainAgentTitle = runtime.mainTitle;
270
283
  if (runtime.gone && w.goneAgent?.agentId !== w.mainAgentId) w.goneAgent = { agentId: w.mainAgentId, at: new Date(this.now()).toISOString(), reason: runtime.gone };
271
284
  if (w.goneAgent?.agentId === w.mainAgentId) w.runtimeReason = GONE_REASON;
@@ -396,7 +409,9 @@ export class Engine {
396
409
  if (state.workspaceOptOuts?.includes(workspaceId)) state.workspaceOptOuts = state.workspaceOptOuts.filter(id => id !== workspaceId);
397
410
  });
398
411
  const activated = findWorkspace(await this.store.snapshot(), workspaceId);
399
- void this.tick();
412
+ // Its PRs fresh, everything else with the usual backoff: before 2026-11-19 this was a full fresh read of every
413
+ // tracked PR (~100 GraphQL points per follow at 100 open PRs).
414
+ void this.tick({ background: true, workspaceId });
400
415
  return activated;
401
416
  }
402
417
  /** Records the developer's answer, then queues it unless they chose to copy it or put it in chat. */
package/server/github.ts CHANGED
@@ -5,7 +5,7 @@ import type { PrWorkflow } from "../shared/pr-workflow";
5
5
  import type { Pr, Snapshot } from "../shared/model";
6
6
  import type { Deployments } from "./deployments";
7
7
  import { notSetUpEvidence } from "../shared/task-trigger";
8
- import { budgetTier, cadence, dueForRead, type Budget } from "../shared/poll";
8
+ import { budgetTier, cadence, dueForRead, probeVerdict, SAFETY_READ_MS, type Budget, type Fingerprint } from "../shared/poll";
9
9
  import { cliApi, githubApi, type GithubApi } from "./github-api";
10
10
  import { splitReviewers, TEAM_SLUG, USER_LOGIN } from "../shared/reviewers";
11
11
  const exec = promisify(execFile);
@@ -68,21 +68,58 @@ export function parsePr(pr: Node, trunk: string, observedAt: string, required: s
68
68
  };
69
69
  }
70
70
 
71
+ /** Check counts by state: the whole connection's, whatever page of nodes comes back. */
72
+ const COUNTS = "checkRunCountsByState{state count} statusContextCountsByState{state count}";
73
+ /**
74
+ * A probe's fields (shared/poll.ts, change-first reads): everything the full read decides on that GitHub can report
75
+ * without per-check or per-comment nodes. ~3 requests per PR, so ~1 point per 33 PRs; the full read is ~107 per PR.
76
+ */
77
+ const PROBE = `updatedAt state headRefOid baseRefName isDraft mergeable mergeStateStatus reviewDecision isInMergeQueue autoMergeRequest{enabledAt}
78
+ reviewThreads(first:100){pageInfo{hasNextPage} nodes{id isResolved}}
79
+ commits(last:1){nodes{commit{statusCheckRollup{contexts(first:1){${COUNTS}}}}}}`;
80
+ /** PRs per probe query (one account, any number of its repositories): ~300 requests, about 3 points. */
81
+ const PROBE_CHUNK = 100;
82
+ const RUNNING_STATES = new Set(["QUEUED", "IN_PROGRESS", "PENDING", "WAITING", "REQUESTED", "EXPECTED"]);
83
+ const FAILED_STATES = new Set(["FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"]);
84
+ /**
85
+ * The fingerprint of a PR as a probe or a full read returned it, or null when it can't be compared (threads past one
86
+ * page, no updatedAt or no check counts: an older GitHub), which leaves that PR on full reads.
87
+ */
88
+ export function fingerprint(pr: Node): Fingerprint | null {
89
+ const threads = pr.reviewThreads;
90
+ if (typeof pr.updatedAt !== "string" || !threads || !Array.isArray(threads.nodes) || threads.pageInfo?.hasNextPage !== false) return null;
91
+ const contexts = pr.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts;
92
+ if (contexts && (!Array.isArray(contexts.checkRunCountsByState) || !Array.isArray(contexts.statusContextCountsByState))) return null;
93
+ const counts: [string, number][] = [
94
+ ...(contexts?.checkRunCountsByState ?? []).map((c: Node): [string, number] => [`run:${c.state}`, Number(c.count) || 0]),
95
+ ...(contexts?.statusContextCountsByState ?? []).map((c: Node): [string, number] => [`status:${c.state}`, Number(c.count) || 0]),
96
+ ].filter(([, n]) => n > 0).sort(([a], [b]) => a.localeCompare(b));
97
+ const sum = (states: Set<string>) => counts.reduce((total, [key, n]) => total + (states.has(key.slice(key.indexOf(":") + 1)) ? n : 0), 0);
98
+ const unresolved = threads.nodes.filter((t: Node) => !t.isResolved).map((t: Node) => String(t.id)).sort();
99
+ return {
100
+ core: JSON.stringify([pr.updatedAt, pr.state, pr.headRefOid, pr.baseRefName, !!pr.isDraft, pr.mergeable ?? null, pr.mergeStateStatus ?? null, pr.reviewDecision ?? null, pr.isInMergeQueue ?? null, !!pr.autoMergeRequest, unresolved]),
101
+ checks: JSON.stringify(counts), running: sum(RUNNING_STATES), failed: sum(FAILED_STATES),
102
+ };
103
+ }
104
+
71
105
  /** Ruleset rules for a ref (GraphQL `Ref.rules`), the same set REST `rules/branches/<branch>` returns. */
72
106
  const RULES = "rules(first:100){pageInfo{hasNextPage} nodes{type repositoryRuleset{enforcement} parameters{...on RequiredStatusChecksParameters{requiredStatusChecks{context}}}}}";
73
- const fields = `number title url state headRefOid headRefName baseRefName isDraft mergeable mergeStateStatus reviewDecision mergedAt mergeCommit{oid} isInMergeQueue autoMergeRequest{enabledAt}
107
+ const fields = `number title url state updatedAt headRefOid headRefName baseRefName isDraft mergeable mergeStateStatus reviewDecision mergedAt mergeCommit{oid} isInMergeQueue autoMergeRequest{enabledAt}
74
108
  author{login}
75
109
  reviewRequests(first:100){pageInfo{hasNextPage} nodes{requestedReviewer{__typename ...on User{login} ...on Team{slug}}}}
76
110
  latestReviews(first:100){pageInfo{hasNextPage} nodes{state author{__typename login}}}
77
111
  baseRef{branchProtectionRule{requiredStatusCheckContexts} ${RULES} associatedPullRequests(first:100,states:[OPEN]){nodes{number headRefName state headRepository{nameWithOwner}}}}
78
112
  reviewThreads(first:100){pageInfo{hasNextPage} nodes{id isResolved comments(last:1){nodes{updatedAt}}}}
79
- commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{
113
+ commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){${COUNTS} pageInfo{hasNextPage} nodes{
80
114
  ...on CheckRun{name status conclusion} ...on StatusContext{context state}
81
115
  }}}}}}`;
82
116
 
83
- /** A GitHub write that failed outright (refused) or whose outcome is unknown (timed out, no reply). */
84
- /** Merged with a complete snapshot: final. Never read again except on its workspace's Refresh, and never in error. */
85
- const finalMerged = (p: Pr): boolean => p.snapshot?.state === "MERGED" && !!p.snapshot.complete;
117
+ /**
118
+ * Merged or closed with a complete snapshot: final. Never read again except on its workspace's Refresh, and never in
119
+ * error. Closed joined merged on 2026-11-19: closed PRs were re-read every minute forever. A reopened PR shows on
120
+ * the workspace's Refresh, or when its agent registers it again.
121
+ */
122
+ const finalMerged = (p: Pr): boolean => (p.snapshot?.state === "MERGED" || p.snapshot?.state === "CLOSED") && !!p.snapshot.complete;
86
123
 
87
124
  export class GithubWriteError extends Error { constructor(message: string, readonly uncertain: boolean) { super(message); } }
88
125
  type Method = "squash" | "merge" | "rebase";
@@ -194,17 +231,39 @@ export class Github {
194
231
  const last = this.last.get(p.key);
195
232
  return cadence(last?.snapshot, p.error || last?.error, this.changedAt.get(p.key) ?? null, this.now()) !== "idle";
196
233
  }
197
- /** Requests GitHub reads made, for tests and the poll-cost harness. */
198
- readonly stats = { graphql: 0, rest: 0, skipped: 0, points: 0 };
234
+ /** Requests GitHub reads made, for tests and the poll-cost harness. `probes`: probe queries; `unchanged`: PRs a probe settled. */
235
+ readonly stats = { graphql: 0, rest: 0, skipped: 0, points: 0, probes: 0, unchanged: 0 };
236
+ /** Each PR's fingerprint from its last full read, and when that read was (change-first reads, shared/poll.ts). */
237
+ private fingerprints = new Map<string, Fingerprint>();
238
+ private fullAt = new Map<string, number>();
239
+ private noteBudget(owner: string, rate: Node | undefined): void {
240
+ if (!rate || typeof rate.remaining !== "number") return;
241
+ this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt) || this.now() + 3_600_000, ...(typeof rate.limit === "number" ? { limit: rate.limit } : {}) });
242
+ this.stats.points += Number(rate.cost) || 0;
243
+ }
244
+ private outOfBudget(owner: string, error: unknown): void {
245
+ this.budgets.set(owner, { remaining: 0, resetAt: (error as { resetAt?: number }).resetAt ?? this.now() + 10 * 60_000 });
246
+ }
247
+ /** A due PR that a probe may settle: read in full before, nothing wrong with that read, not asked for fresh. */
248
+ private probeable(p: Pr, o: { background?: boolean; fresh?: Set<string> }): boolean {
249
+ const last = this.last.get(p.key);
250
+ return !!o.background && !o.fresh?.has(p.key) && !!last?.snapshot?.complete && !last.error && !p.error && this.fingerprints.has(p.key) && this.now() - (this.fullAt.get(p.key) ?? 0) < SAFETY_READ_MS;
251
+ }
199
252
  /**
200
253
  * Reads every PR fresh, unless `background` (the engine's timer tick) allows backoff. Then only `fresh` keys,
201
254
  * `hot` keys (busy workspaces) and hot PRs force their repository to be read this tick.
255
+ *
256
+ * Change-first (invariant `github-reads-scale-with-change`): a due PR read in full before is probed first, one query
257
+ * per account for every such PR, and read in full only when the probe saw a change that matters (`probeVerdict`).
258
+ * A fresh request (Refresh, opening the panel) and a foreground read (agent tools, actions) read in full.
202
259
  */
203
260
  async observe(prs: Pr[], o: { background?: boolean; fresh?: Set<string>; hot?: Set<string> } = {}): Promise<Map<string, Observation>> {
204
261
  const result = new Map<string, Observation>();
205
262
  const repositories = [...new Set(prs.map(p => p.repo))];
206
263
  const modes = new Map<string, PrWorkflow>();
207
264
  for (const repo of repositories) modes.set(repo, this.workflow ? await this.workflow(repo).catch((): PrWorkflow => "github") : "graphite");
265
+ const full = new Map<string, Pr[]>();
266
+ const probes = new Map<string, Pr[]>();
208
267
  for (const repo of repositories) {
209
268
  const targets = [...new Map(prs.filter(p => p.repo === repo).map(p => [p.key, p])).values()];
210
269
  const owner = repo.split("/")[0];
@@ -212,29 +271,66 @@ export class Github {
212
271
  const pinned = (p: Pr) => o.hot?.has(p.key) || o.fresh?.has(p.key);
213
272
  const repoUrgent = targets.some(p => pinned(p) || this.hot(p));
214
273
  // Per-PR backoff (shared/poll.ts): only due PRs go into this tick's queries; the rest reuse their last
215
- // observation. A read costs ~1 GraphQL point per PR, so reading fewer PRs is what saves the budget.
274
+ // observation.
216
275
  const due = targets.filter(p => {
217
- // Merged is final: a merged PR whose status is known isn't read again, not even on a cold start. Only the
276
+ // Merged or closed is final: one whose status is known isn't read again, not even on a cold start. Only the
218
277
  // developer's Refresh of its workspace (fresh) reads it.
219
278
  // A stored error doesn't undo that (2.0.1-beta.0 left some behind): the skip below reports no error, clearing it.
220
279
  if (finalMerged(p) && !o.fresh?.has(p.key)) return false;
221
280
  if (tier === "critical") return false;
281
+ // Under the reserve, background reads stop; the developer's Refresh and foreground reads (agent tools) still go.
282
+ if (tier === "reserve" && o.background && !o.fresh?.has(p.key)) return false;
222
283
  if (!o.background || !this.last.has(p.key) || o.fresh?.has(p.key) || o.hot?.has(p.key)) return true;
223
284
  const last = this.last.get(p.key)!;
224
285
  return dueForRead({ snapshot: last.snapshot, error: p.error || last.error, changedAt: this.changedAt.get(p.key) ?? null, readAt: this.readAt.get(p.key) ?? 0, now: this.now(), tier, repoUrgent, since: this.changedAt.get(p.key) ?? this.seenAt.get(p.key) ?? null });
225
286
  });
226
287
  const dueKeys = new Set(due.map(p => p.key));
227
288
  for (const p of targets) if (!dueKeys.has(p.key)) { this.stats.skipped++; result.set(p.key, finalMerged(p) ? { snapshot: { ...p.snapshot! }, error: null } : this.standIn(p, owner)); }
228
- if (!due.length) continue;
289
+ for (const p of due) { const into = this.probeable(p, o) ? probes : full; into.set(into === probes ? owner : repo, [...(into.get(into === probes ? owner : repo) ?? []), p]); }
290
+ }
291
+ // Probes: one query per account (owner) for up to PROBE_CHUNK PRs across its repositories.
292
+ for (const [owner, group] of probes) {
293
+ for (let offset = 0; offset < group.length; offset += PROBE_CHUNK) {
294
+ const chunk = group.slice(offset, offset + PROBE_CHUNK);
295
+ const byRepo = [...new Set(chunk.map(p => p.repo))];
296
+ const query = `query{rateLimit{cost remaining resetAt limit} ${byRepo.map((repo, r) => {
297
+ const [o, n] = repo.split("/");
298
+ return `r${r}:repository(owner:${JSON.stringify(o)},name:${JSON.stringify(n)}){${chunk.filter(p => p.repo === repo).map(p => `p${p.number}:pullRequest(number:${p.number}){${PROBE}}`).join(" ")}}`;
299
+ }).join(" ")}}`;
300
+ const reread = (p: Pr) => full.set(p.repo, [...(full.get(p.repo) ?? []), p]);
301
+ try {
302
+ this.stats.graphql++; this.stats.probes++;
303
+ const payload = await this.api.graphql(byRepo[0], query, {});
304
+ if (((payload.errors ?? []) as Node[]).some(e => e.type === "RATE_LIMITED" || e.type === "RATE_LIMIT")) throw Object.assign(new Error("rate limited"), { rateLimited: true });
305
+ this.noteBudget(owner, payload.data?.rateLimit);
306
+ for (const p of chunk) {
307
+ const data = payload.data?.[`r${byRepo.indexOf(p.repo)}`]?.[`p${p.number}`];
308
+ const seen = data ? fingerprint(data) : null;
309
+ const before = this.fingerprints.get(p.key)!;
310
+ if (!seen || probeVerdict(before, seen, this.now() - (this.fullAt.get(p.key) ?? 0)) === "read") { reread(p); continue; }
311
+ // Nothing the full read decides on moved: the last observation is current as of now.
312
+ this.stats.unchanged++; this.readAt.set(p.key, this.now());
313
+ result.set(p.key, { snapshot: { ...this.last.get(p.key)!.snapshot!, observedAt: new Date(this.now()).toISOString() }, error: null });
314
+ }
315
+ } catch (error) {
316
+ if (rateLimited(error)) { this.outOfBudget(owner, error); for (const p of chunk) result.set(p.key, this.standIn(p, owner)); continue; }
317
+ // Any other probe failure: the full read decides (and reports) for these PRs.
318
+ for (const p of chunk) reread(p);
319
+ }
320
+ }
321
+ }
322
+ for (const [repo, due] of full) {
323
+ const owner = repo.split("/")[0];
229
324
  for (let offset = 0; offset < due.length; offset += CHUNK) {
230
325
  const group = due.slice(offset, offset + CHUNK);
231
- const [owner, name] = repo.split("/");
232
- const query = `query($owner:String!,$name:String!){rateLimit{cost remaining resetAt} repository(owner:$owner,name:$name){defaultBranchRef{name branchProtectionRule{requiredStatusCheckContexts} ${RULES}} squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed autoMergeAllowed viewerDefaultMergeMethod mergeQueue{id} ${group.map((p, i) => `p${i}:pullRequest(number:${p.number}){${fields}}`).join(" ")}}}`;
326
+ // A probe (or an earlier chunk) that hit the limit stops the rest of this tick's reads on that account.
327
+ if (budgetTier(this.budgets.get(owner), this.now()) === "critical") { for (const p of group) result.set(p.key, this.standIn(p, owner)); continue; }
328
+ const [, name] = repo.split("/");
329
+ const query = `query($owner:String!,$name:String!){rateLimit{cost remaining resetAt limit} repository(owner:$owner,name:$name){defaultBranchRef{name branchProtectionRule{requiredStatusCheckContexts} ${RULES}} squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed autoMergeAllowed viewerDefaultMergeMethod mergeQueue{id} ${group.map((p, i) => `p${i}:pullRequest(number:${p.number}){${fields}}`).join(" ")}}}`;
233
330
  try {
234
331
  this.stats.graphql++;
235
332
  const payload = await this.api.graphql(repo, query, { owner, name });
236
- const rate = payload.data?.rateLimit;
237
- if (rate && typeof rate.remaining === "number") { this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt) || this.now() + 3_600_000 }); this.stats.points += Number(rate.cost) || 0; }
333
+ this.noteBudget(owner, payload.data?.rateLimit);
238
334
  for (const p of group) this.readAt.set(p.key, this.now());
239
335
  // A partial response fails only the PRs its errors point at. An error outside any PR fails the group.
240
336
  const broken = new Set<string>(); const rulesBroken = new Set<string>();
@@ -270,6 +366,9 @@ export class Github {
270
366
  const trunkChecks = open && stacked(data) ? [...(repository.defaultBranchRef.branchProtectionRule?.requiredStatusCheckContexts ?? []), ...await rulesFor(trunk, trunkRules)] : [];
271
367
  const required = [...new Set([...(data.baseRef?.branchProtectionRule?.requiredStatusCheckContexts ?? []), ...base, ...trunkChecks])];
272
368
  const snapshot = parsePr(data, trunk, new Date(this.now()).toISOString(), required);
369
+ const print = fingerprint(data);
370
+ if (print) this.fingerprints.set(p.key, print); else this.fingerprints.delete(p.key);
371
+ this.fullAt.set(p.key, this.now());
273
372
  if (modes.get(repo) === "github") {
274
373
  // GitHub mode: merge-when-ready is GitHub's auto-merge, and the repository's merge settings travel with the PR.
275
374
  snapshot.prWorkflow = "github"; snapshot.repoMerge = repoMerge(repository);
@@ -281,7 +380,7 @@ export class Github {
281
380
  } catch (error) {
282
381
  // Out of GraphQL budget: don't fail. Keep the last observations and wait for the reset.
283
382
  if (rateLimited(error)) {
284
- this.budgets.set(owner, { remaining: 0, resetAt: (error as { resetAt?: number }).resetAt ?? this.now() + 10 * 60_000 });
383
+ this.outOfBudget(owner, error);
285
384
  for (const p of group) result.set(p.key, this.standIn(p, owner));
286
385
  continue;
287
386
  }
@@ -331,6 +430,15 @@ export class Github {
331
430
  }
332
431
  /** Each owner's GraphQL budget from the last query's rateLimit (owners on one account report the same). */
333
432
  budget(owner: string): Budget | undefined { return this.budgets.get(owner); }
433
+ /**
434
+ * While Follow-up holds back reads on this repository's account for the budget (the reserve or less), when they
435
+ * resume (GitHub's reset); null when reads run. Feeds the workspace's "GitHub budget low" line (Workspace.githubWait).
436
+ */
437
+ waitUntil(repo: string): number | null {
438
+ const budget = this.budgets.get(repo.split("/")[0]);
439
+ const tier = budgetTier(budget, this.now());
440
+ return tier === "reserve" || tier === "critical" ? budget!.resetAt : null;
441
+ }
334
442
  /** Keeps each PR's last observation for backoff, and when its content last changed (observedAt aside). */
335
443
  private remember(key: string, value: Observation): void {
336
444
  const { observedAt: _, deployment: __, ...content } = value.snapshot ?? ({} as Partial<Snapshot>);
@@ -274,6 +274,8 @@ export const mcpSource: string = [
274
274
  " recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),",
275
275
  " batches: w.batches.filter(b => ![\"completed\", \"cancelled\"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),",
276
276
  " nextMessage: w.nextMessageInfo ?? null, sending: w.sending ?? null, heldTasks: w.heldTasks ?? [],",
277
+ " // GitHub budget low: Follow-up's PR reads wait until this time (null: they run); PR statuses are from the last read.",
278
+ " githubWait: w.githubWait ?? null,",
277
279
  " excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: \"summary\" };",
278
280
  "}",
279
281
  "function compact(tool, input, result) {",
package/server/mcp.mjs CHANGED
@@ -272,6 +272,8 @@ function currentWork(w) {
272
272
  recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),
273
273
  batches: w.batches.filter(b => !["completed", "cancelled"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),
274
274
  nextMessage: w.nextMessageInfo ?? null, sending: w.sending ?? null, heldTasks: w.heldTasks ?? [],
275
+ // GitHub budget low: Follow-up's PR reads wait until this time (null: they run); PR statuses are from the last read.
276
+ githubWait: w.githubWait ?? null,
275
277
  excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: "summary" };
276
278
  }
277
279
  function compact(tool, input, result) {
@@ -0,0 +1,63 @@
1
+ /** Standard Israeli SI-1452 key positions, not phonetic transliteration. Other scripts use physical capture. */
2
+ const EN = "qwertyuiopasdfghjkl;'zxcvbnm,./";
3
+ const HE = "/'קראטוןםפשדגכעיחלךף,זסבהנמצתץ.";
4
+ export function swapLayout(text: string, target: "english" | "hebrew"): string {
5
+ const from = target === "english" ? HE : EN, to = target === "english" ? EN : HE;
6
+ return [...text].map(c => { const i = from.indexOf(c.toLowerCase()); return target === "english" && c === "׳" ? "w" : i < 0 ? c : to[i]; }).join("");
7
+ }
8
+ /** Only offer script-appropriate variants. Mixed-script text keeps the already-correct words. */
9
+ export function layoutQueries(query: string, physical?: string | null): string[] {
10
+ const variants: string[] = [];
11
+ if (physical && physical !== query) return [physical];
12
+ if (/[\u0590-\u05ff]/u.test(query)) {
13
+ variants.push(swapLayout(query, "english"));
14
+ // Android Hebrew puts apostrophe and hyphen on Q/W; punctuation otherwise lives in its own row.
15
+ variants.push([...query].map(c => c === "'" ? "q" : c === "-" ? "w" : swapLayout(c, "english")).join(""));
16
+ }
17
+ else if (/[a-z]/i.test(query)) {
18
+ variants.push(swapLayout(query, "hebrew"));
19
+ variants.push([...query].map(c => c.toLowerCase() === "q" ? "'" : c.toLowerCase() === "w" ? "-" : swapLayout(c, "hebrew")).join(""));
20
+ }
21
+ const en = "`qwertyuiop[]asdfghjkl;'zxcvbnm,./", ru = "ёйцукенгшщзхъфывапролджэячсмитьбю.";
22
+ const russian = /[а-яё]/i.test(query);
23
+ if (russian || /[a-z]/i.test(query)) variants.push([...query].map(c => {
24
+ const from = russian ? ru : en, to = russian ? en : ru;
25
+ const i = from.indexOf(c.toLowerCase()); return i < 0 ? c : to[i];
26
+ }).join(""));
27
+ return [...new Set(variants)].filter(q => q !== query && q.trim());
28
+ }
29
+
30
+ export type LayoutKey = { key: string; code: string; shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean; isComposing?: boolean };
31
+ const PUNCT: Record<string, string> = { Space: " ", Minus: "-_", Equal: "=+", BracketLeft: "[{", BracketRight: "]}", Backslash: "\\|", Semicolon: ";:", Quote: "'\"", Comma: ",<", Period: ".>", Slash: "/?", Backquote: "`~" };
32
+ export function usKey(e: LayoutKey): string | null {
33
+ if (/^Key[A-Z]$/.test(e.code)) return e.shiftKey ? e.code.slice(3) : e.code.slice(3).toLowerCase();
34
+ if (/^Digit[0-9]$/.test(e.code)) return e.shiftKey ? ")!@#$%^&*("[Number(e.code.slice(5))] : e.code.slice(5);
35
+ const pair = PUNCT[e.code];
36
+ return pair ? pair[e.shiftKey && pair.length > 1 ? 1 : 0] : null;
37
+ }
38
+ /** Append-only reconstruction. Anything the key event cannot explain invalidates it until the field is empty. */
39
+ export class LayoutCapture {
40
+ private value = "";
41
+ private rebuilt: string | null = "";
42
+ private pending: { value: string; rebuilt: string } | null = null;
43
+ reset() { this.rebuilt = null; this.pending = null; }
44
+ key(e: LayoutKey, value: string, start: number | null, end: number | null) {
45
+ this.pending = null;
46
+ if (e.isComposing || e.altKey || e.ctrlKey || e.metaKey) { this.reset(); return; }
47
+ if (["Shift", "Control", "Alt", "Meta", "CapsLock"].includes(e.key)) return;
48
+ if (!value) { this.value = ""; this.rebuilt = ""; }
49
+ if (value !== this.value || start !== value.length || end !== start) { this.reset(); return; }
50
+ if (e.key === "Backspace" && this.rebuilt !== null) {
51
+ this.pending = { value: value.slice(0, -1), rebuilt: this.rebuilt.slice(0, -1) }; return;
52
+ }
53
+ if (e.key.length !== 1) { if (!["Enter", "Escape", "Tab"].includes(e.key)) this.reset(); return; }
54
+ const key = usKey(e);
55
+ if (!key || this.rebuilt === null) { this.reset(); return; }
56
+ this.pending = { value: value + e.key, rebuilt: this.rebuilt + key };
57
+ }
58
+ change(value: string): string | null {
59
+ this.rebuilt = !value ? "" : this.pending?.value === value ? this.pending.rebuilt : null;
60
+ this.value = value; this.pending = null;
61
+ return this.rebuilt && this.rebuilt !== value ? this.rebuilt : null;
62
+ }
63
+ }
package/shared/model.ts CHANGED
@@ -178,6 +178,11 @@ export const workspaceSchema = z.object({
178
178
  * clears an entry once its item is sent or cancelled; Needs you shows each with Retry and Cancel.
179
179
  */
180
180
  undelivered: z.array(z.object({ id: z.string().max(400), agentId: idSchema, agentTitle: z.string().nullable(), state: z.enum(["queued", "failed"]), reason: z.string().nullable(), since: z.string() })).max(20).optional(),
181
+ /**
182
+ * Follow-up is holding back its GitHub reads for this workspace's PRs until `until` (GitHub's reset): the account's
183
+ * GraphQL budget is under the reserve Follow-up leaves for agents (shared/poll.ts). Null or absent: reads run.
184
+ */
185
+ githubWait: z.object({ until: z.string() }).nullable().optional(),
181
186
  /** The main agent's title from Paseo, for "Next message to <title>". Absent: "the main agent". */
182
187
  mainAgentTitle: z.string().nullable().optional(),
183
188
  /** Open tasks kept out of the next message (reconcile): capped (sent NO_PROGRESS_CAP times unchanged), manual (Auto off for that task) or person (the agent said only a person can move it: Batch.humanOnly). */
@@ -1,3 +1,4 @@
1
+ import { searchRows } from "./search";
1
2
  import { sendingOf, type Sending } from "./sending";
2
3
  import { parseAnswersMessage } from "./questions";
3
4
  import { envelopeParts } from "./queue";
@@ -171,7 +172,12 @@ export const WORKSTREAMS_PAGE = 40;
171
172
  export function pageRows(rows: WorkstreamRow[], opts: { page?: number; size?: number; group?: HomeGroupId; query?: string } = {}) {
172
173
  const size = Math.min(Math.max(opts.size ?? WORKSTREAMS_PAGE, 1), 100);
173
174
  const q = opts.query?.trim().toLowerCase();
174
- const filtered = orderRows(rows).filter(r => (!opts.group || r.group === opts.group) && (!q || [r.title, r.branch, r.project, r.ask, r.activity, ...r.keys, ...r.prs.map(p => `#${p.number}`)].some(x => x?.toLowerCase().includes(q))));
175
+ const grouped = orderRows(rows).filter(r => !opts.group || r.group === opts.group);
176
+ const filtered = searchRows(grouped, r => [
177
+ { field: "name", text: r.title }, { field: "branch", text: r.branch ?? "" },
178
+ { field: "project", text: r.project ?? "" }, { field: "ask", text: [r.ask, r.activity].filter(Boolean).join(" ") },
179
+ { field: "linked", text: r.keys.join(" ") }, { field: "pr", text: r.prs.map(p => `#${p.number}`).join(" ") },
180
+ ], q ?? "");
175
181
  const pages = Math.max(1, Math.ceil(filtered.length / size));
176
182
  const page = Math.min(Math.max(opts.page ?? 1, 1), pages);
177
183
  // Resting workspaces come last and compact: no per-workspace detail, and their agents are likely unloaded.
package/shared/poll.ts CHANGED
@@ -62,26 +62,58 @@ export function cadence(s: Snapshot | null | undefined, error: string | null | u
62
62
  /** A merged PR is final: nothing on it feeds repairs, and its deploy state is probed separately every tick. */
63
63
  export const MERGED_POLL_MS = 30 * 60_000;
64
64
  /**
65
- * GitHub's GraphQL budget (5000 points an hour per account, shared with every agent). A read costs about one point
66
- * per PR. Under LOW_BUDGET points left, settled PRs wait LOW_IDLE_MS (and only in repositories with something
67
- * moving), merged PRs wait for the reset; under CRITICAL_BUDGET nothing is read until the reset.
65
+ * Change-first reads (server/github.ts). A due PR that was read in full before is first *probed*: one cheap query per
66
+ * account for every due PR (scalars, unresolved thread ids, check counts by state; ~1 point per 33 PRs). The full
67
+ * read (~1 point per PR) runs only when the probe saw something the full read decides on (`probeVerdict`), or
68
+ * SAFETY_READ_MS after the last one, for what a probe can't see (a reviewer request, branch protection, a parent).
69
+ * 2026-11-19 live: re-reading every due PR in full cost 4300-6400 points an hour, ~2000 more per pushed 60-PR stack.
68
70
  */
69
- export const LOW_BUDGET = 500;
71
+ export const SAFETY_READ_MS = 30 * 60_000;
72
+ /** Checks still running whose counts moved (one more finished, none failed) are read in full at most this often. */
73
+ export const RUNNING_FULL_MS = 5 * 60_000;
74
+ /** What a probe sees of a PR: `core` is everything but checks, as one string; checks are counts by state. */
75
+ export type Fingerprint = { core: string; checks: string; running: number; failed: number };
76
+ /**
77
+ * Whether a probe's fingerprint calls for a full read, given the fingerprint of the last full read and its age.
78
+ * Anything outside checks (head, updatedAt, state, base, draft, mergeability, review decision, merge queue, auto-merge,
79
+ * unresolved threads) reads at once; so does a change in failures, checks starting or all finishing. Running checks
80
+ * whose counts moved otherwise wait RUNNING_FULL_MS: a required check that passes changes mergeStateStatus, which is core.
81
+ */
82
+ export function probeVerdict(before: Fingerprint, now: Fingerprint, fullAge: number): "same" | "read" {
83
+ if (fullAge >= SAFETY_READ_MS) return "read";
84
+ if (before.core !== now.core || before.failed !== now.failed || (before.running === 0) !== (now.running === 0)) return "read";
85
+ if (before.checks !== now.checks && fullAge >= RUNNING_FULL_MS) return "read";
86
+ return "same";
87
+ }
88
+ /**
89
+ * GitHub's GraphQL budget (5000 points an hour per account, shared with every agent, gt and other plugins). A full
90
+ * read costs about one point per PR; a probe (below) about one point per 33 PRs.
91
+ * - `low` (under LOW_SHARE of the limit): settled PRs wait LOW_IDLE_MS, and only in repositories with something moving.
92
+ * - `reserve` (under RESERVE_SHARE): Follow-up's background reads stop until the reset, leaving the rest to agents.
93
+ * The developer's Refresh and agent tools (a fresh or foreground read of their own workspace) still read.
94
+ * - `critical` (under CRITICAL_BUDGET points): nothing is read until the reset.
95
+ * 2026-11-19 live: background reads ran the account down to 100 points left, so agents' gh calls failed first.
96
+ */
97
+ export const LOW_SHARE = 0.4;
98
+ export const RESERVE_SHARE = 0.2;
70
99
  export const CRITICAL_BUDGET = 100;
100
+ /** The limit GitHub reports for a user token; used when a response doesn't say. */
101
+ export const DEFAULT_LIMIT = 5000;
71
102
  export const LOW_IDLE_MS = 5 * 60_000;
72
- export type Budget = { remaining: number; resetAt: number };
73
- export type Tier = "normal" | "low" | "critical";
103
+ export type Budget = { remaining: number; resetAt: number; limit?: number };
104
+ export type Tier = "normal" | "low" | "reserve" | "critical";
74
105
  export function budgetTier(b: Budget | null | undefined, now: number): Tier {
75
106
  if (!b || now >= b.resetAt) return "normal";
76
- return b.remaining < CRITICAL_BUDGET ? "critical" : b.remaining < LOW_BUDGET ? "low" : "normal";
107
+ const limit = b.limit && b.limit > 0 ? b.limit : DEFAULT_LIMIT;
108
+ return b.remaining < CRITICAL_BUDGET ? "critical" : b.remaining < limit * RESERVE_SHARE ? "reserve" : b.remaining < limit * LOW_SHARE ? "low" : "normal";
77
109
  }
78
110
  /**
79
111
  * Whether a background tick reads this already-observed PR. Moving PRs: every tick, or every RUNNING_POLL_MS when
80
112
  * only checks are running (unless the budget is critical).
81
- * Settled open or closed PRs: every POLL_IDLE_MS. Merged: every MERGED_POLL_MS.
113
+ * Settled open PRs: every POLL_IDLE_MS. Merged (and closed): every MERGED_POLL_MS; server/github.ts skips final ones.
82
114
  */
83
115
  export function dueForRead(i: { snapshot: Snapshot | null | undefined; error: string | null | undefined; changedAt: number | null; readAt: number; now: number; tier: Tier; repoUrgent: boolean; since?: number | null }): boolean {
84
- if (i.tier === "critical") return false;
116
+ if (i.tier === "critical" || i.tier === "reserve") return false;
85
117
  const c = cadence(i.snapshot, i.error, i.changedAt, i.now);
86
118
  if (c === "tick") return true;
87
119
  const age = i.now - i.readAt;
@@ -90,6 +122,7 @@ export function dueForRead(i: { snapshot: Snapshot | null | undefined; error: st
90
122
  const long = i.since != null && i.now - i.since >= LONG_CHECKS_MS;
91
123
  return age >= (long ? LONG_RUNNING_POLL_MS : RUNNING_POLL_MS) - TICK_MS / 2;
92
124
  }
93
- if (i.tier === "low") return i.snapshot?.state !== "MERGED" && i.repoUrgent && age >= LOW_IDLE_MS;
94
- return age >= (i.snapshot?.state === "MERGED" ? MERGED_POLL_MS : POLL_IDLE_MS);
125
+ const settled = i.snapshot?.state === "MERGED" || i.snapshot?.state === "CLOSED";
126
+ if (i.tier === "low") return !settled && i.repoUrgent && age >= LOW_IDLE_MS;
127
+ return age >= (settled ? MERGED_POLL_MS : POLL_IDLE_MS);
95
128
  }
@@ -62,3 +62,17 @@ export function orderedStacks<P extends Pr>(prs: P[]): { name: string; prs: P[]
62
62
  const priority = (rows: Pr[]) => rows.every(settledForDisplay) ? 2 : rows.some(p => prPresentation(p).tone === "warning" || !statusKnown(p) || p.snapshot.state === "CLOSED" && !settled(p)) ? 0 : 1;
63
63
  return [...groups].map(([name, prs]) => ({ name, prs })).sort((a, b) => priority(a.prs) - priority(b.prs));
64
64
  }
65
+
66
+ /**
67
+ * The Pull requests card's line while Follow-up holds back its GitHub reads for the budget (Workspace.githubWait):
68
+ * what is happening, when checks resume (local time), and why the statuses below may be behind. Null when reads run.
69
+ */
70
+ export function githubWaitLine(w: { githubWait?: { until: string } | null }, now: number): { title: string; detail: string; label: string } | null {
71
+ const until = Date.parse(w.githubWait?.until ?? "");
72
+ if (!Number.isFinite(until) || until <= now) return null;
73
+ const at = new Date(until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
74
+ // "updates", not "checks": this card also shows CI checks. "Limit", not "budget": GitHub's own word.
75
+ const title = `GitHub limit low · updates again at ${at}`;
76
+ const detail = "Follow-up paused to leave the rest to your agents. PR statuses here may be behind.";
77
+ return { title, detail, label: `${title}. ${detail}` };
78
+ }
package/shared/search.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { layoutQueries } from "./layout-swap";
1
2
  import type { HomeGroupId, HomeModel, PaseoWorkspaceLite } from "./home";
2
3
  import type { ArchivedListWorkspace, ListWorkspace as Workspace } from "./list";
3
4
  import { linkedSearchText, type LinkedSearchItem } from "./linked-display";
@@ -98,6 +99,8 @@ export type SearchHit = {
98
99
  * 1 a typo, 0 inside a word (the weakest token decides). Optional only for rows built outside `search`.
99
100
  */
100
101
  rank?: Rank;
102
+ /** Query reconstructed from another keyboard layout; absent on direct hits. */
103
+ layoutQuery?: string;
101
104
  };
102
105
  export type Rank = { tier: 0 | 1 | 2; strength: 0 | 1 | 2 };
103
106
  const strengthOf = (m: number): 0 | 1 | 2 => m >= 0.85 ? 2 : m >= 0.45 ? 1 : 0;
@@ -106,9 +109,9 @@ const LAST: Rank = { tier: 2, strength: 0 };
106
109
  * The one ranking for every search over workspaces (one-ranking-for-every-workspace-search): a lower tier first, then
107
110
  * a stronger title match. Equal ranks are a tie each caller breaks its own way (score, or the list's order).
108
111
  */
109
- export function byRank(a: Pick<SearchHit, "rank"> | undefined, b: Pick<SearchHit, "rank"> | undefined): number {
112
+ export function byRank(a: Pick<SearchHit, "rank" | "layoutQuery"> | undefined, b: Pick<SearchHit, "rank" | "layoutQuery"> | undefined): number {
110
113
  const x = a?.rank ?? LAST, y = b?.rank ?? LAST;
111
- return x.tier - y.tier || y.strength - x.strength;
114
+ return Number(!!a?.layoutQuery) - Number(!!b?.layoutQuery) || x.tier - y.tier || y.strength - x.strength;
112
115
  }
113
116
 
114
117
  const DAY = 86_400_000;
@@ -116,7 +119,36 @@ const DAY = 86_400_000;
116
119
  * Every workstream matching all the query's tokens, best first. Archived ones come last, after every live one.
117
120
  * An empty query returns nothing: Home shows its groups instead.
118
121
  */
119
- export function search(index: SearchIndex, query: string, now = Date.now(), limit = 60): SearchHit[] {
122
+ export function search(index: SearchIndex, query: string, now = Date.now(), limit = 60, physical?: string | null): SearchHit[] {
123
+ if (!queryTokens(query).length) return [];
124
+ const direct = searchTyped(index, query, now, Infinity);
125
+ const seen = new Set(direct.map(h => h.key));
126
+ const converted: SearchHit[] = [];
127
+ for (const variant of layoutQueries(query, physical)) for (const hit of searchTyped(index, variant, now, Infinity)) {
128
+ if (seen.has(hit.key)) continue;
129
+ seen.add(hit.key); converted.push({ ...hit, layoutQuery: variant });
130
+ }
131
+ // Keep archived rows under their own heading at the bottom. Inside each group, direct matches come first.
132
+ return [...direct, ...converted].sort((a, b) => Number(a.group === "archived") - Number(b.group === "archived") || byScore(a, b)).slice(0, limit);
133
+ }
134
+
135
+ /** Quiet explanation only when a converted query finds more rows than the typed query. */
136
+ export function layoutHint(hits: readonly SearchHit[]): string | null {
137
+ const direct = hits.filter(h => !h.layoutQuery).length;
138
+ const counts = new Map<string, number>();
139
+ for (const h of hits) if (h.layoutQuery) counts.set(h.layoutQuery, (counts.get(h.layoutQuery) ?? 0) + 1);
140
+ const best = [...counts].sort((a, b) => b[1] - a[1])[0];
141
+ return best && best[1] > direct ? best[0] : null;
142
+ }
143
+
144
+ /** Reuse the workspace matcher for agent-tool filters too. */
145
+ export function searchRows<T>(rows: readonly T[], fields: (row: T) => SearchDoc["fields"], query: string, now = Date.now()): T[] {
146
+ if (!query.trim()) return [...rows];
147
+ const index = indexDocs(rows.map((r, i) => ({ key: String(i), title: "", group: "quiet", at: null, fields: fields(r) })));
148
+ return search(index, query, now, Infinity).map(h => rows[Number(h.key)]);
149
+ }
150
+
151
+ function searchTyped(index: SearchIndex, query: string, now: number, limit: number): SearchHit[] {
120
152
  const qs = queryTokens(query);
121
153
  if (!qs.length) return [];
122
154
  const phrase = qs.join(" ");
@@ -236,8 +268,8 @@ export function overseerProvider(enabled: boolean): OmniboxProvider {
236
268
  export function defaultActive(results: readonly OmniboxItem[] | null): number {
237
269
  return results?.length === 1 && results[0].ask !== undefined && !/\s/.test(results[0].ask) ? -1 : 0;
238
270
  }
239
- export function workspaceProvider(index: SearchIndex, now = Date.now()): OmniboxProvider {
240
- return { id: "workspaces", results: query => search(index, query, now).map(hit => ({ provider: "workspaces", key: hit.key, hit })) };
271
+ export function workspaceProvider(index: SearchIndex, now = Date.now(), physical?: string | null): OmniboxProvider {
272
+ return { id: "workspaces", results: query => search(index, query, now, 60, physical).map(hit => ({ provider: "workspaces", key: hit.key, hit })) };
241
273
  }
242
274
 
243
275
  // ---------- documents from Home's sources ----------
@@ -357,9 +389,9 @@ export function rowHit(hit: SearchHit, row: { title: string; agent?: string | nu
357
389
  * keeps the chosen sort. Only matching rows stay, groups left empty drop out, and archived workspaces aren't listed
358
390
  * (Home's search finds those). An empty query returns the model unchanged.
359
391
  */
360
- export function filterHome(model: HomeModel, index: SearchIndex, query: string, now = Date.now()): { model: HomeModel; hits: Map<string, SearchHit> | null } {
392
+ export function filterHome(model: HomeModel, index: SearchIndex, query: string, now = Date.now(), physical?: string | null): { model: HomeModel; hits: Map<string, SearchHit> | null } {
361
393
  if (!queryTokens(query).length) return { model, hits: null };
362
- const hits = new Map(search(index, query, now, Infinity).filter(h => h.group !== "archived").map(h => [h.key, h]));
394
+ const hits = new Map(search(index, query, now, Infinity, physical).filter(h => h.group !== "archived").map(h => [h.key, h]));
363
395
  // Array sort is stable: an equal rank keeps the list's own order.
364
396
  const groups = model.groups.map(g => ({ ...g, items: g.items.filter(s => hits.has(s.key)).sort((a, b) => byRank(hits.get(a.key), hits.get(b.key))) }))
365
397
  .filter(g => g.items.length);