The best way to control Claude Code, Codex and more from any computer or phone
feat(mobile): add dynamic workflows to the Agents sheet (#18642)
Bilal Bakr committed
Oct 28, 2026 at 21:12 UTC
612a8e59f0f2cee5eaaf24507f848c7a634ac3dc
16 files changed
+1273
-40
apps/mobile/src/features/threads/SubagentStopButton.tsx
new
+65
@@ -0,0 +1,65 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
3
+import { useState } from "react";
4
+import { View } from "react-native";
5
+
6
+import * as Dialog from "../../components/ui/Dialog";
7
+import { IconButton } from "../../components/ui/IconButton";
8
+import { orchestrationEnvironment } from "../../state/orchestration";
9
+import { threadEnvironment } from "../../state/threads";
10
+import { useAtomCommand } from "../../state/use-atom-command";
11
+import {
12
+ resolveSubagentRowPresentation,
13
+ resolveSubagentStopTarget,
14
+} from "./threadAgentsPresentation";
15
+
16
+export function SubagentStopButton(props: {
17
+ readonly environmentId: EnvironmentId;
18
+ readonly subagent: OrchestrationV2Subagent;
19
+ readonly className?: string;
20
+}) {
21
+ const target = resolveSubagentStopTarget(props.subagent);
22
+ const canStop = useAtomValue(
23
+ orchestrationEnvironment.stopWorkflow.permissionAtom(props.environmentId),
24
+ );
25
+ const stopWorkflow = useAtomCommand(orchestrationEnvironment.stopWorkflow);
26
+ const interruptTurn = useAtomCommand(threadEnvironment.interruptTurn);
27
+ const [stopping, setStopping] = useState(false);
28
+
29
+ if (target === null || !canStop) return null;
30
+
31
+ const workflow = target.kind === "workflow";
32
+ const label =
33
+ props.subagent.workflow?.name ?? resolveSubagentRowPresentation(props.subagent).title;
34
+ const stop = async () => {
35
+ setStopping(true);
36
+ const result = await (
37
+ target.kind === "workflow"
38
+ ? stopWorkflow({ environmentId: props.environmentId, input: target.input })
39
+ : interruptTurn({ environmentId: props.environmentId, input: target.input })
40
+ ).finally(() => setStopping(false));
41
+ if (result._tag === "Failure") {
42
+ Dialog.alert(workflow ? "Could not stop workflow" : "Could not stop agent");
43
+ }
44
+ };
45
+
46
+ return (
47
+ <View className={props.className}>
48
+ <IconButton
49
+ icon="stop.fill"
50
+ variant="danger"
51
+ accessibilityLabel={`${stopping ? "Stopping" : "Stop"} ${workflow ? "workflow" : "agent"} ${label}`}
52
+ disabled={stopping}
53
+ onPress={() =>
54
+ Dialog.confirm({
55
+ title: workflow ? "Stop workflow?" : "Stop agent?",
56
+ message: workflow ? `Every running agent in ${label} stops.` : `Stop ${label}?`,
57
+ confirmText: "Stop",
58
+ destructive: true,
59
+ onConfirm: () => void stop(),
60
+ })
61
+ }
62
+ />
63
+ </View>
64
+ );
65
+}
apps/mobile/src/features/threads/ThreadAgentsSheet.tsx
+57
-21
@@ -1,4 +1,8 @@
1
import { useAtomValue } from "@effect/atom-react";
2
+import {
3
+ deriveWorkflowGroups,
4
+ projectedSubagentsToRuntime,
5
+} from "@t3tools/client-runtime/state/subagentRuntime";
6
import type { ThreadTurnSubagents } from "@t3tools/client-runtime/state/thread-subagents";
7
import {
8
isOrchestrationV2WorkActive,
@@ -11,6 +15,7 @@ import { StackActions, useNavigation, type StaticScreenProps } from "@react-navi
15
import * as DateTime from "effect/DateTime";
16
import { Atom } from "effect/reactivity";
17
import * as Haptics from "expo-haptics";
18
+import { useMemo } from "react";
19
import { Platform, Pressable, ScrollView, View } from "react-native";
20
import { ScreenStack } from "react-native-screens";
21
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -23,6 +28,8 @@ import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack";
28
import { useEnvironments } from "../../state/environments";
29
import { SubagentRow } from "./SubagentRow";
30
import { useVisibleSecondClock } from "./use-visible-second-clock";
31
+import { SubagentStopButton } from "./SubagentStopButton";
32
+import { ThreadWorkflowGroup } from "./ThreadWorkflowGroup";
33
import { ScreenContent } from "../../components/ui/ScreenContent";
34
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
35
import { subagentThreadTarget } from "./threadAgentsPresentation";
@@ -54,6 +61,16 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
61
const turn = useThreadTurnSubagents(target);
62
const subagents = turn?.subagents ?? [];
63
const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
64
+ const workflowGroups = useMemo(
65
+ () =>
66
+ new Map(
67
+ deriveWorkflowGroups(projectedSubagentsToRuntime(subagents)).map((group) => [
68
+ group.workflow.id,
69
+ group,
70
+ ]),
71
+ ),
72
+ [subagents],
73
+ );
74
75
const openChildThread = (child: { environmentId: EnvironmentId; threadId: ThreadId }) => {
76
void Haptics.selectionAsync();
@@ -88,15 +105,29 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
105
No agents in this turn.
106
</Text>
107
) : (
91
- subagents.map((subagent) => (
92
- <AgentRow
93
- key={subagent.id}
94
- subagent={subagent}
95
- environmentId={target.environmentId}
96
- tickSeconds={hasLiveAgent}
97
- onOpen={openChildThread}
98
- />
99
- ))
108
+ subagents.map((subagent) => {
109
+ const group = workflowGroups.get(subagent.id);
110
+ return group === undefined ? (
111
+ <View key={subagent.id} className="border-b border-border">
112
+ <AgentRow
113
+ subagent={subagent}
114
+ environmentId={target.environmentId}
115
+ tickSeconds={hasLiveAgent}
116
+ onOpen={openChildThread}
117
+ />
118
+ </View>
119
+ ) : (
120
+ <ThreadWorkflowGroup
121
+ key={subagent.id}
122
+ environmentId={target.environmentId}
123
+ subagent={subagent}
124
+ group={group}
125
+ onOpen={(threadId) =>
126
+ openChildThread({ environmentId: target.environmentId, threadId })
127
+ }
128
+ />
129
+ );
130
+ })
131
)}
132
</ScrollView>
133
);
@@ -154,7 +185,7 @@ function AgentRow(props: {
185
);
186
187
const row = (
157
- <View className="border-b border-border py-3.5">
188
+ <View className="py-3.5">
189
<SubagentRow
190
environmentId={props.environmentId}
191
subagent={subagent}
@@ -164,10 +195,11 @@ function AgentRow(props: {
195
</View>
196
);
197
167
- if (target === null) {
168
- return (
198
+ const content =
199
+ target === null ? (
200
<View
201
accessible
202
+ className="min-w-0 flex-1"
203
accessibilityHint={
204
subagent.remoteChild === undefined
205
? "Provider-managed agent. Its work appears in the transcript."
@@ -176,18 +208,22 @@ function AgentRow(props: {
208
>
209
{row}
210
</View>
211
+ ) : (
212
+ <Pressable
213
+ accessibilityRole="link"
214
+ accessibilityHint="Opens this agent's thread"
215
+ onPress={() => props.onOpen(target)}
216
+ className="min-w-0 flex-1 active:opacity-70"
217
+ >
218
+ {row}
219
+ </Pressable>
220
);
180
- }
221
222
return (
183
- <Pressable
184
- accessibilityRole="link"
185
- accessibilityHint="Opens this agent's thread"
186
- onPress={() => props.onOpen(target)}
187
- className="active:opacity-70"
188
- >
189
- {row}
190
- </Pressable>
223
+ <View className="flex-row items-center">
224
+ {content}
225
+ <SubagentStopButton environmentId={props.environmentId} subagent={subagent} />
226
+ </View>
227
);
228
}
229
apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx
new
+288
@@ -0,0 +1,288 @@
1
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import {
3
+ isActiveSubagentStatus,
4
+ type RuntimeSubagent,
5
+ type SubagentWorkflowGroup,
6
+} from "@t3tools/client-runtime/state/subagentRuntime";
7
+import {
8
+ ThreadId,
9
+ type EnvironmentId,
10
+ type OrchestrationV2Subagent,
11
+ type ServerProvider,
12
+} from "@t3tools/contracts";
13
+import { deriveSubagentElapsedMs, formatDuration } from "@t3tools/shared/orchestrationTiming";
14
+import { useState, type ReactNode } from "react";
15
+import { ScrollView, View } from "react-native";
16
+
17
+import { AppText as Text } from "../../components/ui/AppText";
18
+import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
19
+import { Chip } from "../../components/ui/Chip";
20
+import { ListRowLayout } from "../../components/ui/ListRowLayout";
21
+import { ListSection } from "../../components/ui/ListSection";
22
+import { RowPressable } from "../../components/ui/RowPressable";
23
+import { cn } from "../../lib/cn";
24
+import { useEnvironmentServerConfig, useThreadShell } from "../../state/entities";
25
+import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot";
26
+import { SubagentStopButton } from "./SubagentStopButton";
27
+import {
28
+ nextWorkflowSelection,
29
+ resolveSubagentRowPresentation,
30
+ workflowMemberDetail,
31
+ workflowMemberMetadata,
32
+ workflowRail,
33
+ type WorkflowRailTone,
34
+} from "./threadAgentsPresentation";
35
+import { useVisibleSecondClock } from "./use-visible-second-clock";
36
+
37
+const RAIL_ICON = {
38
+ working: "circle.inset.filled",
39
+ completed: "checkmark.circle.fill",
40
+ failed: "xmark.circle.fill",
41
+ stopped: "circle",
42
+ queued: "circle.dashed",
43
+} as const satisfies Record<WorkflowRailTone, AppSymbolName>;
44
+
45
+export function ThreadWorkflowGroup(props: {
46
+ readonly environmentId: EnvironmentId;
47
+ readonly subagent: OrchestrationV2Subagent;
48
+ readonly group: SubagentWorkflowGroup;
49
+ readonly onOpen: (threadId: ThreadId) => void;
50
+}) {
51
+ const { group } = props;
52
+ const provider = useEnvironmentServerConfig(props.environmentId)?.providers.find(
53
+ (candidate) => candidate.instanceId === props.subagent.providerInstanceId,
54
+ );
55
+ const [selected, setSelected] = useState<string | null>(null);
56
+ const rail = workflowRail(group);
57
+ const open = rail.find((item) => item.key === selected);
58
+ const label = group.workflow.workflowName ?? group.workflow.title;
59
+ const statusLabel = resolveSubagentRowPresentation(props.subagent).statusLabel;
60
+
61
+ return (
62
+ <View className="my-2">
63
+ <ListSection>
64
+ <View className="flex-row items-center">
65
+ <RowPressable
66
+ accessibilityRole="button"
67
+ accessibilityLabel={`${label} workflow, ${statusLabel}`}
68
+ accessibilityHint={open ? "Collapses the workflow" : "Opens the current phase"}
69
+ accessibilityState={{ expanded: open !== undefined }}
70
+ disabled={rail.length === 0}
71
+ onPress={() => setSelected(nextWorkflowSelection(rail, selected))}
72
+ className="min-w-0 flex-1 active:opacity-70"
73
+ >
74
+ <WorkflowHeaderLayout
75
+ label={label}
76
+ statusLabel={statusLabel}
77
+ timing={group.workflow}
78
+ accessory={
79
+ rail.length > 0 ? (
80
+ <SymbolView
81
+ name={open ? "chevron.up" : "chevron.down"}
82
+ size={12}
83
+ tintColorClassName="accent-icon-subtle"
84
+ />
85
+ ) : null
86
+ }
87
+ />
88
+ </RowPressable>
89
+ <SubagentStopButton
90
+ environmentId={props.environmentId}
91
+ subagent={props.subagent}
92
+ className="mr-2"
93
+ />
94
+ </View>
95
+ {rail.length > 0 ? (
96
+ <ScrollView
97
+ horizontal
98
+ showsHorizontalScrollIndicator={false}
99
+ contentContainerClassName="gap-2 px-4 pb-3"
100
+ >
101
+ {rail.map((item) => {
102
+ const count =
103
+ item.tone === "working" || item.tone === "failed"
104
+ ? `${item.completedCount}/${item.members.length}`
105
+ : null;
106
+ return (
107
+ <Chip
108
+ key={item.key}
109
+ icon={RAIL_ICON[item.tone]}
110
+ label={count ? `${count} ${item.title}` : item.title}
111
+ selected={item.key === selected}
112
+ accessibilityLabel={`${item.title} phase, ${item.tone}${count ? `, ${count} completed` : ""}`}
113
+ onPress={() => setSelected(nextWorkflowSelection(rail, selected, item.key))}
114
+ />
115
+ );
116
+ })}
117
+ </ScrollView>
118
+ ) : null}
119
+ {open === undefined ? null : open.members.length === 0 ? (
120
+ <Text
121
+ textRole="footnote"
122
+ className="border-t border-border-subtle px-4 py-3 text-foreground-muted"
123
+ >
124
+ No agents yet
125
+ </Text>
126
+ ) : (
127
+ open.members.map((member) => (
128
+ <WorkflowMemberRow
129
+ key={member.id}
130
+ environmentId={props.environmentId}
131
+ member={member}
132
+ provider={provider}
133
+ onOpen={props.onOpen}
134
+ />
135
+ ))
136
+ )}
137
+ </ListSection>
138
+ </View>
139
+ );
140
+}
141
+
142
+function WorkflowMemberRow(props: {
143
+ readonly environmentId: EnvironmentId;
144
+ readonly member: RuntimeSubagent;
145
+ readonly provider: ServerProvider | undefined;
146
+ readonly onOpen: (threadId: ThreadId) => void;
147
+}) {
148
+ const { member } = props;
149
+ const threadId = member.childThreadId === null ? null : ThreadId.make(member.childThreadId);
150
+ const shell = useThreadShell(
151
+ threadId === null ? null : scopeThreadRef(props.environmentId, threadId),
152
+ );
153
+ const canOpen = threadId !== null && shell !== null;
154
+ const presentation = resolveSubagentRowPresentation({
155
+ title: member.title,
156
+ prompt: "",
157
+ status: member.status,
158
+ result: null,
159
+ childThreadId: threadId,
160
+ });
161
+ const { detail, error } = workflowMemberDetail(member);
162
+ const metadata = workflowMemberMetadata(member, props.provider);
163
+ const labels = [metadata.model, metadata.effort].filter((value) => value !== null);
164
+ return (
165
+ <RowPressable
166
+ accessibilityRole={canOpen ? "link" : undefined}
167
+ accessibilityLabel={[
168
+ presentation.title,
169
+ presentation.statusLabel,
170
+ ...labels,
171
+ ...(metadata.speed === null ? [] : [metadata.speed]),
172
+ ...(error === null ? [] : [error]),
173
+ ].join(", ")}
174
+ accessibilityHint={canOpen ? "Opens this agent's thread" : "Its thread is not available yet"}
175
+ disabled={!canOpen}
176
+ onPress={() => threadId !== null && props.onOpen(threadId)}
177
+ className="min-h-11 flex-row gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
178
+ >
179
+ <View className="h-5 justify-center">
180
+ <SubagentStatusDot tone={presentation.tone} placement="sheet" />
181
+ </View>
182
+ <View className="min-w-0 flex-1 gap-1">
183
+ <View className="min-h-5 flex-row items-center gap-2">
184
+ <View className="min-w-0 flex-1 flex-row items-baseline gap-1.5">
185
+ <Text
186
+ textRole="footnote"
187
+ numberOfLines={1}
188
+ className="min-w-0 shrink font-t3-medium text-foreground"
189
+ >
190
+ {presentation.title}
191
+ </Text>
192
+ <Text
193
+ accessibilityElementsHidden
194
+ importantForAccessibility="no"
195
+ textRole="label"
196
+ className="shrink-0 text-foreground-muted"
197
+ >
198
+ ·
199
+ </Text>
200
+ <Text
201
+ textRole="label"
202
+ className={cn("shrink-0 font-t3-medium", SUBAGENT_TONE_TEXT_CLASS[presentation.tone])}
203
+ >
204
+ {presentation.statusLabel}
205
+ </Text>
206
+ </View>
207
+ <WorkflowElapsed timing={member} />
208
+ {canOpen ? (
209
+ <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
210
+ ) : null}
211
+ </View>
212
+ {labels.length > 0 || metadata.speed !== null ? (
213
+ <View className="min-w-0 flex-row items-center">
214
+ <Text
215
+ textRole="label"
216
+ numberOfLines={1}
217
+ className="min-w-0 shrink text-foreground-muted"
218
+ >
219
+ {labels.join(" · ")}
220
+ {labels.length > 0 && metadata.speed !== null ? " · " : ""}
221
+ </Text>
222
+ {metadata.fast ? (
223
+ <View className="shrink-0 flex-row items-center gap-0.5">
224
+ <SymbolView
225
+ name={{ ios: "bolt.fill", android: "bolt" }}
226
+ size={11}
227
+ tintColorClassName="accent-adaptive-amber-700-300"
228
+ />
229
+ <Text textRole="label" className="text-adaptive-amber-700-300">
230
+ {metadata.speed}
231
+ </Text>
232
+ </View>
233
+ ) : metadata.speed !== null ? (
234
+ <Text textRole="label" className="shrink-0 text-foreground-muted">
235
+ {metadata.speed}
236
+ </Text>
237
+ ) : null}
238
+ </View>
239
+ ) : null}
240
+ {detail ? (
241
+ <Text textRole="label" numberOfLines={1} className="text-foreground-muted">
242
+ {detail}
243
+ </Text>
244
+ ) : null}
245
+ {error ? (
246
+ <Text textRole="label" numberOfLines={1} className={SUBAGENT_TONE_TEXT_CLASS.failed}>
247
+ {error}
248
+ </Text>
249
+ ) : null}
250
+ </View>
251
+ </RowPressable>
252
+ );
253
+}
254
+
255
+function WorkflowHeaderLayout(props: {
256
+ readonly label: string;
257
+ readonly statusLabel: string;
258
+ readonly timing: ElapsedTiming;
259
+ readonly accessory: ReactNode;
260
+}) {
261
+ const elapsed = useElapsedLabel(props.timing);
262
+ return (
263
+ <ListRowLayout
264
+ icon="point.3.connected.trianglepath.dotted"
265
+ label={props.label}
266
+ description={props.statusLabel}
267
+ detail={elapsed ?? undefined}
268
+ accessory={props.accessory}
269
+ />
270
+ );
271
+}
272
+
273
+function WorkflowElapsed(props: { readonly timing: ElapsedTiming }) {
274
+ const elapsed = useElapsedLabel(props.timing);
275
+ return elapsed === null ? null : (
276
+ <Text textRole="label" className="shrink-0 tabular-nums text-foreground-muted">
277
+ {elapsed}
278
+ </Text>
279
+ );
280
+}
281
+
282
+type ElapsedTiming = Parameters<typeof deriveSubagentElapsedMs>[0];
283
+
284
+function useElapsedLabel(timing: ElapsedTiming): string | null {
285
+ const nowMs = useVisibleSecondClock(isActiveSubagentStatus(timing.status));
286
+ const elapsedMs = deriveSubagentElapsedMs(timing, nowMs);
287
+ return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);
288
+}
apps/mobile/src/features/threads/threadAgentsPresentation.test.ts
new
+352
@@ -0,0 +1,352 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import {
3
+ deriveWorkflowGroups,
4
+ projectedSubagentsToRuntime,
5
+} from "@t3tools/client-runtime/state/subagentRuntime";
6
+import {
7
+ NodeId,
8
+ ProviderDriverKind,
9
+ RunId,
10
+ ThreadId,
11
+ type OrchestrationV2SubagentWorkflow,
12
+} from "@t3tools/contracts";
13
+import * as DateTime from "effect/DateTime";
14
+
15
+import {
16
+ nextWorkflowSelection,
17
+ resolveSubagentRowPresentation,
18
+ resolveSubagentStopTarget,
19
+ workflowMemberDetail,
20
+ workflowMemberMetadata,
21
+ workflowRail,
22
+} from "./threadAgentsPresentation";
23
+
24
+const base = {
25
+ title: null,
26
+ prompt: "Audit the timestamps",
27
+ status: "running" as const,
28
+ result: null,
29
+ childThreadId: "thread-child" as never,
30
+};
31
+
32
+describe("resolveSubagentRowPresentation", () => {
33
+ it("leads with progress while the agent is working", () => {
34
+ const row = resolveSubagentRowPresentation({
35
+ ...base,
36
+ progress: "Reading files",
37
+ result: "stale result",
38
+ });
39
+
40
+ expect(row.detail).toBe("Reading files");
41
+ expect(row.tone).toBe("working");
42
+ expect(row.live).toBe(true);
43
+ });
44
+
45
+ it("leads with the result once the agent has settled", () => {
46
+ const row = resolveSubagentRowPresentation({
47
+ ...base,
48
+ status: "completed",
49
+ progress: "Reading files",
50
+ result: "Found two\n problems",
51
+ });
52
+
53
+ expect(row.detail).toBe("Found two problems");
54
+ expect(row.tone).toBe("completed");
55
+ expect(row.statusLabel).toBe("Completed");
56
+ });
57
+
58
+ it("shows a failure's text, since that is where the error lands", () => {
59
+ const row = resolveSubagentRowPresentation({ ...base, status: "failed", result: "Timed out" });
60
+
61
+ expect(row.detail).toBe("Timed out");
62
+ expect(row.tone).toBe("failed");
63
+ });
64
+
65
+ it("falls back to a trimmed prompt when the agent has no title", () => {
66
+ const long = resolveSubagentRowPresentation({ ...base, prompt: "x".repeat(200) });
67
+ const titled = resolveSubagentRowPresentation({ ...base, title: "Subagent: /root/my_worker" });
68
+
69
+ expect(long.title).toHaveLength(80);
70
+ expect(long.title.endsWith("...")).toBe(true);
71
+ expect(titled.title).toBe("My Worker");
72
+ });
73
+
74
+ it("only offers a thread to open when the agent has one", () => {
75
+ expect(resolveSubagentRowPresentation(base).canOpenThread).toBe(true);
76
+ expect(resolveSubagentRowPresentation({ ...base, childThreadId: null }).canOpenThread).toBe(
77
+ false,
78
+ );
79
+ });
80
+
81
+ it("uses the status label when there is nothing to report yet", () => {
82
+ const row = resolveSubagentRowPresentation({ ...base, status: "pending" });
83
+
84
+ expect(row.detail).toBeNull();
85
+ expect(row.statusLabel).toBe("Working");
86
+ });
87
+
88
+ it("bounds long result previews without dropping the agent's status", () => {
89
+ const row = resolveSubagentRowPresentation({
90
+ ...base,
91
+ status: "failed",
92
+ result: "x".repeat(400),
93
+ });
94
+ expect(row.detail).toBe(`${"x".repeat(280)}…`);
95
+ expect(row.statusLabel).toBe("Failed");
96
+ });
97
+});
98
+
99
+type WorkflowAgent = OrchestrationV2SubagentWorkflow["agents"][number];
100
+
101
+const workflowRailOf = (
102
+ agents: ReadonlyArray<WorkflowAgent>,
103
+ status: "running" | "completed" = "running",
104
+) =>
105
+ workflowRail(
106
+ deriveWorkflowGroups(
107
+ projectedSubagentsToRuntime([
108
+ {
109
+ id: "workflow",
110
+ title: "Mobile Stop review",
111
+ prompt: "",
112
+ model: null,
113
+ status,
114
+ result: null,
115
+ startedAt: DateTime.makeUnsafe("2026-08-01T10:00:00.000Z"),
116
+ completedAt: null,
117
+ updatedAt: DateTime.makeUnsafe("2026-08-01T10:00:05.000Z"),
118
+ workflow: {
119
+ phases: [
120
+ { index: 0, title: "Inspect" },
121
+ { index: 1, title: "Verify" },
122
+ { index: 2, title: "Report" },
123
+ ],
124
+ agents,
125
+ },
126
+ },
127
+ ]),
128
+ )[0]!,
129
+ );
130
+
131
+const agent = (
132
+ index: number,
133
+ phaseIndex: number | undefined,
134
+ state: WorkflowAgent["state"],
135
+ overrides: Partial<WorkflowAgent> = {},
136
+): WorkflowAgent => ({
137
+ index,
138
+ label: `agent ${index}`,
139
+ state,
140
+ ...(phaseIndex === undefined ? {} : { phaseIndex }),
141
+ ...overrides,
142
+});
143
+
144
+describe("workflowRail", () => {
145
+ it("keeps declared phases without agents and gives unphased agents a stop", () => {
146
+ const rail = workflowRailOf([
147
+ agent(1, 0, "completed"),
148
+ agent(2, 1, "running"),
149
+ agent(3, undefined, "queued"),
150
+ ]);
151
+
152
+ expect(rail.map((item) => [item.title, item.tone, item.members.length])).toEqual([
153
+ ["Inspect", "completed", 1],
154
+ ["Verify", "working", 1],
155
+ ["Report", "queued", 0],
156
+ ["Other", "queued", 1],
157
+ ]);
158
+ });
159
+
160
+ it("counts only completed agents toward a failed phase's progress", () => {
161
+ const [phase] = workflowRailOf([agent(1, 0, "failed"), agent(2, 0, "completed")], "completed");
162
+
163
+ expect([phase!.tone, phase!.completedCount, phase!.members.length]).toEqual(["failed", 1, 2]);
164
+ });
165
+});
166
+
167
+describe("nextWorkflowSelection", () => {
168
+ const running = workflowRailOf([agent(1, 0, "completed"), agent(2, 1, "running")]);
169
+
170
+ it("opens the running phase from the collapsed title, then collapses", () => {
171
+ expect(nextWorkflowSelection(running, null)).toBe("1");
172
+ expect(nextWorkflowSelection(running, "1")).toBeNull();
173
+ });
174
+
175
+ it("prefers the failed phase, then the latest phase with agents", () => {
176
+ const failed = workflowRailOf([agent(1, 0, "failed"), agent(2, 1, "completed")], "completed");
177
+ const done = workflowRailOf([agent(1, 0, "completed"), agent(2, 1, "completed")], "completed");
178
+
179
+ expect(nextWorkflowSelection(failed, null)).toBe("0");
180
+ expect(nextWorkflowSelection(done, null)).toBe("1");
181
+ expect(nextWorkflowSelection(workflowRailOf([]), null)).toBeNull();
182
+ });
183
+
184
+ it("keeps one phase open: another replaces it and the open one collapses the card", () => {
185
+ expect(nextWorkflowSelection(running, null, "0")).toBe("0");
186
+ expect(nextWorkflowSelection(running, "1", "0")).toBe("0");
187
+ expect(nextWorkflowSelection(running, "0", "0")).toBeNull();
188
+ });
189
+});
190
+
191
+describe("workflow member rows", () => {
192
+ it("keeps reported model, effort, and speed once an agent completes", () => {
193
+ const [completed] = workflowRailOf(
194
+ [
195
+ agent(1, 0, "completed", {
196
+ model: "claude-opus-5-5",
197
+ effort: "high",
198
+ speed: "fast",
199
+ result: "Checked controls",
200
+ }),
201
+ ],
202
+ "completed",
203
+ )[0]!.members;
204
+
205
+ expect(workflowMemberMetadata(completed!, undefined)).toEqual({
206
+ model: "Claude Opus 5.5",
207
+ effort: "High",
208
+ speed: "Fast",
209
+ fast: true,
210
+ });
211
+ expect(workflowMemberDetail(completed!)).toEqual({ detail: "Checked controls", error: null });
212
+ });
213
+
214
+ it("reports nothing the provider did not send", () => {
215
+ expect(workflowMemberMetadata({ model: null, effort: null }, undefined)).toEqual({
216
+ model: null,
217
+ effort: null,
218
+ speed: null,
219
+ fast: false,
220
+ });
221
+ });
222
+
223
+ it("labels effort from the catalog model a reported alias resolves to", () => {
224
+ expect(
225
+ workflowMemberMetadata(
226
+ { model: "opus", effort: "xhigh" },
227
+ {
228
+ driver: ProviderDriverKind.make("claudeAgent"),
229
+ models: [
230
+ {
231
+ slug: "claude-opus-5-5",
232
+ name: "Claude Opus 5.5",
233
+ shortName: "Opus 5.5",
234
+ aliases: ["opus"],
235
+ isCustom: false,
236
+ capabilities: {
237
+ optionDescriptors: [
238
+ {
239
+ id: "effort",
240
+ label: "Reasoning",
241
+ type: "select",
242
+ options: [{ id: "xhigh", label: "Extra High" }],
243
+ },
244
+ ],
245
+ },
246
+ },
247
+ ],
248
+ },
249
+ ),
250
+ ).toMatchObject({ model: "Opus 5.5", effort: "Extra High" });
251
+ });
252
+
253
+ it("shows a failed agent's error under its prompt", () => {
254
+ const [failed] = workflowRailOf([
255
+ agent(1, 0, "failed", { prompt: "Update session store", result: "Type error" }),
256
+ ])[0]!.members;
257
+
258
+ expect(workflowMemberDetail(failed!)).toEqual({
259
+ detail: "Update session store",
260
+ error: "Type error",
261
+ });
262
+ });
263
+});
264
+
265
+const stopAgent = {
266
+ id: NodeId.make("agent"),
267
+ threadId: ThreadId.make("parent"),
268
+ childThreadId: ThreadId.make("child"),
269
+ status: "running" as const,
270
+ origin: "app_owned" as const,
271
+ driver: ProviderDriverKind.make("codex"),
272
+ runId: RunId.make("run"),
273
+ nativeTaskRef: null,
274
+};
275
+
276
+describe("resolveSubagentStopTarget", () => {
277
+ it.each(["pending", "running", "waiting"] as const)(
278
+ "stops the parent task and child of an app-owned %s agent",
279
+ (status) => {
280
+ expect(resolveSubagentStopTarget({ ...stopAgent, status })).toEqual({
281
+ kind: "subagent",
282
+ input: { threadId: stopAgent.threadId, subagentId: stopAgent.id },
283
+ });
284
+ expect(resolveSubagentStopTarget({ ...stopAgent, status, childThreadId: null })).toBeNull();
285
+ },
286
+ );
287
+
288
+ it.each(["idle", "completed", "failed", "cancelled", "interrupted"] as const)(
289
+ "offers no Stop for a %s agent",
290
+ (status) => {
291
+ expect(resolveSubagentStopTarget({ ...stopAgent, status })).toBeNull();
292
+ },
293
+ );
294
+
295
+ const native = {
296
+ ...stopAgent,
297
+ origin: "provider_native" as const,
298
+ driver: ProviderDriverKind.make("claudeAgent"),
299
+ childThreadId: null,
300
+ nativeTaskRef: {
301
+ driver: ProviderDriverKind.make("claudeAgent"),
302
+ strength: "strong" as const,
303
+ nativeId: "native-task",
304
+ },
305
+ };
306
+
307
+ it("targets a supported native task without interrupting its parent run", () => {
308
+ expect(resolveSubagentStopTarget(native)).toEqual({
309
+ kind: "subagent",
310
+ input: { threadId: native.threadId, subagentId: native.id },
311
+ });
312
+ });
313
+
314
+ it("hides native Stop when the task cannot be identified or stopped", () => {
315
+ expect(resolveSubagentStopTarget({ ...native, nativeTaskRef: null })).toBeNull();
316
+ expect(
317
+ resolveSubagentStopTarget({
318
+ ...native,
319
+ nativeTaskRef: { ...native.nativeTaskRef, strength: "weak" },
320
+ }),
321
+ ).toBeNull();
322
+ expect(
323
+ resolveSubagentStopTarget({
324
+ ...native,
325
+ nativeTaskRef: { ...native.nativeTaskRef, nativeId: null },
326
+ }),
327
+ ).toBeNull();
328
+ expect(resolveSubagentStopTarget({ ...native, runId: null })).toBeNull();
329
+ expect(resolveSubagentStopTarget({ ...native, status: "completed" })).toBeNull();
330
+ expect(
331
+ resolveSubagentStopTarget({ ...native, driver: ProviderDriverKind.make("codex") }),
332
+ ).toBeNull();
333
+ });
334
+
335
+ it("stops the whole workflow through its own command", () => {
336
+ const workflow = { name: "Review", phases: [], agents: [] };
337
+ expect(resolveSubagentStopTarget({ ...native, workflow })).toEqual({
338
+ kind: "workflow",
339
+ input: { threadId: native.threadId, subagentId: native.id },
340
+ });
341
+ expect(resolveSubagentStopTarget({ ...native, workflow, status: "waiting" })).toBeNull();
342
+ expect(resolveSubagentStopTarget({ ...stopAgent, workflow })).toBeNull();
343
+ expect(resolveSubagentStopTarget({ ...native, workflow, nativeTaskRef: null })).toBeNull();
344
+ expect(
345
+ resolveSubagentStopTarget({
346
+ ...native,
347
+ workflow,
348
+ nativeTaskRef: { ...native.nativeTaskRef, nativeId: "" },
349
+ }),
350
+ ).toBeNull();
351
+ });
352
+});
apps/mobile/src/features/threads/threadAgentsPresentation.ts
+160
-2
@@ -1,9 +1,22 @@
1
import {
2
formatSubagentDisplayTitle,
3
+ resolveSubagentMetadata,
4
subagentDetailPreview,
5
} from "@t3tools/client-runtime/state/subagent-display";
5
-import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime";
6
-import type { EnvironmentId, OrchestrationV2Subagent, ThreadId } from "@t3tools/contracts";
6
+import {
7
+ isActiveSubagentStatus,
8
+ type RuntimeSubagent,
9
+ type SubagentWorkflowGroup,
10
+} from "@t3tools/client-runtime/state/subagentRuntime";
11
+import type {
12
+ EnvironmentId,
13
+ OrchestrationV2Subagent,
14
+ ServerProvider,
15
+ ThreadId,
16
+} from "@t3tools/contracts";
17
+import { resolveSelectableModel } from "@t3tools/shared/model";
18
+
19
+import { subagentCardDetail } from "./subagent-card-presentation";
20
21
const PROMPT_TITLE_LIMIT = 80;
22
@@ -95,3 +108,148 @@ export function resolveSubagentRowPresentation(
108
runsOn: subagent.remoteChild?.label ?? null,
109
};
110
}
111
+
112
+export type WorkflowRailTone = SubagentRowTone | "queued";
113
+
114
+export interface WorkflowRailItem {
115
+ readonly key: string;
116
+ readonly title: string;
117
+ readonly members: ReadonlyArray<RuntimeSubagent>;
118
+ readonly completedCount: number;
119
+ readonly tone: WorkflowRailTone;
120
+}
121
+
122
+function railTone(members: ReadonlyArray<RuntimeSubagent>): WorkflowRailTone {
123
+ if (members.every((member) => member.status === "pending")) return "queued";
124
+ if (members.some((member) => isActiveSubagentStatus(member.status) || member.status === "idle")) {
125
+ return "working";
126
+ }
127
+ if (members.some((member) => member.status === "failed")) return "failed";
128
+ return members.every((member) => member.status === "completed") ? "completed" : "stopped";
129
+}
130
+
131
+export function workflowRail(group: SubagentWorkflowGroup): ReadonlyArray<WorkflowRailItem> {
132
+ const items = group.phases.map((phase) => ({
133
+ key: String(phase.index),
134
+ title: phase.title,
135
+ members: phase.members,
136
+ }));
137
+ if (group.unphasedMembers.length > 0) {
138
+ items.push({
139
+ key: "unphased",
140
+ title: items.length === 0 ? "Agents" : "Other",
141
+ members: group.unphasedMembers,
142
+ });
143
+ }
144
+ return items.map((item) => ({
145
+ ...item,
146
+ completedCount: item.members.filter((member) => member.status === "completed").length,
147
+ tone: railTone(item.members),
148
+ }));
149
+}
150
+
151
+export function nextWorkflowSelection(
152
+ rail: ReadonlyArray<WorkflowRailItem>,
153
+ selected: string | null,
154
+ tapped?: string,
155
+): string | null {
156
+ const open = rail.some((item) => item.key === selected) ? selected : null;
157
+ if (tapped !== undefined) return tapped === open ? null : tapped;
158
+ if (open !== null) return null;
159
+ const filled = rail.filter((item) => item.members.length > 0);
160
+ return (
161
+ (
162
+ filled.find((item) => item.tone === "working") ??
163
+ filled.find((item) => item.tone === "failed") ??
164
+ filled.at(-1)
165
+ )?.key ?? null
166
+ );
167
+}
168
+
169
+const EFFORT_OPTION_IDS = new Set(["reasoningEffort", "effort", "reasoning", "variant"]);
170
+
171
+function capitalize(value: string): string {
172
+ return value.charAt(0).toUpperCase() + value.slice(1);
173
+}
174
+
175
+export function workflowMemberMetadata(
176
+ member: Pick<RuntimeSubagent, "model" | "effort" | "speed">,
177
+ provider: Pick<ServerProvider, "driver" | "models"> | undefined,
178
+) {
179
+ const model = member.model?.trim()
180
+ ? resolveSubagentMetadata({ model: member.model, provider }).modelLabel
181
+ : null;
182
+ const slug = provider
183
+ ? resolveSelectableModel(provider.driver, member.model, provider.models)
184
+ : null;
185
+ const effortChoice = provider?.models
186
+ .find((candidate) => candidate.slug === slug)
187
+ ?.capabilities?.optionDescriptors?.flatMap((descriptor) =>
188
+ descriptor.type === "select" && EFFORT_OPTION_IDS.has(descriptor.id)
189
+ ? descriptor.options
190
+ : [],
191
+ )
192
+ .find((option) => option.id === member.effort);
193
+ return {
194
+ model,
195
+ effort: member.effort ? (effortChoice?.label ?? capitalize(member.effort)) : null,
196
+ speed: member.speed ? capitalize(member.speed) : null,
197
+ fast: member.speed === "fast",
198
+ };
199
+}
200
+
201
+export function workflowMemberDetail(
202
+ member: Pick<RuntimeSubagent, "status" | "progress" | "result" | "error">,
203
+) {
204
+ return {
205
+ detail: subagentCardDetail(subagentDetailPreview(member)),
206
+ error: member.status === "failed" ? subagentCardDetail(member.error) : null,
207
+ };
208
+}
209
+
210
+export function resolveSubagentStopTarget(
211
+ subagent: Pick<
212
+ OrchestrationV2Subagent,
213
+ | "id"
214
+ | "threadId"
215
+ | "childThreadId"
216
+ | "status"
217
+ | "origin"
218
+ | "driver"
219
+ | "runId"
220
+ | "nativeTaskRef"
221
+ | "workflow"
222
+ >,
223
+) {
224
+ if (!isActiveSubagentStatus(subagent.status)) return null;
225
+ if (subagent.workflow !== undefined) {
226
+ return subagent.status === "running" &&
227
+ subagent.origin === "provider_native" &&
228
+ subagent.driver === "claudeAgent" &&
229
+ Boolean(subagent.nativeTaskRef?.nativeId)
230
+ ? {
231
+ kind: "workflow" as const,
232
+ input: { threadId: subagent.threadId, subagentId: subagent.id },
233
+ }
234
+ : null;
235
+ }
236
+ if (subagent.origin === "app_owned" && subagent.childThreadId !== null) {
237
+ return {
238
+ kind: "subagent" as const,
239
+ input: { threadId: subagent.threadId, subagentId: subagent.id },
240
+ };
241
+ }
242
+ if (
243
+ subagent.origin === "provider_native" &&
244
+ subagent.driver === "claudeAgent" &&
245
+ subagent.runId !== null &&
246
+ subagent.nativeTaskRef?.strength === "strong" &&
247
+ subagent.nativeTaskRef.nativeId !== null
248
+ ) {
249
+ return {
250
+ kind: "subagent" as const,
251
+ input: { threadId: subagent.threadId, subagentId: subagent.id },
252
+ };
253
+ }
254
+ return null;
255
+}
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+108
-3
@@ -12755,7 +12755,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12755
yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
12756
yield* fileSystem.writeFileString(
12757
NodePath.join(transcriptDir, "agent-a1.jsonl"),
12758
- `{"type":"assistant","uuid":"wf-line-1-${options?.nativeSessionId ?? "default"}","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n`,
12758
+ `{"type":"assistant","effort":"xhigh","uuid":"wf-line-1-${options?.nativeSessionId ?? "default"}","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","usage":{"speed":"standard"},"content":[{"type":"text","text":"A1 from the transcript"}]}}\n`,
12759
);
12760
const harness = yield* makeWakeHarnessWithOptions({
12761
...options,
@@ -14014,6 +14014,97 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14014
),
14015
);
14016
14017
+ it.effect("clears workflow member metadata only after a successful transcript read", () =>
14018
+ Effect.scoped(
14019
+ Effect.gen(function* () {
14020
+ const harness = yield* makeWorkflowHarness;
14021
+ const now = yield* DateTime.now;
14022
+ yield* harness.runtime.startTurn(
14023
+ makeClaudeTestTurnInput({
14024
+ threadId: harness.threadId,
14025
+ providerThread: harness.providerThread,
14026
+ now,
14027
+ attemptId: RunAttemptId.make("attempt-claude-workflow-metadata"),
14028
+ text: "Run the alpha workflow in the background.",
14029
+ attachments: [],
14030
+ }),
14031
+ );
14032
+ yield* harness.offerAndWait(workflowToolUse);
14033
+ yield* harness.offerAndWait(workflowTaskStarted);
14034
+ yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
14035
+ yield* harness.offerAndWait(
14036
+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "done" }),
14037
+ );
14038
+ yield* harness.until(
14039
+ () =>
14040
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]
14041
+ ?.effort === "xhigh",
14042
+ );
14043
+ let coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent;
14044
+ assert.equal(coordinator.workflow?.agents[0]?.speed, "standard");
14045
+
14046
+ const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl");
14047
+ NodeFS.renameSync(transcriptPath, `${transcriptPath}.saved`);
14048
+ yield* harness.offerAndWait(
14049
+ workflowSnapshot({
14050
+ uuid: "00000000-0000-4000-8000-000000001041",
14051
+ state: "done",
14052
+ label: "alpha:unreadable",
14053
+ }),
14054
+ );
14055
+ yield* harness.until(
14056
+ () =>
14057
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]
14058
+ ?.label === "alpha:unreadable",
14059
+ );
14060
+ coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent;
14061
+ assert.equal(coordinator.workflow?.agents[0]?.effort, "xhigh");
14062
+ assert.equal(coordinator.workflow?.agents[0]?.speed, "standard");
14063
+
14064
+ NodeFS.renameSync(`${transcriptPath}.saved`, transcriptPath);
14065
+ NodeFS.appendFileSync(
14066
+ transcriptPath,
14067
+ '{"type":"assistant","uuid":"wf-metadata-cleared","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_new","content":[{"type":"text","text":"New answer without metadata"}]}}\n',
14068
+ );
14069
+ yield* harness.offerAndWait(
14070
+ workflowSnapshot({
14071
+ uuid: "00000000-0000-4000-8000-000000001042",
14072
+ state: "done",
14073
+ label: "alpha:new-response",
14074
+ }),
14075
+ );
14076
+ yield* harness.until(() => {
14077
+ const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow
14078
+ ?.agents[0];
14079
+ return (
14080
+ member?.label === "alpha:new-response" &&
14081
+ member.effort === undefined &&
14082
+ member.speed === undefined
14083
+ );
14084
+ });
14085
+ yield* harness.offerAndWait(
14086
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001043", result: "Done." }),
14087
+ );
14088
+ yield* Queue.take(harness.terminalReceipts);
14089
+ const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow
14090
+ ?.agents[0];
14091
+ assert.isUndefined(member?.effort);
14092
+ assert.isUndefined(member?.speed);
14093
+ const childThreadId = member?.childThreadId;
14094
+ assert.deepEqual(
14095
+ threadMessages(harness.events, childThreadId)
14096
+ .filter((event) => event.message.role === "assistant")
14097
+ .map((event) => event.message.text),
14098
+ ["A1 from the transcript", "New answer without metadata"],
14099
+ );
14100
+ }).pipe(
14101
+ Effect.provide(
14102
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14103
+ ),
14104
+ ),
14105
+ ),
14106
+ );
14107
+
14108
it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () =>
14109
Effect.scoped(
14110
Effect.gen(function* () {
@@ -14078,11 +14169,19 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14169
);
14170
yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2);
14171
14081
- const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
14172
+ yield* harness.until(
14173
+ () =>
14174
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]
14175
+ ?.effort === "xhigh",
14176
+ );
14177
+ const coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent;
14178
assert.deepEqual(
14083
- coordinator?.workflow?.agents.map((member) => member.state),
14179
+ coordinator.workflow?.agents.map((member) => member.state),
14180
["completed", "completed"],
14181
);
14182
+ assert.equal(coordinator.workflow?.agents[0]?.speed, "standard");
14183
+ assert.isUndefined(coordinator.workflow?.agents[1]?.effort);
14184
+ assert.isUndefined(coordinator.workflow?.agents[1]?.speed);
14185
assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed");
14186
assert.equal(workflowMemberEvents(harness.events, 2).at(-1)?.subagent.status, "completed");
14187
assert.deepEqual(
@@ -14158,6 +14257,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14257
completedMember?.completedAt && DateTime.toEpochMillis(completedMember.completedAt),
14258
4432,
14259
);
14260
+ assert.isUndefined(
14261
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.effort,
14262
+ );
14263
+ assert.isUndefined(
14264
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.speed,
14265
+ );
14266
assert.notDeepEqual(
14267
workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt,
14268
previousStartedAt,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+39
-1
@@ -7,6 +7,7 @@ import {
7
formatSearchToolLabel,
8
} from "@t3tools/shared/toolActivity";
9
import { field, text } from "../unknownField.ts";
10
+import { mergeWorkflowAgentMetadata, type WorkflowAgentMetadata } from "../workflowAgentAnswers.ts";
11
import {
12
initialWorkflowAgentTranscriptCursor,
13
readWorkflowAgentTranscript,
@@ -4541,6 +4542,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4542
readonly finalTranscriptRead: boolean;
4543
readonly agentId: string | undefined;
4544
readonly transcriptCursor: WorkflowAgentTranscriptCursor;
4545
+ readonly transcriptMetadata: WorkflowAgentMetadata;
4546
readonly nextItemOrdinal: number;
4547
readonly toolCalls: Map<string, ActiveClaudeToolCall>;
4548
readonly textShown: boolean;
@@ -5726,8 +5728,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5728
const now = yield* DateTime.now;
5729
const seen = yield* Ref.get(workflowMemberStates);
5730
const transcriptDir = input.workflow.runHandles?.transcriptDir;
5731
+ const membersWithMetadata = input.workflow.agents.slice();
5732
5730
- for (const member of input.workflow.agents) {
5733
+ for (const [memberIndex, member] of input.workflow.agents.entries()) {
5734
if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
5735
return;
5736
const memberKey = `${input.coordinator.childThreadId}:agent:${member.index}`;
@@ -5913,6 +5916,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5916
previous === undefined || restarted || previous.agentId !== agentId
5917
? initialWorkflowAgentTranscriptCursor
5918
: previous.transcriptCursor;
5919
+ let transcriptMetadata =
5920
+ previous === undefined || restarted || previous.agentId !== agentId
5921
+ ? {}
5922
+ : previous.transcriptMetadata;
5923
let textShown = !restarted && previous?.textShown === true;
5924
let resultShown = !restarted && previous?.resultShown === true;
5925
let turnEnded = !restarted && previous?.turnEnded === true;
@@ -5957,6 +5964,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5964
transcriptRead = true;
5965
const advanced = read.value.cursor.offset !== transcriptCursor.offset;
5966
transcriptCursor = read.value.cursor;
5967
+ transcriptMetadata = mergeWorkflowAgentMetadata(
5968
+ read.value.lines,
5969
+ transcriptMetadata,
5970
+ );
5971
for (const line of read.value.lines) {
5972
if (yield* projectSubagentTranscriptLine(target, line)) textShown = true;
5973
turnEnded = isClaudeTranscriptTurnEnd(line);
@@ -5979,6 +5990,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5990
if (!(yield* drain())) return;
5991
}
5992
}
5993
+ if (
5994
+ transcriptRead &&
5995
+ (transcriptMetadata.effort !== member.effort ||
5996
+ transcriptMetadata.speed !== member.speed)
5997
+ ) {
5998
+ membersWithMetadata[memberIndex] = {
5999
+ ...member,
6000
+ effort: transcriptMetadata.effort,
6001
+ speed: transcriptMetadata.speed,
6002
+ };
6003
+ }
6004
if (settled) {
6005
// Open calls receive no results after their member settles.
6006
yield* endOpenToolCalls();
@@ -6021,6 +6043,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6043
textShown &&
6044
input.coordinator.task.status !== "running"),
6045
transcriptCursor,
6046
+ transcriptMetadata,
6047
nextItemOrdinal,
6048
toolCalls,
6049
textShown,
@@ -6032,6 +6055,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6055
}),
6056
);
6057
}
6058
+ if (
6059
+ membersWithMetadata.some((member, index) => member !== input.workflow.agents[index])
6060
+ ) {
6061
+ if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
6062
+ return;
6063
+ input.coordinator.task = {
6064
+ ...input.coordinator.task,
6065
+ workflow: { ...input.workflow, agents: membersWithMetadata },
6066
+ };
6067
+ yield* emitProviderEvent({
6068
+ type: "subagent.updated",
6069
+ driver: CLAUDE_PROVIDER,
6070
+ subagent: input.coordinator.task,
6071
+ });
6072
+ }
6073
});
6074
6075
const confirmedSubagentOutcome = (task: OrchestrationV2Subagent | undefined) => {
apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts
+36
-2
@@ -128,7 +128,10 @@ describe("mergeClaudeWorkflowProgress", () => {
128
expect(first?.agents[0]?.completedAt).toBe(2010);
129
expect(first?.agents[1]).not.toHaveProperty("completedAt");
130
const second = mergeClaudeWorkflowProgress({
131
- previous: first,
131
+ previous: first && {
132
+ ...first,
133
+ agents: first.agents.map((member) => ({ ...member, effort: "max", speed: "standard" })),
134
+ },
135
message: snapshotFrame([
136
{ type: "workflow_agent", index: 1, label: "alpha:one", state: "start", attempt: 2 },
137
]),
@@ -142,7 +145,7 @@ describe("mergeClaudeWorkflowProgress", () => {
145
phaseIndex: 1,
146
phaseTitle: "Alpha",
147
},
145
- first?.agents[1],
148
+ { ...first?.agents[1], effort: "max", speed: "standard" },
149
]);
150
expect(second?.phases).toEqual(first?.phases);
151
});
@@ -179,6 +182,37 @@ describe("mergeClaudeWorkflowProgress", () => {
182
expect(second?.agents).toEqual(first?.agents);
183
});
184
185
+ it("retains member fields omitted by a later frame in the same attempt", () => {
186
+ const first = mergeClaudeWorkflowProgress({
187
+ previous: undefined,
188
+ message: snapshotFrame([
189
+ agent({
190
+ attempt: 2,
191
+ model: "claude-opus-5[1m]",
192
+ promptPreview: "Current prompt",
193
+ tokens: 100,
194
+ }),
195
+ ]),
196
+ });
197
+ const second = mergeClaudeWorkflowProgress({
198
+ previous: first && {
199
+ ...first,
200
+ agents: first.agents.map((member) => ({ ...member, effort: "xhigh", speed: "standard" })),
201
+ },
202
+ message: snapshotFrame([agent({ state: "done", resultPreview: "Current result" })]),
203
+ });
204
+ expect(second?.agents[0]).toMatchObject({
205
+ state: "completed",
206
+ attempt: 2,
207
+ prompt: "Current prompt",
208
+ result: "Current result",
209
+ totalTokens: 100,
210
+ model: "claude-opus-5[1m]",
211
+ effort: "xhigh",
212
+ speed: "standard",
213
+ });
214
+ });
215
+
216
it("drops malformed entries instead of failing the frame", () => {
217
const workflow = mergeClaudeWorkflowProgress({
218
previous: undefined,
apps/server/src/orchestration-v2/workflowAgentAnswers.test.ts
new
+48
@@ -0,0 +1,48 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { mergeWorkflowAgentMetadata } from "./workflowAgentAnswers.ts";
4
+
5
+describe("mergeWorkflowAgentMetadata", () => {
6
+ it("keeps effort and speed across reads of a split assistant message", () => {
7
+ const metadata = mergeWorkflowAgentMetadata([
8
+ {
9
+ type: "assistant",
10
+ effort: "xhigh",
11
+ message: { id: "a", content: [], usage: { speed: "standard" } },
12
+ },
13
+ ]);
14
+ expect(metadata).toEqual({ messageId: "a", effort: "xhigh", speed: "standard" });
15
+ expect(
16
+ mergeWorkflowAgentMetadata(
17
+ [{ type: "assistant", message: { id: "a", content: [{ type: "text", text: "Done" }] } }],
18
+ metadata,
19
+ ),
20
+ ).toEqual(metadata);
21
+ expect(mergeWorkflowAgentMetadata([], metadata)).toEqual(metadata);
22
+ });
23
+
24
+ it("ignores bookkeeping and API errors without clearing prior metadata", () => {
25
+ const metadata = { messageId: "a", effort: "max", speed: "standard" };
26
+ expect(
27
+ mergeWorkflowAgentMetadata(
28
+ [
29
+ { type: "user", effort: "high", message: { usage: { speed: "fast" } } },
30
+ { type: "assistant", isMeta: true, effort: "high" },
31
+ { type: "assistant", isApiErrorMessage: true, message: { id: "error" } },
32
+ { type: "assistant", effort: 1, message: { id: "a", usage: { speed: false } } },
33
+ ],
34
+ metadata,
35
+ ),
36
+ ).toEqual(metadata);
37
+ });
38
+
39
+ it.each(["b", undefined])("clears omitted metadata for a new response with id %s", (id) => {
40
+ expect(
41
+ mergeWorkflowAgentMetadata([{ type: "assistant", message: { id, content: [] } }], {
42
+ messageId: "a",
43
+ effort: "max",
44
+ speed: "standard",
45
+ }),
46
+ ).toEqual(id === undefined ? {} : { messageId: id });
47
+ });
48
+});
apps/server/src/orchestration-v2/workflowAgentAnswers.ts
new
+33
@@ -0,0 +1,33 @@
1
+import type { OrchestrationV2WorkflowAgent } from "@t3tools/contracts";
2
+
3
+import { field, text } from "./unknownField.ts";
4
+
5
+export type WorkflowAgentMetadata = Pick<OrchestrationV2WorkflowAgent, "effort" | "speed"> & {
6
+ readonly messageId?: string;
7
+};
8
+
9
+export function mergeWorkflowAgentMetadata(
10
+ lines: ReadonlyArray<unknown>,
11
+ previous: WorkflowAgentMetadata = {},
12
+): WorkflowAgentMetadata {
13
+ let metadata = previous;
14
+ for (const entry of lines) {
15
+ if (
16
+ field(entry, "type") !== "assistant" ||
17
+ field(entry, "isMeta") === true ||
18
+ field(entry, "isApiErrorMessage") === true
19
+ )
20
+ continue;
21
+ const message = field(entry, "message");
22
+ const messageId = text(field(message, "id"));
23
+ const effort = text(field(entry, "effort"));
24
+ const speed = text(field(field(message, "usage"), "speed"));
25
+ metadata = {
26
+ ...(messageId !== undefined && messageId === metadata.messageId ? metadata : {}),
27
+ ...(messageId === undefined ? {} : { messageId }),
28
+ ...(effort === undefined ? {} : { effort }),
29
+ ...(speed === undefined ? {} : { speed }),
30
+ };
31
+ }
32
+ return metadata;
33
+}
packages/client-runtime/src/state/commandPermissions.test.ts
+33
-8
@@ -16,6 +16,7 @@ import {
16
AuthSourceControlWriteScope,
17
ThreadId,
18
EnvironmentId,
19
+ ORCHESTRATION_V2_WS_METHODS,
20
ScheduledTaskId,
21
WS_METHODS,
22
type AuthSessionState,
@@ -121,21 +122,45 @@ describe("command permissions", () => {
122
),
123
);
124
124
- it.effect("uses the target grant for both availability and execution", () =>
125
+ it.effect("requires the destination settings grant to check OTLP endpoints", () =>
126
Effect.scoped(
127
Effect.gen(function* () {
128
const registry = yield* setup;
129
+ const check = createCommandPermissions(runtime, WS_METHODS.serverCheckOtlpEndpoint);
130
registry.set(sessions(env), AsyncResult.success(grant(true)));
129
- expect(registry.get(permissions.permissionAtom(env))).toBe(true);
130
- expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
131
- yield* permissions.authorize(registry, env);
132
- registry.set(sessions(other), AsyncResult.success(grant(false)));
133
- expect(registry.get(permissions.permissionAtom(other))).toBe(false);
134
- const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
135
- expect(denied._tag).toBe("EnvironmentAuthorizationError");
131
+ expect(registry.get(check.permissionAtom(env))).toBe(false);
132
+ registry.set(
133
+ sessions(env),
134
+ AsyncResult.success({
135
+ ...grant(false),
136
+ scopes: [AuthSettingsWriteScope],
137
+ permissions: [AuthSettingsWriteScope],
138
+ }),
139
+ );
140
+ expect(registry.get(check.permissionAtom(env))).toBe(true);
141
+ yield* check.authorize(registry, env);
142
}),
143
),
144
);
145
+
146
+ it.effect.each([WS_METHODS.scheduledTasksDelete, ORCHESTRATION_V2_WS_METHODS.stopWorkflow])(
147
+ "uses the target grant for both availability and execution of %s",
148
+ (method) =>
149
+ Effect.scoped(
150
+ Effect.gen(function* () {
151
+ const registry = yield* setup;
152
+ const permissions = createCommandPermissions(runtime, method);
153
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
154
+ expect(registry.get(permissions.permissionAtom(env))).toBe(true);
155
+ expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
156
+ yield* permissions.authorize(registry, env);
157
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
158
+ expect(registry.get(permissions.permissionAtom(other))).toBe(false);
159
+ const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
160
+ expect(denied._tag).toBe("EnvironmentAuthorizationError");
161
+ }),
162
+ ),
163
+ );
164
it.effect("waits for an initial grant", () =>
165
Effect.scoped(
166
Effect.gen(function* () {
packages/client-runtime/src/state/subagentRuntime.test.ts
+9
@@ -59,6 +59,9 @@ describe("projectedSubagentsToRuntime workflow expansion", () => {
59
agents: [
60
member({
61
state: "completed",
62
+ model: "claude-opus-5[1m]",
63
+ effort: "xhigh",
64
+ speed: "standard",
65
startedAt: Date.UTC(2026, 7, 1, 10, 0, 0),
66
durationMs: 1500,
67
completedAt: Date.UTC(2026, 7, 1, 10, 0, 4, 432),
@@ -74,6 +77,9 @@ describe("projectedSubagentsToRuntime workflow expansion", () => {
77
expect(settled?.status).toBe("completed");
78
expect(settled?.completedAt).toBe("2026-08-01T10:00:04.432Z");
79
expect(settled?.result).toBe("A1");
80
+ expect(settled?.model).toBe("claude-opus-5[1m]");
81
+ expect(settled?.effort).toBe("xhigh");
82
+ expect(settled?.speed).toBe("standard");
83
expect(settled?.progress).toBe("Reply with exactly: A1");
84
expect(settled?.usage).toEqual({ totalTokens: 71_141, toolUses: 3, durationMs: 1500 });
85
});
@@ -108,6 +114,9 @@ describe("projectedSubagentsToRuntime workflow expansion", () => {
114
"2026-08-01T10:00:09.000Z",
115
"2026-08-01T10:00:01.500Z",
116
]);
117
+ expect(members?.[0]?.model).toBeNull();
118
+ expect(members?.[0]?.effort).toBeNull();
119
+ expect(members?.[0]?.speed).toBeUndefined();
120
},
121
);
122
});
packages/client-runtime/src/state/subagentRuntime.ts
+3
@@ -52,6 +52,7 @@ export interface RuntimeSubagent {
52
readonly role: string | null;
53
readonly model: string | null;
54
readonly effort: string | null;
55
+ readonly speed?: string | undefined;
56
readonly status: RuntimeSubagentStatus;
57
readonly activationCount: number;
58
readonly usage: SubagentUsage | null;
@@ -150,6 +151,8 @@ function workflowMembersToRuntime(
151
kind: "workflow_agent" as const,
152
title: agent.label,
153
model: agent.model ?? null,
154
+ effort: agent.effort ?? null,
155
+ ...(agent.speed === undefined ? {} : { speed: agent.speed }),
156
status,
157
activationCount: agent.attempt ?? 1,
158
usage: workflowUsage(agent),
packages/client-runtime/src/state/threadSubagents.test.ts
+31
-3
@@ -56,6 +56,33 @@ const activeRun = run("run-1", "running");
56
const finishedRun = run("run-1", "completed");
57
58
describe("deriveThreadTurnSubagents", () => {
59
+ it.each(["running", "completed"] as const)(
60
+ "keeps finished workflows after a later %s turn",
61
+ (status) => {
62
+ const workflow = subagent({
63
+ id: "workflow",
64
+ status: "completed",
65
+ workflow: { phases: [], agents: [] },
66
+ });
67
+ const turn = deriveThreadTurnSubagents({
68
+ runs: [finishedRun, run("run-2", status)],
69
+ subagents: [
70
+ workflow,
71
+ subagent({ id: "old", status: "completed" }),
72
+ subagent({
73
+ id: "recent",
74
+ runId: RunId.make("run-2"),
75
+ status,
76
+ updatedAt: at("2026-06-20T00:00:09.000Z"),
77
+ }),
78
+ ],
79
+ });
80
+
81
+ expect(turn?.subagents.map((entry) => entry.id)).toEqual(["recent", "workflow"]);
82
+ expect(resolveSubagentPillSegment(turn)).not.toBeNull();
83
+ },
84
+ );
85
+
86
it("scopes the roster to the active run and orders it by start time", () => {
87
const turn = deriveThreadTurnSubagents({
88
runs: [run("run-0", "completed"), activeRun],
@@ -264,15 +291,16 @@ describe("deriveThreadTurnSubagents", () => {
291
const turn = deriveThreadTurnSubagents({
292
runs: [activeRun],
293
subagents: [
267
- subagent({ id: "a", status: "running" }),
294
+ subagent({ id: "a", status: "completed" }),
295
subagent({ id: "b", status: "idle" }),
296
subagent({ id: "c", status: "failed" }),
297
],
298
});
299
273
- expect(turn?.liveCount).toBe(1);
274
- expect(turn?.settledCount).toBe(1);
300
+ expect(turn?.liveCount).toBe(0);
301
+ expect(turn?.settledCount).toBe(2);
302
expect(turn?.subagents).toHaveLength(3);
303
+ expect(resolveSubagentPillSegment(turn)?.label).toBe("2 done");
304
});
305
306
it("keeps settled workflows reachable without counting idle agents as done", () => {
packages/contracts/src/orchestrationV2.test.ts
+9
@@ -358,6 +358,9 @@ describe("orchestration V2 contracts", () => {
358
index: 1,
359
label: "Member",
360
state: "completed" as const,
361
+ model: "claude-opus-5[1m]",
362
+ effort: "xhigh",
363
+ speed: "standard",
364
prompt: preview,
365
result: preview,
366
},
@@ -379,10 +382,16 @@ describe("orchestration V2 contracts", () => {
382
expect(decode(json).workflow?.agents[0]).toMatchObject({
383
prompt: preview,
384
result: preview,
385
+ model: "claude-opus-5[1m]",
386
+ effort: "xhigh",
387
+ speed: "standard",
388
});
389
expect(decode(incoming).workflow?.agents[0]).toMatchObject({
390
prompt: preview,
391
result: preview,
392
+ model: "claude-opus-5[1m]",
393
+ effort: "xhigh",
394
+ speed: "standard",
395
});
396
}
397
},
packages/contracts/src/orchestrationV2.ts
+2
@@ -787,6 +787,8 @@ export const OrchestrationV2WorkflowAgent = Schema.Struct({
787
phaseIndex: Schema.optional(NonNegativeInt),
788
phaseTitle: Schema.optional(TrimmedNonEmptyString),
789
model: Schema.optional(TrimmedNonEmptyString),
790
+ effort: Schema.optional(TrimmedNonEmptyString),
791
+ speed: Schema.optional(TrimmedNonEmptyString),
792
attempt: Schema.optional(NonNegativeInt),
793
totalTokens: Schema.optional(NonNegativeInt),
794
toolCalls: Schema.optional(NonNegativeInt),