Open History to see the last commit
1import type { SubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
2import { formatDuration } from "@t3tools/shared/orchestrationTiming";
3import { GlassContainer, GlassView } from "expo-glass-effect";
4import { type ReactNode, useEffect, useRef, useState } from "react";
5import {
6 ActivityIndicator,
7 type LayoutChangeEvent,
8 Pressable,
9 Text as SystemText,
10 useWindowDimensions,
11 View,
12} from "react-native";
13import Animated, {
14 Easing,
15 FadeIn,
16 FadeOut,
17 ReduceMotion,
18 type SharedValue,
19 useAnimatedStyle,
20 useSharedValue,
21 withTiming,
22} from "react-native-reanimated";
23import { withUniwind } from "uniwind";
24
25import { AppText as Text } from "../../components/AppText";
26import { SymbolView } from "../../components/AppSymbol";
27import { ControlPill } from "../../components/ControlPill";
28import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
29import { BrowserPreviewButton } from "../browser/browser-preview-button";
30import { DevicePreviewButton } from "../devices/device-preview-button";
31import type { FloatingWorkingStatus } from "./floating-working-status";
32import { ShimmeringWorkContent } from "./thread-work-log";
33import { useVisibleSecondClock } from "./use-visible-second-clock";
34
35const CONTROL_HEIGHT = 38.5; // h-11 with the mobile 14px rem
36// The collapsed composer capsule starts 6 below its overlay's top edge, so
37// the pill sits at (gap - 6) above the overlay to leave the same gap to the
38// capsule as the feed's end inset leaves between it and the last row.
39const CONTROL_GAP = 8;
40const COMPOSER_CAPSULE_INSET = 6;
41const GLASS_MERGE_SPACING = 12;
42const CONTROL_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);
43const CONTROL_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
44const CONTROL_TIMING = {
45 duration: 240,
46 easing: Easing.out(Easing.cubic),
47 reduceMotion: ReduceMotion.System,
48} as const;
49const CONTROL_SEPARATION = (16 + CONTROL_HEIGHT) / 2;
50// Both rows share the same centered anchor, so the outgoing one clears fast and
51// the incoming one waits for it to be mostly gone before it starts to show.
52const LABEL_ENTERING = FadeIn.duration(160).delay(80).reduceMotion(ReduceMotion.System);
53const LABEL_EXITING = FadeOut.duration(100).reduceMotion(ReduceMotion.System);
54
55// Expo reapplies glass after native layout and window reattachment, when UIKit
56// can otherwise leave the label visible but lose the material behind it.
57const UniwindGlassView = withUniwind(GlassView, {
58 style: { fromClassName: "className" },
59});
60const UniwindGlassContainer = withUniwind(GlassContainer, {
61 style: { fromClassName: "className" },
62});
63const AnimatedGlassView = Animated.createAnimatedComponent(UniwindGlassView);
64
65const CONTROL_OVERLAY_OFFSET = CONTROL_HEIGHT + CONTROL_GAP - COMPOSER_CAPSULE_INSET;
66export const FLOATING_WORKING_CONTROL_COVERAGE = CONTROL_OVERLAY_OFFSET + CONTROL_GAP;
67
68export function FloatingWorkingControl(props: {
69 readonly colorScheme: "light" | "dark";
70 readonly status: FloatingWorkingStatus | null;
71 readonly devicePreview: { readonly count: number; readonly onPress: () => void } | null;
72 readonly browserPreview: { readonly count: number; readonly onPress: () => void } | null;
73 readonly showScrollToEnd: boolean;
74 readonly onScrollToEnd: () => void;
75 readonly agents: SubagentPillSegment | null;
76 readonly onOpenAgents: () => void;
77 readonly queuedCount: number;
78 readonly onOpenQueue: () => void;
79 /** Extra distance to rise above the anchor, e.g. an overlay card's coverage. */
80 readonly lift?: SharedValue<number>;
81}) {
82 const { width: windowWidth } = useWindowDimensions();
83 const [overlayWidth, setOverlayWidth] = useState(windowWidth);
84 const [queueWidth, setQueueWidth] = useState(0);
85 const [agentsWidth, setAgentsWidth] = useState(0);
86 const hasQueue = props.queuedCount > 0;
87 const hasPreview = props.devicePreview !== null || props.browserPreview !== null;
88 const [previewWidth, setPreviewWidth] = useState(0);
89 const agents = props.agents;
90 const hasAgents = agents !== null;
91 // Segments keep their measured width; only the status label absorbs the
92 // remainder, so a long "Working 12m 04s" truncates before a count does.
93 const labelWidth = Math.max(
94 0,
95 Math.min(overlayWidth, windowWidth) -
96 CONTROL_HEIGHT -
97 32 -
98 (hasQueue ? queueWidth : 0) -
99 (hasAgents ? agentsWidth : 0) -
100 (hasPreview ? previewWidth : 0),
101 );
102 const separationProgress = useSharedValue(props.showScrollToEnd ? 1 : 0);
103
104 useEffect(() => {
105 separationProgress.value = withTiming(props.showScrollToEnd ? 1 : 0, CONTROL_TIMING);
106 }, [props.showScrollToEnd, separationProgress]);
107
108 const lift = props.lift;
109 const liftStyle = useAnimatedStyle(() => ({
110 transform: [{ translateY: -(lift?.value ?? 0) }],
111 }));
112 const arrowTransformStyle = useAnimatedStyle(() => ({
113 transform: [{ translateX: -CONTROL_SEPARATION * (1 - separationProgress.value) }],
114 }));
115 const arrowContentStyle = useAnimatedStyle(() => ({
116 opacity: separationProgress.value,
117 }));
118
119 // Animate an in-flow sizer so native glass receives real layout updates.
120 // Measure labels in a separate, fixed-width host: measuring against the
121 // animated capsule constrains the incoming text to each intermediate width
122 // and repeatedly retargets the animation as it grows.
123 const capsuleWidth = useSharedValue<number | null>(null);
124 const measuredWidthRef = useRef<number | null>(null);
125 const handleLabelLayout = (event: LayoutChangeEvent) => {
126 const width = event.nativeEvent.layout.width;
127 if (width === measuredWidthRef.current) {
128 return;
129 }
130 const first = measuredWidthRef.current === null;
131 measuredWidthRef.current = width;
132 capsuleWidth.value = first ? width : withTiming(width, CONTROL_TIMING);
133 };
134 // Forget the width while no label is shown so the next one appears at its
135 // own size instead of animating from the previous label's.
136 const hasStatus = props.status !== null;
137 const hasCapsule = hasStatus || hasQueue || hasAgents || hasPreview;
138 useEffect(() => {
139 if (!hasStatus) {
140 measuredWidthRef.current = null;
141 capsuleWidth.value = null;
142 }
143 }, [capsuleWidth, hasStatus]);
144 const capsuleStyle = useAnimatedStyle(() => ({
145 transform: [{ translateX: CONTROL_SEPARATION * (1 - separationProgress.value) }],
146 }));
147 // Zero until the first measurement lands, so the capsule never paints around
148 // a label it has not sized to yet.
149 const capsuleSizerStyle = useAnimatedStyle(() => ({
150 width: capsuleWidth.value ?? 0,
151 }));
152
153 if (!hasCapsule && !props.showScrollToEnd) {
154 return null;
155 }
156
157 // Both preview buttons fit beside each other only as icons.
158 const previewCompact =
159 hasStatus ||
160 hasAgents ||
161 hasQueue ||
162 (props.devicePreview !== null && props.browserPreview !== null);
163 // The queue, agents, and reconnect labels have separate tap targets.
164 const statusInteractive = props.status?.kind === "connection";
165 const capsuleInteractive = statusInteractive || hasQueue || hasAgents || hasPreview;
166 // The host stays centered on the capsule, but its measurement constraint
167 // comes from the overlay, independent of the capsule's current width.
168 const statusContent =
169 props.status !== null ? (
170 <View
171 pointerEvents={props.status.kind === "connection" ? "box-none" : "none"}
172 className="h-11 items-center justify-center"
173 >
174 <Animated.View className="h-11" style={capsuleSizerStyle} />
175 <View
176 pointerEvents={statusInteractive ? "box-none" : "none"}
177 className="absolute h-11 items-center justify-center"
178 style={{ width: labelWidth }}
179 >
180 <FloatingStatusLabel
181 key={
182 props.status.kind === "working" || props.status.kind === "compacting"
183 ? props.status.kind
184 : `${props.status.kind}:${props.status.label}`
185 }
186 status={props.status}
187 onLayout={handleLabelLayout}
188 />
189 </View>
190 </View>
191 ) : null;
192
193 const capsuleContent = (
194 <View className="flex-row items-center">
195 {statusContent}
196 {hasPreview ? (
197 <View
198 className="h-11 flex-row items-center"
199 onLayout={(event) => setPreviewWidth(event.nativeEvent.layout.width)}
200 >
201 {hasStatus ? <View className="h-4 w-px bg-border" /> : null}
202 {props.devicePreview !== null ? (
203 <DevicePreviewButton {...props.devicePreview} compact={previewCompact} />
204 ) : null}
205 {props.browserPreview !== null ? (
206 <BrowserPreviewButton {...props.browserPreview} compact={previewCompact} />
207 ) : null}
208 </View>
209 ) : null}
210 {agents !== null ? (
211 <Pressable
212 accessibilityRole="button"
213 accessibilityLabel={`Open agents, ${agents.accessibilityLabel}`}
214 accessibilityHint="Opens this turn's subagents"
215 onPress={props.onOpenAgents}
216 onLayout={(event) => setAgentsWidth(event.nativeEvent.layout.width)}
217 className="h-11 flex-row items-center gap-1.5 px-3 active:opacity-70"
218 >
219 {hasStatus || hasPreview ? <View className="mr-1 h-4 w-px bg-border" /> : null}
220 <SymbolView name="person.2" size={13} tintColorClassName="accent-foreground-muted" />
221 <Text className="font-t3-medium text-xs tabular-nums" numberOfLines={1}>
222 {agents.label}
223 </Text>
224 </Pressable>
225 ) : null}
226 {hasQueue ? (
227 <Pressable
228 accessibilityRole="button"
229 accessibilityLabel={`Open queue, ${props.queuedCount} messages`}
230 accessibilityHint="Opens queued messages for reordering, steering, or removal"
231 onPress={props.onOpenQueue}
232 onLayout={(event) => setQueueWidth(event.nativeEvent.layout.width)}
233 style={{ maxWidth: Math.min(overlayWidth, windowWidth) * 0.45 }}
234 className="h-11 flex-row items-center gap-2 px-3 active:opacity-70"
235 >
236 {hasStatus || hasPreview || hasAgents ? (
237 <View className="mr-1 h-4 w-px bg-border" />
238 ) : null}
239 <SymbolView name="list.number" size={13} tintColorClassName="accent-foreground-muted" />
240 <Text className="shrink font-t3-medium text-xs tabular-nums" numberOfLines={1}>
241 {props.queuedCount} queued
242 </Text>
243 </Pressable>
244 ) : null}
245 </View>
246 );
247
248 return (
249 <Animated.View
250 pointerEvents="box-none"
251 className="absolute left-0 right-0 z-20 items-center"
252 style={[{ top: -CONTROL_OVERLAY_OFFSET }, liftStyle]}
253 onLayout={(event) => setOverlayWidth(event.nativeEvent.layout.width)}
254 entering={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_ENTERING}
255 exiting={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_EXITING}
256 >
257 {hasCapsule && NATIVE_LIQUID_GLASS_SUPPORTED ? (
258 <UniwindGlassContainer
259 spacing={GLASS_MERGE_SPACING}
260 pointerEvents="box-none"
261 className="flex-row items-center gap-4"
262 >
263 <AnimatedGlassView
264 colorScheme={props.colorScheme}
265 glassEffectStyle="regular"
266 isInteractive={capsuleInteractive}
267 pointerEvents={capsuleInteractive ? "box-none" : "none"}
268 className="h-11 items-center justify-center overflow-hidden rounded-full"
269 style={capsuleStyle}
270 >
271 {capsuleContent}
272 </AnimatedGlassView>
273
274 <AnimatedGlassView
275 colorScheme={props.colorScheme}
276 glassEffectStyle="regular"
277 isInteractive
278 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
279 accessibilityElementsHidden={!props.showScrollToEnd}
280 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
281 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
282 style={arrowTransformStyle}
283 >
284 <Animated.View style={arrowContentStyle}>
285 <ScrollToEndButton disabled={!props.showScrollToEnd} onPress={props.onScrollToEnd} />
286 </Animated.View>
287 </AnimatedGlassView>
288 </UniwindGlassContainer>
289 ) : hasCapsule ? (
290 <View pointerEvents="box-none" className="flex-row items-center gap-4">
291 <Animated.View
292 pointerEvents={capsuleInteractive ? "box-none" : "none"}
293 className="h-11 items-center justify-center overflow-hidden rounded-full border border-border bg-glass-fallback shadow-md shadow-black/10"
294 style={capsuleStyle}
295 >
296 {capsuleContent}
297 </Animated.View>
298
299 <Animated.View
300 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
301 accessibilityElementsHidden={!props.showScrollToEnd}
302 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
303 style={[arrowTransformStyle, arrowContentStyle]}
304 >
305 <ControlPill
306 accessibilityLabel="Scroll to end"
307 activateOnPressIn
308 className="h-11 w-11 border border-border bg-glass-fallback shadow-md shadow-black/10"
309 disabled={!props.showScrollToEnd}
310 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
311 onPress={props.onScrollToEnd}
312 />
313 </Animated.View>
314 </View>
315 ) : NATIVE_LIQUID_GLASS_SUPPORTED ? (
316 <UniwindGlassView
317 colorScheme={props.colorScheme}
318 glassEffectStyle="regular"
319 isInteractive
320 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
321 >
322 <ScrollToEndButton onPress={props.onScrollToEnd} />
323 </UniwindGlassView>
324 ) : (
325 <ControlPill
326 accessibilityLabel="Scroll to end"
327 activateOnPressIn
328 className="h-11 w-11 border border-border bg-glass-fallback shadow-md shadow-black/10"
329 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
330 onPress={props.onScrollToEnd}
331 />
332 )}
333 </Animated.View>
334 );
335}
336
337function CompactingLabel(props: { readonly onLayout: (event: LayoutChangeEvent) => void }) {
338 return (
339 <StatusLabelRow accessibilityLabel="Compacting" className="gap-1.5" onLayout={props.onLayout}>
340 <SymbolView
341 name="arrow.down.right.and.arrow.up.left"
342 size={13}
343 tintColorClassName="foreground"
344 type="monochrome"
345 />
346 <Text className="font-t3-medium text-xs text-foreground">Compacting…</Text>
347 </StatusLabelRow>
348 );
349}
350
351function FloatingStatusLabel(props: {
352 readonly status: FloatingWorkingStatus;
353 readonly onLayout: (event: LayoutChangeEvent) => void;
354}) {
355 // Keyed by kind so a swap mounts a fresh row and the two cross-fade while
356 // the capsule animates to the new row's measured width.
357 if (props.status.kind === "syncing") {
358 return (
359 <StatusLabelRow
360 key="syncing"
361 accessibilityLabel={props.status.label}
362 className="gap-2"
363 onLayout={props.onLayout}
364 >
365 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
366 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
367 {props.status.label}
368 </Text>
369 </StatusLabelRow>
370 );
371 }
372 if (props.status.kind === "compacting") {
373 return <CompactingLabel key="compacting" onLayout={props.onLayout} />;
374 }
375 if (props.status.kind === "connection") {
376 return (
377 <StatusLabelRow
378 key="connection"
379 accessibilityLabel={props.status.label}
380 accessibilityRole="button"
381 className="gap-2"
382 onLayout={props.onLayout}
383 onPress={props.status.onPress}
384 >
385 {props.status.tone === "reconnecting" ? (
386 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
387 ) : (
388 <View className="h-2 w-2 rounded-full bg-red-500" />
389 )}
390 <Text
391 className="max-w-[260px] shrink font-t3-medium text-xs text-foreground"
392 numberOfLines={1}
393 >
394 {props.status.label}
395 </Text>
396 </StatusLabelRow>
397 );
398 }
399 if (props.status.kind === "background") {
400 return (
401 <StatusLabelRow
402 key="background"
403 accessibilityLabel={props.status.accessibilityLabel}
404 className="gap-2"
405 onLayout={props.onLayout}
406 >
407 {/* A dev server can run for hours after the agent is done, so only work
408 that will wake the agent gets the bolt. */}
409 <SymbolView
410 name={props.status.waiting ? { ios: "bolt", android: "bolt" } : "terminal"}
411 size={13}
412 tintColorClassName="foreground"
413 type="monochrome"
414 />
415 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
416 {props.status.label}
417 </Text>
418 </StatusLabelRow>
419 );
420 }
421 if (props.status.kind === "goal") {
422 return (
423 <StatusLabelRow
424 key="goal"
425 accessibilityLabel={props.status.accessibilityLabel}
426 className="gap-2"
427 onLayout={props.onLayout}
428 >
429 <SymbolView name="target" size={13} tintColorClassName="foreground" type="monochrome" />
430 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
431 {props.status.label}
432 </Text>
433 </StatusLabelRow>
434 );
435 }
436 if (props.status.kind === "preparing") {
437 return (
438 <StatusLabelRow
439 key="preparing"
440 accessibilityLabel={props.status.label}
441 className="gap-1.5"
442 onLayout={props.onLayout}
443 >
444 <SymbolView
445 name="arrow.triangle.branch"
446 size={13}
447 tintColorClassName="foreground"
448 type="monochrome"
449 />
450 <ShimmeringWorkContent
451 className="flex-none"
452 textClassName="font-t3-medium"
453 compact
454 icon="arrow.triangle.branch"
455 iconSubtleColor="transparent"
456 label={props.status.label}
457 showIcon={false}
458 />
459 </StatusLabelRow>
460 );
461 }
462 return (
463 <WorkingDuration key="working" startedAt={props.status.startedAt} onLayout={props.onLayout} />
464 );
465}
466
467// Absolute rows cross-fade around the same center without affecting each other.
468function StatusLabelRow(props: {
469 readonly accessibilityLabel?: string;
470 readonly accessibilityRole?: "button";
471 readonly className?: string;
472 readonly children: ReactNode;
473 readonly onLayout: (event: LayoutChangeEvent) => void;
474 readonly onPress?: () => void;
475}) {
476 const rowClassName = `h-11 flex-row items-center px-4 ${props.className ?? ""}`;
477 return (
478 <Animated.View
479 className="absolute max-w-full"
480 entering={LABEL_ENTERING}
481 exiting={LABEL_EXITING}
482 onLayout={props.onLayout}
483 >
484 {props.onPress ? (
485 <Pressable
486 accessibilityLabel={props.accessibilityLabel}
487 accessibilityRole={props.accessibilityRole}
488 className={`${rowClassName} active:opacity-70`}
489 onPress={props.onPress}
490 >
491 {props.children}
492 </Pressable>
493 ) : (
494 <View accessible accessibilityLabel={props.accessibilityLabel} className={rowClassName}>
495 {props.children}
496 </View>
497 )}
498 </Animated.View>
499 );
500}
501
502function WorkingDuration(props: {
503 readonly startedAt: string;
504 readonly onLayout: (event: LayoutChangeEvent) => void;
505}) {
506 return (
507 <StatusLabelRow onLayout={props.onLayout}>
508 <WorkingTimer startedAt={props.startedAt} />
509 </StatusLabelRow>
510 );
511}
512
513export function WorkingTimer(props: { readonly startedAt: string }) {
514 const nowMs = useVisibleSecondClock(true);
515 return (
516 <SystemText
517 className="shrink text-xs text-foreground"
518 numberOfLines={1}
519 style={{ fontVariant: ["tabular-nums"], fontWeight: "500" }}
520 >
521 Working {formatWorkingDuration(props.startedAt, nowMs)}
522 </SystemText>
523 );
524}
525
526function formatWorkingDuration(startedAt: string, nowMs: number): string {
527 const startedAtMs = Date.parse(startedAt);
528 if (!Number.isFinite(startedAtMs) || nowMs <= startedAtMs) {
529 return "0s";
530 }
531
532 const totalSeconds = Math.floor((nowMs - startedAtMs) / 1_000);
533 if (totalSeconds < 60) {
534 return `${totalSeconds}s`;
535 }
536 if (totalSeconds >= 3_600) {
537 return formatDuration(totalSeconds * 1_000);
538 }
539
540 const minutes = Math.floor(totalSeconds / 60);
541 const seconds = String(totalSeconds % 60).padStart(2, "0");
542 return `${minutes}m ${seconds}s`;
543}
544
545function ScrollToEndButton(props: { readonly disabled?: boolean; readonly onPress: () => void }) {
546 return (
547 <ControlPill
548 accessibilityLabel="Scroll to end"
549 activateOnPressIn
550 className="h-11 w-11 bg-transparent"
551 disabled={props.disabled}
552 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
553 onPress={props.onPress}
554 />
555 );
556}