fix(orchestration-v2): restore generated thread titles (#5176)

This commit is contained in:
Yusuf Rawat authored and Julius Marminge committed 2026-08-15 16:51:13 +02:00
1 parent 28d429d047
commit 0dd6b54c8a
23 files changed
+1139 -580

No files matched your search

@@ -1,14 +1,9 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
import {
StackActions,
useFocusEffect,
useNavigation,
usePreventRemove,
} from "@react-navigation/native";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Platform, Pressable, ScrollView, View, useColorScheme } from "react-native";
import {
KeyboardController,
KeyboardAvoidingView,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
@@ -16,31 +11,31 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { EnvironmentId } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
ComposerInlineControl,
ComposerToolbarButton,
ComposerToolbarRow,
ComposerToolbarScroller,
} from "../../components/ComposerToolbar";
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ComposerSurface } from "./ThreadComposer";
import {
useThreadSettingsSheetPresentation,
type NavigationWithFinishTransitioning,
} from "./use-thread-settings-sheet-presentation";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
@@ -50,39 +45,26 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { useNewTaskFlow } from "./new-task-flow-provider";
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import {
resolveNewTaskBranchLabel,
resolveNewTaskWorkspaceLabel,
} from "./new-task-context-presentation";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function NewTaskWorkspaceIcon(props: {
readonly workspaceMode: "local" | "worktree";
readonly worktreePath: string | null;
}) {
const iconColor = useThemeColor("--color-icon-muted");
if (props.workspaceMode === "local" && props.worktreePath === null) {
return <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />;
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
readonly currentBranchName: string | null;
readonly selectedBranchName: string | null;
}): string {
const branchName = input.selectedBranchName ?? input.currentBranchName;
if (input.workspaceMode === "worktree") {
return branchName ? `New worktree · ${branchName}` : "New worktree";
}
return (
<View className="size-4">
<SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />
<View className="absolute -right-1 -bottom-1">
<SymbolView name="arrow.triangle.branch" size={9} tintColor={iconColor} type="monochrome" />
</View>
</View>
);
return branchName ? `Current · ${branchName}` : "Current checkout";
}
export function NewTaskDraftScreen(props: {
@@ -109,8 +91,7 @@ export function NewTaskDraftScreen(props: {
const insets = useSafeAreaInsets();
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = Math.max(insets.bottom, 10);
const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
@@ -128,49 +109,6 @@ export function NewTaskDraftScreen(props: {
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
});
useEffect(() => {
if (Platform.OS !== "ios") {
return;
}
navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
}, [isKeyboardVisible, navigation]);
useEffect(() => {
return () => {
if (Platform.OS === "ios") {
navigation.getParent()?.setOptions({ gestureEnabled: true });
}
};
}, [navigation]);
const settingsRoutePresentedRef = useRef(false);
useEffect(() => {
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
return;
}
settingsRoutePresentedRef.current = true;
navigation.dispatch(StackActions.push("ThreadSettings"));
}, [navigation, settingsSheetPresentation.isVisible]);
useFocusEffect(
useCallback(() => {
if (!settingsRoutePresentedRef.current) {
return;
}
settingsRoutePresentedRef.current = false;
settingsSheetPresentation.onDismissed();
}, [settingsSheetPresentation.onDismissed]),
);
useEffect(
() =>
// UIKit's completion callback for the sheet dismissal, surfaced by the
// native-stack patch. This is when the queued keyboard restore runs.
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
"finishTransitioning",
settingsSheetPresentation.onStackTransitionsFinished,
),
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
);
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
@@ -290,9 +228,9 @@ export function NewTaskDraftScreen(props: {
}, [props.pendingTaskId, cancelEditingPendingTask]);
const foregroundColor = useThemeColor("--color-foreground");
const projectUnderlineColor = useThemeColor("--color-foreground-muted");
const regularFontFamily = useFontFamily("regular");
const bodyText = useScaledTextRole("body");
const headlineText = useScaledTextRole("headline");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
@@ -378,7 +316,7 @@ export function NewTaskDraftScreen(props: {
return;
}
loadedBranchesProjectKeyRef.current = projectKey;
flow.loadBranches();
void flow.loadBranches();
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
@@ -580,31 +518,173 @@ export function NewTaskDraftScreen(props: {
shareImportAttempt,
]);
useEffect(() => {
// Android starts with the collapsed composer pill (like an open thread)
// and only expands/focuses when tapped.
if (!selectedProject || Platform.OS === "android") {
return;
}
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => {
// The delayed focus can land after the settings sheet opened, which
// would pop the keyboard underneath its modal.
if (!settingsSheetPresentation.isActiveRef.current) {
promptInputRef.current?.focus();
} else {
settingsSheetPresentation.restoreFocusAfterSave();
}
});
});
return () => {
interaction.cancel();
if (focusFrame !== null) {
cancelAnimationFrame(focusFrame);
}
};
}, [
selectedProject,
settingsSheetPresentation.isActiveRef,
settingsSheetPresentation.restoreFocusAfterSave,
]);
const environmentMenuActions = useMemo(
() =>
flow.environments.map((environment) => ({
id: `environment:${environment.environmentId}`,
title: environment.environmentLabel,
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
state:
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
})),
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
capabilities: flow.selectedModelOption?.capabilities,
selections: flow.selectedModel?.options,
}),
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
? [
{
id: "workspace:branch:none",
title: flow.branchesLoading ? "Loading branches…" : "No branches available",
attributes: { disabled: true },
},
]
: flow.availableBranches.slice(0, 12).map((branch) => {
const badge = branchBadgeLabel({
branch,
project: flow.selectedProject,
});
return {
id: `workspace:branch:${branch.name}`,
title: branch.name,
subtitle: badge ? badge.toUpperCase() : undefined,
state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
};
});
return [
{
id: "workspace:mode",
title: "Mode",
subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
subactions: (["local", "worktree"] as const).map((value) => ({
id: `workspace:mode:${value}`,
title: value === "local" ? "Current checkout" : "New worktree",
state: flow.workspaceMode === value ? ("on" as const) : undefined,
})),
},
{
id: "workspace:branch",
title: "Branch",
subtitle: flow.selectedBranchName ?? "Choose branch",
subactions: branchActions,
},
...(flow.workspaceMode === "worktree"
? [
{
id: "workspace:start-from-origin",
title: "Start from origin",
subtitle: "Base the worktree on the latest origin branch",
image: "arrow.triangle.pull",
state: flow.startFromOrigin ? ("on" as const) : undefined,
},
]
: []),
];
}, [
flow.availableBranches,
flow.branchesLoading,
flow.selectedBranchName,
flow.selectedProject,
flow.startFromOrigin,
flow.workspaceMode,
]);
const selectedEnvironmentLabel =
flow.environments.find(
(environment) => environment.environmentId === flow.selectedEnvironmentId,
)?.environmentLabel ?? "Environment";
const availableCurrentBranchName =
const currentBranchName =
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const selectedBranchName = resolveProjectThreadCreationBranch({
workspaceMode: flow.workspaceMode,
selectedBranch:
flow.selectedBranchName ??
(flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
currentCheckoutBranch: flow.currentCheckoutBranchName,
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: flow.selectedModelOption?.label ?? "Model",
optionDescriptors: providerOptionDescriptors,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
});
const selectedBranchLabel = resolveNewTaskBranchLabel({
branchName: selectedBranchName,
startFromOrigin: flow.startFromOrigin,
workspaceMode: flow.workspaceMode,
});
const workspaceLabel = resolveNewTaskWorkspaceLabel({
workspaceMode: flow.workspaceMode,
worktreePath: flow.selectedWorktreePath,
});
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
currentBranchName,
selectedBranchName: flow.selectedBranchName,
workspaceMode: flow.workspaceMode,
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
}
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
if (event.startsWith("workspace:mode:")) {
flow.setWorkspaceMode(
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
);
return;
}
if (event === "workspace:start-from-origin") {
flow.setStartFromOrigin(!flow.startFromOrigin);
return;
}
if (event.startsWith("workspace:branch:")) {
const branchName = event.slice("workspace:branch:".length);
const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
if (branch) {
flow.selectBranch(branch);
}
}
}
async function handlePickImages(): Promise<void> {
if (isIncomingShareTransferPending) {
@@ -654,9 +734,7 @@ export function NewTaskDraftScreen(props: {
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
const interactionMode = flow.planModeEnabled
? (draft.interactionMode ?? flow.interactionMode)
: "default";
const interactionMode = draft.interactionMode ?? flow.interactionMode;
const initialMessageText = draft.text.trim();
if (
@@ -716,20 +794,17 @@ export function NewTaskDraftScreen(props: {
// -only Activity start. If creation fails, the token registration's replay
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: selectedProject.environmentId,
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
threadTitle: deriveThreadTitleSeed({
text: initialMessageText,
attachments: draft.attachments,
}),
projectTitle: selectedProject.title,
});
const creationBranch = resolveProjectThreadCreationBranch({
workspaceMode,
selectedBranch: selectedBranchName,
currentCheckoutBranch: flow.currentCheckoutBranchName,
});
const result = await createProjectThread({
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: creationBranch,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
startFromOrigin,
runtimeMode,
@@ -780,7 +855,7 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet" collapsable={false}>
<View className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
@@ -795,6 +870,11 @@ export function NewTaskDraftScreen(props: {
const isAndroid = Platform.OS === "android";
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
// The settings sheet dismisses the keyboard, so its flag keeps the Android
// draft composer expanded through the blur (mirrors ThreadComposer).
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -806,279 +886,235 @@ export function NewTaskDraftScreen(props: {
const promptEditor = (
<ComposerEditor
ref={promptInputRef}
// The context-first screen intentionally opens with the keyboard closed.
// Focusing is a user action, so presenting the form sheet has one motion.
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
// forces the iOS keyboard bring-up during the formSheet present
// animation and stalls it. The runAfterInteractions effect above focuses
// the editor once the transition settles instead.
autoFocus={false}
editable={!isIncomingShareTransferPending}
multiline
scrollEnabled
scrollEnabled={isExpanded}
value={flow.prompt}
skills={flow.selectedProviderSkills}
onChangeText={flow.setPrompt}
onFocus={() => setIsComposerFocused(true)}
onBlur={() => setIsComposerFocused(false)}
onPasteImages={(uris) => void handleNativePasteImages(uris)}
placeholder="Ask anything…"
singleLineCentered={false}
contentInsetVertical={0}
style={{
minHeight: 72,
maxHeight: 160,
paddingHorizontal: 4,
paddingVertical: 4,
}}
textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
placeholder={`Describe a coding task in ${selectedProject.title}`}
// Same collapsed centering as ThreadComposer: native vertical gravity
// in a pill-height box.
singleLineCentered={!isExpanded}
contentInsetVertical={isAndroid ? 0 : undefined}
style={
isAndroid
? isExpanded
? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
: { height: 36 }
: { flex: 1, minHeight: 0 }
}
textStyle={
isAndroid
? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
: headlineText
}
/>
);
const closeNewTask = () => {
void KeyboardController.dismiss({ animated: true });
const parentNavigation = navigation.getParent();
if (parentNavigation) {
parentNavigation.goBack();
return;
}
navigation.goBack();
};
const chooseProject = () => {
if (isIncomingShareTransferPending) {
return;
}
promptInputRef.current?.blur();
void KeyboardController.dismiss({ animated: true });
navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
};
const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
if (isIncomingShareTransferPending) {
return;
}
promptInputRef.current?.blur();
void KeyboardController.dismiss({ animated: true });
navigation.dispatch(StackActions.push(routeName));
};
const hero = (
<View className="items-center gap-6 px-6" testID="new-task-hero">
<View className="w-full items-center gap-1.5">
<Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
What should we build
</Text>
<View className="max-w-full flex-row items-center justify-center">
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
<Pressable
accessibilityHint="Opens the project picker"
accessibilityLabel={`Change project from ${selectedProject.title}`}
accessibilityRole="button"
disabled={isIncomingShareTransferPending}
onPress={chooseProject}
className="min-w-0 max-w-[250px] active:opacity-65"
style={{
borderBottomColor: projectUnderlineColor,
borderBottomWidth: 1,
}}
>
<Text
className="text-2xl font-t3-medium tracking-tight text-foreground"
numberOfLines={1}
>
{selectedProject.title}
</Text>
</Pressable>
<Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
</View>
</View>
<ComposerInlineControl
accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
chevronDirection="right"
disabled={isIncomingShareTransferPending}
icon="desktopcomputer"
label={`on ${selectedEnvironmentLabel}`}
maxWidth={260}
onPress={
flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
}
showChevron={flow.environments.length > 1}
static={flow.environments.length <= 1}
/>
</View>
);
const heroViewport = (
<View className="flex-1" collapsable={false}>
<ScrollView
alwaysBounceVertical={isKeyboardVisible}
className="flex-1"
contentInsetAdjustmentBehavior="never"
contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
testID="new-task-hero-scroll"
>
{hero}
</ScrollView>
</View>
);
const workspaceControls = (
<View className="flex-row items-center gap-1 px-2">
<ComposerInlineControl
accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
accessibilityLabel={workspaceLabel}
disabled={isIncomingShareTransferPending}
iconNode={
<NewTaskWorkspaceIcon
workspaceMode={flow.workspaceMode}
worktreePath={flow.selectedWorktreePath}
/>
}
label={workspaceLabel}
maxWidth={flow.workspaceMode === "local" ? 220 : 148}
onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
const toolbarPills = (
<>
<ComposerToolbarButton
icon="plus"
onPress={() => void handlePickImages()}
showChevron={false}
/>
<ComposerInlineControl
accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
chevronDirection="right"
disabled={isIncomingShareTransferPending}
icon="arrow.triangle.branch"
label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
maxWidth={190}
onPress={() => openContextPicker("NewTaskBranch")}
/>
</View>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Environment"
disabled={isIncomingShareTransferPending}
icon="desktopcomputer"
label={selectedEnvironmentLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Workspace"
disabled={isIncomingShareTransferPending}
icon="point.topleft.down.curvedto.point.bottomright.up"
label={workspaceLabel}
/>
</ControlPillMenu>
</>
);
const composerDock = (
<View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
<View className="pb-1">{workspaceControls}</View>
const settingsSheet = (
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={flow.providerGroups}
selectedModel={flow.selectedModel}
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={flow.setSelectedModelOptions}
runtimeMode={flow.runtimeMode}
onUpdateRuntimeMode={flow.setRuntimeMode}
/>
);
<ComposerSurface
animateLayout={false}
isDarkMode={isDarkMode}
style={{
borderRadius: 26,
minHeight: 140,
overflow: "hidden",
paddingBottom: 6,
paddingHorizontal: 14,
paddingTop: 14,
}}
>
{flow.attachments.length > 0 ? (
<View className="pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
imageBorderRadius={16}
imageSize={72}
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
/>
</View>
) : null}
{promptEditor}
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
<ComposerToolbarScroller
fadeOpaque={sheetFadeOpaque}
fadeTransparent={sheetFadeTransparent}
contentPaddingRight={8}
>
<ComposerToolbarButton
accessibilityLabel="Add attachment"
disabled={isIncomingShareTransferPending}
icon="plus"
onPress={() => void handlePickImages()}
showChevron={false}
/>
<ComposerInlineControl
accessibilityLabel="Model and reasoning settings"
disabled={isIncomingShareTransferPending}
emphasized
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
}
label={flow.selectedModelOption?.label ?? "Choose model"}
maxWidth={152}
onPress={settingsSheetPresentation.open}
/>
{flow.planModeEnabled ? (
<ComposerInlineControl
accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
disabled={isIncomingShareTransferPending}
emphasized
icon={
flow.interactionMode === "plan"
? { ios: "list.bullet.clipboard", android: "auto_awesome" }
: { ios: "hammer", android: "construction" }
}
label={flow.interactionMode === "plan" ? "Plan" : "Build"}
onPress={() =>
flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")
}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
}
disabled={!canStart}
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
onPress={() => void handleStart()}
showChevron={false}
variant="primary"
/>
</ComposerToolbarRow>
</ComposerSurface>
</View>
const startButton = (
<ComposerToolbarButton
accessibilityLabel={
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
}
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
onPress={() => void handleStart()}
variant="primary"
showChevron={false}
disabled={!canStart}
/>
);
if (isAndroid) {
// The draft is a thread that doesn't exist yet, so it mirrors the thread
// page: in-screen header, empty feed canvas above, and the same floating
// composer chrome as ThreadComposer (collapsed pill → expanded card).
//
// Composer positioning mirrors ThreadDetailScreen's floating overlay
// (KeyboardStickyView, absolute bottom overlay) rather than
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
// resolves the composer's on-screen frame via a native
// viewPositionInWindow measurement, which this app's Android
// edge-to-edge setup (KeyboardProvider's native content-view margin
// handling neutralizes windowSoftInputMode="adjustResize" while active)
// makes unreliable — the composer stayed under the keyboard instead of
// translating above it. KeyboardStickyView sticks directly to the
// animated keyboard height instead, sidestepping that measurement.
return (
<View className="flex-1 bg-sheet" collapsable={false}>
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New task" onBack={closeNewTask} />
{heroViewport}
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
<View className="flex-1" />
<KeyboardStickyView
enabled={isKeyboardVisible}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: keyboardOpenedOffset }}
offset={{ closed: 0, opened: 0 }}
>
{composerDock}
<View
className="px-4 pt-2"
style={{
paddingBottom: controlsBottomPadding,
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
}}
>
<ComposerSurface
isDarkMode={isDarkMode}
style={
isExpanded
? {
borderRadius: 20,
overflow: "hidden",
paddingHorizontal: 14,
paddingVertical: 12,
}
: {
borderRadius: 999,
overflow: "hidden",
flexDirection: "row",
alignItems: "center",
paddingLeft: 18,
paddingRight: 5,
paddingVertical: 5,
}
}
>
{isExpanded && flow.attachments.length > 0 ? (
<View className="pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
}
/>
</View>
) : null}
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
{!isExpanded ? (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canStart}
onPress={() => void handleStart()}
/>
) : null}
</ComposerSurface>
{isExpanded ? (
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
>
{toolbarPills}
</ComposerToolbarScroller>
{startButton}
</ComposerToolbarRow>
) : null}
</View>
</KeyboardStickyView>
{settingsSheet}
</View>
);
}
return (
<View className="flex-1 bg-sheet" collapsable={false}>
<NativeStackScreenOptions
options={{
headerBackVisible: false,
headerShadowVisible: false,
title: "",
}}
/>
<NativeHeaderToolbar placement="left">
<NativeHeaderToolbar.Button
accessibilityLabel="Cancel new task"
label="Cancel"
onPress={closeNewTask}
/>
</NativeHeaderToolbar>
<View className="flex-1 bg-sheet">
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
{heroViewport}
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: keyboardOpenedOffset }}
>
{composerDock}
</KeyboardStickyView>
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
{flow.attachments.length > 0 ? (
<View className="px-4 pt-3">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
</View>
) : null}
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
<ComposerToolbarScroller
fadeOpaque={sheetFadeOpaque}
fadeTransparent={sheetFadeTransparent}
>
{toolbarPills}
</ComposerToolbarScroller>
{startButton}
</ComposerToolbarRow>
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
+2 -11
View File
@@ -7,19 +7,10 @@ import {
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0) {
return "New thread";
}
const compact = trimmed.replace(/\s+/g, " ");
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
export interface ProjectThreadStartTurnSpec {
readonly projectId: ProjectId;
readonly projectCwd: string;
@@ -46,7 +37,7 @@ export interface ProjectThreadStartTurnSpec {
* offline outbox drain so both deliver identical commands.
*/
export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {
const title = deriveThreadTitleFromPrompt(spec.text);
const title = deriveThreadTitleSeed({ text: spec.text, attachments: spec.attachments });
const isWorktree = spec.workspaceMode === "worktree";
return {
commandId: CommandId.make(spec.commandId),
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
import {
flattenQueuedThreadMessages,
type QueuedThreadCreation,
@@ -26,7 +26,7 @@ export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
tasks.push({
message,
creation: message.creation,
title: deriveThreadTitleFromPrompt(message.text),
title: deriveThreadTitleSeed({ text: message.text, attachments: message.attachments }),
});
}
tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt));
@@ -5,6 +5,7 @@ import {
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -231,6 +232,10 @@ export function useThreadOutboxDrain(): void {
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
},
modelSelection: settings.modelSelection,
titleSeed: deriveThreadTitleSeed({
text: queuedMessage.text,
attachments: queuedMessage.attachments,
}),
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
@@ -90,6 +90,13 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
type: Schema.Literal("attachment.cleanup"),
attachmentIds: Schema.Array(Schema.String),
}),
Schema.Struct({
type: Schema.Literal("thread-title.generate"),
kind: Schema.Union([
Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
Schema.Struct({ type: Schema.Literal("regenerate") }),
]),
}),
]);
export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
@@ -99,6 +106,7 @@ export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
"checkpoint.capture",
"terminal.cleanup",
"attachment.cleanup",
"thread-title.generate",
] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
export const PROCESS_BOUND_EFFECT_TYPES = [
@@ -265,6 +273,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
available,
Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
).pipe(Effect.asVoid);
// Title generation is correlated metadata work, so it has its own
// per-thread lane and cannot delay provider lifecycle effects.
const claimableCandidatePredicate = (availableBefore?: string) =>
sql`
${
@@ -278,6 +288,17 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
FROM orchestration_v2_effect_outbox AS active
WHERE active.thread_id = candidate.thread_id
AND active.status = 'running'
AND (
(
candidate.effect_type = 'thread-title.generate'
AND active.effect_type = 'thread-title.generate'
)
OR
(
candidate.effect_type != 'thread-title.generate'
AND active.effect_type != 'thread-title.generate'
)
)
)
`;
@@ -1,6 +1,7 @@
import { assert, it } from "@effect/vitest";
import {
CommandId,
MessageId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
@@ -36,6 +37,7 @@ import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
import { ProviderTurnStartError, ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";
import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
import { ThreadTitleRegenerationService } from "./ThreadTitleRegenerationService.ts";
const threadId = ThreadId.make("thread:effect-worker-restart");
const oldSessionId = ProviderSessionId.make("provider-session:effect-worker-restart:old");
@@ -142,6 +144,12 @@ function makeExecutorLayer(input: {
RuntimeRequestServiceV2,
RuntimeRequestServiceV2.of({ respond: () => Effect.void }),
),
Layer.succeed(
ThreadTitleRegenerationService,
ThreadTitleRegenerationService.of({
execute: ({ requestId, kind }) => record(`title:${kind.type}:${requestId}`),
}),
),
);
return executorLayer.pipe(Layer.provide(dependencies));
}
@@ -714,6 +722,39 @@ it.effect("detaches a handed-off session only after the old turn terminalizes",
}),
);
it.effect("executes durable thread title generation effects", () =>
Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);
const events = yield* Ref.make<ReadonlyArray<string>>([]);
const commandId = CommandId.make("command:title-generation");
const effect: OrchestrationEffectV2 = {
id: "effect:title-generation",
commandId,
threadId,
request: {
type: "thread-title.generate",
kind: { type: "initial", messageId: MessageId.make("message:title-generation") },
},
status: "running",
attemptCount: 1,
availableAt: now,
leaseOwner: "test-worker",
leaseExpiresAt: now,
createdAt: now,
updatedAt: now,
completedAt: null,
lastError: null,
};
yield* Effect.gen(function* () {
const executor = yield* OrchestrationEffectExecutorV2;
yield* executor.execute(effect);
}).pipe(Effect.provide(makeExecutorLayer({ events })));
assert.deepEqual(yield* Ref.get(events), [`title:initial:${commandId}`]);
}),
);
it.effect("safely retries after replacement cleanup succeeds and start fails", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
@@ -27,6 +27,7 @@ import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
import { ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";
import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
import { ThreadTitleRegenerationService } from "./ThreadTitleRegenerationService.ts";
export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<OrchestrationEffectExecutionError>()(
"OrchestrationEffectExecutionError",
@@ -81,6 +82,7 @@ export const executorLayer: Layer.Layer<
| ProviderTurnControlServiceV2
| ProviderTurnStartServiceV2
| RuntimeRequestServiceV2
| ThreadTitleRegenerationService
> = Layer.effect(
OrchestrationEffectExecutorV2,
Effect.gen(function* () {
@@ -91,6 +93,7 @@ export const executorLayer: Layer.Layer<
const providerTurnControl = yield* ProviderTurnControlServiceV2;
const providerTurnStart = yield* ProviderTurnStartServiceV2;
const runtimeRequests = yield* RuntimeRequestServiceV2;
const threadTitleRegeneration = yield* ThreadTitleRegenerationService;
return OrchestrationEffectExecutorV2.of({
execute: (effect) => {
switch (effect.request.type) {
@@ -290,6 +293,23 @@ export const executorLayer: Layer.Layer<
}),
),
);
case "thread-title.generate":
return threadTitleRegeneration
.execute({
threadId: effect.threadId,
requestId: effect.commandId,
kind: effect.request.kind,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
}
},
});
@@ -1071,6 +1071,111 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("runs title generation beside critical work while serializing each lane", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const commandId = CommandId.make("command:foundation-title-effect-lane");
const threadId = ThreadId.make("thread:foundation-title-effect-lane");
const titleEffectId = "effect:foundation-title-effect-lane:a-title";
const providerEffectId = "effect:foundation-title-effect-lane:b-provider";
const nextTitleEffectId = "effect:foundation-title-effect-lane:c-title";
const nextCriticalEffectId = "effect:foundation-title-effect-lane:d-critical";
yield* outbox.enqueue([
{
id: titleEffectId,
commandId,
threadId,
request: {
type: "thread-title.generate",
kind: {
type: "initial",
messageId: MessageId.make("message:foundation-title-effect-lane"),
},
},
},
{
id: providerEffectId,
commandId,
threadId,
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-title-effect-lane"),
},
},
{
id: nextTitleEffectId,
commandId,
threadId,
request: { type: "thread-title.generate", kind: { type: "regenerate" } },
},
{
id: nextCriticalEffectId,
commandId,
threadId,
request: { type: "terminal.cleanup" },
},
]);
const title = yield* outbox.claimNext({
workerId: "title-lane-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(title));
if (Option.isNone(title)) return;
assert.equal(title.value.id, titleEffectId);
const provider = yield* outbox.claimNext({
workerId: "critical-lane-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(provider));
if (Option.isNone(provider)) return;
assert.equal(provider.value.id, providerEffectId);
assert.isTrue(
Option.isNone(
yield* outbox.claimNext({
workerId: "blocked-lanes-worker",
leaseDurationMs: 30_000,
}),
),
);
yield* outbox.succeed({
effectId: provider.value.id,
workerId: "critical-lane-worker",
});
const nextCritical = yield* outbox.claimNext({
workerId: "critical-lane-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(nextCritical));
if (Option.isNone(nextCritical)) return;
assert.equal(nextCritical.value.id, nextCriticalEffectId);
yield* outbox.succeed({
effectId: nextCritical.value.id,
workerId: "critical-lane-worker",
});
yield* outbox.succeed({
effectId: title.value.id,
workerId: "title-lane-worker",
});
const nextTitle = yield* outbox.claimNext({
workerId: "title-lane-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(nextTitle));
if (Option.isSome(nextTitle)) {
assert.equal(nextTitle.value.id, nextTitleEffectId);
yield* outbox.succeed({
effectId: nextTitle.value.id,
workerId: "title-lane-worker",
});
}
}),
);
it.effect("ignores deadlines blocked by a running effect on the same thread", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
@@ -1,6 +1,7 @@
import {
type ChatAttachment,
CommandId,
type MessageId,
type ModelSelection,
OrchestrationV2Command,
type OrchestrationV2AppThread,
@@ -196,6 +197,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
case "thread.title.regeneration.complete":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
case "thread.model-selection.set":
@@ -223,6 +225,21 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
}
}
function pendingThreadTitleGenerationEffect(
commandId: CommandId,
threadId: ThreadId,
kind:
| { readonly type: "initial"; readonly messageId: MessageId }
| { readonly type: "regenerate" },
): PendingOrchestrationEffectV2 {
return {
id: `effect:${commandId}:thread-title.generate`,
commandId,
threadId,
request: { type: "thread-title.generate", kind },
};
}
function nextTurnItemOrdinal(projection: OrchestrationV2ThreadProjection): number {
return Math.max(0, ...projection.turnItems.map((item) => item.ordinal)) + 1;
}
@@ -943,6 +960,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
| "thread.visit"
| "thread.mark-unread"
| "thread.metadata.update"
| "thread.title.regeneration.complete"
| "thread.runtime-mode.set"
| "thread.interaction-mode.set"
| "thread.model-selection.set"
@@ -1100,11 +1118,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const updatedThread: OrchestrationV2AppThread = (() => {
switch (command.type) {
case "thread.archive":
return { ...thread, archivedAt: now, updatedAt: now };
return { ...thread, archivedAt: now, titleRegeneration: null, updatedAt: now };
case "thread.unarchive":
return { ...thread, archivedAt: null, updatedAt: now };
case "thread.delete":
return { ...thread, deletedAt: thread.deletedAt ?? now, updatedAt: now };
return {
...thread,
deletedAt: thread.deletedAt ?? now,
titleRegeneration: null,
updatedAt: now,
};
case "thread.settle": {
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
return {
@@ -1173,6 +1196,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: {}),
updatedAt: now,
};
case "thread.title.regeneration.complete":
return thread.titleRegeneration?.requestId === command.requestId
? {
...thread,
...(command.title === undefined ? {} : { title: command.title }),
titleRegeneration: null,
updatedAt: now,
}
: thread;
case "thread.runtime-mode.set":
return { ...thread, runtimeMode: command.runtimeMode, updatedAt: now };
case "thread.interaction-mode.set":
@@ -1208,6 +1240,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "thread.mark-unread":
return "thread.marked-unread" as const;
case "thread.metadata.update":
case "thread.title.regeneration.complete":
return "thread.metadata-updated" as const;
case "thread.runtime-mode.set":
return "thread.runtime-mode-updated" as const;
@@ -1230,6 +1263,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
payload: updatedThread,
});
if (command.type === "thread.metadata.update" && command.regenerateTitle === true) {
yield* Ref.update(effects, (existing) => [
...existing,
pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
type: "regenerate",
}),
]);
}
if (command.type === "thread.archive" || command.type === "thread.delete") {
const emitEvent = emit(events, command);
const activeRunIds = new Set(
@@ -2343,6 +2385,33 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
projection = yield* getProjectionWithPendingEvents(command.threadId, events);
}
if (command.titleSeed !== undefined && projection.messages.length === 0) {
const now = yield* DateTime.now;
const thread: OrchestrationV2AppThread = {
...projection.thread,
title: command.titleSeed,
titleRegeneration: { requestId: command.commandId, startedAt: now },
updatedAt: now,
};
yield* emit(
events,
command,
)({
type: "thread.metadata-updated",
threadId: command.threadId,
providerInstanceId: thread.providerInstanceId,
occurredAt: now,
payload: thread,
});
yield* Ref.update(effects, (existing) => [
...existing,
pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
type: "initial",
messageId: command.messageId,
}),
]);
projection = yield* getProjectionWithPendingEvents(command.threadId, events);
}
const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
const dispatchMode = command.dispatchMode;
const sourcePlanProjection =
@@ -5702,6 +5771,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
case "thread.title.regeneration.complete":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
case "thread.model-selection.set":
@@ -10,6 +10,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -17,9 +18,11 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
import * as GitWorkflow from "../git/GitWorkflowService.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
@@ -33,6 +36,7 @@ import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ThreadLaunch from "./ThreadLaunchService.ts";
import * as ThreadManagement from "./ThreadManagementService.ts";
import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
const projectId = ProjectId.make("project:launch-test");
@@ -94,6 +98,9 @@ function makeHarness(options: HarnessOptions = {}) {
const generateBranchName = vi.fn(
options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })),
);
const generateThreadTitle = vi.fn(
options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
);
const externalServices = Layer.mergeAll(
Layer.succeed(ProjectService.ProjectService, {
create: () => Effect.die("unused"),
@@ -115,8 +122,7 @@ function makeHarness(options: HarnessOptions = {}) {
runForThread: runSetup,
}),
Layer.mock(TextGeneration.TextGeneration)({
generateThreadTitle:
options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
generateThreadTitle,
generateBranchName,
}),
ServerSettings.layerTest(options.serverSettings),
@@ -125,10 +131,31 @@ function makeHarness(options: HarnessOptions = {}) {
const launch = ThreadLaunch.layer.pipe(
Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
);
const projectedProjects = Layer.mock(ProjectionProjectRepository)({
getById: ({ projectId: requestedProjectId }) =>
Effect.succeed(
requestedProjectId === projectId
? Option.some({
projectId,
title: project.title,
workspaceRoot: project.workspaceRoot,
defaultModelSelection: project.defaultModelSelection,
scripts: project.scripts,
createdAt: project.createdAt,
updatedAt: project.updatedAt,
deletedAt: project.deletedAt,
})
: Option.none(),
),
});
const titleRegeneration = ThreadTitleRegeneration.layer.pipe(
Layer.provide(Layer.mergeAll(threadManagement, projectedProjects, externalServices)),
);
return {
layer: Layer.mergeAll(launch, threadManagement, outbox, database),
layer: Layer.mergeAll(launch, threadManagement, titleRegeneration, outbox, database),
createWorktree,
generateBranchName,
generateThreadTitle,
runSetup,
};
}
@@ -412,45 +439,191 @@ it.effect(
}),
);
it.effect("does not put optional title generation on the provisioning critical path", () =>
it.effect("arms durable title generation after accepting the first message", () =>
Effect.gen(function* () {
const titleStarted = yield* Deferred.make<void>();
const allowTitle = yield* Deferred.make<void>();
const setupEntered = yield* Deferred.make<void>();
const harness = makeHarness({
generateTitle: () =>
Deferred.succeed(titleStarted, undefined).pipe(
Effect.andThen(Deferred.await(allowTitle)),
Effect.as({ title: "Generated later" }),
),
runSetup: () =>
Deferred.succeed(setupEntered, undefined).pipe(Effect.as({ status: "no-script" as const })),
generateTitle: (input) =>
Effect.succeed({
title: input.previousTitle === undefined ? "Generated title" : "Regenerated title",
}),
});
yield* Effect.gen(function* () {
const launches = yield* ThreadLaunch.ThreadLaunchService;
const threads = yield* ThreadManagement.ThreadManagementService;
const input = launchInput({
command: "command:launch:title-independent",
thread: "thread:launch:title-independent",
message: "Generate my title slowly",
});
const outbox = yield* EffectOutbox.EffectOutboxV2;
const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
const input = {
...launchInput({
command: "command:launch:title-generation",
thread: "thread:launch:title-generation",
message: "Generate my title",
}),
title: "Generate my title",
generateTitle: true,
};
const launched = yield* launches.launch(input);
yield* Deferred.await(titleStarted);
yield* Deferred.await(setupEntered);
yield* waitUntil(() =>
threads
.getThreadProjection(launched.threadId)
.pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")),
const generationCommandId = CommandId.make("command:launch:title-generation:initial-message");
const projection = yield* threads.getThreadProjection(launched.threadId);
assert.equal(projection.thread.title, "Generate my title");
assert.equal(projection.thread.titleRegeneration?.requestId, generationCommandId);
assert.deepEqual(
(yield* outbox.listByCommandId(generationCommandId)).map((effect) => effect.request),
[
{
type: "thread-title.generate",
kind: { type: "initial", messageId: MessageId.make("Generate my title:id") },
},
],
);
yield* titleRegeneration.execute({
threadId: launched.threadId,
requestId: generationCommandId,
kind: { type: "initial", messageId: MessageId.make("Generate my title:id") },
});
const generated = yield* threads.getThreadProjection(launched.threadId);
assert.equal(generated.thread.title, "Generated title");
assert.deepEqual(
harness.generateThreadTitle.mock.calls[0]?.[0].modelSelection,
DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
);
const manualRequestId = CommandId.make("command:title-generation:manual");
yield* threads.dispatch({
type: "thread.metadata.update",
commandId: manualRequestId,
threadId: launched.threadId,
regenerateTitle: true,
});
assert.deepEqual(
(yield* outbox.listByCommandId(manualRequestId)).map((effect) => effect.request),
[{ type: "thread-title.generate", kind: { type: "regenerate" } }],
);
yield* titleRegeneration.execute({
threadId: launched.threadId,
requestId: manualRequestId,
kind: { type: "regenerate" },
});
const regenerated = yield* threads.getThreadProjection(launched.threadId);
assert.equal(regenerated.thread.title, "Regenerated title");
assert.equal(harness.generateThreadTitle.mock.calls[1]?.[0].previousTitle, "Generated title");
yield* threads.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make("command:title-generation:user-rename"),
threadId: launched.threadId,
title: "Keep my title",
});
const renamed = yield* threads.getThreadProjection(launched.threadId);
yield* TestClock.adjust(Duration.seconds(1));
yield* threads.dispatch({
type: "thread.title.regeneration.complete",
commandId: CommandId.make("command:title-generation:stale-completion"),
threadId: launched.threadId,
requestId: generationCommandId,
title: "Stale generated title",
});
const afterStaleCompletion = yield* threads.getThreadProjection(launched.threadId);
assert.equal(afterStaleCompletion.thread.title, "Keep my title");
assert.equal(
(yield* threads.getThreadProjection(launched.threadId)).thread.title,
"New thread",
DateTime.toEpochMillis(afterStaleCompletion.thread.updatedAt),
DateTime.toEpochMillis(renamed.thread.updatedAt),
);
yield* Deferred.succeed(allowTitle, undefined);
yield* waitUntil(() =>
threads
.getThreadProjection(launched.threadId)
.pipe(Effect.map((projection) => projection.thread.title === "Generated later")),
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("does not update a reused thread title when the initial message is rejected", () =>
Effect.gen(function* () {
const harness = makeHarness();
yield* Effect.gen(function* () {
const launches = yield* ThreadLaunch.ThreadLaunchService;
const threads = yield* ThreadManagement.ThreadManagementService;
const outbox = yield* EffectOutbox.EffectOutboxV2;
const threadId = ThreadId.make("thread:launch:reused-title-failure");
yield* threads.dispatch({
type: "thread.create",
commandId: CommandId.make("command:launch:reused-title-failure:create"),
threadId,
projectId,
title: "Original title",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdBy: "user",
creationSource: "web",
});
const commandId = CommandId.make("command:launch:reused-title-failure");
const failed = yield* launches
.launch({
...launchInput({
command: commandId,
thread: threadId,
message: "Generate a provisional title",
}),
reuseExistingThread: true,
title: "Generate a provisional title",
generateTitle: true,
modelSelection: {
instanceId: ProviderInstanceId.make("missing-provider"),
model: "missing-model",
},
})
.pipe(Effect.exit);
assert.isTrue(Exit.isFailure(failed));
const projection = yield* threads.getThreadProjection(threadId);
assert.equal(projection.thread.title, "Original title");
assert.isUndefined(projection.thread.titleRegeneration);
assert.isEmpty(projection.messages);
assert.isEmpty(yield* outbox.listByCommandId(CommandId.make(`${commandId}:initial-message`)));
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("generates an initial title for an attachment-only message", () =>
Effect.gen(function* () {
const harness = makeHarness();
yield* Effect.gen(function* () {
const launches = yield* ThreadLaunch.ThreadLaunchService;
const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
const messageId = MessageId.make("message:image-only");
const input = {
...launchInput({
command: "command:launch:image-only",
thread: "thread:launch:image-only",
}),
title: "Image: screenshot.png",
generateTitle: true,
initialMessage: {
messageId,
text: "",
attachments: [
{
type: "image" as const,
id: "attachment-image-only",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 128,
},
],
},
};
const launched = yield* launches.launch(input);
yield* titleRegeneration.execute({
threadId: launched.threadId,
requestId: CommandId.make("command:launch:image-only:initial-message"),
kind: { type: "initial", messageId },
});
assert.equal(harness.generateThreadTitle.mock.calls[0]?.[0].message, "");
assert.equal(
harness.generateThreadTitle.mock.calls[0]?.[0].attachments?.[0]?.name,
"screenshot.png",
);
}).pipe(Effect.provide(harness.layer));
}),
@@ -59,6 +59,7 @@ export interface ThreadLaunchInput {
readonly reuseExistingThread?: boolean;
readonly projectId: ProjectId;
readonly title: string;
readonly generateTitle?: boolean;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
@@ -198,34 +199,6 @@ export const make = Effect.gen(function* () {
),
);
if (input.title === "New thread" && input.initialMessage !== undefined) {
yield* textGeneration
.generateThreadTitle({
cwd: project.workspaceRoot,
message: input.initialMessage.text,
attachments: input.initialMessage.attachments,
modelSelection: input.modelSelection,
})
.pipe(
Effect.flatMap((result) =>
threads.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`${input.commandId}:title`),
threadId,
title: result.title,
}),
),
Effect.catchCause((cause) =>
Effect.logWarning("Thread title generation failed", {
commandId: input.commandId,
threadId,
cause,
}),
),
Effect.forkIn(preparationScope),
);
}
const initialMessage = input.initialMessage;
let branch =
input.workspaceStrategy.type === "worktree" &&
@@ -502,6 +475,7 @@ export const make = Effect.gen(function* () {
messageId,
text: input.initialMessage.text,
attachments: input.initialMessage.attachments,
...(input.generateTitle === true ? { titleSeed: input.title } : {}),
modelSelection: input.modelSelection,
dispatchMode: { type: "defer_start" },
createdBy: input.createdBy,
@@ -1,11 +1,21 @@
import { type ChatAttachment, CommandId, type ThreadId } from "@t3tools/contracts";
import {
type ChatAttachment,
CommandId,
type MessageId,
type ServerSettingsError,
type ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as ProjectService from "../project/ProjectService.ts";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import type { OrchestratorV2Error } from "./Orchestrator.ts";
import { ThreadManagementService } from "./ThreadManagementService.ts";
const MAX_REGENERATION_ATTACHMENTS = 4;
@@ -69,92 +79,116 @@ export function formatThreadTitleContext(
};
}
/**
* Reacts to thread.metadata-updated events that arm the titleRegeneration
* marker: generates a title from the thread's conversation and lands it via a
* follow-up metadata update (which clears the marker), or clears the marker
* explicitly when generation fails. Event-driven so every dispatch surface
* (ws, MCP, mobile) gets the same behavior.
*/
export const workerLive = Layer.effectDiscard(
Effect.gen(function* () {
const threads = yield* ThreadManagementService;
const projects = yield* ProjectService.ProjectService;
const textGeneration = yield* TextGeneration.TextGeneration;
const handledRequestIds = new Set<string>();
export class ThreadTitleRegenerationService extends Context.Service<
ThreadTitleRegenerationService,
{
readonly execute: (input: {
readonly threadId: ThreadId;
readonly requestId: CommandId;
readonly kind:
| { readonly type: "initial"; readonly messageId: MessageId }
| { readonly type: "regenerate" };
}) => Effect.Effect<
void,
OrchestratorV2Error | ProjectionRepositoryError | ServerSettingsError
>;
}
>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
const regenerate = Effect.fn("ThreadTitleRegenerationService.regenerate")(function* (
threadId: ThreadId,
requestId: CommandId,
) {
const projection = yield* threads.getThreadProjection(threadId);
if (projection.thread.titleRegeneration?.requestId !== requestId) {
return;
export const make = Effect.gen(function* () {
const threads = yield* ThreadManagementService;
const projects = yield* ProjectionProjectRepository;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const textGeneration = yield* TextGeneration.TextGeneration;
const complete = (input: {
readonly threadId: ThreadId;
readonly requestId: CommandId;
readonly title?: string;
}) =>
threads
.dispatch({
type: "thread.title.regeneration.complete",
commandId: CommandId.make(`${input.requestId}:title-complete`),
threadId: input.threadId,
requestId: input.requestId,
...(input.title === undefined ? {} : { title: input.title }),
})
.pipe(Effect.asVoid);
const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
"ThreadTitleRegenerationService.execute",
)(function* (input) {
const outcome:
| { readonly type: "stale" }
| { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
const projection = yield* threads.getThreadProjection(input.threadId);
if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
return { type: "stale" as const };
}
const project = yield* projects.getById(projection.thread.projectId);
const project = yield* projects.getById({ projectId: projection.thread.projectId });
if (Option.isNone(project)) {
return;
return { type: "complete" as const };
}
const context = formatThreadTitleContext(
projection.messages.filter((message) => !message.streaming),
);
if (context.message.length === 0) {
yield* threads.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`${requestId}:title-clear`),
threadId,
regenerateTitle: false,
});
return;
let context: {
readonly message: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
};
if (input.kind.type === "initial") {
const messageId = input.kind.messageId;
const message = projection.messages.find(
(candidate) => candidate.id === messageId && !candidate.streaming,
);
context =
message === undefined
? { message: "", attachments: [] }
: { message: message.text, attachments: message.attachments };
} else {
context = formatThreadTitleContext(
projection.messages.filter((message) => !message.streaming),
);
}
if (context.message.length === 0 && context.attachments.length === 0) {
return { type: "complete" as const };
}
const settings = yield* serverSettings.getSettings;
const result = yield* textGeneration.generateThreadTitle({
cwd: projection.thread.worktreePath ?? Option.getOrThrow(project).workspaceRoot,
cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
message: context.message,
attachments: context.attachments,
modelSelection: projection.thread.modelSelection,
...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
modelSelection: settings.textGenerationModelSelection,
});
yield* threads.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`${requestId}:title`),
threadId,
title: result.title,
});
});
yield* threads.streamDomainEvents.pipe(
Stream.runForEach((event) => {
if (event.type !== "thread.metadata-updated") {
return Effect.void;
}
const marker = event.payload.titleRegeneration;
if (marker === null || marker === undefined || handledRequestIds.has(marker.requestId)) {
return Effect.void;
}
handledRequestIds.add(marker.requestId);
return regenerate(event.threadId, marker.requestId).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Thread title regeneration failed", {
threadId: event.threadId,
requestId: marker.requestId,
const generatedTitle = result.title.trim();
return generatedTitle === "New thread" ||
(input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
? { type: "complete" as const }
: { type: "complete" as const, title: result.title };
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.interrupt
: Effect.logWarning("Thread title generation failed", {
threadId: input.threadId,
requestId: input.requestId,
cause,
}).pipe(
Effect.andThen(
threads
.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`${marker.requestId}:title-clear`),
threadId: event.threadId,
regenerateTitle: false,
})
.pipe(Effect.ignore),
),
),
),
Effect.forkDetach,
Effect.asVoid,
);
}),
Effect.forkScoped,
}).pipe(Effect.as({ type: "complete" as const })),
),
);
}),
);
if (outcome.type === "stale") {
return;
}
yield* complete({
...input,
...(outcome.title === undefined ? {} : { title: outcome.title }),
});
});
return ThreadTitleRegenerationService.of({ execute });
});
export const layer = Layer.effect(ThreadTitleRegenerationService, make);
@@ -4,6 +4,7 @@ import {
OrchestrationLayerLive,
} from "../orchestration/runtimeLayer.ts";
import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import { layer as projectServiceLayer } from "../project/ProjectService.ts";
import { layer as projectSetupScriptRunnerLayer } from "../project/ProjectSetupScriptRunner.ts";
import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts";
@@ -27,7 +28,7 @@ import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts"
import { layerFromProviderInstanceRegistry as providerAdapterRegistryLayerFromProviderInstances } from "./ProviderAdapterRegistry.ts";
import { layer as providerContinuationRequestsLayer } from "./ProviderContinuationRequests.ts";
import { workerLive as providerContinuationWorkerLive } from "./ProviderContinuationService.ts";
import { workerLive as threadTitleRegenerationWorkerLive } from "./ThreadTitleRegenerationService.ts";
import { layer as threadTitleRegenerationServiceLayer } from "./ThreadTitleRegenerationService.ts";
import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts";
import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts";
import { layer as providerRuntimeRecoveryLayer } from "./ProviderRuntimeRecoveryService.ts";
@@ -157,33 +158,6 @@ const runFinalizationServiceProvided = runFinalizationServiceLayer.pipe(
Layer.provide(Layer.merge(checkpointCaptureServiceProvided, projectionStoreLayer)),
);
const effectExecutorProvided = effectExecutorLayer.pipe(
Layer.provide(
Layer.mergeAll(
runFinalizationServiceProvided,
checkpointRollbackServiceProvided,
providerSessionManagerProvided,
providerTurnControlServiceProvided,
providerTurnStartServiceProvided,
runtimeRequestServiceProvided,
),
),
);
const effectWorkerProvided = effectWorkerLayer.pipe(
Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)),
);
const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
Layer.provide(
Layer.mergeAll(
effectWorkerProvided,
storesLayer,
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
),
),
);
const orchestratorProvided = orchestratorLayer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -191,7 +165,6 @@ const orchestratorProvided = orchestratorLayer.pipe(
commandPolicyLayer,
storesLayer,
eventSinkProvided,
effectWorkerProvided,
commandReceiptStoreProvided,
contextHandoffServiceProvided,
idAllocatorLayer,
@@ -237,8 +210,37 @@ const providerContinuationWorkerProvided = providerContinuationWorkerLive.pipe(
Layer.mergeAll(providerContinuationRequestsLayer, threadManagementProvided, idAllocatorLayer),
),
);
const threadTitleRegenerationWorkerProvided = threadTitleRegenerationWorkerLive.pipe(
Layer.provide(Layer.merge(threadManagementProvided, ProjectServiceLayerLive)),
const threadTitleRegenerationProvided = threadTitleRegenerationServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(threadManagementProvided, ProjectionProjectRepositoryLive, TextGeneration.layer),
),
);
const effectExecutorProvided = effectExecutorLayer.pipe(
Layer.provide(
Layer.mergeAll(
runFinalizationServiceProvided,
checkpointRollbackServiceProvided,
providerSessionManagerProvided,
providerTurnControlServiceProvided,
providerTurnStartServiceProvided,
runtimeRequestServiceProvided,
threadTitleRegenerationProvided,
),
),
);
const effectWorkerProvided = effectWorkerLayer.pipe(
Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)),
);
const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
Layer.provide(
Layer.mergeAll(
effectWorkerProvided,
storesLayer,
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
),
),
);
export const OrchestrationV2LayerLive = Layer.mergeAll(
@@ -254,7 +256,6 @@ export const OrchestrationV2LayerLive = Layer.mergeAll(
export const OrchestrationV2ProductionLayerLive = Layer.mergeAll(
OrchestrationLayerLive,
OrchestrationV2LayerLive,
threadTitleRegenerationWorkerProvided,
ProjectServiceLayerLive,
threadLaunchProvided,
threadLifecycleProvided,
@@ -108,6 +108,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
case "thread.title.regeneration.complete":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
case "thread.model-selection.set":
@@ -42,6 +42,7 @@ import { layer as providerTurnControlServiceLayer } from "../ProviderTurnControl
import { layer as providerTurnStartServiceLayer } from "../ProviderTurnStartService.ts";
import { layer as runExecutionServiceLayer } from "../RunExecutionService.ts";
import { layer as runFinalizationServiceLayer } from "../RunFinalizationService.ts";
import { ThreadTitleRegenerationService } from "../ThreadTitleRegenerationService.ts";
import {
layer as runtimePolicyLayer,
layerWithOverride as runtimePolicyLayerWithOverride,
@@ -334,6 +335,10 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
const runFinalizationServiceProvided = runFinalizationServiceLayer.pipe(
Layer.provide(Layer.merge(checkpointCaptureServiceProvided, storesLayer)),
);
const threadTitleRegenerationTestLayer = Layer.succeed(
ThreadTitleRegenerationService,
ThreadTitleRegenerationService.of({ execute: () => Effect.void }),
);
const effectExecutorProvided = effectExecutorLayer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -343,6 +348,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
providerTurnControlServiceProvided,
providerTurnStartServiceProvided,
runtimeRequestServiceProvided,
threadTitleRegenerationTestLayer,
),
),
);
@@ -355,7 +361,6 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
checkpointServiceProvided,
commandPolicyLayer,
contextHandoffServiceProvided,
effectWorkerProvided,
persistenceLayer,
registryLayer,
runtimeLayer,
+3
View File
@@ -1142,6 +1142,9 @@ const makeWsRpcLayer = (
: { reuseExistingThread: input.reuseExistingThread }),
projectId: input.projectId,
title: input.title,
...(input.generateTitle === undefined
? {}
: { generateTitle: input.generateTitle }),
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
+13 -33
View File
@@ -26,6 +26,7 @@ import {
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
deriveThreadActivityRun,
@@ -5232,26 +5233,18 @@ function ChatViewContent(props: ChatViewProps) {
clearComposerDraftContent(composerDraftTarget);
composerRef.current?.resetCursorState();
let firstComposerImageName: string | null = null;
if (composerImagesSnapshot.length > 0) {
const firstComposerImage = composerImagesSnapshot[0];
if (firstComposerImage) {
firstComposerImageName = firstComposerImage.name;
}
}
let titleSeed = trimmed;
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `Image: ${firstComposerImageName}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
titleSeed = formatElementContextLabel(composerElementContextsSnapshot[0]!);
} else {
titleSeed = "New thread";
}
}
const title = truncate(titleSeed);
const title = deriveThreadTitleSeed({
text: trimmed,
attachments: composerImagesSnapshot,
fallbackLabels: [
composerTerminalContextsSnapshot[0] === undefined
? null
: formatTerminalContextLabel(composerTerminalContextsSnapshot[0]),
composerElementContextsSnapshot[0] === undefined
? null
: formatElementContextLabel(composerElementContextsSnapshot[0]),
],
});
const threadCreateModelSelection = createModelSelection(
ctxSelectedModelSelection.instanceId,
ctxSelectedModel || activeProject.defaultModelSelection?.model || DEFAULT_MODEL,
@@ -5259,19 +5252,6 @@ function ChatViewContent(props: ChatViewProps) {
);
let failure: AtomCommandResult<unknown, unknown> | null = null;
// Auto-title from first message
if (isFirstMessage && isServerThread) {
const titleResult = await updateThreadMetadata({
environmentId,
input: {
threadId: threadIdForSend,
title,
},
});
if (titleResult._tag === "Failure") {
failure = titleResult;
}
}
if (failure === null && isServerThread) {
const settingsResult = await persistThreadSettingsForNextTurn({
@@ -231,6 +231,7 @@ describe("V2 environment commands", () => {
},
runtimeMode: "full-access",
interactionMode: "default",
titleSeed: "Implement the plan",
sourceProposedPlan: {
threadId: ThreadId.make("thread-plan"),
planId: PlanId.make("plan-1"),
@@ -242,6 +243,7 @@ describe("V2 environment commands", () => {
type: "message.dispatch",
commandId: "implement-plan",
threadId: v2ThreadId,
titleSeed: "Implement the plan",
sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
dispatchMode: { type: "start_immediately" },
});
@@ -264,6 +266,7 @@ describe("V2 environment commands", () => {
},
runtimeMode: "full-access",
interactionMode: "default",
titleSeed: "Continue here",
bootstrap: {
createThread: {
projectId: ProjectId.make("project-1"),
@@ -280,6 +283,8 @@ describe("V2 environment commands", () => {
expect(launches[0]).toMatchObject({
threadId: v2ThreadId,
title: "Continue here",
generateTitle: true,
workspaceStrategy: {
type: "existing_worktree",
worktreePath: "/workspace/project-worktrees/feature",
@@ -528,7 +528,8 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
threadId: input.threadId,
...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
projectId: thread.projectId,
title: thread.title,
title: input.titleSeed ?? thread.title,
generateTitle: input.titleSeed !== undefined,
modelSelection: input.modelSelection ?? thread.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
@@ -587,6 +588,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
messageId: input.message.messageId,
text: input.message.text,
attachments,
...(input.titleSeed === undefined || projection.messages.length > 0
? {}
: { titleSeed: input.titleSeed }),
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
dispatchMode,
@@ -1,2 +1,3 @@
export * from "./commands.ts";
export * from "./projects.ts";
export * from "./threadTitle.ts";
@@ -0,0 +1,47 @@
import { describe, expect, it } from "@effect/vitest";
import { deriveThreadTitleSeed } from "./threadTitle.ts";
describe("deriveThreadTitleSeed", () => {
it("prefers normalized message text", () => {
expect(
deriveThreadTitleSeed({
text: " Investigate\n login failures ",
attachments: [{ name: "login-error.png" }],
fallbackLabels: ["Terminal 1"],
}),
).toBe("Investigate login failures");
});
it("uses the first attachment name when text is empty", () => {
expect(
deriveThreadTitleSeed({
text: " \n ",
attachments: [{ name: "login-error.png" }, { name: "other.png" }],
}),
).toBe("Image: login-error.png");
});
it("uses the first non-empty fallback label after text and attachments", () => {
expect(
deriveThreadTitleSeed({
text: "",
attachments: [],
fallbackLabels: [null, " ", "Terminal 1"],
}),
).toBe("Terminal 1");
});
it("falls back to New thread", () => {
expect(deriveThreadTitleSeed({ text: "", attachments: [] })).toBe("New thread");
});
it("applies the shared title truncation", () => {
expect(
deriveThreadTitleSeed({
text: "x".repeat(60),
attachments: [],
}),
).toBe(`${"x".repeat(50)}...`);
});
});
@@ -0,0 +1,32 @@
import { truncate } from "@t3tools/shared/String";
export interface ThreadTitleSeedInput {
readonly text: string;
readonly attachments: ReadonlyArray<{ readonly name: string }>;
readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;
}
function normalizeTitleSeed(value: string): string {
return value.trim().replace(/\s+/gu, " ");
}
export function deriveThreadTitleSeed(input: ThreadTitleSeedInput): string {
const text = normalizeTitleSeed(input.text);
if (text.length > 0) {
return truncate(text);
}
const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
if (attachmentName.length > 0) {
return truncate(`Image: ${attachmentName}`);
}
for (const label of input.fallbackLabels ?? []) {
const normalized = normalizeTitleSeed(label ?? "");
if (normalized.length > 0) {
return truncate(normalized);
}
}
return "New thread";
}
+10
View File
@@ -1939,6 +1939,13 @@ export const OrchestrationV2Command = Schema.Union([
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
}),
Schema.Struct({
type: Schema.Literal("thread.title.regeneration.complete"),
commandId: CommandId,
threadId: ThreadId,
requestId: CommandId,
title: Schema.optional(TrimmedNonEmptyString),
}),
Schema.Struct({
type: Schema.Literal("thread.runtime-mode.set"),
commandId: CommandId,
@@ -1972,6 +1979,8 @@ export const OrchestrationV2Command = Schema.Union([
messageId: MessageId,
text: Schema.String,
attachments: Schema.Array(ChatAttachment),
/** Seed the temporary title and generate a durable replacement for the first message. */
titleSeed: Schema.optional(TrimmedNonEmptyString),
modelSelection: Schema.optional(ModelSelection),
sourcePlanRef: Schema.optional(Schema.Struct({ threadId: ThreadId, planId: PlanId })),
dispatchMode: Schema.Union([
@@ -2179,6 +2188,7 @@ export const OrchestrationV2ThreadLaunchInput = Schema.Struct({
reuseExistingThread: Schema.optional(Schema.Boolean),
projectId: ProjectId,
title: TrimmedNonEmptyString,
generateTitle: Schema.optional(Schema.Boolean),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,