diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 295fd4331d..a4c0279d38 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -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={ + + } layoutVariant={layoutVariant} skills={selectedProviderSkills} /> @@ -384,17 +393,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread ) : null} - {/* Floating composer — sticks to keyboard via KeyboardStickyView */} - {showContent ? ( - - {/* 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. */} - - + + {props.activePendingApproval || props.activePendingUserInput ? ( ; readonly contentPresentation: ThreadContentPresentation; @@ -158,13 +167,89 @@ export interface ThreadFeedProps { readonly contentInsetEndAdjustment: SharedValue; 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; } +async function waitForThreadShell(environmentId: EnvironmentId, threadId: ThreadId): Promise { + const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId)); + const deadline = Date.now() + 2_000; + while (appAtomRegistry.get(atom) === null && Date.now() < deadline) { + await new Promise((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 ( + { + 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 ? ( + + ) : ( + + )} + + ); +} + 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 ( - + + {message.createdBy === "agent" ? ( + + Sent by another agent + + ) : null} + 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 : - } - contentContainerStyle={{ - paddingTop: 12, - paddingHorizontal: contentHorizontalPadding, - }} - /> - - {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={ + <> + + {props.topAccessory} + + } + contentContainerStyle={{ + paddingTop: 12, + paddingHorizontal: horizontalPadding, + }} + /> + {props.feed.length === 0 ? ( (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(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 ( + + + + Queue + + {workflow.queuedRuns.length} + + + + {workflow.queuedRuns.map(({ run, text }, index) => ( + + + {index + 1} + + + {text} + + void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)} + className="h-9 w-9 items-center justify-center disabled:opacity-30" + > + + + void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)} + className="h-9 w-9 items-center justify-center disabled:opacity-30" + > + + + 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]" + > + + Steer + + + ))} + + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx new file mode 100644 index 0000000000..bf970456b6 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx @@ -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 = []; + +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>(() => { + 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 ( + <> + { + 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]" + > + + + {summary} + + {rows.length > 1 ? ( + +{rows.length - 1} + ) : null} + + + + setVisible(false)} + > + + + setVisible(false)} /> + + + + + Thread lineage + + {rows.length} related {rows.length === 1 ? "thread" : "threads"} + + + setVisible(false)} + className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]" + > + + + + + + {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 ( + 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]" + > + + + + + + {relationshipLabel(edge, props.threadId)} + + + {node?.thread?.title ?? threadId} + + + {availability ? ( + {availability} + ) : ( + + )} + + ); + })} + + + {canMerge || canDetach ? ( + + {canMerge ? ( + void merge()} + className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3" + > + {busyAction === "merge" ? ( + + ) : ( + + )} + + Merge back to source + + + ) : null} + {canDetach ? ( + 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" ? : null} + + Disconnect agent session + + + ) : null} + + ) : null} + + + + + ); +} diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 4a634f64df..b695a82851 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -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, -): ReadonlyArray { - 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, - 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 + { + 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]" + > + {label} + + ); } @@ -157,9 +165,12 @@ export function ThreadWorkLog(props: { const iconIsDestructive = row.icon === "alert" || row.icon === "warning"; return ( - ) : null} - + {row.prominent ? ( + + ) : null} + ); })} diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 0955f67592..b2d13bf7c5 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -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", () => { diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index fd42c3e9f8..ded3b082d3 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -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): 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); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 60dd399e60..ebea34ccd1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -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; diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 5f697db8f6..e589129659 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -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(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)} > @@ -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)} > @@ -100,7 +82,7 @@ export function QueuedRunsControl(props: {