Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadAgentsSheet.tsx

202 lines7.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { ThreadTurnSubagents } from "@t3tools/client-runtime/state/thread-subagents";
3import {
4 isOrchestrationV2WorkActive,
5 type EnvironmentId,
6 type OrchestrationV2Subagent,
7 type ThreadId,
8} from "@t3tools/contracts";
9import { deriveSubagentElapsedMs, formatDuration } from "@t3tools/shared/orchestrationTiming";
10import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
11import * as DateTime from "effect/DateTime";
12import * as Haptics from "expo-haptics";
13import { useEffect, useState } from "react";
14import { Platform, Pressable, ScrollView, View } from "react-native";
15import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17​
18import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
19import { AppText as Text } from "../../components/AppText";
20import { SymbolView } from "../../components/AppSymbol";
21import { useUniwindTheme } from "../../lib/useUniwindTheme";
22import { environmentThreadDetails } from "../../state/threads";
23import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
24import { resolveSubagentRowPresentation } from "./threadAgentsPresentation";
25​
26import { SubagentStatusDot } from "./SubagentStatusDot";
27​
28const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
29​
30type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
31​
32export function useThreadTurnSubagents(target: AgentsTarget): ThreadTurnSubagents | null {
33 return useAtomValue(environmentThreadDetails.turnSubagentsAtom(target));
35​
36export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
37 const target = route.params;
38 const navigation = useNavigation();
39 const insets = useSafeAreaInsets();
40 const theme = useUniwindTheme();
41 const turn = useThreadTurnSubagents(target);
42 const subagents = turn?.subagents ?? [];
43 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
44​
45 const openChildThread = (childThreadId: ThreadId) => {
46 void Haptics.selectionAsync();
47 // Replace rather than push: the sheet is a leaf, and the child thread
48 // belongs in the workspace stack where Home's back button expects it.
49 navigation.dispatch(
50 StackActions.replace("Thread", {
51 environmentId: target.environmentId,
52 threadId: childThreadId,
53 }),
54 );
55 };
56​
57 const content = (
58 <ScrollView
59 className="flex-1"
60 // The iOS header is translucent and floats over this view; UIKit has to
61 // inset the content or the first row sits underneath the title.
62 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
63 contentContainerClassName="px-5 pb-6"
64 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
65 >
66 {subagents.length === 0 ? (
67 <Text className="pt-6 text-center text-sm text-foreground-muted">
68 No agents in this turn.
69 </Text>
70 ) : (
71 subagents.map((subagent) => (
72 <AgentRow
73 key={subagent.id}
74 subagent={subagent}
75 tickSeconds={hasLiveAgent}
76 onOpen={openChildThread}
77 />
78 ))
79 )}
80 </ScrollView>
81 );
82​
83 if (Platform.OS === "ios") {
84 // A plain formSheet screen never renders a stack header, so it comes from
85 // a nested native stack inside the sheet (same shape as the git sheet).
86 return (
87 <View collapsable={false} className="flex-1 bg-sheet">
88 <ScreenStack style={{ flex: 1 }}>
89 <Screen
90 activityState={2}
91 enabled
92 isNativeStack
93 screenId="thread-agents-sheet-native"
94 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
95 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
96 >
97 {content}
98 <ScreenStackHeaderConfig
99 backgroundColor="rgba(0,0,0,0)"
100 color={theme["--color-foreground"]}
101 hideBackButton
102 hideShadow={false}
103 title="Agents"
104 titleColor={theme["--color-foreground"]}
105 titleFontSize={18}
106 titleFontWeight="800"
107 translucent
108 />
109 </Screen>
110 </ScreenStack>
111 </View>
112 );
113 }
114​
115 return (
116 <View collapsable={false} className="flex-1 bg-sheet">
117 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
118 {content}
119 </View>
120 );
122​
123function AgentRow(props: {
124 readonly subagent: OrchestrationV2Subagent;
125 readonly tickSeconds: boolean;
126 readonly onOpen: (childThreadId: ThreadId) => void;
127}) {
128 const { subagent } = props;
129 const presentation = resolveSubagentRowPresentation(subagent);
130 const childThreadId = subagent.childThreadId;
131 const elapsed = useSubagentElapsed(subagent, props.tickSeconds);
132​
133 const row = (
134 <View className="min-h-14 flex-row items-center gap-3 border-b border-border py-3">
135 <SubagentStatusDot tone={presentation.tone} placement="sheet" />
136 <View className="min-w-0 flex-1 gap-0.5">
137 <Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
138 {presentation.title}
139 </Text>
140 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
141 {presentation.detail ?? presentation.statusLabel}
142 </Text>
143 </View>
144 {elapsed === null ? null : (
145 <Text className="shrink-0 text-2xs tabular-nums text-foreground-muted">{elapsed}</Text>
146 )}
147 {presentation.canOpenThread ? (
148 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
149 ) : null}
150 </View>
151 );
152​
153 if (childThreadId === null) {
154 return (
155 <View
156 accessible
157 accessibilityLabel={`${presentation.title}, ${presentation.statusLabel}`}
158 accessibilityHint="Provider-managed agent. Its work appears in the transcript."
159 >
160 {row}
161 </View>
162 );
163 }
164​
165 return (
166 <Pressable
167 accessibilityRole="link"
168 accessibilityLabel={`${presentation.title}, ${presentation.statusLabel}`}
169 accessibilityHint="Opens this agent's thread"
170 onPress={() => props.onOpen(childThreadId)}
171 className="active:opacity-70"
172 >
173 {row}
174 </Pressable>
175 );
177​
178/**
179 * Elapsed time for one agent. Only a roster with live work subscribes to the
180 * shared second tick, so a settled sheet never repaints.
181 */
182function useSubagentElapsed(
183 subagent: Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">,
184 tickSeconds: boolean,
185): string | null {
186 const [nowMs, setNowMs] = useState(() => Date.now());
187 const running = isOrchestrationV2WorkActive(subagent.status);
188 useEffect(() => {
189 if (!tickSeconds || !running) return;
190 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
191 return () => clearInterval(intervalId);
192 }, [running, tickSeconds]);
193 const elapsedMs = deriveSubagentElapsedMs(
194 {
195 status: subagent.status,
196 startedAt: subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt),
197 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
198 },
199 nowMs,
200 );
201 return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);