@devries-cameron20 / t3code Mirror · read-only / commits / 3ff5b3c82a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 05:30 UTC

fix(web): a workflow thread opens with its phases and agents instead of its script (#20857)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 18, 2026 at 08:45 UTC 3ff5b3c82a62baddc0c2b1b227e9d3a06190c426
14 files changed +1080 -5
apps/mobile/src/features/threads/ThreadFeed.tsx
+17
@@ -19,6 +19,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
19 import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
20 import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
21 import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
22 +import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
23 import {
24 type OrchestrationMessageContext,
25 ThreadId,
@@ -217,6 +218,7 @@ import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
218 import * as Option from "effect/Option";
219 import { appAtomRegistry } from "../../state/atom-registry";
220 import { environmentThreadShells, threadEnvironment } from "../../state/threads";
221 +import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening";
222 import { useAtomCommand } from "../../state/use-atom-command";
223 import { useV2ItemSupport } from "../../state/v2-item-support";
224 import {
@@ -1005,6 +1007,7 @@ function renderFeedEntry(
1007 readonly markdownContentWidth: number;
1008 readonly contentWidth: number;
1009 readonly threadTitle: string;
1010 + readonly workflowOpening: WorkflowOpening | null;
1011 },
1012 ) {
1013 const entry = info.item;
@@ -1152,6 +1155,15 @@ function renderFeedEntry(
1155 !assistantTurnStillInProgress &&
1156 !message.streaming;
1157
1158 + if (isUser && props.workflowOpening?.messageId === message.id) {
1159 + return (
1160 + <ThreadWorkflowOpening
1161 + environmentId={props.environmentId}
1162 + threadId={props.threadId}
1163 + opening={props.workflowOpening}
1164 + />
1165 + );
1166 + }
1167 if (isUser) {
1168 const enterAnimated = isFreshTimestamp(message.createdAt);
1169 const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
@@ -1661,6 +1673,7 @@ function ThreadFeedPlaceholder(props: {
1673 }
1674
1675 export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1676 + const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);
1677 const deviceType = useDeviceType();
1678 const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType);
1679 const openPullRequest = useOpenPullRequest();
@@ -2010,6 +2023,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2023 themeAppearance,
2024 userBubbleColor,
2025 viewportWidth,
2026 + workflowOpening,
2027 }),
2028 [
2029 props.worktreeSetup,
@@ -2026,6 +2040,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2040 themeAppearance,
2041 userBubbleColor,
2042 viewportWidth,
2043 + workflowOpening,
2044 ],
2045 );
2046 const reportHeaderMaterialVisibility = useCallback(
@@ -2476,6 +2491,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2491 threadTitle: props.threadTitle,
2492 skills: props.skills,
2493 workspaceRoot: props.workspaceRoot,
2494 + workflowOpening,
2495 })}
2496 {props.worktreeSetup && info.index === setupAnchorIndex ? (
2497 <WorktreeSetupCard key={props.threadId} {...props.worktreeSetup} />
@@ -2525,6 +2541,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2541 props.threadTitle,
2542 props.skills,
2543 props.workspaceRoot,
2544 + workflowOpening,
2545 renderMarkdownImage,
2546 renderViewedImage,
2547 renderReasoning,
apps/mobile/src/features/threads/thread-workflow-opening.tsx new
+202
@@ -0,0 +1,202 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { StackActions, useNavigation } from "@react-navigation/native";
3 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
4 +import {
5 + resolveWorkflowOpening,
6 + workflowOpeningHeadline,
7 + workflowOpeningParentThreadId,
8 + type RuntimeSubagent,
9 +} from "@t3tools/client-runtime/state/subagentRuntime";
10 +import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
11 +import { useState } from "react";
12 +import { Pressable, View } from "react-native";
13 +
14 +import { AppText as Text } from "../../components/ui/AppText";
15 +import { environmentThreadDetails } from "../../state/threads";
16 +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
17 +import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
18 +import { SubagentRow } from "./SubagentRow";
19 +import { WorkLogBlock } from "./work-log-layout";
20 +
21 +// A script longer than this many lines shows its head until opened.
22 +const FOLDED_SCRIPT_LINES = 10;
23 +
24 +/** The workflow opening for a thread, or null; the parent's detail loads only for a workflow. */
25 +export function useWorkflowOpening(environmentId: EnvironmentId, threadId: ThreadId) {
26 + const threadAtom = environmentThreadDetails.threadAtom(scopeThreadRef(environmentId, threadId));
27 + // Selected as a primitive so an ordinary thread's updates never change the result.
28 + const parentId = useAtomValue(threadAtom, (thread) =>
29 + thread === null
30 + ? null
31 + : workflowOpeningParentThreadId({
32 + thread: thread.projection.thread,
33 + messages: thread.projection.messages,
34 + }),
35 + );
36 + const projection = useAtomValue(threadAtom, (thread) =>
37 + parentId === null ? null : (thread?.projection ?? null),
38 + );
39 + const parentSubagents = useAtomValue(
40 + environmentThreadDetails.threadAtom(scopeThreadRef(environmentId, parentId ?? threadId)),
41 + (parent) => (parentId === null ? null : (parent?.projection.subagents ?? null)),
42 + );
43 + return projection === null
44 + ? null
45 + : resolveWorkflowOpening({
46 + thread: projection.thread,
47 + messages: projection.messages,
48 + parentSubagents,
49 + });
50 +}
51 +
52 +function memberRowSubagent(
53 + member: RuntimeSubagent,
54 + opening: WorkflowOpeningValue,
55 + coordinatorThreadId: ThreadId,
56 +) {
57 + return {
58 + // A member's parent thread is the coordinator's thread, the one showing this opening.
59 + threadId: coordinatorThreadId,
60 + childThreadId: member.childThreadId as ThreadId | null,
61 + model: member.model,
62 + driver: opening.driver!,
63 + providerInstanceId: opening.providerInstanceId!,
64 + title: member.title,
65 + prompt: member.progress ?? member.title,
66 + status: member.status,
67 + progress: undefined,
68 + result: member.result ?? member.error,
69 + };
70 +}
71 +
72 +type WorkflowOpeningValue = NonNullable<ReturnType<typeof useWorkflowOpening>>;
73 +
74 +/** Replaces a workflow coordinator's script message: the plan, its agents, then the script. */
75 +export function ThreadWorkflowOpening(props: {
76 + readonly environmentId: EnvironmentId;
77 + readonly threadId: ThreadId;
78 + readonly opening: WorkflowOpeningValue;
79 +}) {
80 + const navigation = useNavigation();
81 + const { opening } = props;
82 + const headline = workflowOpeningHeadline(opening);
83 + const canListMembers = opening.driver !== null && opening.providerInstanceId !== null;
84 + const phases = (opening.group?.phases ?? []).filter((phase) => phase.members.length > 0);
85 + const unphased = opening.group?.unphasedMembers ?? [];
86 + const renderMember = (member: RuntimeSubagent) => {
87 + const threadId = member.childThreadId;
88 + return (
89 + <Pressable
90 + key={member.id}
91 + accessibilityRole={threadId === null ? undefined : "link"}
92 + accessibilityHint={threadId === null ? undefined : "Opens this agent's thread"}
93 + disabled={threadId === null}
94 + onPress={() => {
95 + if (threadId !== null)
96 + navigation.dispatch(
97 + StackActions.push("Thread", {
98 + environmentId: String(props.environmentId),
99 + threadId,
100 + }),
101 + );
102 + }}
103 + className="rounded-lg px-3 py-3 active:bg-subtle"
104 + >
105 + <SubagentRow
106 + environmentId={props.environmentId}
107 + subagent={memberRowSubagent(member, opening, props.threadId)}
108 + elapsed={null}
109 + />
110 + </Pressable>
111 + );
112 + };
113 + return (
114 + <WorkLogBlock>
115 + <View className="mb-5 gap-3">
116 + <View className="flex-row items-start gap-2">
117 + <View className="min-w-0 flex-1 gap-0.5">
118 + <Text className="font-t3-medium text-2xs text-foreground-muted">Workflow started</Text>
119 + <Text numberOfLines={1} className="font-t3-medium text-sm text-foreground">
120 + {headline.title}
121 + </Text>
122 + {headline.description ? (
123 + <Text className="text-xs text-foreground-muted">{headline.description}</Text>
124 + ) : null}
125 + </View>
126 + {headline.agents ? (
127 + <Text className="shrink-0 text-2xs tabular-nums text-foreground-muted">
128 + {headline.agents}
129 + </Text>
130 + ) : null}
131 + </View>
132 + {canListMembers
133 + ? phases.map((phase) => (
134 + <View key={phase.index} className="gap-px">
135 + <Text className="px-1 pt-1 font-t3-medium text-2xs text-foreground-muted">
136 + {phase.title} · {phase.settledCount}/{phase.members.length}
137 + </Text>
138 + {phase.members.map(renderMember)}
139 + </View>
140 + ))
141 + : null}
142 + {canListMembers ? unphased.map(renderMember) : null}
143 + <WorkflowScript script={opening.script} />
144 + </View>
145 + </WorkLogBlock>
146 + );
147 +}
148 +
149 +/** The script as highlighted code; a long one shows its head until opened. */
150 +function WorkflowScript(props: { readonly script: string }) {
151 + const [expanded, setExpanded] = useState(false);
152 + const { themeAppearance } = useAppearancePreferences();
153 + const script = props.script.trimEnd();
154 + const lines = useMarkdownCodeHighlight({
155 + code: script,
156 + language: "javascript",
157 + theme: themeAppearance,
158 + enabled: true,
159 + });
160 + const lineCount = script.split("\n").length;
161 + const canFold = lineCount > FOLDED_SCRIPT_LINES;
162 + const shownLines = canFold && !expanded ? FOLDED_SCRIPT_LINES : lineCount;
163 + // Tokens are keyed by their offset into the script, like the work log's REPL code.
164 + let offset = 0;
165 + const highlighted = lines?.slice(0, shownLines).flatMap((line, lineIndex) => {
166 + const separator = lineIndex > 0 ? "\n" : "";
167 + offset += separator.length;
168 + return [
169 + separator,
170 + ...line.map((token) => {
171 + const start = offset;
172 + offset += token.content.length;
173 + return (
174 + <Text key={start} style={token.color ? { color: token.color } : undefined}>
175 + {token.content}
176 + </Text>
177 + );
178 + }),
179 + ];
180 + });
181 + return (
182 + <View className="gap-1">
183 + <View className="rounded-lg bg-subtle px-3 py-2.5">
184 + <Text selectable className="font-mono text-2xs leading-normal text-foreground">
185 + {highlighted ?? script.split("\n").slice(0, shownLines).join("\n")}
186 + </Text>
187 + </View>
188 + {canFold ? (
189 + <Pressable
190 + accessibilityRole="button"
191 + accessibilityState={{ expanded }}
192 + onPress={() => setExpanded((value) => !value)}
193 + className="self-start py-1 active:opacity-70"
194 + >
195 + <Text className="font-t3-medium text-xs text-foreground-muted">
196 + {expanded ? "Show less" : "Show full script"}
197 + </Text>
198 + </Pressable>
199 + ) : null}
200 + </View>
201 + );
202 +}
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+89
@@ -11663,6 +11663,95 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11663 ),
11664 );
11665
11666 + it.effect("marks a workflow coordinator's script prompt and leaves a subagent brief plain", () =>
11667 + Effect.scoped(
11668 + Effect.gen(function* () {
11669 + const harness = yield* makeWorkflowHarness;
11670 + const script =
11671 + 'export const meta = { name: "probe-wf", description: "Run the alpha workflow" };';
11672 + yield* harness.runtime.startTurn(
11673 + makeClaudeTestTurnInput({
11674 + threadId: harness.threadId,
11675 + providerThread: harness.providerThread,
11676 + now: yield* DateTime.now,
11677 + attemptId: RunAttemptId.make("attempt-workflow-script-prompt"),
11678 + text: "Run the workflow and an auditor.",
11679 + attachments: [],
11680 + }),
11681 + );
11682 + yield* harness.offerAndWait(workflowToolUse);
11683 + yield* harness.offerAndWait(claudeSdkFrame({ ...workflowTaskStarted, prompt: script }));
11684 + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
11685 + yield* harness.offerAndWait(
11686 + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001289", state: "start" }),
11687 + );
11688 + yield* harness.offerAndWait(
11689 + claudeSdkFrame({
11690 + type: "system",
11691 + subtype: "task_started",
11692 + task_id: "task-plain-auditor",
11693 + description: "Audit recent commits",
11694 + task_type: "local_agent",
11695 + prompt: "Audit the last five commits.",
11696 + uuid: "00000000-0000-4000-8000-000000001290",
11697 + session_id: WAKE_NATIVE_SESSION,
11698 + }),
11699 + );
11700 + yield* awaitUntil(
11701 + () =>
11702 + workflowCoordinatorEvents(harness.events).length > 0 &&
11703 + harness.events.some(
11704 + (event) =>
11705 + event.type === "subagent.updated" &&
11706 + event.subagent.nativeTaskRef?.nativeId === "task-plain-auditor",
11707 + ),
11708 + "workflow coordinator and auditor projected",
11709 + );
11710 + const subagentPrompt = (nativeTaskId: string) => {
11711 + const subagent = harness.events.flatMap((event) =>
11712 + event.type === "subagent.updated" &&
11713 + event.subagent.nativeTaskRef?.nativeId === nativeTaskId
11714 + ? [event.subagent]
11715 + : [],
11716 + )[0];
11717 + assert.isDefined(subagent);
11718 + const message = threadMessages(harness.events, subagent?.childThreadId).find(
11719 + (event) => event.message.role === "user",
11720 + )?.message;
11721 + const turnItem = harness.events.findLast(
11722 + (event) =>
11723 + event.type === "turn_item.updated" &&
11724 + event.turnItem.type === "user_message" &&
11725 + event.turnItem.messageId === message?.id,
11726 + );
11727 + return {
11728 + text: message?.text,
11729 + messageMark: message?.workflowScript,
11730 + itemMark:
11731 + turnItem?.type === "turn_item.updated" && turnItem.turnItem.type === "user_message"
11732 + ? turnItem.turnItem.workflowScript
11733 + : undefined,
11734 + };
11735 + };
11736 + assert.deepEqual(subagentPrompt(WORKFLOW_TASK_ID), {
11737 + text: script,
11738 + messageMark: true,
11739 + itemMark: true,
11740 + });
11741 + // A brief is marked as not a script, so its text is never read as one.
11742 + assert.deepEqual(subagentPrompt("task-plain-auditor"), {
11743 + text: "Audit the last five commits.",
11744 + messageMark: false,
11745 + itemMark: false,
11746 + });
11747 + }).pipe(
11748 + Effect.provide(
11749 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
11750 + ),
11751 + ),
11752 + ),
11753 + );
11754 +
11755 it.effect("scopes workflow member artifacts to the provider thread", () =>
11756 Effect.scoped(
11757 Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+8
@@ -4477,6 +4477,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4477 readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
4478 readonly role: "user" | "assistant";
4479 readonly text: string;
4480 + readonly workflowScript?: boolean;
4481 readonly ordinal: number;
4482 readonly now: DateTime.Utc;
4483 }) {
@@ -4501,6 +4502,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4502 },
4503 role: input.role,
4504 text: input.text,
4505 + ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
4506 ordinal: input.ordinal,
4507 now: input.now,
4508 });
@@ -5218,6 +5220,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5220 rootNodeId: childRootNodeId,
5221 role: "user",
5222 text: task.prompt,
5223 + // A workflow's prompt is its script; clients open the thread with
5224 + // the workflow's plan instead and keep the script collapsed. A
5225 + // brief says it is not one, so its text is never taken for one.
5226 + ...(existingSubagent === undefined
5227 + ? { workflowScript: task.workflow !== undefined }
5228 + : {}),
5229 ordinal: existingSubagent === undefined ? 100 : ++subagent.nextChildItemOrdinal,
5230 now,
5231 });
apps/server/src/orchestration-v2/threadHistoryPaging.test.ts
+29
@@ -619,6 +619,35 @@ describe("threadHistoryPaging", () => {
619 );
620 });
621
622 + it("keeps a workflow coordinator's script outside the bounded window", () => {
623 + const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
624 + const message = (index: number, workflowScript?: boolean) => ({
625 + id: MessageId.make(`message-${index}`),
626 + threadId: THREAD,
627 + runId: RunId.make(`old-run-${index}`),
628 + nodeId: null,
629 + role: "user" as const,
630 + text: `message ${index}`,
631 + attachments: [],
632 + streaming: false,
633 + createdBy: "agent" as const,
634 + creationSource: "provider" as const,
635 + createdAt: NOW,
636 + updatedAt: NOW,
637 + ...(workflowScript === undefined ? {} : { workflowScript }),
638 + });
639 + const full = {
640 + ...projection,
641 + messages: [message(0, true), message(1, false), message(2)],
642 + } as typeof projection;
643 +
644 + const bounded = buildBoundedThreadProjection({ projection: full, snapshotSequence: 9 });
645 +
646 + expect(bounded.projection.messages.map((retained) => retained.id)).toEqual([
647 + MessageId.make("message-0"),
648 + ]);
649 + });
650 +
651 it("omits historical control details that remain available from history items", () => {
652 const projection = makeProjection(Array.from({ length: 200 }, (_, index) => makeRow(index)));
653 const populated = {
apps/server/src/orchestration-v2/threadHistoryPaging.ts
+4 -1
@@ -417,7 +417,10 @@ function messagesForBoundedProjection(
417 (message) =>
418 retainedMessageIds.has(String(message.id)) ||
419 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
420 - message.delegatedCompletion !== undefined,
420 + message.delegatedCompletion !== undefined ||
421 + // Clients open a workflow coordinator's thread from its script, however
422 + // far back the history window starts. A thread has at most one.
423 + message.workflowScript === true,
424 );
425 }
426
apps/web/src/components/ChatView.tsx
+27
@@ -100,6 +100,10 @@ import {
100 presentPendingBackgroundWork,
101 presentProviderGoal,
102 } from "@t3tools/client-runtime/state/thread-execution";
103 +import {
104 + resolveWorkflowOpening,
105 + workflowOpeningParentThreadId,
106 +} from "@t3tools/client-runtime/state/subagentRuntime";
107 import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows";
108 import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
109 import { HandoffRow } from "./chat/V2LifecycleRow";
@@ -1488,6 +1492,28 @@ export default function ChatView(props: ChatViewProps) {
1492 return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId);
1493 })();
1494 const parentSubagentThread = useQuietThreadShell(parentSubagentThreadRef);
1495 + // A workflow coordinator's thread opens with its script; the plan that replaces it lives on
1496 + // the parent's coordinator row, so the parent's detail loads only for such a thread.
1497 + const workflowOpeningParentId =
1498 + serverProjection === null
1499 + ? null
1500 + : workflowOpeningParentThreadId({
1501 + thread: serverProjection.thread,
1502 + messages: serverProjection.messages,
1503 + });
1504 + const workflowOpeningParentProjection = useThreadProjection(
1505 + workflowOpeningParentId === null || parentSubagentEnvironmentId === null
1506 + ? null
1507 + : scopeThreadRef(parentSubagentEnvironmentId, workflowOpeningParentId),
1508 + );
1509 + const workflowOpening =
1510 + serverProjection === null || workflowOpeningParentId === null
1511 + ? null
1512 + : resolveWorkflowOpening({
1513 + thread: serverProjection.thread,
1514 + messages: serverProjection.messages,
1515 + parentSubagents: workflowOpeningParentProjection?.projection.subagents ?? null,
1516 + });
1517 const parentThreadLink =
1518 parentSubagentThreadRef === null
1519 ? null
@@ -7967,6 +7993,7 @@ export default function ChatView(props: ChatViewProps) {
7993 }
7994 onOpenThread={onOpenRelatedThreadStable}
7995 parentThreadLink={paintOnlyDisplayedTimeline ? null : parentThreadLink}
7996 + workflowOpening={paintOnlyDisplayedTimeline ? null : workflowOpening}
7997 onForkFromRun={paintOnlyDisplayedTimeline ? async () => {} : onForkFromRunStable}
7998 onRollbackCheckpoint={onTimelineRollbackCheckpointStable}
7999 supportsConversationRollback={
apps/web/src/components/chat/MessagesTimeline.tsx
+21 -1
@@ -57,6 +57,7 @@ import {
57 subagentGroupSummary,
58 summarizeSubagentStatuses,
59 } from "@t3tools/client-runtime/state/subagent-display";
60 +import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
61 import { observeResize } from "~/lib/observeResize";
62
63 const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
@@ -293,6 +294,7 @@ import {
294 } from "./V2LifecycleRow";
295 import { SecretRequestCard } from "./SecretRequestCard";
296 import { TimelineSystemDivider } from "./TimelineSystemDivider";
297 +import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
298
299 import { SkillChipIcon, SkillInlineText } from "./SkillInlineText";
300 import * as DateTime from "effect/DateTime";
@@ -326,6 +328,7 @@ interface TimelineRowSharedState {
328 displayThreadKey?: string;
329 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
330 onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
331 + workflowOpening: WorkflowOpening | null;
332 onForkFromRun: (input: {
333 readonly sourceThreadId: ThreadId;
334 readonly runId: RunId;
@@ -468,6 +471,8 @@ interface MessagesTimelineProps {
471 readonly threadId: ThreadId;
472 readonly title: string;
473 } | null;
474 + /** Set on a workflow coordinator's thread: its script message renders as this opening. */
475 + workflowOpening?: WorkflowOpening | null;
476 onForkFromRun: (input: {
477 readonly sourceThreadId: ThreadId;
478 readonly runId: RunId;
@@ -569,6 +574,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
574 onOpenTurnDiff,
575 onOpenThread,
576 parentThreadLink = null,
577 + workflowOpening = null,
578 onForkFromRun,
579 onRollbackCheckpoint,
580 supportsConversationRollback,
@@ -1229,6 +1235,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1235 openPullRequest,
1236 onOpenTurnDiff,
1237 onOpenThread,
1238 + workflowOpening,
1239 onForkFromRun,
1240 onRollbackCheckpoint,
1241 onToggleTurnFold,
@@ -1946,7 +1953,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
1953 {row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
1954 {row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
1955 {row.kind === "context-compaction" ? <ContextCompactionTimelineRow row={row} /> : null}
1949 - {row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
1956 + {row.kind === "message" && row.message.role === "user" ? <UserMessageRow row={row} /> : null}
1957 {row.kind === "message" && row.message.role === "assistant" ? (
1958 <AssistantTimelineRow row={row} />
1959 ) : null}
@@ -2067,6 +2074,19 @@ function MessageAuthorHeading({ children }: { children: string }) {
2074 return <h3 className="sr-only select-none">{children}</h3>;
2075 }
2076
2077 +function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
2078 + const ctx = use(TimelineRowCtx);
2079 + return ctx.workflowOpening?.messageId === row.message.id ? (
2080 + <WorkflowOpeningBlock
2081 + opening={ctx.workflowOpening}
2082 + environmentId={ctx.activeThreadEnvironmentId}
2083 + onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
2084 + />
2085 + ) : (
2086 + <UserTimelineRow row={row} />
2087 + );
2088 +}
2089 +
2090 function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
2091 const ctx = use(TimelineRowCtx);
2092 const { onImageExpand, onFileOpen } = ctx;
apps/web/src/components/chat/WorkflowOpeningBlock.browser.test.tsx new
+124
@@ -0,0 +1,124 @@
1 +import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
2 +import { EnvironmentId } from "@t3tools/contracts";
3 +import { act } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +
7 +import "~/index.css";
8 +
9 +import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
10 +import { MarkdownFindContext } from "./markdownFindContext";
11 +import { useThreadFindHighlights } from "./threadFindHighlights";
12 +import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
13 +
14 +vi.mock(import("../../state/server"), async (original) => {
15 + const actual = await original();
16 + const { Atom } = await import("effect/reactivity");
17 + const providers = Atom.make([]).pipe(Atom.keepAlive);
18 + const noConfig = Atom.make(null);
19 + return {
20 + ...actual,
21 + providersIgnoringCheckedAtAtom: (() => providers) as never,
22 + serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
23 + };
24 +});
25 +
26 +const SHORT_SCRIPT =
27 + "export const meta = { name: 'repo-check' }\nagent('Run SCRIPTONLY with Bash')";
28 +const LONG_SCRIPT = [
29 + "export const meta = { name: 'repo-check' }",
30 + ...Array.from({ length: 24 }, (_, index) => `const step${index} = await agent('Step ${index}')`),
31 + "return 'TAILONLY'",
32 +].join("\n");
33 +
34 +const opening = (script: string): WorkflowOpening => ({
35 + messageId: "message-script",
36 + script,
37 + name: "repo-check",
38 + description: "Two agents each inspect one file",
39 + driver: null,
40 + providerInstanceId: null,
41 + group: null,
42 +});
43 +
44 +function Find(props: { readonly container: HTMLElement | null; readonly query: string }) {
45 + useThreadFindHighlights({
46 + container: props.container,
47 + query: props.query,
48 + activeRowId: "opening",
49 + activeOccurrence: 0,
50 + onActiveRange: () => undefined,
51 + });
52 + return null;
53 +}
54 +
55 +let root: Root;
56 +let host: HTMLElement;
57 +
58 +beforeEach(() => {
59 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
60 + host = document.createElement("div");
61 + host.style.width = "720px";
62 + document.body.append(host);
63 + root = createRoot(host);
64 +});
65 +
66 +afterEach(async () => {
67 + await act(async () => root.unmount());
68 + host.remove();
69 + CSS.highlights.clear();
70 + vi.unstubAllGlobals();
71 +});
72 +
73 +async function render(script: string, query = "") {
74 + await act(async () =>
75 + root.render(
76 + <AppAtomRegistryProvider>
77 + <MarkdownFindContext value={query.length > 0}>
78 + <div data-timeline-row-id="opening">
79 + <WorkflowOpeningBlock
80 + opening={opening(script)}
81 + environmentId={EnvironmentId.make("environment-local")}
82 + onOpenThread={() => undefined}
83 + />
84 + </div>
85 + </MarkdownFindContext>
86 + <Find container={host} query={query} />
87 + </AppAtomRegistryProvider>,
88 + ),
89 + );
90 + await act(async () => {
91 + await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
92 + });
93 +}
94 +
95 +const foldToggle = () =>
96 + [...host.querySelectorAll("button")].find((button) =>
97 + /Show full script|Show less/.test(button.textContent ?? ""),
98 + );
99 +
100 +it("shows a short script as highlighted code with nothing to open", async () => {
101 + await render(SHORT_SCRIPT);
102 + expect(host.querySelector('[data-language="javascript"]')?.textContent).toContain("SCRIPTONLY");
103 + await vi.waitFor(() => expect(host.querySelector(".chat-markdown-shiki")).not.toBeNull());
104 + expect(foldToggle()).toBeUndefined();
105 +});
106 +
107 +it("folds a long script until it is opened", async () => {
108 + await render(LONG_SCRIPT);
109 + expect(foldToggle()?.getAttribute("aria-expanded")).toBe("false");
110 + expect(host.querySelector("[data-thread-find-fold]")).not.toBeNull();
111 + await act(async () => foldToggle()?.click());
112 + expect(foldToggle()?.getAttribute("aria-expanded")).toBe("true");
113 + expect(host.querySelector("[data-thread-find-fold]")).toBeNull();
114 +});
115 +
116 +it("finds the workflow's name and opens a folded script on a match below the fold", async () => {
117 + await render(LONG_SCRIPT, "repo-check");
118 + expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
119 + expect(foldToggle()?.getAttribute("aria-expanded")).toBe("false");
120 +
121 + await render(LONG_SCRIPT, "TAILONLY");
122 + expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
123 + expect(foldToggle()?.getAttribute("aria-expanded")).toBe("true");
124 +});
apps/web/src/components/chat/WorkflowOpeningBlock.tsx new
+242
@@ -0,0 +1,242 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + isTerminalSubagentStatus,
4 + workflowOpeningHeadline,
5 + type RuntimeSubagent,
6 + type WorkflowOpening,
7 +} from "@t3tools/client-runtime/state/subagentRuntime";
8 +import type {
9 + EnvironmentId,
10 + ProviderDriverKind,
11 + ProviderInstanceId,
12 + ServerProvider,
13 +} from "@t3tools/contracts";
14 +import { ChevronRightIcon, WorkflowIcon } from "lucide-react";
15 +import { useState } from "react";
16 +
17 +import { cn } from "../../lib/utils";
18 +import { providersIgnoringCheckedAtAtom } from "../../state/server";
19 +import ChatMarkdown from "../ChatMarkdown";
20 +import { ThreadHoverCardPopup } from "../ThreadHoverCard";
21 +import { Button } from "../ui/button";
22 +import { Tooltip, TooltipTrigger } from "../ui/tooltip";
23 +import { AgentElapsed } from "./AgentElapsed";
24 +import { findRevealRef } from "./markdownFindContext";
25 +import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
26 +import { SubagentTooltipContent } from "./SubagentTooltipContent";
27 +import { EnvironmentSubagentAvatar } from "./V2LifecycleRow";
28 +
29 +const FOLDED_SCRIPT_MASK = "linear-gradient(to bottom, black calc(100% - 1.75rem), transparent)";
30 +
31 +/** The script as a fenced block, so it renders like any other code in the thread. */
32 +function scriptMarkdown(script: string) {
33 + const longestRun = Math.max(2, ...(script.match(/`+/g) ?? []).map((run) => run.length));
34 + const fence = "`".repeat(longestRun + 1);
35 + return `${fence}javascript\n${script.trimEnd()}\n${fence}`;
36 +}
37 +
38 +/** Opens a workflow coordinator's thread in place of its script: the plan, its agents, then the script. */
39 +export function WorkflowOpeningBlock(props: {
40 + readonly opening: WorkflowOpening;
41 + readonly environmentId: EnvironmentId;
42 + readonly onOpenThread: (threadId: string) => void;
43 +}) {
44 + const { opening } = props;
45 + const providers = useAtomValue(providersIgnoringCheckedAtAtom(props.environmentId));
46 + const headline = workflowOpeningHeadline(opening);
47 + const phases = opening.group?.phases.filter((phase) => phase.members.length > 0) ?? [];
48 + const memberRow = (member: RuntimeSubagent) =>
49 + opening.providerInstanceId === null ? null : (
50 + <WorkflowMemberRow
51 + key={member.id}
52 + member={member}
53 + environmentId={props.environmentId}
54 + providerInstanceId={opening.providerInstanceId}
55 + providers={providers}
56 + driver={opening.driver ?? undefined}
57 + onOpenThread={props.onOpenThread}
58 + />
59 + );
60 + return (
61 + <section
62 + aria-label={`Workflow started: ${headline.title}`}
63 + className="flex min-w-0 flex-col gap-3 px-1 py-0.5"
64 + data-workflow-opening
65 + >
66 + <header className="flex min-w-0 items-start gap-2">
67 + <WorkflowIcon aria-hidden className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
68 + <div className="flex min-w-0 flex-1 flex-col gap-0.5">
69 + <p className="text-2xs font-medium text-muted-foreground">Workflow started</p>
70 + <h3 className="truncate text-sm font-medium text-foreground" data-thread-find-text="true">
71 + {headline.title}
72 + </h3>
73 + {headline.description ? (
74 + <p className="text-xs text-muted-foreground" data-thread-find-text="true">
75 + {headline.description}
76 + </p>
77 + ) : null}
78 + </div>
79 + {headline.agents ? (
80 + <span aria-live="polite" className="shrink-0 text-2xs tabular-nums text-muted-foreground">
81 + {headline.agents}
82 + </span>
83 + ) : null}
84 + </header>
85 + {phases.map((phase) => (
86 + <section key={phase.index} aria-label={`${phase.title} phase`}>
87 + <h4 className="flex items-baseline gap-2 px-2 pb-0.5 text-2xs font-medium text-muted-foreground">
88 + <span className="min-w-0 truncate" data-thread-find-text="true">
89 + {phase.title}
90 + </span>
91 + <span className="shrink-0 font-normal tabular-nums">
92 + {phase.settledCount}/{phase.members.length}
93 + </span>
94 + </h4>
95 + <ul className="m-0 list-none p-0">{phase.members.map(memberRow)}</ul>
96 + </section>
97 + ))}
98 + {opening.group && opening.group.unphasedMembers.length > 0 ? (
99 + <ul className="m-0 list-none p-0">{opening.group.unphasedMembers.map(memberRow)}</ul>
100 + ) : null}
101 + <WorkflowScript script={opening.script} />
102 + </section>
103 + );
104 +}
105 +
106 +/** One member agent, drawn like the timeline's subagent rows; it opens the member's thread. */
107 +function WorkflowMemberRow(props: {
108 + readonly member: RuntimeSubagent;
109 + readonly environmentId: EnvironmentId;
110 + readonly providerInstanceId: ProviderInstanceId;
111 + readonly providers: ReadonlyArray<ServerProvider>;
112 + readonly driver: ProviderDriverKind | undefined;
113 + readonly onOpenThread: (threadId: string) => void;
114 +}) {
115 + const { member } = props;
116 + const threadId = member.childThreadId;
117 + const failed = member.status === "failed";
118 + const detail = (
119 + isTerminalSubagentStatus(member.status)
120 + ? (member.error ?? member.result ?? member.progress)
121 + : member.progress
122 + )
123 + ?.replace(/`/g, "")
124 + .replace(/\s+/g, " ")
125 + .trim();
126 + const className =
127 + "group/subagent flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left";
128 + return (
129 + <li>
130 + <Tooltip>
131 + <TooltipTrigger
132 + delay={200}
133 + render={
134 + threadId === null ? (
135 + <div aria-description={member.status} className={className} />
136 + ) : (
137 + <button
138 + type="button"
139 + aria-label={`Open ${member.title}`}
140 + aria-description={member.status}
141 + onClick={() => props.onOpenThread(threadId)}
142 + className={cn(
143 + className,
144 + "cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
145 + )}
146 + />
147 + )
148 + }
149 + >
150 + <EnvironmentSubagentAvatar
151 + environmentId={props.environmentId}
152 + providerInstanceId={props.providerInstanceId}
153 + driver={props.driver}
154 + status={member.status}
155 + />
156 + <span className="min-w-0 flex-1">
157 + <span className="block truncate text-xs font-medium text-foreground">
158 + {member.title}
159 + </span>
160 + {detail ? (
161 + <span
162 + className={cn(
163 + "block truncate text-2xs leading-relaxed",
164 + failed ? "text-destructive" : "text-muted-foreground",
165 + )}
166 + >
167 + {detail}
168 + </span>
169 + ) : null}
170 + </span>
171 + {member.startedAt ? (
172 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
173 + <AgentElapsed agent={member} />
174 + </span>
175 + ) : null}
176 + {threadId !== null ? (
177 + <ChevronRightIcon
178 + aria-hidden
179 + className="size-3.5 shrink-0 text-muted-foreground/60 transition-colors group-hover/subagent:text-foreground"
180 + />
181 + ) : null}
182 + </TooltipTrigger>
183 + <ThreadHoverCardPopup>
184 + <SubagentTooltipContent
185 + title={member.title}
186 + model={member.model}
187 + providerInstanceId={props.providerInstanceId}
188 + origin="provider_native"
189 + provider={props.providers.find(
190 + (provider) => provider.instanceId === props.providerInstanceId,
191 + )}
192 + providers={props.providers}
193 + driver={props.driver}
194 + elapsed={<AgentElapsed agent={member} />}
195 + status={member.status}
196 + result={member.result ?? member.error}
197 + progress={member.progress}
198 + />
199 + </ThreadHoverCardPopup>
200 + </Tooltip>
201 + </li>
202 + );
203 +}
204 +
205 +/** The script as highlighted code, folded like a long message until opened or found. */
206 +function WorkflowScript(props: { readonly script: string }) {
207 + const [expanded, setExpanded] = useState(false);
208 + const revealRef = findRevealRef(() => setExpanded(true));
209 + const canFold = shouldCollapseUserMessage(props.script);
210 + const folded = canFold && !expanded;
211 + return (
212 + <div>
213 + <div
214 + ref={revealRef}
215 + className={cn("relative", folded && "max-h-44 overflow-hidden")}
216 + data-thread-find-text="true"
217 + data-thread-find-fold={folded ? "" : undefined}
218 + style={
219 + folded
220 + ? { WebkitMaskImage: FOLDED_SCRIPT_MASK, maskImage: FOLDED_SCRIPT_MASK }
221 + : undefined
222 + }
223 + >
224 + <ChatMarkdown text={scriptMarkdown(props.script)} cwd={undefined} />
225 + </div>
226 + {canFold ? (
227 + <div className="-ms-1">
228 + <Button
229 + type="button"
230 + size="xs"
231 + variant="ghost-muted"
232 + aria-expanded={expanded}
233 + data-scroll-anchor-ignore
234 + onClick={() => setExpanded((value) => !value)}
235 + >
236 + {expanded ? "Show less" : "Show full script"}
237 + </Button>
238 + </div>
239 + ) : null}
240 + </div>
241 + );
242 +}
packages/client-runtime/src/state/subagentRuntime.test.ts
+173 -2
@@ -1,8 +1,21 @@
1 import { describe, expect, it } from "vite-plus/test";
2 -import type { OrchestrationV2Subagent, OrchestrationV2SubagentWorkflow } from "@t3tools/contracts";
2 +import {
3 + ProviderDriverKind,
4 + ProviderInstanceId,
5 + ThreadId,
6 + type OrchestrationV2Subagent,
7 + type OrchestrationV2SubagentWorkflow,
8 +} from "@t3tools/contracts";
9 import * as DateTime from "effect/DateTime";
10
5 -import { deriveWorkflowGroups, projectedSubagentsToRuntime } from "./subagentRuntime.ts";
11 +import {
12 + deriveWorkflowGroups,
13 + isWorkflowScriptMessage,
14 + projectedSubagentsToRuntime,
15 + resolveWorkflowOpening,
16 + workflowOpeningHeadline,
17 + workflowOpeningParentThreadId,
18 +} from "./subagentRuntime.ts";
19
20 const at = (iso: string) => DateTime.makeUnsafe(iso);
21
@@ -214,3 +227,161 @@ describe("deriveWorkflowGroups over a dynamic workflow", () => {
227 expect(groups[1]?.unphasedMembers).toEqual([]);
228 });
229 });
230 +
231 +describe("resolveWorkflowOpening", () => {
232 + const SCRIPT = '// probe\nexport const meta = { name: "probe-wf" };\nconst GROUPS = [];';
233 + const childThread = {
234 + id: ThreadId.make("child"),
235 + lineage: {
236 + parentThreadId: ThreadId.make("parent"),
237 + relationshipToParent: "subagent" as const,
238 + rootThreadId: ThreadId.make("parent"),
239 + },
240 + creationSource: "provider" as const,
241 + };
242 + const coordinator = (workflow?: OrchestrationV2SubagentWorkflow) => ({
243 + ...subagent({
244 + title: "Run the alpha workflow",
245 + childThreadId: "child",
246 + ...(workflow === undefined ? {} : { workflow }),
247 + }),
248 + driver: ProviderDriverKind.make("claudeAgent"),
249 + providerInstanceId: ProviderInstanceId.make("claude"),
250 + });
251 + const brief = (text: string, workflowScript?: boolean) => ({
252 + id: "message-1",
253 + role: "user",
254 + text,
255 + ...(workflowScript === undefined ? {} : { workflowScript }),
256 + });
257 +
258 + it("opens a marked thread with the coordinator's plan and members", () => {
259 + const opening = resolveWorkflowOpening({
260 + thread: childThread,
261 + messages: [brief(SCRIPT, true)],
262 + parentSubagents: [
263 + coordinator({
264 + name: "probe-wf",
265 + phases: [{ index: 1, title: "Alpha" }],
266 + agents: [member({ childThreadId: ThreadId.make("member-1") })],
267 + }),
268 + ],
269 + });
270 + expect(opening).toMatchObject({
271 + messageId: "message-1",
272 + script: SCRIPT,
273 + name: "probe-wf",
274 + description: "Run the alpha workflow",
275 + });
276 + expect(
277 + opening?.group?.phases.map((phase) => ({
278 + title: phase.title,
279 + members: phase.members.map((agent) => [agent.title, agent.status, agent.childThreadId]),
280 + })),
281 + ).toEqual([{ title: "Alpha", members: [["alpha:one", "running", "member-1"]] }]);
282 + });
283 +
284 + it("recognizes an unmarked script before the parent loads", () => {
285 + const opening = resolveWorkflowOpening({
286 + thread: childThread,
287 + messages: [brief(SCRIPT)],
288 + parentSubagents: null,
289 + });
290 + expect(opening).toMatchObject({ script: SCRIPT, name: null, group: null });
291 + });
292 +
293 + it("recognizes an unmarked first message from the parent's workflow row", () => {
294 + const opening = resolveWorkflowOpening({
295 + thread: childThread,
296 + messages: [brief("Run the alpha workflow.")],
297 + parentSubagents: [coordinator({ name: "probe-wf", phases: [], agents: [] })],
298 + });
299 + expect(opening?.name).toBe("probe-wf");
300 + });
301 +
302 + it("leaves an ordinary subagent thread and other threads alone", () => {
303 + expect(
304 + resolveWorkflowOpening({
305 + thread: childThread,
306 + messages: [brief("Audit the last five commits.")],
307 + parentSubagents: [coordinator()],
308 + }),
309 + ).toBeNull();
310 + expect(
311 + resolveWorkflowOpening({
312 + thread: {
313 + ...childThread,
314 + lineage: { ...childThread.lineage, relationshipToParent: null, parentThreadId: null },
315 + },
316 + messages: [brief(SCRIPT)],
317 + parentSubagents: null,
318 + }),
319 + ).toBeNull();
320 + expect(isWorkflowScriptMessage({ role: "user", text: "Explain `export const meta`." })).toBe(
321 + false,
322 + );
323 + expect(isWorkflowScriptMessage({ role: "assistant", text: SCRIPT })).toBe(false);
324 + });
325 +
326 + it("trusts a brief marked as not a script even when its text looks like one", () => {
327 + expect(isWorkflowScriptMessage(brief(SCRIPT, false))).toBe(false);
328 + expect(
329 + resolveWorkflowOpening({
330 + thread: childThread,
331 + messages: [brief(SCRIPT, false)],
332 + parentSubagents: [coordinator()],
333 + }),
334 + ).toBeNull();
335 + expect(
336 + workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT, false)] }),
337 + ).toBeNull();
338 + });
339 +
340 + it("loads the parent only for a thread that opens with a workflow script", () => {
341 + expect(
342 + workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT, true)] }),
343 + ).toBe("parent");
344 + expect(workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT)] })).toBe(
345 + "parent",
346 + );
347 + expect(
348 + workflowOpeningParentThreadId({
349 + thread: childThread,
350 + messages: [brief("Audit the last five commits.")],
351 + }),
352 + ).toBeNull();
353 + });
354 +
355 + it("heads the opening with the workflow name, description, and agent tally", () => {
356 + const opening = resolveWorkflowOpening({
357 + thread: childThread,
358 + messages: [brief(SCRIPT, true)],
359 + parentSubagents: [
360 + coordinator({
361 + name: "probe-wf",
362 + phases: [{ index: 1, title: "Alpha" }],
363 + agents: [
364 + member(),
365 + member({ index: 2, label: "alpha:two", state: "completed" }),
366 + member({ index: 3, label: "loose", state: "failed", phaseIndex: undefined }),
367 + ],
368 + }),
369 + ],
370 + });
371 + expect(opening && workflowOpeningHeadline(opening)).toEqual({
372 + title: "probe-wf",
373 + description: "Run the alpha workflow",
374 + agents: "3 agents · 1 working · 1 done · 1 failed",
375 + });
376 + const unloaded = resolveWorkflowOpening({
377 + thread: childThread,
378 + messages: [brief(SCRIPT)],
379 + parentSubagents: null,
380 + });
381 + expect(unloaded && workflowOpeningHeadline(unloaded)).toEqual({
382 + title: "Workflow",
383 + description: null,
384 + agents: null,
385 + });
386 + });
387 +});
packages/client-runtime/src/state/subagentRuntime.ts
+131 -1
@@ -1,11 +1,12 @@
1 import { groupBy } from "effect/Array";
2 import * as DateTime from "effect/DateTime";
3 import type {
4 + OrchestrationV2AppThread,
5 OrchestrationV2Subagent,
6 OrchestrationV2SubagentWorkflow,
7 OrchestrationV2TurnItem,
8 } from "@t3tools/contracts";
8 -import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
9 +import { isOrchestrationV2WorkActive, isProviderNativeSubagentThread } from "@t3tools/contracts";
10
11 export type RuntimeSubagentStatus =
12 | "pending"
@@ -289,3 +290,132 @@ export function deriveWorkflowGroups(
290 return { workflow, phases, unphasedMembers };
291 });
292 }
293 +
294 +// Workflow scripts open with their `meta` export, after any leading comments.
295 +const WORKFLOW_SCRIPT_START = /^\s*(?:(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*export\s+const\s+meta\b/;
296 +
297 +/**
298 + * Whether a user message is the script a provider-native workflow runs. Servers mark every
299 + * subagent prompt either way; only threads recorded before the mark fall back to the text.
300 + */
301 +export function isWorkflowScriptMessage(message: {
302 + readonly role: string;
303 + readonly text: string;
304 + readonly workflowScript?: boolean | undefined;
305 +}): boolean {
306 + return (
307 + message.role === "user" && (message.workflowScript ?? WORKFLOW_SCRIPT_START.test(message.text))
308 + );
309 +}
310 +
311 +type ProjectedSubagent = Parameters<typeof projectedSubagentsToRuntime>[0][number] &
312 + Pick<OrchestrationV2Subagent, "driver" | "providerInstanceId">;
313 +
314 +export interface WorkflowOpening {
315 + readonly messageId: string;
316 + readonly script: string;
317 + readonly name: string | null;
318 + readonly description: string | null;
319 + readonly driver: OrchestrationV2Subagent["driver"] | null;
320 + readonly providerInstanceId: OrchestrationV2Subagent["providerInstanceId"] | null;
321 + /** Null until the parent thread's coordinator row is loaded. */
322 + readonly group: SubagentWorkflowGroup | null;
323 +}
324 +
325 +/**
326 + * The opening of a workflow coordinator's thread: its first user message is the workflow script,
327 + * shown as the workflow's plan. The coordinator row lives on the parent thread, so
328 + * `parentSubagents` is the parent projection's subagents, or null when it is not loaded.
329 + */
330 +export function resolveWorkflowOpening(input: {
331 + readonly thread: Pick<OrchestrationV2AppThread, "id" | "lineage" | "creationSource">;
332 + readonly messages: ReadonlyArray<{
333 + readonly id: string;
334 + readonly role: string;
335 + readonly text: string;
336 + readonly workflowScript?: boolean | undefined;
337 + }>;
338 + readonly parentSubagents: ReadonlyArray<ProjectedSubagent> | null;
339 +}): WorkflowOpening | null {
340 + if (!isProviderNativeSubagentThread(input.thread)) return null;
341 + const first = input.messages.find((message) => message.role === "user");
342 + if (first === undefined) return null;
343 + const coordinator = input.parentSubagents?.find(
344 + (subagent) => subagent.childThreadId === input.thread.id,
345 + );
346 + if (first.workflowScript === false) return null;
347 + if (coordinator?.workflow === undefined && !isWorkflowScriptMessage(first)) return null;
348 + return {
349 + messageId: first.id,
350 + script: first.text,
351 + name: coordinator?.workflow?.name ?? null,
352 + description: coordinator?.title ?? null,
353 + driver: coordinator?.driver ?? null,
354 + providerInstanceId: coordinator?.providerInstanceId ?? null,
355 + group:
356 + coordinator?.workflow === undefined
357 + ? null
358 + : (deriveWorkflowGroups(projectedSubagentsToRuntime([coordinator]))[0] ?? null),
359 + };
360 +}
361 +
362 +/**
363 + * The parent thread whose subagent rows describe this thread's workflow, or null when the thread
364 + * does not open with a workflow script. Gates loading the parent so ordinary subagent threads
365 + * never subscribe to their parent's detail.
366 + */
367 +export function workflowOpeningParentThreadId(input: {
368 + readonly thread: Pick<OrchestrationV2AppThread, "lineage" | "creationSource">;
369 + readonly messages: ReadonlyArray<Parameters<typeof isWorkflowScriptMessage>[0]>;
370 +}): OrchestrationV2AppThread["id"] | null {
371 + if (!isProviderNativeSubagentThread(input.thread)) return null;
372 + const first = input.messages.find((message) => message.role === "user");
373 + return first !== undefined && isWorkflowScriptMessage(first)
374 + ? input.thread.lineage.parentThreadId
375 + : null;
376 +}
377 +
378 +/** The opening block's heading: the workflow, what it does, and how its agents stand. */
379 +export function workflowOpeningHeadline(opening: WorkflowOpening): {
380 + readonly title: string;
381 + readonly description: string | null;
382 + readonly agents: string | null;
383 +} {
384 + const title = opening.name ?? opening.description ?? "Workflow";
385 + const members =
386 + opening.group === null
387 + ? []
388 + : [
389 + ...opening.group.phases.flatMap((phase) => phase.members),
390 + ...opening.group.unphasedMembers,
391 + ];
392 + const counts = new Map<string, number>();
393 + for (const member of members) {
394 + const key = isTerminalSubagentStatus(member.status)
395 + ? member.status === "completed"
396 + ? "done"
397 + : member.status === "failed"
398 + ? "failed"
399 + : "stopped"
400 + : "working";
401 + counts.set(key, (counts.get(key) ?? 0) + 1);
402 + }
403 + const agents =
404 + members.length === 0
405 + ? null
406 + : `${members.length} ${members.length === 1 ? "agent" : "agents"} · ${[
407 + "working",
408 + "done",
409 + "failed",
410 + "stopped",
411 + ]
412 + .filter((key) => counts.has(key))
413 + .map((key) => `${counts.get(key)} ${key}`)
414 + .join(" · ")}`;
415 + return {
416 + title,
417 + description:
418 + opening.description !== null && opening.description !== title ? opening.description : null,
419 + agents,
420 + };
421 +}
packages/contracts/src/orchestrationV2.ts
+7
@@ -1087,6 +1087,11 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({
1087 ...OrchestrationV2CreationFields,
1088 scheduledTaskId: Schema.optional(ScheduledTaskId),
1089 senderThreadId: Schema.optional(ThreadId),
1090 + /**
1091 + * The message is the script a provider-native workflow run executes, not prose. Clients show
1092 + * the workflow's opening instead and keep the script behind a disclosure.
1093 + */
1094 + workflowScript: Schema.optional(Schema.Boolean),
1095 id: MessageId,
1096 threadId: ThreadId,
1097 runId: Schema.NullOr(RunId),
@@ -1337,6 +1342,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
1342 messageId: MessageId,
1343 scheduledTaskId: Schema.optional(ScheduledTaskId),
1344 senderThreadId: Schema.optional(ThreadId),
1345 + workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
1346 inputIntent: OrchestrationV2UserMessageInputIntent,
1347 text: Schema.String,
1348 context: Schema.optional(OrchestrationMessageContext),
@@ -2092,6 +2098,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
2098 messageId: MessageId,
2099 scheduledTaskId: Schema.optional(ScheduledTaskId),
2100 senderThreadId: Schema.optional(ThreadId),
2101 + workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
2102 inputIntent: OrchestrationV2UserMessageInputIntent,
2103 text: Schema.String,
2104 context: Schema.optional(OrchestrationMessageContext),
packages/provider-core/src/server/subagentProjection.ts
+6
@@ -98,6 +98,8 @@ export function makeSubagentConversationArtifacts(input: {
98 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
99 readonly role: "user" | "assistant";
100 readonly text: string;
101 + /** Whether a user message is the script a workflow run executes; unset for older callers. */
102 + readonly workflowScript?: boolean;
103 readonly ordinal: number;
104 readonly now: DateTime.Utc;
105 }): {
@@ -115,6 +117,9 @@ export function makeSubagentConversationArtifacts(input: {
117 ...(input.role === "user" && input.senderThreadId !== undefined
118 ? { senderThreadId: input.senderThreadId }
119 : {}),
120 + ...(input.role === "user" && input.workflowScript !== undefined
121 + ? { workflowScript: input.workflowScript }
122 + : {}),
123 text: input.text,
124 attachments: [],
125 streaming: false,
@@ -147,6 +152,7 @@ export function makeSubagentConversationArtifacts(input: {
152 creationSource: "provider",
153 type: "user_message",
154 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
155 + ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
156 inputIntent: "turn_start",
157 attachments: [],
158 }