paseo-follow-up 2.2.0-beta.1 → 2.2.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.
package/client/brief.tsx CHANGED
@@ -14,6 +14,7 @@ import { briefKey, HEADLINE_WORD } from "../shared/headline";
14
14
  const word = (kind: Brief["kind"]) => HEADLINE_WORD[briefKey(kind)];
15
15
  import { answerQuestionRpc, briefActionRpc, browserStatusRpc, inboxBriefRpc } from "../shared/contracts";
16
16
  import { errorText, mootNote } from "../shared/errors";
17
+ import { PRIMARY_FORM } from "./dock";
17
18
  import { OTHER, OTHER_LABEL, OWN_ANSWER_HINT, briefAnswerStatus, isOther, type Question } from "../shared/questions";
18
19
  import type { ListQuestion, ListWorkspace } from "../shared/list";
19
20
  import { useDetailGate, useWorkspace } from "./workspace-data";
@@ -184,7 +185,8 @@ function BriefBody({ b, c, compact, tight, embedded, height, mode, picks, onPick
184
185
  {(!readonly || isOther(d.chosen)) && <OptionRow other option={{ letter: "", label: OTHER_LABEL, consequence: readonly ? `"${d.words ?? ""}"` : null }} recommended={false} mode={mode} answerLabel={answerLabel}
185
186
  selected={readonly ? isOther(d.chosen) : isOther(picks[d.id])} answered={readonly && !!d.chosen} sending={busy === `${d.id}:${OTHER}`} disabled={!!busy} tight={false} open={false} onToggle={() => undefined}
186
187
  onPress={() => onPick(d.id, OTHER)} c={c} compact={compact} />}
187
- {!readonly && isOther(picks[d.id]) && <View style={{ gap: 8 }}>
188
+ {/* Something else's field with its Send answer, kept on screen together while typing (DockedPane). */}
189
+ {!readonly && isOther(picks[d.id]) && <View {...PRIMARY_FORM} style={{ gap: 8 }}>
188
190
  <TextInput accessibilityLabel={`Your answer${numbered ? ` to question ${i + 1}` : ""}, required`} placeholder="Your answer (required)" placeholderTextColor={c.foregroundMuted} autoFocus multiline maxLength={2000}
189
191
  value={words[d.id] ?? ""} editable={!busy} onChangeText={t => onWords?.(d.id, t)}
190
192
  style={{ minHeight: compact ? 66 : 58, paddingHorizontal: 10, paddingVertical: 8, borderRadius: 8, borderWidth: 1, borderColor: words[d.id]?.trim() ? c.border : withAlpha(c.accent, 0.7), color: c.foreground, backgroundColor: c.surface0, fontSize: 14, lineHeight: 20, textAlignVertical: "top" }} />
@@ -194,7 +196,7 @@ function BriefBody({ b, c, compact, tight, embedded, height, mode, picks, onPick
194
196
  </View>}
195
197
  </View>}
196
198
  {/* A note on a lettered pick ("A, but…"): quiet until asked for, never in the way of the one-tap answer. */}
197
- {!readonly && !isOther(picks[d.id]) && (notesOpen[d.id] ? <View style={{ gap: 6, marginTop: 2 }}>
199
+ {!readonly && !isOther(picks[d.id]) && (notesOpen[d.id] ? <View {...PRIMARY_FORM} style={{ gap: 6, marginTop: 2 }}>
198
200
  <Text style={{ color: c.foregroundMuted, fontSize: 12, lineHeight: 16, fontWeight: "600" }}>Note</Text>
199
201
  <TextInput accessibilityLabel={`Note for the agent${numbered ? ` on decision ${i + 1}` : ""}, optional`} placeholder={mode === "select" ? "Sent with your pick for this decision" : "Sent with the option you tap"}
200
202
  placeholderTextColor={c.foregroundMuted} autoFocus={focusNote === d.id} multiline maxLength={2000} value={notes[d.id] ?? ""} editable={!busy} onChangeText={t => onNote?.(d.id, t)}
@@ -0,0 +1,497 @@
1
+ // Catch up: everything in Needs you, one card at a time (docs/design/catch-up.md, docs/needs-you.md#catch-up). It
2
+ // renders the same components the panel and Home use (QuestionBody, NeedsYouList, BriefCard, the permission block), so
3
+ // the answer flow is the shared one, never a fork (one-answer-flow-for-every-question). The deck's order and every
4
+ // move are the pure session in shared/catch-up.ts (context-never-blocks-the-deck, the-card-on-screen-never-moves).
5
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
6
+ import { PanResponder, Platform, View } from "react-native";
7
+ import { Pressable, Text } from "./text";
8
+ import { useRpc } from "@getpaseo/plugin/client";
9
+ import { Icon, ScrollView, TextInput } from "@getpaseo/plugin/client/ui";
10
+ import { useQuery } from "@tanstack/react-query";
11
+ import { inboxBriefRpc } from "../shared/contracts";
12
+ import { needsYou } from "../shared/attention";
13
+ import { liveBrief } from "../shared/brief";
14
+ import { age, snoozeUntil } from "../shared/inbox";
15
+ import { laterChoices } from "../shared/row-menu";
16
+ import { errorText } from "../shared/errors";
17
+ import { CATCH_UP_RAIL_DEFAULT, CATCH_UP_RAIL_MAX, CATCH_UP_RAIL_MIN } from "../shared/display";
18
+ import { CATCH_UP_KEYS, CONTEXT_ASKS, MODE, askHeadline, catchUpKey, keyLabel, deckCards, groupOf, park, prevPos, settle as settleCard, startSession, statsOf, sync, type ContextRequest, type DeckCard, type Outcome, type Session } from "../shared/catch-up";
19
+ import type { Workspace } from "../shared/model";
20
+ import type { ListWorkspace } from "../shared/list";
21
+ import { bottomInset, Button, IconButton, text, type Theme } from "./kit";
22
+ import { glyphColor } from "./home-list";
23
+ import { useHomeModel, type HomeSources } from "./home-data";
24
+ import { useInbox } from "./inbox";
25
+ import { QuestionBody } from "./questions";
26
+ import { NeedsYouList } from "./needs-you";
27
+ import { BriefCard, type BriefDeps } from "./brief";
28
+ import { SummaryLine } from "./about";
29
+ import { ReferencesLine } from "./linked";
30
+ import { openRowCopy, useWorkspace } from "./workspace-data";
31
+ import { mergedColor, withAlpha, tint } from "./theme";
32
+ import { RichText } from "./rich-text";
33
+ import { DisplaySplit, PermissionBlock, useAgentLive } from "./home";
34
+ import { DockedPane } from "./docked-pane";
35
+ import { PRIMARY_FORM } from "./dock";
36
+
37
+ /** react-native-web's data attribute, so the option-letter keys find this card's radios. */
38
+ const CARD_MARK = { dataSet: { catchUpCard: "1" } } as object;
39
+ const RAIL_MIN_PX = 240;
40
+ const CARD_MIN_PX = 480;
41
+
42
+ const isMac = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test((navigator as { platform?: string }).platform ?? "");
43
+
44
+ export type CatchUpDeps = { sources: HomeSources; briefDeps: BriefDeps; openHome(): void; openPanel(workspaceId: string): void };
45
+ type Nav = { openAgent(a: { agentId: string }): void; openWorkspace(a: { workspaceId: string }): void } | undefined;
46
+
47
+ /** One card's label in the queue rail and in a More context ask: "Q1 · Retry declined cards?", "Merge #255". */
48
+ export function cardLabel(card: DeckCard, w: ListWorkspace | undefined): string {
49
+ if (card.kind === "permission") return "Permission";
50
+ if (card.kind === "question") { const q = w?.questions.find(x => x.id === card.questionId); return q ? `${q.id} · ${q.title}` : card.questionId ?? "Question"; }
51
+ if (card.kind === "item" && card.item) return card.item.title;
52
+ if (card.kind === "brief") return card.s.line || card.s.word || "Ask";
53
+ return card.s.line || "Finished";
54
+ }
55
+ /** The card's own word: a workspace row's word names its first item, the card names its own. */
56
+ function cardWord(card: DeckCard): string {
57
+ if (card.kind === "permission") return "Permission";
58
+ if (card.kind === "question") return card.item?.kind === "question" && card.item.state === "stopped" ? "Agent stopped" : "Question";
59
+ if (card.kind === "finished") return "Finished";
60
+ if (card.kind === "brief") return card.s.word ?? "Ask";
61
+ switch (card.item?.kind) {
62
+ case "merge": return "Merge"; case "reviewers": return "Add reviewers"; case "send": return "Send"; case "answer": return "Your answer";
63
+ case "hold": return "Paused"; case "retry": case "capped": case "message": return "Retry"; case "check": return "Check"; case "decision": return "Blocked";
64
+ default: return card.s.word ?? "Needs you";
65
+ }
66
+ }
67
+ const cardIcon = (card: DeckCard) => card.kind === "permission" ? "ShieldQuestion" : card.kind === "question" ? "MessageCircleQuestion"
68
+ : card.item?.kind === "merge" ? "GitMerge" : card.item?.kind === "reviewers" ? "UserPlus" : card.item?.kind === "send" ? "Send" : card.kind === "finished" ? "Flag" : card.s.icon;
69
+ /** The newest ask about this card, if any. */
70
+ const askFor = (context: readonly ContextRequest[], key: string) => [...context].reverse().find(r => r.cardKey === key) ?? null;
71
+
72
+ export function CatchUp({ theme, compact, deps, navigation, onExit }: { theme: Theme; compact: boolean; deps: CatchUpDeps; navigation: Nav; onExit: () => void }) {
73
+ const c = theme.colors; const t = text(c, compact);
74
+ const { inbox, live, extras } = deps.sources;
75
+ const model = useHomeModel(deps.sources);
76
+ const rows = useInbox(inbox, () => inbox.rows());
77
+ const version = useSyncExternalStore(live.subscribe, live.version, live.version);
78
+ const context = useSyncExternalStore(extras.subscribe, extras.context, extras.context);
79
+ // Everything comes from what the client already holds: Home's model, the inbox rows, the listed workspaces.
80
+ const liveCards = useMemo(() => deckCards({ model, rows, items: id => { const w = live.get(id); return w ? needsYou(w as unknown as Workspace) : []; } }),
81
+ [model, rows, version, live]); // eslint-disable-line react-hooks/exhaustive-deps
82
+ const byKey = useMemo(() => new Map(liveCards.map(x => [x.key, x])), [liveCards]);
83
+ // A card that left Needs you keeps its last copy, so it can say "Handled elsewhere" in place.
84
+ const seen = useRef(new Map<string, DeckCard>());
85
+ for (const card of liveCards) seen.current.set(card.key, card);
86
+ const cardOf = (k: string | undefined) => k ? byKey.get(k) ?? seen.current.get(k) ?? null : null;
87
+
88
+ const [session, setSession] = useState<Session>(() => startSession(liveCards));
89
+ const settled = (id: string) => { const r = context.find(x => x.id === id); return !r || r.state !== "asking"; };
90
+ useEffect(() => { setSession(s => s.order.length || !liveCards.length ? sync(s, liveCards, settled) : startSession(liveCards)); },
91
+ [liveCards, context]); // eslint-disable-line react-hooks/exhaustive-deps
92
+ // Opening and each move read the asks once: a 0.15 host (no feed) is never stale for long, and nothing polls.
93
+ useEffect(() => { void extras.refreshContext(); }, [session.pos]); // eslint-disable-line react-hooks/exhaustive-deps
94
+
95
+ const [more, setMore] = useState(false);
96
+ // M opens More context below the card's answers; bring it into view so the key's result is never off screen.
97
+ useEffect(() => {
98
+ if (!more || Platform.OS !== "web") return;
99
+ const t = setTimeout(() => (globalThis as { document?: { querySelector(q: string): { scrollIntoView?(o: object): void } | null } }).document
100
+ ?.querySelector("[data-catch-up-more]")?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }), 50);
101
+ return () => clearTimeout(t);
102
+ }, [more]);
103
+ const key = session.order[session.pos];
104
+ const card = cardOf(key);
105
+ const gone = !!key && session.outcomes[key] === "gone";
106
+ const finished = session.pos >= session.order.length;
107
+ const settle = (outcome: Outcome) => { setMore(false); setSession(s => settleCard(s, outcome)); };
108
+ const skip = () => settle("skipped");
109
+ const back = () => { setMore(false); setSession(s => ({ ...s, pos: prevPos(s) })); };
110
+ const jump = (i: number) => { setMore(false); setSession(s => ({ ...s, pos: i })); };
111
+ const w = card?.s.workspaceId ? live.get(card.s.workspaceId) : undefined;
112
+ // The next card's workspace detail is read while this one is on screen, so it paints at once (prefetch, no poll).
113
+ const nextCard = cardOf(session.order[session.pos + 1]);
114
+ useWorkspace(live, nextCard?.s.workspaceId ?? "", { enabled: !!nextCard?.s.workspaceId });
115
+
116
+ const ask = async (target: "overseer" | "agent", words: string) => {
117
+ if (!card) return;
118
+ const out = await extras.askContext({ workspaceId: card.s.workspaceId, agentId: card.s.agentId, cardKey: card.key, card: cardLabel(card, w).slice(0, 300), target, ask: words });
119
+ setMore(false);
120
+ // context-never-blocks-the-deck: the workstream waits, the deck moves on.
121
+ if (out.request.state === "asking") setSession(s => park(s, out.request.id, card.key));
122
+ };
123
+
124
+ // Desktop keys (CATCH_UP_KEYS, catchUpKey in shared/catch-up.ts): every move has one. The card's controls are found
125
+ // by the names they already carry (option letters, Later (L), Open chat (O)), so a key does exactly what a click does.
126
+ const [keysOpen, setKeysOpen] = useState(false);
127
+ useEffect(() => {
128
+ if (Platform.OS !== "web" || compact) return;
129
+ type Ev = { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean; isComposing: boolean; target: unknown; preventDefault(): void };
130
+ type El = { tagName?: string; isContentEditable?: boolean; click?(): void; focus?(): void; closest?(q: string): El | null };
131
+ type Doc = { querySelector(q: string): El | null; querySelectorAll(q: string): ArrayLike<El>; activeElement?: El | null; addEventListener(t: string, f: (e: Ev) => void): void; removeEventListener(t: string, f: (e: Ev) => void): void };
132
+ const doc = (globalThis as { document?: Doc }).document; if (!doc) return;
133
+ const mac = isMac();
134
+ const inCard = (q: string) => doc.querySelector(`[data-catch-up-card] ${q}`);
135
+ const railItems = () => Array.from(doc.querySelectorAll("[data-catch-up-rail] [role=\"button\"]"));
136
+ const onKey = (e: Ev) => {
137
+ const el = e.target as El | null;
138
+ const typing = !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || !!el.isContentEditable);
139
+ const hit = catchUpKey({ key: e.key, meta: e.metaKey, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, composing: e.isComposing, mac },
140
+ { typing, inMore: !!el?.closest?.("[data-catch-up-more]"), moreOpen: more, inRail: !!el?.closest?.("[data-catch-up-rail]") });
141
+ if (!hit || finished && !["back", "keys", "leave", "rail"].includes(hit.action)) return;
142
+ const click = (q: string) => { const b = doc.querySelector(q); b?.click?.(); return !!b; };
143
+ switch (hit.action) {
144
+ case "skip": skip(); break;
145
+ case "back": back(); break;
146
+ case "more": setMore(v => !v); break;
147
+ case "keys": setKeysOpen(v => !v); break;
148
+ case "leave": onExit(); break;
149
+ case "pick": inCard(`[role="radio"][aria-label^="${hit.arg}. "]`)?.click?.(); break;
150
+ case "own": inCard('[role="radio"][aria-label^="Something else"]')?.click?.(); break;
151
+ case "send": { const b = inCard('[aria-label^="Send your"]') ?? inCard('[aria-label^="Send "]'); if (!b) return; b.click?.(); break; }
152
+ case "note": { const add = inCard('[aria-label^="Add a note"]'); if (add) add.click?.(); else doc.querySelector('[aria-label="Tell the agent something"]')?.focus?.(); break; }
153
+ case "later": if (!click('[aria-label="Later (L)"]')) return; setTimeout(() => doc.querySelector('[data-catch-up-later] [role="button"]')?.focus?.(), 0); break;
154
+ case "chat": if (!click('[aria-label="Open chat (O)"]')) return; break;
155
+ case "chip": doc.querySelectorAll("[data-catch-up-more] [role=\"radio\"]")[Number(hit.arg) - 1]?.click?.(); break;
156
+ case "ask-overseer": if (!click('[data-catch-up-more] [aria-label="Ask the Overseer"]')) return; break;
157
+ case "ask-agent": if (!click('[data-catch-up-more] [data-ask-agent] [role="button"]')) return; break;
158
+ case "rail": {
159
+ const items = railItems();
160
+ if (el?.closest?.("[data-catch-up-rail]")) { (el as { blur?(): void }).blur?.(); break; }
161
+ (doc.querySelector("[data-catch-up-rail] [data-catch-up-here]") ?? items[0])?.focus?.();
162
+ break;
163
+ }
164
+ case "rail-up": case "rail-down": {
165
+ const items = railItems(); const i = items.indexOf(el as El);
166
+ items[Math.max(0, Math.min(items.length - 1, i + (hit.action === "rail-up" ? -1 : 1)))]?.focus?.();
167
+ break;
168
+ }
169
+ default: return;
170
+ }
171
+ e.preventDefault();
172
+ };
173
+ doc.addEventListener("keydown", onKey);
174
+ return () => doc.removeEventListener("keydown", onKey);
175
+ });
176
+ // Phones: swipe left to skip, right to go back. Answers are never a swipe: a stray thumb must not decide anything.
177
+ const pan = useMemo(() => PanResponder.create({
178
+ onMoveShouldSetPanResponder: (_e, g) => compact && Math.abs(g.dx) > 24 && Math.abs(g.dx) > Math.abs(g.dy) * 2,
179
+ onPanResponderRelease: (_e, g) => { if (g.dx < -80) skip(); else if (g.dx > 80) back(); },
180
+ }), [compact, key]); // eslint-disable-line react-hooks/exhaustive-deps
181
+
182
+ const stats = statsOf(session);
183
+ const total = session.order.length;
184
+ const waitingChip = stats.waiting > 0 && <View accessibilityLabel={`${MODE.waiting(stats.waiting)}. They come back as the next card when the answer is ready; Back reaches them any time.`}
185
+ style={{ flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 8, height: 22, borderRadius: 11, backgroundColor: c.surface2 }}>
186
+ <Icon name="Hourglass" size={11} color={c.foregroundMuted} /><Text style={[t.small, { fontWeight: "600" }]}>{MODE.waiting(stats.waiting)}</Text>
187
+ </View>;
188
+ const progress = <View style={{ gap: 6, paddingHorizontal: compact ? 16 : 20, paddingTop: compact ? 8 : 14, paddingBottom: 10 }}>
189
+ <View style={{ flexDirection: "row", alignItems: "center", flexWrap: "wrap", gap: 8, minHeight: compact ? 44 : 32 }}>
190
+ {/* Phones: the host header's ← is the only back control (DESIGN.md "One header"). */}
191
+ {!compact && <IconButton theme={theme} compact={compact} icon="X" label={`Leave ${MODE.name} (X)`} tooltip onPress={onExit} />}
192
+ <Text accessibilityRole="header" style={[t.title, { flex: 1 }]}>{finished || !total ? MODE.name : <>{MODE.name} <Text style={{ color: c.foregroundMuted, fontWeight: "400", fontVariant: ["tabular-nums"] }}>{MODE.progress(session.pos + 1, total).slice(MODE.name.length + 1)}</Text></>}</Text>
193
+ {waitingChip}
194
+ {!compact && <Pressable accessibilityRole="button" accessibilityLabel="Show the keys (S)" onPress={() => setKeysOpen(v => !v)}><Text style={t.small}>{finished ? "S keys · X leave" : "J skip · K back · M more context · S keys · X leave"}</Text></Pressable>}
195
+ </View>
196
+ {/* One segment per card: done in the foreground colour, skipped hollow, waiting for context amber-tinted, the current one amber. */}
197
+ {total > 0 && <View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" style={{ flexDirection: "row", gap: 3 }}>
198
+ {total > 24 ? <View style={{ flex: 1, height: 4, borderRadius: 2, backgroundColor: c.border }}><View style={{ width: `${Math.round(100 * (stats.done + stats.later + stats.gone) / total)}%`, height: 4, borderRadius: 2, backgroundColor: c.foreground }} /></View>
199
+ : session.order.map((k, i) => {
200
+ const o = session.outcomes[k];
201
+ const waiting = !o && !!session.parked[groupOf(k)];
202
+ const bg = i === session.pos && !finished ? c.statusWarning : o === "done" || o === "later" ? c.foreground : o ? withAlpha(c.foreground, 0.35) : waiting ? withAlpha(c.statusWarning, 0.4) : c.border;
203
+ return <View key={k} style={{ flex: 1, height: 4, borderRadius: 2, backgroundColor: bg }} />;
204
+ })}
205
+ </View>}
206
+ </View>;
207
+
208
+ const body = finished || !card ? <Finished theme={theme} compact={compact} stats={stats} empty={!total} onHome={onExit}
209
+ onSkipped={() => setSession(s => ({ ...s, pos: s.order.findIndex(k => s.outcomes[k] === "skipped"), lapped: true }))} />
210
+ : <CardView key={card.key} card={card} w={w} theme={theme} compact={compact} deps={deps} navigation={navigation} gone={gone} more={more} setMore={setMore}
211
+ request={askFor(context, card.key)} waiting={!!session.parked[card.s.key]} onAsk={ask}
212
+ sameWorkspace={session.order.filter(k => cardOf(k)?.s.key === card.s.key)}
213
+ onDone={() => settle("done")} onSkip={skip} onBack={session.pos > 0 ? back : undefined} onLater={() => settle("later")} />;
214
+
215
+ const rail = <ScrollView {...({ dataSet: { catchUpRail: "1" } } as object)} contentContainerStyle={{ paddingVertical: 8 }}>
216
+ {session.order.map((k, i) => {
217
+ const x = cardOf(k); if (!x) return null;
218
+ const xw = x.s.workspaceId ? live.get(x.s.workspaceId) : undefined;
219
+ const o = session.outcomes[k]; const here = i === session.pos;
220
+ const waiting = !o && !!session.parked[x.s.key];
221
+ const firstOfWs = i === 0 || cardOf(session.order[i - 1])?.s.key !== x.s.key;
222
+ const label = cardLabel(x, xw);
223
+ return <View key={k}>
224
+ {firstOfWs && <Text numberOfLines={1} style={[t.small, { paddingHorizontal: 16, paddingTop: i ? 10 : 2, paddingBottom: 2, fontWeight: "600" }]}>{x.s.title}</Text>}
225
+ <Pressable {...({ dataSet: here ? { catchUpHere: "1" } : {} } as object)} accessibilityRole="button" accessibilityState={{ selected: here }} accessibilityLabel={`${label}${o ? `, ${o === "gone" ? "handled elsewhere" : o}` : waiting ? ", getting context" : ""}`} onPress={() => jump(i)}
226
+ style={state => ({ flexDirection: "row", alignItems: "center", gap: 8, minHeight: 32, paddingHorizontal: 16, backgroundColor: here ? c.surface2 : (state as { hovered?: boolean }).hovered ? c.surface1 : "transparent",
227
+ borderLeftWidth: 2, borderLeftColor: here ? c.statusWarning : "transparent" })}>
228
+ <Icon name={o === "done" ? "CircleCheck" : o === "skipped" ? "CornerUpRight" : o === "later" ? "AlarmClock" : o === "gone" ? "CircleCheck" : waiting ? "Hourglass" : cardIcon(x)} size={13}
229
+ color={o === "done" || o === "gone" ? c.statusSuccess : o || waiting ? c.foregroundMuted : glyphColor(x.s, c, false)} />
230
+ <Text numberOfLines={1} style={[t.meta, { flex: 1, color: o ? c.foregroundMuted : c.foreground, textDecorationLine: o === "done" ? "line-through" : "none" }]}>{label}</Text>
231
+ </Pressable>
232
+ </View>;
233
+ })}
234
+ </ScrollView>;
235
+
236
+ const main = <View style={{ flex: 1, minWidth: 0 }} {...pan.panHandlers}>{body}</View>;
237
+ return <View style={{ flex: 1, backgroundColor: c.surface0 }}>
238
+ {progress}
239
+ <View style={{ flex: 1, borderTopWidth: 1, borderTopColor: c.border }}>
240
+ {/* Desktop: the queue rail beside the card, resizable (side-panes-are-resizable); its width is the Display field catch_up_rail_fraction. */}
241
+ {keysOpen && !compact && <KeysSheet theme={theme} onClose={() => setKeysOpen(false)} />}
242
+ {!compact && total > 0 && !finished
243
+ ? <DisplaySplit theme={theme} main={main} side={rail} field="catch_up_rail_fraction" testID="follow-up-catch-up-split" label="Resize the queue"
244
+ defaultFraction={CATCH_UP_RAIL_DEFAULT} range={[CATCH_UP_RAIL_MIN, CATCH_UP_RAIL_MAX]} minSide={RAIL_MIN_PX} minMain={CARD_MIN_PX} />
245
+ : main}
246
+ </View>
247
+ </View>;
248
+ }
249
+
250
+ /** One card: who and what, the ask through its own surface's component, then the deck's moves pinned to the bottom. */
251
+ function CardView({ card, w, theme, compact, deps, navigation, gone, more, setMore, request, waiting, onAsk, sameWorkspace, onDone, onSkip, onBack, onLater }: {
252
+ card: DeckCard; w: ListWorkspace | undefined; theme: Theme; compact: boolean; deps: CatchUpDeps; navigation: Nav; gone: boolean; more: boolean; setMore: (v: boolean | ((v: boolean) => boolean)) => void;
253
+ request: ContextRequest | null; waiting: boolean; onAsk: (target: "overseer" | "agent", words: string) => Promise<void>;
254
+ sameWorkspace: string[]; onDone: () => void; onSkip: () => void; onBack?: () => void; onLater: () => void;
255
+ }) {
256
+ const c = theme.colors; const t = text(c, compact);
257
+ const s = card.s;
258
+ const { workspace: full } = useWorkspace(deps.sources.live, s.workspaceId ?? "");
259
+ const ws = openRowCopy<ListWorkspace>(w, full);
260
+ const overseerOn = useSyncExternalStore(deps.sources.extras.subscribe, () => deps.sources.extras.overseer()?.enabled !== false, () => true);
261
+ const [laterOpen, setLaterOpen] = useState(false);
262
+ const openChat = () => { if (!navigation) return; if (s.agentId) navigation.openAgent({ agentId: s.agentId }); else if (s.workspaceId) navigation.openWorkspace({ workspaceId: s.workspaceId }); };
263
+ const word = cardWord(card);
264
+ const color = card.item?.kind === "merge" ? mergedColor(c) : card.kind === "finished" ? c.foregroundMuted : c.statusWarning;
265
+ const q = card.kind === "question" ? ws?.questions.find(x => x.id === card.questionId) ?? null : null;
266
+ const nth = sameWorkspace.indexOf(card.key);
267
+ const agentName = s.agent ?? "the agent";
268
+
269
+ const head = <View style={{ gap: 6 }}>
270
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
271
+ <Icon name={cardIcon(card)} size={14} color={color} />
272
+ <Text numberOfLines={1} style={[t.meta, { flex: 1 }]}>
273
+ <Text style={{ color, fontWeight: "600" }}>{word}</Text>
274
+ {[s.at ? `${age(s.at, Date.now())} ago` : "", s.project].filter(Boolean).map(x => ` · ${x}`).join("")}
275
+ {sameWorkspace.length > 1 ? ` · ${nth + 1} of ${sameWorkspace.length} here` : ""}
276
+ </Text>
277
+ </View>
278
+ <Text accessibilityRole="header" numberOfLines={2} style={compact ? t.title : [t.title, { fontSize: 17, lineHeight: 23 }]}>{s.title}{s.agent ? <Text style={{ color: c.foregroundMuted, fontWeight: "400" }}>{` › ${s.agent}`}</Text> : null}</Text>
279
+ {ws && <SummaryLine key={ws.id} workspace={ws} theme={theme} compact={compact} />}
280
+ {full && <ReferencesLine workspace={full} theme={theme} compact={compact} />}
281
+ </View>;
282
+
283
+ const goneBanner = gone && <View accessibilityRole="alert" style={{ flexDirection: "row", alignItems: "center", gap: 8, padding: 12, borderRadius: 10, backgroundColor: c.surface1, borderWidth: 1, borderColor: c.border }}>
284
+ <Icon name="CircleCheck" size={16} color={c.statusSuccess} />
285
+ <Text style={[t.body, { flex: 1 }]}>Handled elsewhere. Nothing left to do here.</Text>
286
+ <Button theme={theme} compact={compact} kind="primary" icon="ArrowRight" title="Next" onPress={onSkip} />
287
+ </View>;
288
+
289
+ const askBlock = card.kind === "question" && q && ws
290
+ ? <View style={{ gap: 8 }}>
291
+ <RichText plain style={compact ? t.ask : [t.body, { fontSize: 15, lineHeight: 21, fontWeight: "600" }]}>{`${q.id} · ${q.title}`}</RichText>
292
+ <QuestionBody key={q.id} workspace={ws} question={q} theme={theme} compact={compact} inline={false}
293
+ openAgent={id => navigation?.openAgent({ agentId: id })} onAnswered={onDone} />
294
+ </View>
295
+ : card.kind === "item" && card.item && full
296
+ ? <View style={{ borderRadius: 10, borderWidth: 1, borderColor: withAlpha(c.statusWarning, 0.45), overflow: "hidden" }}>
297
+ <NeedsYouList workspace={full} theme={theme} compact={compact} rows={[card.item]} flush actions={{ after: onDone, openAgent: openChat } as never} />
298
+ </View>
299
+ : card.kind === "permission" ? <PermissionCard s={s} theme={theme} compact={compact} onDone={onDone} />
300
+ : card.kind === "brief" ? <BriefAsk s={s} theme={theme} compact={compact} deps={deps} />
301
+ : <View style={{ gap: 10 }}>
302
+ <Text style={compact ? t.ask : [t.body, { fontSize: 15, lineHeight: 21, fontWeight: "600" }]}>{s.line || "The agent finished its turn."}</Text>
303
+ <Text style={t.meta}>Nothing to decide. Sign it off once you've read it, or reply.</Text>
304
+ <View style={{ flexDirection: "row", gap: 8 }}><Button theme={theme} compact={compact} grow={compact} kind="primary" icon="Check" title="Sign off" onPress={() => { if (s.agentId) void deps.sources.inbox.signOff([s.agentId]); onDone(); }} /></View>
305
+ </View>;
306
+
307
+ // Add context without answering: every card that isn't a question has the agent's reply box (a question has its note).
308
+ const reply = card.kind !== "question" && s.agentId && <NoteRow theme={theme} compact={compact} agentId={s.agentId} />;
309
+ const contextBlock = request && <ContextAnswer theme={theme} compact={compact} request={request} waiting={waiting} agent={agentName} openChat={openChat} />;
310
+ const moreBlock = more && <MorePanel theme={theme} compact={compact} agent={agentName} hasAgent={!!s.agentId} overseerOn={overseerOn} onClose={() => setMore(false)} onAsk={onAsk} />;
311
+ const later = (until: string) => { setLaterOpen(false); if (s.agentId) void deps.sources.inbox.snooze([s.agentId], until); onLater(); };
312
+ const laterRow = laterOpen && <View {...({ dataSet: { catchUpLater: "1" } } as object)} accessibilityRole="menu" style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, paddingHorizontal: compact ? 12 : 0, paddingTop: 8 }}>
313
+ {laterChoices(new Date()).map(([k, label]) => <Button key={k} theme={theme} compact={compact} kind="ghost" icon="AlarmClock" title={label} onPress={() => later(snoozeUntil(k, new Date()))} />)}
314
+ </View>;
315
+
316
+ // The deck's moves: in thumb reach on phones, under the card on desktop. One primary lives in the card (Send,
317
+ // Merge, Allow); these stay secondary. Icon-only moves carry their name for screen readers and as a desktop tooltip.
318
+ const moves = <View style={{ flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: compact ? 12 : 0, paddingTop: compact ? 10 : 4 }}>
319
+ <IconButton theme={theme} compact={compact} icon="ChevronLeft" label={compact ? "Back" : "Back (K or ←)"} tooltip={!compact} disabled={!onBack} onPress={() => onBack?.()} />
320
+ {compact ? <View style={{ flex: 1 }}><Button theme={theme} compact grow icon="Sparkles" title="Context" accessibilityLabel="More context" onPress={() => setMore(v => !v)} /></View>
321
+ : <Tip label="More context (M)"><Button theme={theme} icon="Sparkles" title="More context" accessibilityHint="M" onPress={() => setMore(v => !v)} /></Tip>}
322
+ <IconButton theme={theme} compact={compact} icon="AlarmClock" label={compact ? "Later" : "Later (L)"} tooltip={!compact} disabled={!s.agentId} onPress={() => setLaterOpen(v => !v)} />
323
+ <IconButton theme={theme} compact={compact} icon="MessageSquare" label={compact ? "Open chat" : "Open chat (O)"} tooltip={!compact} disabled={!navigation} onPress={openChat} />
324
+ {!compact && <View style={{ flex: 1 }} />}
325
+ {compact ? <View style={{ flex: 1 }}><Button theme={theme} compact grow icon="ArrowRight" title="Skip" onPress={onSkip} /></View>
326
+ : <Tip label="Skip (J or →)"><Button theme={theme} icon="ArrowRight" title="Skip" accessibilityHint="J" onPress={onSkip} /></Tip>}
327
+ </View>;
328
+
329
+ // a-focused-field-and-its-send-stay-in-view: the phone's bar is DockedPane's dock, so while a field has focus or the
330
+ // keyboard is up the bar steps aside and the field (Something else, a note, the More context ask) keeps its Send in view.
331
+ return <DockedPane compact={compact}
332
+ contentContainerStyle={{ padding: compact ? 16 : 28, gap: compact ? 16 : 18, ...(compact ? {} : { maxWidth: 720, width: "100%", alignSelf: "center" }) }}
333
+ dock={({ yields }) => compact && !yields && <View style={[{ borderTopWidth: 1, borderTopColor: c.border, backgroundColor: c.surface0 }, bottomInset(compact)]}>{laterRow}{moves}</View>}>
334
+ {goneBanner}
335
+ {head}
336
+ {contextBlock}
337
+ <View {...CARD_MARK} style={{ gap: 16 }}>{askBlock}</View>
338
+ {reply}
339
+ {moreBlock}
340
+ {!compact && laterRow}
341
+ {!compact && moves}
342
+ </DockedPane>;
343
+ }
344
+
345
+ /** What came back for this card: the answer, "answered in its chat", a failure, or (seen going Back) that it's still asking. */
346
+ function ContextAnswer({ theme, compact, request, waiting, agent, openChat }: { theme: Theme; compact: boolean; request: ContextRequest; waiting: boolean; agent: string; openChat: () => void }) {
347
+ const c = theme.colors; const t = text(c, compact);
348
+ const who = request.target === "overseer" ? "Overseer" : agent === "the agent" ? "The agent" : agent;
349
+ const asking = request.state === "asking";
350
+ return <View accessibilityLiveRegion="polite" style={{ gap: 8, padding: compact ? 14 : 16, borderRadius: 12, borderWidth: 1, borderColor: asking ? c.border : withAlpha(c.statusSuccess, 0.4), backgroundColor: c.surface1 }}>
351
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
352
+ <Icon name={asking ? "Hourglass" : request.state === "failed" ? "CircleAlert" : "Sparkles"} size={14} color={request.state === "failed" ? c.statusDanger : c.foregroundMuted} />
353
+ <RichText plain style={[t.small, { flex: 1 }]}>{asking ? `Asked ${who === "Overseer" ? "the Overseer" : who}${waiting ? " · this comes back as the next card when it answers. You can still act on it now" : ""}` : `${who} · you asked: ${askHeadline(request.ask)}`}</RichText>
354
+ </View>
355
+ {request.state === "answered" && request.answer && <RichText selectable style={t.body}>{request.answer}</RichText>}
356
+ {request.state === "chat" && <View style={{ gap: 8 }}>
357
+ <Text style={t.body}>{`${who} answered in its chat.`}</Text>
358
+ <View style={{ flexDirection: "row" }}><Button theme={theme} compact={compact} icon="MessageSquare" title="Open chat" onPress={openChat} /></View>
359
+ </View>}
360
+ {request.state === "failed" && <Text style={t.body}>{request.error ?? "The ask didn't go through. Try again, or open the chat."}</Text>}
361
+ </View>;
362
+ }
363
+
364
+ function PermissionCard({ s, theme, compact, onDone }: { s: DeckCard["s"]; theme: Theme; compact: boolean; onDone: () => void }) {
365
+ const agent = useAgentLive(s.agentId);
366
+ const t = text(theme.colors, compact);
367
+ if (!agent.permissions.length) return <Text style={t.ask}>{s.line || "Permission"}</Text>;
368
+ return <View style={{ gap: 10 }}>{agent.permissions.map(p => <PermissionBlock key={p.id} p={p} theme={theme} compact={compact} busy={false} primary
369
+ onRespond={r => { void agent.handle?.respondToPermission({ requestId: p.id, response: r as never }); onDone(); }} />)}</View>;
370
+ }
371
+
372
+ function BriefAsk({ s, theme, compact, deps }: { s: DeckCard["s"]; theme: Theme; compact: boolean; deps: CatchUpDeps }) {
373
+ const read = useRpc(inboxBriefRpc);
374
+ const brief = useQuery({ queryKey: ["follow-up", "home-brief", s.agentId, "catch-up"], queryFn: () => read({ agentId: s.agentId! }), enabled: !!s.agentId });
375
+ const b = liveBrief(brief.data?.brief);
376
+ if (!b) return <Text style={text(theme.colors, compact).ask}>{s.line}</Text>;
377
+ return <BriefCard {...({ embedded: true, item: { data: b }, theme, layout: { compact }, agentId: s.agentId, deps: deps.briefDeps } as unknown as Parameters<typeof BriefCard>[0])} />;
378
+ }
379
+
380
+ /**
381
+ * More context: "I don't get it" first (most asks just need explaining), then the developer's own words. The Overseer
382
+ * answers from what it already reads and wakes nobody; the card's agent knows best and may wake, because the
383
+ * developer asked. Either way the deck moves on and this workspace comes back when the answer is ready.
384
+ */
385
+ function MorePanel({ theme, compact, agent, hasAgent, overseerOn, onClose, onAsk }: { theme: Theme; compact: boolean; agent: string; hasAgent: boolean; overseerOn: boolean; onClose: () => void; onAsk: (target: "overseer" | "agent", words: string) => Promise<void> }) {
386
+ const c = theme.colors; const t = text(c, compact);
387
+ const [words, setWords] = useState<string>(CONTEXT_ASKS[0].text);
388
+ const [picked, setPicked] = useState<string>(CONTEXT_ASKS[0].id);
389
+ const [busy, setBusy] = useState<"overseer" | "agent" | null>(null);
390
+ const [error, setError] = useState<string | null>(null);
391
+ const send = (target: "overseer" | "agent") => {
392
+ if (!words.trim() || busy) return;
393
+ setBusy(target); setError(null);
394
+ // The words stay unless the ask is recorded.
395
+ onAsk(target, words.trim()).catch(e => setError(errorText(e))).finally(() => setBusy(null));
396
+ };
397
+ const agentLabel = agent === "the agent" ? "Ask the agent" : `Ask ${agent}`;
398
+ return <View {...({ dataSet: { catchUpMore: "1" } } as object)} style={{ gap: 10, padding: compact ? 14 : 16, borderRadius: 12, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface1 }}>
399
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
400
+ <Icon name="Sparkles" size={14} color={c.foreground} />
401
+ <Text style={[t.label, { flex: 1, fontWeight: "600" }]}>More context</Text>
402
+ <IconButton theme={theme} compact={compact} icon="X" label="Close more context" onPress={onClose} />
403
+ </View>
404
+ <View accessibilityRole="radiogroup" style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
405
+ {CONTEXT_ASKS.map((x, i) => <Pressable key={x.id} accessibilityLabel={compact ? x.label : `${x.label} (${i + 1})`} accessibilityRole="radio" accessibilityState={{ checked: picked === x.id }} onPress={() => { setPicked(x.id); setWords(x.text); }}
406
+ style={{ minHeight: compact ? 36 : 28, justifyContent: "center", paddingHorizontal: 10, borderRadius: 999, borderWidth: 1, borderColor: picked === x.id ? c.foreground : c.border, backgroundColor: picked === x.id ? c.surface2 : "transparent" }}>
407
+ <Text style={[t.meta, { color: picked === x.id ? c.foreground : c.foregroundMuted }]}>{x.label}</Text>
408
+ </Pressable>)}
409
+ </View>
410
+ <View {...PRIMARY_FORM} style={{ gap: 10 }}>
411
+ <TextInput accessibilityLabel="What do you want to know?" placeholder="What do you want to know?" placeholderTextColor={c.foregroundMuted} value={words} multiline
412
+ onChangeText={v => { setWords(v); setPicked(CONTEXT_ASKS.find(x => x.text === v)?.id ?? ""); }}
413
+ style={{ minHeight: compact ? 44 : 36, paddingHorizontal: 10, paddingVertical: 8, borderRadius: 6, borderWidth: 1, borderColor: c.border, color: c.foreground, backgroundColor: c.surface0 }} />
414
+ {!!error && <Text accessibilityRole="alert" style={[t.meta, { color: c.statusDanger }]}>{error}</Text>}
415
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
416
+ {overseerOn && <Button theme={theme} compact={compact} grow={compact} kind="primary" icon="MessagesSquare" title="Ask the Overseer" loading={busy === "overseer"} disabled={!words.trim() || !!busy}
417
+ accessibilityHint={compact ? "Answers from what Follow-up and the chats already hold; wakes nobody" : `Answers from what Follow-up and the chats already hold; wakes nobody. ${keyLabel("⌘↵", isMac())}`} onPress={() => send("overseer")} />}
418
+ {hasAgent && <View {...({ dataSet: { askAgent: "1" } } as object)} style={compact ? { flexGrow: 1 } : null}><Button theme={theme} compact={compact} grow={compact} kind={overseerOn ? "secondary" : "primary"} icon="MessageSquareText" title={agentLabel} loading={busy === "agent"} disabled={!words.trim() || !!busy}
419
+ accessibilityHint={compact ? "Sends it to the agent, which may wake it" : `Sends it to the agent, which may wake it. ${keyLabel("⌘⇧↵", isMac())}`} onPress={() => send("agent")} /></View>}
420
+ </View>
421
+ </View>
422
+ <Text style={t.small}>This workspace steps aside while you keep going, and comes back as your next card with the answer. Back reaches it any time.</Text>
423
+ </View>;
424
+ }
425
+
426
+ function Finished({ theme, compact, stats, empty, onHome, onSkipped }: { theme: Theme; compact: boolean; stats: ReturnType<typeof statsOf>; empty: boolean; onHome: () => void; onSkipped: () => void }) {
427
+ const c = theme.colors; const t = text(c, compact);
428
+ // "All caught up" only when it is true: a skipped or waiting card means the developer is not, so the end says so.
429
+ const caughtUp = !stats.skipped && !stats.waiting;
430
+ const icon = caughtUp ? "Check" : stats.waiting ? "Hourglass" : "CornerUpRight";
431
+ const tone = caughtUp ? c.statusSuccess : stats.waiting ? c.statusWarning : c.foregroundMuted;
432
+ const line = [stats.done && `${stats.done} done`, stats.skipped && `${stats.skipped} skipped`, stats.later && `${stats.later} for later`, stats.gone && `${stats.gone} handled elsewhere`].filter(Boolean).join(" · ");
433
+ return <ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 14 }}>
434
+ <View style={{ width: 56, height: 56, borderRadius: 28, alignItems: "center", justifyContent: "center", backgroundColor: tint(tone, c) }}>
435
+ <Icon name={icon} size={28} color={tone} />
436
+ </View>
437
+ <Text accessibilityRole="header" style={t.headline}>{empty ? MODE.empty : caughtUp ? MODE.finished : MODE.endOfDeck}</Text>
438
+ {!!line && <Text style={[t.body, { color: c.foregroundMuted, textAlign: "center" }]}>{line}</Text>}
439
+ {stats.waiting > 0 && <Text style={[t.body, { textAlign: "center" }]}>{`${MODE.waiting(stats.waiting)}. ${stats.waiting === 1 ? "It comes" : "They come"} back here when the answer is ready; Back reaches ${stats.waiting === 1 ? "it" : "them"} now.`}</Text>}
440
+ {stats.done > 0 && <Text style={[t.meta, { textAlign: "center", maxWidth: 420 }]}>Your answers are on their way; agents pick them up as soon as they're free. Anything new shows in Needs you and the pill.</Text>}
441
+ <View style={{ flexDirection: compact ? "column" : "row", alignSelf: compact ? "stretch" : "center", gap: 8, marginTop: 6 }}>
442
+ {stats.skipped > 0 && <Button theme={theme} compact={compact} grow={compact} kind="primary" icon="CornerUpRight" title={`Catch up on ${stats.skipped} skipped`} onPress={onSkipped} />}
443
+ <Button theme={theme} compact={compact} grow={compact} kind={stats.skipped ? "secondary" : "primary"} icon="House" title="Back to Home" onPress={onHome} />
444
+ </View>
445
+ </ScrollView>;
446
+ }
447
+
448
+ /** S: the keys, from the one list the handler reads (shared/catch-up.ts). A dialog over the card; S or its X closes it. */
449
+ export function KeysSheet({ theme, onClose }: { theme: Theme; onClose: () => void }) {
450
+ const c = theme.colors; const t = text(c, false);
451
+ const row = (k: typeof CATCH_UP_KEYS[number]) => <View key={`${k.action}-${k.key}`} style={{ flexDirection: "row", gap: 10, alignItems: "center" }}>
452
+ <View style={{ minWidth: 64 }}><Text style={[t.meta, { alignSelf: "flex-start", paddingHorizontal: 6, borderRadius: 4, borderWidth: 1, borderColor: c.border, color: c.foreground, fontVariant: ["tabular-nums"] }]}>{keyLabel(k.key, isMac())}</Text></View>
453
+ <Text style={t.meta}>{k.what}</Text>
454
+ </View>;
455
+ const section = (title: string, keys: readonly typeof CATCH_UP_KEYS[number][]) => <View style={{ gap: 6 }}>
456
+ <Text style={[t.small, { fontWeight: "600" }]}>{title}</Text>{keys.map(row)}
457
+ </View>;
458
+ return <View accessibilityRole={"dialog" as never} accessibilityLabel="Catch up keys" style={{ position: "absolute", zIndex: 10, right: 20, top: 8, width: 300, padding: 16, gap: 12, borderRadius: 10, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface1, shadowColor: "#000", shadowOpacity: 0.25, shadowRadius: 12 }}>
459
+ <View style={{ flexDirection: "row", alignItems: "center" }}>
460
+ <Text style={[t.label, { flex: 1, fontWeight: "600" }]}>Keys</Text>
461
+ <IconButton theme={theme} compact={false} icon="X" label="Close the keys (S)" tooltip onPress={onClose} />
462
+ </View>
463
+ {section("On a card", CATCH_UP_KEYS.filter(k => !k.when))}
464
+ {section("In More context", CATCH_UP_KEYS.filter(k => k.when === "more"))}
465
+ {section("In the queue", CATCH_UP_KEYS.filter(k => k.when === "rail"))}
466
+ </View>;
467
+ }
468
+
469
+ /** A desktop hover title on any control (react-native-web drops `title` on a Pressable; IconButton does the same). */
470
+ function Tip({ label, children }: { label: string; children: ReactNode }) {
471
+ const ref = useRef<View>(null);
472
+ useEffect(() => { if (Platform.OS === "web") (ref.current as unknown as { setAttribute?: (k: string, v: string) => void } | null)?.setAttribute?.("title", label); }, [label]);
473
+ return Platform.OS === "web" ? <View ref={ref}>{children}</View> : <>{children}</>;
474
+ }
475
+
476
+ /**
477
+ * Home's way in. It counts cards (one per thing to act on), which can differ from Needs you's workspace count beside
478
+ * it, so its accessible name and desktop tooltip say what the number is.
479
+ */
480
+ export function CatchUpButton({ theme, compact, count, onPress }: { theme: Theme; compact: boolean; count: number; onPress: () => void }): ReactNode {
481
+ if (!count) return null;
482
+ const label = MODE.buttonLabel(count);
483
+ const button = <Button theme={theme} compact={compact} grow={compact} kind="primary" icon="Layers" title={MODE.button(count)} accessibilityLabel={label} onPress={onPress} />;
484
+ return Platform.OS === "web" && !compact ? <View {...({ dataSet: { tooltip: label }, title: label } as object)}>{button}</View> : button;
485
+ }
486
+
487
+ /** Tell the agent something with or without acting: a plain message, the detail pane's reply box in a line. */
488
+ function NoteRow({ theme, compact, agentId }: { theme: Theme; compact: boolean; agentId: string }) {
489
+ const c = theme.colors;
490
+ const agent = useAgentLive(agentId);
491
+ const [words, setWords] = useState("");
492
+ return <View {...PRIMARY_FORM} style={{ flexDirection: "row", alignItems: "flex-end", gap: 8 }}>
493
+ <TextInput accessibilityLabel="Tell the agent something" placeholder="Tell the agent something" placeholderTextColor={c.foregroundMuted} value={words} onChangeText={setWords} multiline
494
+ style={{ flex: 1, minHeight: compact ? 44 : 36, paddingHorizontal: 10, paddingVertical: 8, borderRadius: 6, borderWidth: 1, borderColor: c.border, color: c.foreground, backgroundColor: c.surface0 }} />
495
+ <IconButton theme={theme} compact={compact} icon="Send" label="Send to the agent" tooltip={!compact} disabled={!words.trim()} onPress={() => { void agent.handle?.send(words.trim()); setWords(""); }} />
496
+ </View>;
497
+ }
package/client/dock.ts ADDED
@@ -0,0 +1,70 @@
1
+ // What a docked pane does around a field (`a-focused-field-and-its-send-stay-in-view`): pure, so tests can run it
2
+ // without React Native. client/docked-pane.tsx wires it to focus, the keyboard and the scroll view.
3
+
4
+ /** The bit of a DOM element this needs; tests pass plain objects. */
5
+ export type DockNode = {
6
+ tagName?: string;
7
+ isContentEditable?: boolean;
8
+ parentElement?: DockNode | null;
9
+ dataset?: Record<string, string | undefined>;
10
+ style?: { scrollMarginBottom?: string; scrollMarginTop?: string };
11
+ scrollIntoView?(o?: { block?: "nearest" | "start" | "end" | "center"; inline?: "nearest" }): void;
12
+ };
13
+
14
+ /** A field the keyboard types into. */
15
+ export const isField = (n: DockNode | null | undefined): boolean =>
16
+ !!n && (n.tagName === "TEXTAREA" || n.tagName === "INPUT" || !!n.isContentEditable);
17
+
18
+ /**
19
+ * What must stay on screen while `field` has focus: the nearest enclosing primary form (the field with its Send,
20
+ * marked `dataSet={{ primaryForm: "1" }}`, PRIMARY_FORM), else the field itself.
21
+ */
22
+ export function revealTarget(field: DockNode): DockNode {
23
+ for (let n: DockNode | null | undefined = field; n; n = n.parentElement) if (n.dataset?.primaryForm !== undefined) return n;
24
+ return field;
25
+ }
26
+
27
+ /** Scroll the focused field's form into view, the least distance that shows it all. Returns what it revealed. */
28
+ export function revealFocused(field: DockNode | null | undefined): DockNode | null {
29
+ if (!isField(field)) return null;
30
+ const target = revealTarget(field!);
31
+ // A gutter's gap from the dock below and the header above, never flush against either.
32
+ if (target.style) { target.style.scrollMarginBottom = `${REVEAL_GAP}px`; target.style.scrollMarginTop = `${REVEAL_GAP}px`; }
33
+ target.scrollIntoView?.({ block: "nearest", inline: "nearest" });
34
+ return target;
35
+ }
36
+
37
+ /**
38
+ * The dock's extras (Sign off, Sign off & next, Later; setup's Back and Continue) step aside on a phone while a field
39
+ * in the pane has focus or the keyboard is up, so the pane's height goes to what is being typed and its Send.
40
+ */
41
+ export const dockYields = (s: { compact: boolean; fieldFocused: boolean; keyboardUp: boolean }): boolean =>
42
+ s.compact && (s.fieldFocused || s.keyboardUp);
43
+
44
+ /**
45
+ * What a docked pane shows around a field. `yields`: the dock drops its extras and the header its secondary lines.
46
+ * `typingInContent`: a field in the content (not the dock's own reply box) has focus, so the whole dock steps aside
47
+ * and only one text box is on screen.
48
+ */
49
+ export type DockState = { yields: boolean; typingInContent: boolean };
50
+ export const dockState = (s: { compact: boolean; fieldFocused: boolean; fieldInDock: boolean; keyboardUp: boolean }): DockState =>
51
+ ({ yields: dockYields(s), typingInContent: s.compact && s.fieldFocused && !s.fieldInDock });
52
+
53
+ /** The gap kept between a revealed form and the dock or header (the 16 px gutter). */
54
+ export const REVEAL_GAP = 16;
55
+
56
+ /**
57
+ * How much of the layout the on-screen keyboard covers on the web: the layout viewport below the visual one. Zero
58
+ * when the browser resizes the page for the keyboard (the pane shrinks on its own) or no keyboard is up.
59
+ */
60
+ export const keyboardOverlap = (v: { innerHeight: number; viewportHeight: number; offsetTop: number }): number =>
61
+ Math.max(0, Math.round(v.innerHeight - v.viewportHeight - v.offsetTop));
62
+
63
+ /** Above this, a shrunken visual viewport is the keyboard, not browser chrome sliding in. */
64
+ export const KEYBOARD_MIN = 150;
65
+
66
+ /**
67
+ * The marker a primary form carries: spread it on the View holding a field and its Send. React Native web turns
68
+ * dataSet into data-* attributes (dataset.primaryForm); its types don't list dataSet, hence the spread.
69
+ */
70
+ export const PRIMARY_FORM = { dataSet: { primaryForm: "1" } } as object;