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 type LayoutChangeEvent,
7 Pressable,
8 Text as SystemText,
9 useWindowDimensions,
10 View,
11} from "react-native";
12import Animated, {
13 Easing,
14 FadeIn,
15 FadeOut,
16 ReduceMotion,
17 type SharedValue,
18 useAnimatedStyle,
19 useSharedValue,
20 withTiming,
21} from "react-native-reanimated";
22import { withUniwind } from "uniwind";
23
24import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
25import { AppText as Text } from "../../components/ui/AppText";
26import { SymbolView } from "../../components/ui/AppSymbol";
27import { ControlPill } from "../../components/ui/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;
36const CONTROL_GAP = 8;
37const COMPOSER_CAPSULE_INSET = 6;
38const GLASS_MERGE_SPACING = 12;
39const CONTROL_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);
40const CONTROL_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
41const CONTROL_TIMING = {
42 duration: 240,
43 easing: Easing.out(Easing.cubic),
44 reduceMotion: ReduceMotion.System,
45} as const;
46const CONTROL_ROW_GAP = 14;
47const CONTROL_SEPARATION = (CONTROL_ROW_GAP + CONTROL_HEIGHT) / 2;
48const LABEL_ENTERING = FadeIn.duration(160).delay(80).reduceMotion(ReduceMotion.System);
49const LABEL_EXITING = FadeOut.duration(100).reduceMotion(ReduceMotion.System);
50
51// Expo reapplies glass after native layout and window reattachment, when UIKit
52// can otherwise leave the label visible but lose the material behind it.
53const UniwindGlassView = withUniwind(GlassView, {
54 style: { fromClassName: "className" },
55});
56const UniwindGlassContainer = withUniwind(GlassContainer, {
57 style: { fromClassName: "className" },
58});
59const AnimatedGlassView = Animated.createAnimatedComponent(UniwindGlassView);
60
61// The segment widths feed labelWidth, and labelWidth moves the segments. Pixel
62// rounding then flips a segment's width by one physical pixel per layout, which
63// re-ellipsizes a truncated label every frame. Sub-point changes are ignored.
64function settleWidth(next: number) {
65 return (current: number) => (Math.abs(current - next) < 1 ? current : next);
66}
67
68const CONTROL_OVERLAY_OFFSET = CONTROL_HEIGHT + CONTROL_GAP - COMPOSER_CAPSULE_INSET;
69export const FLOATING_WORKING_CONTROL_COVERAGE = CONTROL_OVERLAY_OFFSET + CONTROL_GAP;
70
71export function FloatingWorkingControl(props: {
72 readonly colorScheme: "light" | "dark";
73 readonly status: FloatingWorkingStatus | null;
74 readonly devicePreview: { readonly count: number; readonly onPress: () => void } | null;
75 readonly browserPreview: { readonly count: number; readonly onPress: () => void } | null;
76 readonly showScrollToEnd: boolean;
77 readonly onScrollToEnd: () => void;
78 readonly agents: SubagentPillSegment | null;
79 readonly onOpenAgents: () => void;
80 readonly queuedCount: number;
81 readonly onOpenQueue: () => void;
82 readonly lift?: SharedValue<number>;
83}) {
84 const { width: windowWidth } = useWindowDimensions();
85 const [overlayWidth, setOverlayWidth] = useState(windowWidth);
86 const [queueWidth, setQueueWidth] = useState(0);
87 const [agentsWidth, setAgentsWidth] = useState(0);
88 const hasQueue = props.queuedCount > 0;
89 const hasPreview = props.devicePreview !== null || props.browserPreview !== null;
90 const [previewWidth, setPreviewWidth] = useState(0);
91 const agents = props.agents;
92 const hasAgents = agents !== null;
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 const hasStatus = props.status !== null;
135 const hasCapsule = hasStatus || hasQueue || hasAgents || hasPreview;
136 useEffect(() => {
137 if (!hasStatus) {
138 measuredWidthRef.current = null;
139 capsuleWidth.value = null;
140 }
141 }, [capsuleWidth, hasStatus]);
142 const capsuleStyle = useAnimatedStyle(() => ({
143 transform: [{ translateX: CONTROL_SEPARATION * (1 - separationProgress.value) }],
144 }));
145 const capsuleSizerStyle = useAnimatedStyle(() => ({
146 width: capsuleWidth.value ?? 0,
147 }));
148
149 if (!hasCapsule && !props.showScrollToEnd) {
150 return null;
151 }
152
153 const previewCompact =
154 hasStatus ||
155 hasAgents ||
156 hasQueue ||
157 (props.devicePreview !== null && props.browserPreview !== null);
158 const statusInteractive =
159 props.status?.kind === "connection" || props.status?.kind === "child-input";
160 const capsuleInteractive = statusInteractive || hasQueue || hasAgents || hasPreview;
161 const statusContent =
162 props.status !== null ? (
163 <View
164 pointerEvents={statusInteractive ? "box-none" : "none"}
165 className="h-11 items-center justify-center"
166 >
167 <Animated.View className="h-11" style={capsuleSizerStyle} />
168 <View
169 pointerEvents={statusInteractive ? "box-none" : "none"}
170 className="absolute h-11 items-center justify-center"
171 style={{ width: labelWidth }}
172 >
173 <FloatingStatusLabel
174 key={
175 props.status.kind === "working" || props.status.kind === "compacting"
176 ? props.status.kind
177 : `${props.status.kind}:${props.status.label}`
178 }
179 status={props.status}
180 onLayout={handleLabelLayout}
181 />
182 </View>
183 </View>
184 ) : null;
185
186 const capsuleContent = (
187 <View className="flex-row items-center">
188 {statusContent}
189 {hasPreview ? (
190 <View
191 className="h-11 flex-row items-center"
192 onLayout={(event) => setPreviewWidth(settleWidth(event.nativeEvent.layout.width))}
193 >
194 {hasStatus ? <View className="h-4 w-px bg-border" /> : null}
195 {props.devicePreview !== null ? (
196 <DevicePreviewButton {...props.devicePreview} compact={previewCompact} />
197 ) : null}
198 {props.browserPreview !== null ? (
199 <BrowserPreviewButton {...props.browserPreview} compact={previewCompact} />
200 ) : null}
201 </View>
202 ) : null}
203 {agents !== null ? (
204 <Pressable
205 accessibilityRole="button"
206 accessibilityLabel={`Open agents, ${agents.accessibilityLabel}`}
207 accessibilityHint="Opens this turn's subagents"
208 onPress={props.onOpenAgents}
209 onLayout={(event) => setAgentsWidth(settleWidth(event.nativeEvent.layout.width))}
210 className="h-11 flex-row items-center gap-1.5 px-3 active:opacity-70"
211 >
212 {hasStatus || hasPreview ? <View className="mr-1 h-4 w-px bg-border" /> : null}
213 <SymbolView name="person.2" size={13} tintColorClassName="accent-foreground-muted" />
214 <Text className="font-t3-medium text-xs tabular-nums" numberOfLines={1}>
215 {agents.label}
216 </Text>
217 </Pressable>
218 ) : null}
219 {hasQueue ? (
220 <Pressable
221 accessibilityRole="button"
222 accessibilityLabel={`Open queue, ${props.queuedCount} messages`}
223 accessibilityHint="Opens queued messages for reordering, steering, or removal"
224 onPress={props.onOpenQueue}
225 onLayout={(event) => setQueueWidth(settleWidth(event.nativeEvent.layout.width))}
226 style={{ maxWidth: Math.min(overlayWidth, windowWidth) * 0.45 }}
227 className="h-11 flex-row items-center gap-2 px-3 active:opacity-70"
228 >
229 {hasStatus || hasPreview || hasAgents ? (
230 <View className="mr-1 h-4 w-px bg-border" />
231 ) : null}
232 <SymbolView name="list.number" size={13} tintColorClassName="accent-foreground-muted" />
233 <Text className="shrink font-t3-medium text-xs tabular-nums" numberOfLines={1}>
234 {props.queuedCount} queued
235 </Text>
236 </Pressable>
237 ) : null}
238 </View>
239 );
240
241 return (
242 <Animated.View
243 pointerEvents="box-none"
244 className="absolute left-0 right-0 z-20 items-center"
245 style={[{ top: -CONTROL_OVERLAY_OFFSET }, liftStyle]}
246 onLayout={(event) => setOverlayWidth(event.nativeEvent.layout.width)}
247 entering={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_ENTERING}
248 exiting={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_EXITING}
249 >
250 {hasCapsule && NATIVE_LIQUID_GLASS_SUPPORTED ? (
251 <UniwindGlassContainer
252 spacing={GLASS_MERGE_SPACING}
253 pointerEvents="box-none"
254 className="flex-row items-center gap-4"
255 >
256 <AnimatedGlassView
257 colorScheme={props.colorScheme}
258 glassEffectStyle="regular"
259 isInteractive={capsuleInteractive}
260 pointerEvents={capsuleInteractive ? "box-none" : "none"}
261 className="h-11 items-center justify-center overflow-hidden rounded-full"
262 style={capsuleStyle}
263 >
264 {capsuleContent}
265 </AnimatedGlassView>
266
267 <AnimatedGlassView
268 colorScheme={props.colorScheme}
269 glassEffectStyle={{ style: props.showScrollToEnd ? "regular" : "none", animate: true }}
270 isInteractive
271 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
272 accessibilityElementsHidden={!props.showScrollToEnd}
273 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
274 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
275 style={arrowTransformStyle}
276 >
277 <Animated.View style={arrowContentStyle}>
278 <ScrollToEndButton disabled={!props.showScrollToEnd} onPress={props.onScrollToEnd} />
279 </Animated.View>
280 </AnimatedGlassView>
281 </UniwindGlassContainer>
282 ) : hasCapsule ? (
283 <View pointerEvents="box-none" className="flex-row items-center gap-4">
284 <Animated.View
285 pointerEvents={capsuleInteractive ? "box-none" : "none"}
286 className="h-11 items-center justify-center overflow-hidden rounded-full border border-border bg-glass-fallback shadow-md shadow-black/10"
287 style={capsuleStyle}
288 >
289 {capsuleContent}
290 </Animated.View>
291
292 <Animated.View
293 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
294 accessibilityElementsHidden={!props.showScrollToEnd}
295 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
296 style={[arrowTransformStyle, arrowContentStyle]}
297 >
298 <ControlPill
299 accessibilityLabel="Scroll to end"
300 activateOnPressIn
301 className="h-11 w-11 border border-border bg-glass-fallback shadow-md shadow-black/10"
302 disabled={!props.showScrollToEnd}
303 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
304 onPress={props.onScrollToEnd}
305 />
306 </Animated.View>
307 </View>
308 ) : NATIVE_LIQUID_GLASS_SUPPORTED ? (
309 <UniwindGlassView
310 colorScheme={props.colorScheme}
311 glassEffectStyle="regular"
312 isInteractive
313 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
314 >
315 <ScrollToEndButton onPress={props.onScrollToEnd} />
316 </UniwindGlassView>
317 ) : (
318 <ControlPill
319 accessibilityLabel="Scroll to end"
320 activateOnPressIn
321 className="h-11 w-11 border border-border bg-glass-fallback shadow-md shadow-black/10"
322 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
323 onPress={props.onScrollToEnd}
324 />
325 )}
326 </Animated.View>
327 );
328}
329
330function CompactingLabel(props: { readonly onLayout: (event: LayoutChangeEvent) => void }) {
331 return (
332 <StatusLabelRow accessibilityLabel="Compacting" className="gap-1.5" onLayout={props.onLayout}>
333 <SymbolView
334 name="arrow.down.right.and.arrow.up.left"
335 size={13}
336 tintColorClassName="foreground"
337 type="monochrome"
338 />
339 <Text className="font-t3-medium text-xs text-foreground">Compacting…</Text>
340 </StatusLabelRow>
341 );
342}
343
344function FloatingStatusLabel(props: {
345 readonly status: FloatingWorkingStatus;
346 readonly onLayout: (event: LayoutChangeEvent) => void;
347}) {
348 if (props.status.kind === "syncing") {
349 return (
350 <StatusLabelRow
351 key="syncing"
352 accessibilityLabel={props.status.label}
353 className="gap-2"
354 onLayout={props.onLayout}
355 >
356 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
357 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
358 {props.status.label}
359 </Text>
360 </StatusLabelRow>
361 );
362 }
363 if (props.status.kind === "compacting") {
364 return <CompactingLabel key="compacting" onLayout={props.onLayout} />;
365 }
366 if (props.status.kind === "child-input") {
367 return (
368 <StatusLabelRow
369 key="child-input"
370 accessibilityLabel={props.status.accessibilityLabel}
371 accessibilityRole="button"
372 className="gap-2"
373 onLayout={props.onLayout}
374 onPress={props.status.onPress}
375 >
376 <SymbolView name="text.bubble" size={13} tintColorClassName="foreground" />
377 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
378 {props.status.label}
379 </Text>
380 </StatusLabelRow>
381 );
382 }
383 if (props.status.kind === "connection") {
384 return (
385 <StatusLabelRow
386 key="connection"
387 accessibilityLabel={props.status.label}
388 accessibilityRole="button"
389 className="gap-2"
390 onLayout={props.onLayout}
391 onPress={props.status.onPress}
392 >
393 {props.status.tone === "reconnecting" ? (
394 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
395 ) : (
396 <View className="h-2 w-2 rounded-full bg-red-500" />
397 )}
398 <Text
399 className="max-w-[260px] shrink font-t3-medium text-xs text-foreground"
400 numberOfLines={1}
401 >
402 {props.status.label}
403 </Text>
404 </StatusLabelRow>
405 );
406 }
407 if (props.status.kind === "background") {
408 return (
409 <StatusLabelRow
410 key="background"
411 accessibilityLabel={props.status.accessibilityLabel}
412 className="gap-2"
413 onLayout={props.onLayout}
414 >
415 <SymbolView
416 name={props.status.waiting ? { ios: "bolt", android: "bolt" } : "terminal"}
417 size={13}
418 tintColorClassName="foreground"
419 type="monochrome"
420 />
421 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
422 {props.status.label}
423 </Text>
424 </StatusLabelRow>
425 );
426 }
427 if (props.status.kind === "goal") {
428 return (
429 <StatusLabelRow
430 key="goal"
431 accessibilityLabel={props.status.accessibilityLabel}
432 className="gap-2"
433 onLayout={props.onLayout}
434 >
435 <SymbolView name="target" size={13} tintColorClassName="foreground" type="monochrome" />
436 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
437 {props.status.label}
438 </Text>
439 </StatusLabelRow>
440 );
441 }
442 if (props.status.kind === "preparing") {
443 return (
444 <StatusLabelRow
445 key="preparing"
446 accessibilityLabel={props.status.label}
447 className="gap-1.5"
448 onLayout={props.onLayout}
449 >
450 <SymbolView
451 name="arrow.triangle.branch"
452 size={13}
453 tintColorClassName="foreground"
454 type="monochrome"
455 />
456 <ShimmeringWorkContent
457 className="flex-none"
458 textClassName="font-t3-medium"
459 compact
460 icon="arrow.triangle.branch"
461 iconSubtleColor="transparent"
462 label={props.status.label}
463 showIcon={false}
464 />
465 </StatusLabelRow>
466 );
467 }
468 return (
469 <WorkingDuration key="working" startedAt={props.status.startedAt} onLayout={props.onLayout} />
470 );
471}
472
473function StatusLabelRow(props: {
474 readonly accessibilityLabel?: string;
475 readonly accessibilityRole?: "button";
476 readonly className?: string;
477 readonly children: ReactNode;
478 readonly onLayout: (event: LayoutChangeEvent) => void;
479 readonly onPress?: () => void;
480}) {
481 const rowClassName = `h-11 flex-row items-center px-4 ${props.className ?? ""}`;
482 return (
483 <Animated.View
484 className="absolute max-w-full"
485 entering={LABEL_ENTERING}
486 exiting={LABEL_EXITING}
487 onLayout={props.onLayout}
488 >
489 {props.onPress ? (
490 <Pressable
491 accessibilityLabel={props.accessibilityLabel}
492 accessibilityRole={props.accessibilityRole}
493 className={`${rowClassName} active:opacity-70`}
494 onPress={props.onPress}
495 >
496 {props.children}
497 </Pressable>
498 ) : (
499 <View accessible accessibilityLabel={props.accessibilityLabel} className={rowClassName}>
500 {props.children}
501 </View>
502 )}
503 </Animated.View>
504 );
505}
506
507function WorkingDuration(props: {
508 readonly startedAt: string;
509 readonly onLayout: (event: LayoutChangeEvent) => void;
510}) {
511 return (
512 <StatusLabelRow onLayout={props.onLayout}>
513 <WorkingTimer startedAt={props.startedAt} />
514 </StatusLabelRow>
515 );
516}
517
518export function WorkingTimer(props: { readonly startedAt: string }) {
519 const nowMs = useVisibleSecondClock(true);
520 return (
521 <SystemText
522 className="shrink text-xs text-foreground"
523 numberOfLines={1}
524 style={{ fontVariant: ["tabular-nums"], fontWeight: "500" }}
525 >
526 Working {formatWorkingDuration(props.startedAt, nowMs)}
527 </SystemText>
528 );
529}
530
531function formatWorkingDuration(startedAt: string, nowMs: number): string {
532 const startedAtMs = Date.parse(startedAt);
533 if (!Number.isFinite(startedAtMs) || nowMs <= startedAtMs) {
534 return "0s";
535 }
536
537 const totalSeconds = Math.floor((nowMs - startedAtMs) / 1_000);
538 if (totalSeconds < 60) {
539 return `${totalSeconds}s`;
540 }
541 if (totalSeconds >= 3_600) {
542 return formatDuration(totalSeconds * 1_000);
543 }
544
545 const minutes = Math.floor(totalSeconds / 60);
546 const seconds = String(totalSeconds % 60).padStart(2, "0");
547 return `${minutes}m ${seconds}s`;
548}
549
550function ScrollToEndButton(props: { readonly disabled?: boolean; readonly onPress: () => void }) {
551 return (
552 <ControlPill
553 accessibilityLabel="Scroll to end"
554 activateOnPressIn
555 className="h-11 w-11 bg-transparent"
556 disabled={props.disabled}
557 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
558 onPress={props.onPress}
559 />
560 );
561}