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