Expose V2 thread workflows on mobile

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and maria-rcks committed 2026-08-03 11:45:06 -04:00
1 parent 2fde64e80f
commit beab58b45b
16 files changed
+1025 -218

No files matched your search

@@ -39,6 +39,8 @@ import {
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
import { ThreadQueueControl } from "./ThreadQueueControl";
import type { ThreadContentPresentation } from "./threadContentPresentation";
export interface ThreadDetailScreenProps {
@@ -354,6 +356,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
threadTitle={props.selectedThread.title}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
@@ -365,6 +368,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={headerHeight}
contentBottomInset={estimatedOverlayHeight}
topAccessory={
<ThreadRelationshipsBanner
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
}
layoutVariant={layoutVariant}
skills={selectedProviderSkills}
/>
@@ -384,17 +393,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
{/* No paddingTop here: the overlay's measured height becomes the
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
<ThreadQueueControl
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
+137 -104
View File
@@ -1,7 +1,15 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import {
ThreadId,
type EnvironmentId,
type MessageId,
type OrchestrationV2ProjectedTurnItem,
type RunId,
} from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import { SymbolView } from "../../components/AppSymbol";
@@ -78,15 +86,11 @@ import {
} from "../review/nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
scaledTypographyLineHeight,
} from "../../lib/appearancePreferences";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import type { LayoutVariant } from "../../lib/layout";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { buildThreadRoutePath } from "../../lib/routes";
import { uuidv4 } from "../../lib/uuid";
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
@@ -103,6 +107,10 @@ import {
} from "./thread-work-log";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -147,6 +155,7 @@ function isFreshTimestamp(input: string): boolean {
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly threadTitle: string;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
@@ -158,13 +167,89 @@ export interface ThreadFeedProps {
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly contentMaxWidth?: number;
readonly topAccessory?: ReactNode;
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
async function waitForThreadShell(environmentId: EnvironmentId, threadId: ThreadId): Promise<void> {
const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
const deadline = Date.now() + 2_000;
while (appAtomRegistry.get(atom) === null && Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 40));
}
}
function AssistantForkButton(props: {
readonly environmentId: EnvironmentId;
readonly iconColor: ColorValue;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly sourceTitle: string;
}) {
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: props.projectedItem.sourceThreadId,
sourceItemId: props.projectedItem.sourceItemId,
});
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
const router = useRouter();
const [busy, setBusy] = useState(false);
const canFork = canForkProjectedAssistantItem({
projectedItem: props.projectedItem,
capabilities: support.providerSession?.capabilities,
});
const runId = props.projectedItem.item.runId;
if (!canFork || runId === null) return null;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel="Fork from this response"
disabled={busy}
onPress={() => {
const targetThreadId = ThreadId.make(uuidv4());
setBusy(true);
void Haptics.selectionAsync();
void forkFromRun({
environmentId: props.environmentId,
input: {
sourceThreadId: props.projectedItem.sourceThreadId,
targetThreadId,
runId,
title: `${props.sourceTitle} fork`,
},
})
.then(async (result) => {
if (result._tag !== "Success") return;
await waitForThreadShell(props.environmentId, targetThreadId);
router.push(
buildThreadRoutePath({
environmentId: props.environmentId,
threadId: targetThreadId,
}),
);
})
.finally(() => setBusy(false));
}}
className="h-7 w-7 items-center justify-center disabled:opacity-40"
>
{busy ? (
<ActivityIndicator size="small" />
) : (
<SymbolView
name="arrow.triangle.branch"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
)}
</Pressable>
);
}
function MessageAttachmentImage(props: {
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
@@ -835,6 +920,7 @@ function renderFeedEntry(
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
readonly threadTitle: string;
},
) {
const entry = info.item;
@@ -894,10 +980,12 @@ function renderFeedEntry(
if (isUser) {
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
<Animated.View
className="mb-5 items-end"
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
>
<View className="mb-5 items-end">
{message.createdBy === "agent" ? (
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
Sent by another agent
</Text>
) : null}
<View
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
@@ -989,6 +1077,12 @@ function renderFeedEntry(
})}
{showAssistantMeta ? (
<View className="mt-1 flex-row items-center gap-1">
<AssistantForkButton
environmentId={props.environmentId}
iconColor={iconSubtleColor}
projectedItem={message.projectedItem}
sourceTitle={props.threadTitle}
/>
<CopyTextButton
accessibilityLabel="Copy message"
text={message.text}
@@ -1744,6 +1838,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
threadTitle: props.threadTitle,
skills: props.skills,
workspaceRoot: props.workspaceRoot,
}),
@@ -1765,6 +1860,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkGroup,
onToggleWorkRow,
props.environmentId,
props.threadTitle,
props.skills,
props.workspaceRoot,
],
@@ -1813,95 +1909,32 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// render into — which is why the header blur was missing on threads.
scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={feedItemLayoutTransition}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
// content rest below the transparent header rather than at frame top.
contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
// UIKit's automatic behavior adds the safe-area bottom on top of the
// raw contentInset the keyboard integration writes. The detail screen
// under-reports the composer inset by this amount (see
// ThreadDetailScreen); this tells LegendList's scroll math about the
// extra so programmatic end scrolls land at the true resting offset.
contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
// The keyboard integration's offset math (end pinning, max scroll)
// must add the same UIKit-added extra, or its keyboard-open end
// targets land one safe-area short of the true resting offset.
adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
freeze={props.freeze}
// Animated: on send, the optimistic message's dataChange fires
// maintainScrollAtEnd before any render-cycle suppression could
// engage — an instant snap there teleports the feed to the anchor
// instead of scrolling to it. Keeping it enabled (animated) during
// anchor scrolls also lets it correct a scroll that landed on a
// stale end target once the anchor row finishes measuring.
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: true,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition={maintainVisibleContentPosition}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
getFixedItemSize={getFixedItemSize}
// Measure rows well before they scroll into view so estimate→actual
// corrections land offscreen instead of under the user's finger.
drawDistance={500}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
// Seed the list's scroll math with the real viewport before its own
// onLayout: the empty→filled remount can then tell at mount that
// short content underflows the viewport and skip programmatic
// positioning entirely (any offset write during screen attach races
// UIKit's adjustedContentInset application and lands high or low).
{...(viewportHeight > 0 && viewportWidth > 0
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
: {})}
// RN's native scrollTo command clamps targets to a floor of
// -contentInset.top using the RAW inset — under automatic insets the
// header inset only exists in adjustedContentInset, so scrolls to
// negative offsets (content top below the transparent header) get
// clamped to 0. This prop disables that clamp; UIKit still bounces
// user overscroll back to the adjusted rest position.
scrollToOverflowEnabled
estimatedItemSize={180}
// Chat-style bottom alignment: when a thread is shorter than the
// viewport, pad above the content so messages rest just above the
// composer instead of under the header. No effect on threads that
// overflow the viewport (the padding clamps to zero).
alignItemsAtEnd
initialScrollAtEnd
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: contentHorizontalPadding,
}}
/>
</View>
{props.feed.length === 0 &&
props.activeWorkStartedAt === null &&
props.contentPresentation.kind === "ready" ? (
}
maintainVisibleContentPosition
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
estimatedItemSize={180}
initialScrollAtEnd
ListHeaderComponent={
<>
<View style={{ height: topContentInset }} />
{props.topAccessory}
</>
}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: horizontalPadding,
}}
/>
{props.feed.length === 0 ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
title="No conversation yet"
@@ -0,0 +1,115 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
import { useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadProjection } from "../../state/use-thread-detail";
export function ThreadQueueControl(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const scoped = useThreadProjection(props);
const workflow = useMemo(
() => (scoped ? deriveThreadQueueWorkflowState(scoped.projection) : null),
[scoped],
);
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
const iconColor = useThemeColor("--color-icon-subtle");
if (!workflow || workflow.queuedRuns.length === 0) return null;
const move = async (runId: RunId, beforeRunId: RunId | null) => {
setBusyRunId(runId);
void Haptics.selectionAsync();
await reorder({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId, beforeRunId },
});
setBusyRunId(null);
};
const steer = async (queuedRunId: RunId) => {
if (!workflow.activeRun || !workflow.canPromoteToSteer) return;
setBusyRunId(queuedRunId);
void Haptics.selectionAsync();
await promote({
environmentId: props.environmentId,
input: {
threadId: props.threadId,
queuedRunId,
targetRunId: workflow.activeRun.id,
},
});
setBusyRunId(null);
};
return (
<View className="mx-4 mb-3 overflow-hidden rounded-2xl border border-neutral-300/60 bg-card dark:border-white/[0.1]">
<View className="flex-row items-center gap-2 border-b border-neutral-300/50 px-3 py-2 dark:border-white/[0.08]">
<SymbolView name="list.number" size={13} tintColor={iconColor} type="monochrome" />
<Text className="font-t3-medium text-xs text-foreground">Queue</Text>
<Text className="ml-auto text-2xs tabular-nums text-foreground-muted">
{workflow.queuedRuns.length}
</Text>
</View>
<ScrollView style={{ maxHeight: 156 }} contentContainerStyle={{ paddingVertical: 4 }}>
{workflow.queuedRuns.map(({ run, text }, index) => (
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
{index + 1}
</Text>
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
{text}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Move queued message up"
disabled={busyRunId !== null || !workflow.canReorder || index === 0}
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
className="h-9 w-9 items-center justify-center disabled:opacity-30"
>
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Move queued message down"
disabled={
busyRunId !== null ||
!workflow.canReorder ||
index === workflow.queuedRuns.length - 1
}
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
className="h-9 w-9 items-center justify-center disabled:opacity-30"
>
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Promote queued message to steer"
disabled={busyRunId !== null || !workflow.canPromoteToSteer}
onPress={() => void steer(run.id)}
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
>
<SymbolView
name="arrow.turn.left.up"
size={12}
tintColor={iconColor}
type="monochrome"
/>
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
</Pressable>
</View>
))}
</ScrollView>
</View>
);
}
@@ -0,0 +1,295 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "@t3tools/client-runtime/state/thread-relationships";
import { canDetachThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { useRouter } from "expo-router";
import { useMemo, useState } from "react";
import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { buildThreadRoutePath } from "../../lib/routes";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadShells } from "../../state/entities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadProjection } from "../../state/use-thread-detail";
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): string {
if (edge.kind === "transfer") {
return edge.sourceThreadId === currentThreadId ? "Context sent to" : "Context received from";
}
if (edge.kind === "subagent") {
return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
}
return edge.sourceThreadId === currentThreadId ? "Fork" : "Forked from";
}
function relationshipSymbol(edge: ThreadRelationshipEdge): SFSymbol {
if (edge.kind === "subagent") return "person.2";
if (edge.kind === "transfer") return "arrow.left.arrow.right";
return "arrow.triangle.branch";
}
function threadAvailability(
thread: OrchestrationV2ThreadShell | null,
missing: boolean,
): string | null {
if (missing) return "Unavailable";
if (thread?.deletedAt !== null && thread?.deletedAt !== undefined) return "Deleted";
if (thread?.archivedAt !== null && thread?.archivedAt !== undefined) return "Archived";
return null;
}
const EMPTY_THREAD_SHELLS: ReadonlyArray<OrchestrationV2ThreadShell> = [];
export function ThreadRelationshipsBanner(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const scopedProjection = useThreadProjection(props);
const projection = scopedProjection?.projection ?? null;
const threadShells = useThreadShells();
const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
const archived = useArchivedThreadSnapshots(environmentIds);
const archivedShells =
archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
.threads ?? EMPTY_THREAD_SHELLS;
const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
const environmentShells: OrchestrationV2ThreadShell[] = [];
for (const thread of threadShells) {
if (thread.environmentId === props.environmentId) {
environmentShells.push(thread.source);
}
}
environmentShells.push(...archivedShells);
return environmentShells;
}, [archivedShells, props.environmentId, threadShells]);
const graph = useMemo(
() => deriveThreadRelationshipGraph({ threads: shells, projection }),
[projection, shells],
);
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
const rows = useMemo(
() =>
immediateThreadRelationships(graph, props.threadId).toSorted(
(left, right) =>
Number(right.threadId === mergeTargetThreadId) -
Number(left.threadId === mergeTargetThreadId),
),
[graph, mergeTargetThreadId, props.threadId],
);
const latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null;
const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
const [visible, setVisible] = useState(false);
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
const router = useRouter();
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
const insets = useSafeAreaInsets();
const backdropColor = useThemeColor("--color-backdrop");
const sheetColor = useThemeColor("--color-sheet");
const iconColor = useThemeColor("--color-icon-subtle");
if (rows.length === 0 && !canDetach) return null;
const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
const summary = primaryParent
? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
: "Agent session connected";
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
setVisible(false);
void Haptics.selectionAsync();
router.push(
archivedThread
? "/settings/archive"
: buildThreadRoutePath({ environmentId: props.environmentId, threadId }),
);
};
const merge = async () => {
if (!canMerge || mergeTargetThreadId === null || latestCompletedRun === null) return;
setBusyAction("merge");
const result = await mergeBack({
environmentId: props.environmentId,
input: {
sourceThreadId: props.threadId,
targetThreadId: mergeTargetThreadId,
runId: latestCompletedRun.id,
},
});
setBusyAction(null);
if (result._tag === "Success") openThread(mergeTargetThreadId, false);
};
const detach = async () => {
if (!canDetach) return;
setBusyAction("detach");
await stopSession({
environmentId: props.environmentId,
input: { threadId: props.threadId },
});
setBusyAction(null);
};
return (
<>
<Pressable
accessibilityRole="button"
accessibilityLabel={`${summary}. Show thread relationships`}
onPress={() => {
void Haptics.selectionAsync();
setVisible(true);
}}
className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-neutral-300/60 bg-card px-3 py-2.5 dark:border-white/[0.1]"
>
<SymbolView
name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
size={14}
tintColor={iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
{summary}
</Text>
{rows.length > 1 ? (
<Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
</Pressable>
<Modal
transparent
animationType="fade"
visible={visible}
statusBarTranslucent
onRequestClose={() => setVisible(false)}
>
<View className="flex-1 justify-end">
<View
pointerEvents="none"
className="absolute inset-0"
style={{ backgroundColor: backdropColor }}
/>
<Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
<View
className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
>
<View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
<View className="mb-3 flex-row items-center justify-between px-1">
<View>
<Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
<Text className="text-xs text-foreground-muted">
{rows.length} related {rows.length === 1 ? "thread" : "threads"}
</Text>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close thread lineage"
onPress={() => setVisible(false)}
className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]"
>
<SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
<ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
{rows.map(({ threadId, edge }) => {
const node = graph.nodes.get(threadId);
const availability = threadAvailability(
node?.thread ?? null,
node?.missing ?? true,
);
const archivedThread = availability === "Archived";
const disabled = availability === "Unavailable" || availability === "Deleted";
return (
<Pressable
key={`${edge.kind}:${threadId}`}
accessibilityRole={disabled ? undefined : "link"}
accessibilityState={{ disabled }}
disabled={disabled}
onPress={() => openThread(threadId, archivedThread)}
className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-neutral-300/50 bg-card px-3 py-2.5 dark:border-white/[0.08]"
>
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/60 dark:bg-white/[0.06]">
<SymbolView
name={relationshipSymbol(edge)}
size={14}
tintColor={iconColor}
type="monochrome"
/>
</View>
<View className="min-w-0 flex-1">
<Text className="text-3xs uppercase tracking-wide text-foreground-muted">
{relationshipLabel(edge, props.threadId)}
</Text>
<Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
{node?.thread?.title ?? threadId}
</Text>
</View>
{availability ? (
<Text className="text-2xs text-foreground-muted">{availability}</Text>
) : (
<SymbolView
name="chevron.right"
size={12}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
);
})}
</ScrollView>
{canMerge || canDetach ? (
<View className="mt-4 gap-2 border-t border-neutral-300/50 pt-4 dark:border-white/[0.08]">
{canMerge ? (
<Pressable
accessibilityRole="button"
disabled={busyAction !== null}
onPress={() => void merge()}
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
>
{busyAction === "merge" ? (
<ActivityIndicator color="white" />
) : (
<SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
)}
<Text className="font-t3-medium text-sm text-primary-foreground">
Merge back to source
</Text>
</Pressable>
) : null}
{canDetach ? (
<Pressable
accessibilityRole="button"
disabled={busyAction !== null}
onPress={() => void detach()}
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-neutral-300/60 px-3 dark:border-white/[0.1]"
>
{busyAction === "detach" ? <ActivityIndicator /> : null}
<Text className="font-t3-medium text-sm text-foreground">
Disconnect agent session
</Text>
</Pressable>
) : null}
</View>
) : null}
</View>
</View>
</Modal>
</>
);
}
@@ -1,12 +1,15 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useRouter } from "expo-router";
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
import { cn } from "../../lib/cn";
import { buildThreadRoutePath } from "../../lib/routes";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { ThreadActivityInspector } from "./ThreadActivityInspector";
const WORK_LOG_LAYOUT_ANIMATION = {
@@ -71,51 +74,56 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
}
}
// Entering fades only for rows created moments ago: rows remount whenever the
// list scrolls them back into view, and old rows must not replay an entrance.
const FRESH_ROW_WINDOW_MS = 3_000;
function isFreshRow(createdAt: string): boolean {
const timestamp = Date.parse(createdAt);
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
}
function ThreadActivityThreadLink(props: {
readonly activity: ThreadFeedActivity;
readonly environmentId: EnvironmentId;
readonly iconColor: import("react-native").ColorValue;
}) {
const row = props.activity.projectedItem;
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
});
const router = useRouter();
const item = row.item;
let targetThreadId: ThreadId | null = null;
let label = "Open related thread";
// Tool-like activities with a neutral status carry no signal worth a row.
export function visibleWorkLogActivities(
activities: ReadonlyArray<ThreadFeedActivity>,
): ReadonlyArray<ThreadFeedActivity> {
return activities.filter((activity) => !(activity.toolLike && activity.status === "neutral"));
}
// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log
// rows are single-line (numberOfLines={1}) inside a min-height that stays
// taller than the text at every supported base font size (text-xs reaches
// 23px at the 22pt maximum, under the 32px min-h-8), so row height is
// deterministic. The "work log" label has no such clamp — its height follows
// the scaled text-2xs line height. Values mirror the classNames below — keep
// them in sync; a mismatch only costs a one-time correction on measure.
const WORK_ROW_HEIGHT = 32; // min-h-8
const WORK_ROW_GAP = 1; // gap-px
const WORK_LOG_HEADER_PADDING = 2; // pb-0.5 under the "work log" label
const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1
export const WORK_GROUP_TOGGLE_HEIGHT = 36; // min-h-8 (32) + mb-1 (4)
export function collapsedWorkLogHeight(
activities: ReadonlyArray<ThreadFeedActivity>,
baseFontSize: number,
): number {
const rows = visibleWorkLogActivities(activities);
if (rows.length === 0) {
return 0;
if (item.type === "thread_created") {
targetThreadId = item.targetThreadId;
label = "Open created thread";
} else if (item.type === "subagent") {
targetThreadId = support.subagent?.childThreadId ?? item.childThreadId;
label = "Open subagent thread";
} else if (item.type === "fork") {
targetThreadId =
item.targetThreadId === row.sourceThreadId && item.source.type === "run"
? item.source.threadId
: item.targetThreadId;
label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
}
const onlyToolRows = rows.every((row) => row.toolLike);
const headerHeight =
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING;
if (targetThreadId === null) return null;
return (
WORK_LOG_BOTTOM_MARGIN +
(onlyToolRows ? 0 : headerHeight) +
rows.length * WORK_ROW_HEIGHT +
(rows.length - 1) * WORK_ROW_GAP
<Pressable
accessibilityRole="link"
accessibilityLabel={label}
onPress={() => {
void Haptics.selectionAsync();
router.push(
buildThreadRoutePath({
environmentId: props.environmentId,
threadId: targetThreadId,
}),
);
}}
className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]"
>
<Text className="font-t3-medium text-2xs text-foreground">{label}</Text>
<SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
</Pressable>
);
}
@@ -157,9 +165,12 @@ export function ThreadWorkLog(props: {
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
return (
<Animated.View
<View
key={row.id}
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
className={cn(
row.prominent &&
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
)}
>
<Pressable
accessibilityRole={canExpand ? "button" : undefined}
@@ -258,7 +269,14 @@ export function ThreadWorkLog(props: {
/>
</View>
) : null}
</Animated.View>
{row.prominent ? (
<ThreadActivityThreadLink
activity={row}
environmentId={props.environmentId}
iconColor={props.iconSubtleColor}
/>
) : null}
</View>
);
})}
</View>
@@ -129,6 +129,57 @@ describe("buildThreadFeed", () => {
"inherited",
"synthetic",
]);
expect(activities.at(-1)?.prominent).toBe(true);
});
it("keeps orchestration relationship cards visible when a completed run is folded", () => {
const { providerThreadId: _providerThreadId, ...forkBase } = base(
"item-fork",
"2026-06-20T00:00:02.500Z",
2,
);
const feed = buildThreadFeed([
projected(userMessage(), 0),
projected(command(), 1),
projected(
{
...forkBase,
type: "fork",
source: { type: "run", threadId, runId },
targetThreadId: sourceThreadId,
},
2,
),
projected(assistantMessage(), 3),
]);
const collapsed = deriveThreadFeedPresentation(
feed,
{
runId,
status: "completed",
startedAt: "2026-06-20T00:00:01.000Z",
completedAt: "2026-06-20T00:00:03.000Z",
},
new Set(),
);
expect(
collapsed.some(
(entry) =>
entry.type === "activity-group" &&
entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
),
).toBe(true);
expect(
collapsed.some(
(entry) =>
entry.type === "activity-group" &&
entry.activities.some(
(activity) => activity.projectedItem.item.type === "command_execution",
),
),
).toBe(false);
});
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
+22 -2
View File
@@ -49,6 +49,7 @@ export interface ThreadFeedActivity {
| "wrench"
| "zap";
readonly toolLike: boolean;
readonly prominent: boolean;
readonly status: "success" | "failure" | "neutral" | null;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
}
@@ -149,6 +150,10 @@ function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
);
}
function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
return item.type === "fork" || item.type === "thread_created" || item.type === "subagent";
}
function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
if (!itemIsToolLike(item)) return null;
if (item.type === "error" || item.status === "failed") return "failure";
@@ -316,6 +321,7 @@ function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivi
)
.join("\n"),
toolLike: itemIsToolLike(item),
prominent: itemIsProminent(item),
status: itemStatus(item),
projectedItem: row,
};
@@ -339,7 +345,12 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
continue;
}
const previous = grouped.at(-1);
if (previous?.type === "activity-group" && previous.runId === entry.runId) {
if (
previous?.type === "activity-group" &&
previous.runId === entry.runId &&
!entry.activity.prominent &&
!previous.activities.some((activity) => activity.prominent)
) {
grouped[grouped.length - 1] = {
...previous,
activities: [...previous.activities, entry.activity],
@@ -435,7 +446,16 @@ function deriveThreadFeedRunFolds(
}
const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
const hiddenEntryIds = new Set(
group.entries.filter((entry) => entry.id !== terminalAssistantId).map((entry) => entry.id),
group.entries
.filter(
(entry) =>
entry.id !== terminalAssistantId &&
!(
entry.type === "activity-group" &&
entry.activities.some((activity) => activity.prominent)
),
)
.map((entry) => entry.id),
);
const firstEntry = group.entries[0];
const lastEntry = group.entries.at(-1);
@@ -9,6 +9,7 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
@@ -1191,17 +1192,10 @@ function AssistantForkButton({
sourceThreadId: projectedItem.sourceThreadId,
sourceItemId: projectedItem.sourceItemId,
});
const capabilities = support.providerSession?.capabilities;
const canForkNatively =
capabilities?.threads.canForkThread === true &&
capabilities.threads.canForkFromTurn === true &&
capabilities.identity.nativeThreadIds === "strong";
const canFork =
projectedItem.item.runId !== null &&
projectedItem.item.status === "completed" &&
(capabilities === undefined ||
canForkNatively ||
capabilities.context.supportsFullThreadHandoff === true);
const canFork = canForkProjectedAssistantItem({
projectedItem,
capabilities: support.providerSession?.capabilities,
});
if (!canFork || projectedItem.item.runId === null) return null;
const runId = projectedItem.item.runId;
@@ -1,4 +1,5 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
import { ArrowDownIcon, ArrowUpIcon, CornerUpRightIcon, ListOrderedIcon } from "lucide-react";
import { useMemo, useState } from "react";
@@ -18,31 +19,12 @@ export function QueuedRunsControl(props: {
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun);
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
const queued = useMemo(
() =>
(projection?.runs ?? [])
.filter((run) => run.status === "queued")
.toSorted(
(left, right) =>
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
left.ordinal - right.ordinal,
)
.map((run) => ({
run,
text:
projection?.messages.find((message) => message.id === run.userMessageId)?.text ??
"Queued message",
})),
const workflow = useMemo(
() => (projection ? deriveThreadQueueWorkflowState(projection) : null),
[projection],
);
const activeRun =
projection?.runs.findLast(
(run) =>
run.status === "preparing" ||
run.status === "starting" ||
run.status === "running" ||
run.status === "waiting",
) ?? null;
const queued = workflow?.queuedRuns ?? [];
const activeRun = workflow?.activeRun ?? null;
if (queued.length === 0) return null;
@@ -83,7 +65,7 @@ export function QueuedRunsControl(props: {
size="icon-xs"
variant="ghost"
aria-label="Move queued message up"
disabled={busyRunId !== null || index === 0}
disabled={busyRunId !== null || !workflow?.canReorder || index === 0}
onClick={() => void move(run.id, queued[index - 1]?.run.id ?? null)}
>
<ArrowUpIcon className="size-3" />
@@ -92,7 +74,7 @@ export function QueuedRunsControl(props: {
size="icon-xs"
variant="ghost"
aria-label="Move queued message down"
disabled={busyRunId !== null || index === queued.length - 1}
disabled={busyRunId !== null || !workflow?.canReorder || index === queued.length - 1}
onClick={() => void move(run.id, queued[index + 2]?.run.id ?? null)}
>
<ArrowDownIcon className="size-3" />
@@ -100,7 +82,7 @@ export function QueuedRunsControl(props: {
<Button
size="xs"
variant="outline"
disabled={busyRunId !== null || activeRun === null}
disabled={busyRunId !== null || !workflow?.canPromoteToSteer}
title={activeRun === null ? "There is no active run to steer" : "Promote to steer"}
onClick={() => void steer(run.id)}
>
@@ -1,4 +1,11 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "@t3tools/client-runtime/state/thread-relationships";
import { canDetachThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import {
@@ -13,12 +20,6 @@ import {
import { useState } from "react";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "../../lib/threadRelationships";
import { buildThreadRouteParams } from "../../threadRoutes";
import { useThreadProjection, useThreadShells } from "../../state/entities";
import { threadEnvironment } from "../../state/threads";
@@ -91,10 +92,7 @@ export function ThreadRelationshipsPanel(props: {
Number(left.threadId === mergeTargetThreadId),
);
const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
const canDetach =
projection?.providerSessions.some(
(session) => session.status !== "stopped" && session.status !== "error",
) ?? false;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
if (relationshipRows.length === 0) {
return null;
@@ -31,7 +31,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ProviderModelPicker } from "../components/chat/ProviderModelPicker";
import { usePrimarySettings } from "../hooks/useSettings";
import { resolveMergeBackTargetThreadId } from "../lib/threadRelationships";
import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils";
import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection";
import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders";
+6 -6
View File
@@ -135,13 +135,13 @@
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
},
"./state/thread-settled": {
"types": "./src/state/threadSettled.ts",
"default": "./src/state/threadSettled.ts"
"./state/thread-relationships": {
"types": "./src/state/threadRelationships.ts",
"default": "./src/state/threadRelationships.ts"
},
"./state/thread-search": {
"types": "./src/state/threadSearch.ts",
"default": "./src/state/threadSearch.ts"
"./state/thread-workflows": {
"types": "./src/state/threadWorkflows.ts",
"default": "./src/state/threadWorkflows.ts"
},
"./state/vcs": {
"types": "./src/state/vcs.ts",
@@ -7,7 +7,7 @@ import {
relatedThreadIds,
resolveMergeBackTargetThreadId,
walkThreadRelationships,
} from "./threadRelationships";
} from "./threadRelationships.ts";
describe("thread relationships", () => {
it("keeps missing parents and cycles navigable without recursive traversal", () => {
@@ -48,6 +48,64 @@ describe("thread relationships", () => {
]);
});
it("combines subagent and transfer edges with archived shell state", () => {
const parent = ThreadId.make("thread-parent");
const child = ThreadId.make("thread-child");
const transferTarget = ThreadId.make("thread-transfer");
const graph = deriveThreadRelationshipGraph({
threads: [
{
id: parent,
title: "Parent",
status: "completed",
archivedAt: null,
forkedFrom: null,
lineage: { rootThreadId: parent, parentThreadId: null, relationshipToParent: null },
},
{
id: child,
title: "Subagent",
status: "completed",
archivedAt: "2026-06-24T00:00:00.000Z",
forkedFrom: null,
lineage: {
rootThreadId: parent,
parentThreadId: parent,
relationshipToParent: "subagent",
},
},
] as never,
projection: {
thread: { id: parent },
subagents: [{ childThreadId: child, status: "completed" }],
contextTransfers: [
{
sourceThreadId: child,
targetThreadId: transferTarget,
status: "completed",
},
],
} as never,
});
expect(graph.nodes.get(child)?.thread?.archivedAt).not.toBeNull();
expect(graph.nodes.get(transferTarget)?.missing).toBe(true);
expect(graph.edges).toEqual(
expect.arrayContaining([
expect.objectContaining({
sourceThreadId: parent,
targetThreadId: child,
kind: "subagent",
}),
expect.objectContaining({
sourceThreadId: child,
targetThreadId: transferTarget,
kind: "transfer",
}),
]),
);
});
it("resolves merge-back only for forks and prefers the recorded fork source", () => {
const source = ThreadId.make("thread-source");
const fallbackParent = ThreadId.make("thread-parent");
@@ -0,0 +1,133 @@
import { describe, expect, it } from "vite-plus/test";
import {
canDetachThreadProviderSession,
canForkProjectedAssistantItem,
deriveThreadQueueWorkflowState,
} from "./threadWorkflows.ts";
const capabilities = (input?: {
readonly queued?: boolean;
readonly steer?: boolean;
readonly restartSteer?: boolean;
readonly nativeFork?: boolean;
readonly portableFork?: boolean;
}) =>
({
turns: {
supportsQueuedMessages: input?.queued ?? false,
supportsActiveSteering: input?.steer ?? false,
supportsSteeringByInterruptRestart: input?.restartSteer ?? false,
},
threads: {
canForkThread: input?.nativeFork ?? false,
canForkFromTurn: input?.nativeFork ?? false,
},
identity: { nativeThreadIds: input?.nativeFork ? "strong" : "none" },
context: { supportsFullThreadHandoff: input?.portableFork ?? false },
}) as never;
describe("thread workflows", () => {
it("sorts queued messages and gates reorder and promotion from capabilities", () => {
const state = deriveThreadQueueWorkflowState({
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [
{ id: "active", status: "running", providerThreadId: "provider-thread", ordinal: 1 },
{ id: "later", status: "queued", userMessageId: "message-later", ordinal: 3 },
{
id: "first",
status: "queued",
userMessageId: "message-first",
ordinal: 2,
queuePosition: 1,
},
],
messages: [
{ id: "message-first", text: "First" },
{ id: "message-later", text: "Later" },
],
providerThreads: [
{
id: "provider-thread",
appThreadId: "thread",
providerSessionId: "provider-session",
},
],
providerSessions: [
{
id: "provider-session",
status: "running",
capabilities: capabilities({ queued: true, restartSteer: true }),
},
],
} as never);
expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
["first", "First"],
["later", "Later"],
]);
expect(state.activeRun?.id).toBe("active");
expect(state.canReorder).toBe(true);
expect(state.canPromoteToSteer).toBe(true);
});
it("does not expose known unsupported queue or fork actions", () => {
const projection = {
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [{ id: "queued", status: "queued", userMessageId: "message", ordinal: 1 }],
messages: [],
providerThreads: [
{
id: "provider-thread",
appThreadId: "thread",
providerSessionId: "provider-session",
},
],
providerSessions: [
{
id: "provider-session",
status: "ready",
capabilities: capabilities(),
},
],
} as never;
const queue = deriveThreadQueueWorkflowState(projection);
const projectedItem = {
item: { type: "assistant_message", runId: "run", status: "completed" },
} as never;
expect(queue.canReorder).toBe(false);
expect(queue.canPromoteToSteer).toBe(false);
expect(canForkProjectedAssistantItem({ projectedItem, capabilities: capabilities() })).toBe(
false,
);
expect(canDetachThreadProviderSession(projection)).toBe(true);
});
it("allows native, portable, and capability-unknown exact-run forks", () => {
const projectedItem = {
item: { type: "assistant_message", runId: "run", status: "completed" },
} as never;
expect(
canForkProjectedAssistantItem({
projectedItem,
capabilities: capabilities({ nativeFork: true }),
}),
).toBe(true);
expect(
canForkProjectedAssistantItem({
projectedItem,
capabilities: capabilities({ portableFork: true }),
}),
).toBe(true);
expect(canForkProjectedAssistantItem({ projectedItem })).toBe(true);
expect(
canForkProjectedAssistantItem({
projectedItem: {
item: { type: "assistant_message", runId: "run", status: "running" },
} as never,
}),
).toBe(false);
});
});
@@ -0,0 +1,107 @@
import type {
OrchestrationV2ProjectedTurnItem,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
type Projection = OrchestrationV2ThreadProjection;
type Run = Projection["runs"][number];
type ProviderSession = Projection["providerSessions"][number];
const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
export interface QueuedThreadRun {
readonly run: Run;
readonly text: string;
}
export interface ThreadQueueWorkflowState {
readonly activeRun: Run | null;
readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
readonly canReorder: boolean;
readonly canPromoteToSteer: boolean;
}
export function resolveActiveThreadRun(projection: Projection): Run | null {
return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
}
export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
const activeRun = resolveActiveThreadRun(projection);
const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
const activeProviderThread =
providerThreadId === null
? null
: (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
const attachedProviderThread =
activeProviderThread ??
projection.providerThreads.find(
(thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
) ??
null;
const sessionId = attachedProviderThread?.providerSessionId ?? null;
if (sessionId !== null) {
return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
}
return (
projection.providerSessions.findLast(
(session) => session.status !== "stopped" && session.status !== "error",
) ?? null
);
}
export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
const activeRun = resolveActiveThreadRun(projection);
const session = resolveThreadProviderSession(projection);
const capabilities = session?.capabilities.turns;
const queuedRuns = projection.runs
.filter((run) => run.status === "queued")
.toSorted(
(left, right) =>
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
left.ordinal - right.ordinal,
)
.map((run) => ({
run,
text:
projection.messages.find((message) => message.id === run.userMessageId)?.text ??
"Queued message",
}));
return {
activeRun,
queuedRuns,
canReorder: capabilities?.supportsQueuedMessages === true,
canPromoteToSteer:
activeRun !== null &&
(capabilities?.supportsActiveSteering === true ||
capabilities?.supportsSteeringByInterruptRestart === true),
};
}
export function canForkProjectedAssistantItem(input: {
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
}): boolean {
const item = input.projectedItem.item;
if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
return false;
}
if (input.capabilities === undefined) {
// Historical and inherited rows may outlive their provider-session record.
// Keep the portable server-side fallback available when capability evidence
// is absent; a known incapable provider is rejected below.
return true;
}
const capabilities = input.capabilities;
const canForkNatively =
capabilities.threads.canForkThread &&
capabilities.threads.canForkFromTurn &&
capabilities.identity.nativeThreadIds === "strong";
return canForkNatively || capabilities.context.supportsFullThreadHandoff;
}
export function canDetachThreadProviderSession(projection: Projection): boolean {
const session = resolveThreadProviderSession(projection);
return session !== null && session.status !== "stopped" && session.status !== "error";
}