Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import {
4 resolveWorkflowOpening,
5 workflowMemberModelSelection,
6 workflowOpeningHeadline,
7 workflowOpeningParentThreadId,
8 type RuntimeSubagent,
9} from "@t3tools/client-runtime/state/subagentRuntime";
10import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
11import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
12import { Atom } from "effect/reactivity";
13import { T, useGT, useMessages } from "gt-react-native";
14import { useState } from "react";
15import { Pressable, View } from "react-native";
16
17import { AppText as Text } from "../../components/ui/AppText";
18import { environmentThreadDetails } from "../../state/threads";
19import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
20import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
21import { SubagentRow } from "./SubagentRow";
22import { WorkLogBlock } from "./work-log-layout";
23import { useOpenLinkedThread } from "./useOpenLinkedThread";
24import { withTokenStarts } from "../../lib/highlights";
25
26const FOLDED_SCRIPT_LINES = 10;
27
28const NO_THREAD_ATOM = Atom.make<EnvironmentThread | null>(null);
29
30export function useWorkflowOpening(ref: ScopedThreadRef | null) {
31 const messages = useMessages();
32 const threadAtom = ref === null ? NO_THREAD_ATOM : environmentThreadDetails.threadAtom(ref);
33 // Selected as a primitive so an ordinary thread's updates never change the result.
34 const parentId = useAtomValue(threadAtom, (thread) =>
35 thread === null
36 ? null
37 : workflowOpeningParentThreadId({
38 thread: thread.projection.thread,
39 messages: thread.projection.messages,
40 }),
41 );
42 const projection = useAtomValue(threadAtom, (thread) =>
43 parentId === null ? null : (thread?.projection ?? null),
44 );
45 const parentSubagents = useAtomValue(
46 ref === null || parentId === null
47 ? NO_THREAD_ATOM
48 : environmentThreadDetails.threadAtom(scopeThreadRef(ref.environmentId, parentId)),
49 (parent) => (parentId === null ? null : (parent?.projection.subagents ?? null)),
50 );
51 return projection === null
52 ? null
53 : resolveWorkflowOpening(
54 {
55 thread: projection.thread,
56 messages: projection.messages,
57 parentSubagents,
58 },
59 messages,
60 );
61}
62
63function memberRowSubagent(
64 member: RuntimeSubagent,
65 opening: WorkflowOpeningValue,
66 coordinatorThreadId: ThreadId,
67) {
68 return {
69 // A member's parent thread is the coordinator's thread, the one showing this opening.
70 threadId: coordinatorThreadId,
71 childThreadId: member.childThreadId as ThreadId | null,
72 model: member.model,
73 modelSelection: workflowMemberModelSelection(member, opening.providerInstanceId!),
74 driver: opening.driver!,
75 providerInstanceId: opening.providerInstanceId!,
76 title: member.title,
77 prompt: member.progress ?? member.title,
78 status: member.status,
79 progress: undefined,
80 result: member.result ?? member.error,
81 };
82}
83
84type WorkflowOpeningValue = NonNullable<ReturnType<typeof useWorkflowOpening>>;
85
86export function ThreadWorkflowOpening(props: {
87 readonly environmentId: EnvironmentId;
88 readonly threadId: ThreadId;
89 readonly opening: WorkflowOpeningValue;
90}) {
91 const gt = useGT();
92 const messages = useMessages();
93 const openLinkedThread = useOpenLinkedThread();
94 const { opening } = props;
95 const headline = workflowOpeningHeadline(opening, messages);
96 const canListMembers = opening.driver !== null && opening.providerInstanceId !== null;
97 const phases = (opening.group?.phases ?? []).filter((phase) => phase.members.length > 0);
98 const unphased = opening.group?.unphasedMembers ?? [];
99 const renderMember = (member: RuntimeSubagent) => {
100 const threadId = member.childThreadId;
101 return (
102 <Pressable
103 key={member.id}
104 accessibilityRole={threadId === null ? undefined : "link"}
105 accessibilityHint={threadId === null ? undefined : gt("Opens this agent's thread")}
106 disabled={threadId === null}
107 onPress={() => {
108 if (threadId !== null)
109 openLinkedThread({ environmentId: String(props.environmentId), threadId });
110 }}
111 className="rounded-lg px-3 py-3 active:bg-subtle"
112 >
113 <SubagentRow
114 environmentId={props.environmentId}
115 subagent={memberRowSubagent(member, opening, props.threadId)}
116 elapsed={null}
117 />
118 </Pressable>
119 );
120 };
121 return (
122 <WorkLogBlock>
123 <View className="mb-5 gap-3">
124 <View className="flex-row items-start gap-2">
125 <View className="min-w-0 flex-1 gap-0.5">
126 <Text className="font-t3-medium text-2xs text-foreground-muted">
127 <T>Workflow started</T>
128 </Text>
129 <Text numberOfLines={1} className="font-t3-medium text-sm text-foreground">
130 {headline.title}
131 </Text>
132 {headline.description ? (
133 <Text className="text-xs text-foreground-muted">{headline.description}</Text>
134 ) : null}
135 </View>
136 {headline.agents ? (
137 <Text className="shrink-0 text-2xs tabular-nums text-foreground-muted">
138 {headline.agents}
139 </Text>
140 ) : null}
141 </View>
142 {canListMembers
143 ? phases.map((phase) => (
144 <View key={phase.index} className="gap-px">
145 <Text className="px-1 pt-1 font-t3-medium text-2xs text-foreground-muted">
146 {phase.title} · {phase.settledCount}/{phase.members.length}
147 </Text>
148 {phase.members.map(renderMember)}
149 </View>
150 ))
151 : null}
152 {canListMembers ? unphased.map(renderMember) : null}
153 <WorkflowScript script={opening.script} />
154 </View>
155 </WorkLogBlock>
156 );
157}
158
159function WorkflowScript(props: { readonly script: string }) {
160 const gt = useGT();
161 const [expanded, setExpanded] = useState(false);
162 const { themeAppearance } = useAppearancePreferences();
163 const script = props.script.trimEnd();
164 const lines = useMarkdownCodeHighlight({
165 code: script,
166 language: "javascript",
167 theme: themeAppearance,
168 enabled: true,
169 });
170 const lineCount = script.split("\n").length;
171 const canFold = lineCount > FOLDED_SCRIPT_LINES;
172 const shownLines = canFold && !expanded ? FOLDED_SCRIPT_LINES : lineCount;
173 const highlighted = (lines ? withTokenStarts(lines) : undefined)
174 ?.slice(0, shownLines)
175 .flatMap((line, lineIndex) => {
176 const separator = lineIndex > 0 ? "\n" : "";
177 return [
178 separator,
179 ...line.map(({ token, start }) => {
180 return (
181 <Text key={start} style={token.color ? { color: token.color } : undefined}>
182 {token.content}
183 </Text>
184 );
185 }),
186 ];
187 });
188 return (
189 <View className="gap-1">
190 <View className="rounded-lg bg-subtle px-3 py-2.5">
191 <Text selectable className="font-mono text-2xs leading-normal text-foreground">
192 {highlighted ?? script.split("\n").slice(0, shownLines).join("\n")}
193 </Text>
194 </View>
195 {canFold ? (
196 <Pressable
197 accessibilityRole="button"
198 accessibilityState={{ expanded }}
199 onPress={() => setExpanded((value) => !value)}
200 className="self-start py-1 active:opacity-70"
201 >
202 <Text className="font-t3-medium text-xs text-foreground-muted">
203 {expanded
204 ? gt("Show less", { $context: "collapses the workflow script" })
205 : gt("Show full script")}
206 </Text>
207 </Pressable>
208 ) : null}
209 </View>
210 );
211}