Compare commits

..
69 changed files with 1192 additions and 1535 deletions

No files matched your search

+44
View File
@@ -28,6 +28,50 @@ Start Metro for the dev client:
vp run dev:client
```
### Android
Local Android builds require Android Studio, JDK 17, and an Android SDK. On an Apple Silicon Mac,
the following setup installs the API 36.1 emulator used to exercise promoted ongoing notifications
(Android Live Updates):
```bash
brew install --cask android-studio android-commandlinetools
brew install openjdk@17
export JAVA_HOME="/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"
export ANDROID_HOME="$HOME/Library/Android/sdk"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/emulator:$ANDROID_HOME/platform-tools:$PATH"
yes | sdkmanager --sdk_root="$ANDROID_HOME" --licenses
sdkmanager --sdk_root="$ANDROID_HOME" \
"platform-tools" \
"emulator" \
"platforms;android-36" \
"build-tools;36.0.0" \
"system-images;android-36.1;google_apis;arm64-v8a"
echo no | avdmanager create avd \
--name T3Code_API_36_1 \
--package "system-images;android-36.1;google_apis;arm64-v8a" \
--device pixel_9
```
Add the four exports to your shell profile, start `T3Code_API_36_1` from Android Studio's Device
Manager, then build and run the development client:
```bash
vp run android:dev
```
The first native build may need roughly 20 GB of free space for SDK, NDK, Gradle, and emulator
caches. In a development build on Android, Settings includes an **Android Live Update · Mock**
section for exercising the active-agents and needs-attention states without the relay.
The mock preview is entirely local. It does not require T3 Connect, a hosted relay, Clerk
configuration, Firebase/FCM credentials, or a connected T3 Code server. Remote delivery and
background reconciliation require the separate T3 Connect infrastructure.
Build and run the local iOS dev client:
```bash
+1
View File
@@ -315,6 +315,7 @@ const config: ExpoConfig = {
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
"./plugins/withAndroidGradleHeap.cjs",
"./plugins/withAndroidUnifiedNdk.cjs",
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
@@ -0,0 +1,20 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.agentliveupdate'
version = '0.0.0'
android {
namespace 'expo.modules.t3agentliveupdate'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
implementation 'androidx.core:core:1.17.0'
}
@@ -0,0 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
<application>
<receiver
android:name="expo.modules.t3agentliveupdate.AgentLiveUpdateDismissReceiver"
android:exported="false" />
</application>
</manifest>
@@ -0,0 +1,11 @@
package expo.modules.t3agentliveupdate
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
internal class AgentLiveUpdateDismissReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
AgentLiveUpdateManager(context.applicationContext).cancel()
}
}
@@ -0,0 +1,194 @@
package expo.modules.t3agentliveupdate
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
internal class AgentLiveUpdateManager(private val context: Context) {
private val notificationManager = context.getSystemService(NotificationManager::class.java)
private val notificationManagerCompat = NotificationManagerCompat.from(context)
fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
CHANNEL_ID,
"Agent live updates",
NotificationManager.IMPORTANCE_LOW,
).apply {
description = "Ongoing status for active T3 Code agents"
enableVibration(false)
lockscreenVisibility = Notification.VISIBILITY_PRIVATE
setShowBadge(false)
setSound(null, null)
}
notificationManager.createNotificationChannel(channel)
}
fun show(snapshot: LiveUpdateSnapshot): Map<String, Any> {
ensureChannel()
checkNotificationPermission()
val title = snapshot.title.trim().ifEmpty { "T3 Code agents" }.take(MAX_TITLE_LENGTH)
val summary = snapshot.summary.trim().ifEmpty { "Agent activity is in progress" }
val expandedText = snapshot.lines
.asSequence()
.map(String::trim)
.filter(String::isNotEmpty)
.take(MAX_VISIBLE_LINES)
.joinToString("\n")
.ifEmpty { summary }
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.t3_agent_live_update)
.setContentTitle(title)
.setContentText(summary)
.setStyle(NotificationCompat.BigTextStyle().bigText(expandedText))
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setColorized(false)
.setRequestPromotedOngoing(true)
.setWhen(System.currentTimeMillis())
.setShowWhen(true)
.setDeleteIntent(dismissPendingIntent())
.addAction(
NotificationCompat.Action.Builder(
0,
"Stop",
dismissPendingIntent(),
).build(),
)
contentPendingIntent()?.let(builder::setContentIntent)
snapshot.shortCriticalText
.trim()
.take(MAX_SHORT_CRITICAL_TEXT_LENGTH)
.takeIf(String::isNotEmpty)
?.let(builder::setShortCriticalText)
val notification = builder.build()
notificationManagerCompat.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification)
return status()
}
fun cancel(): Map<String, Any> {
notificationManagerCompat.cancel(NOTIFICATION_TAG, NOTIFICATION_ID)
return status(null)
}
fun status(): Map<String, Any> = status(activeNotification())
fun openPromotionSettings(): Map<String, Any> {
val promotionIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
Intent(Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS)
} else {
appNotificationSettingsIntent()
}
promotionIntent
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(promotionIntent)
} catch (_: ActivityNotFoundException) {
context.startActivity(appNotificationSettingsIntent())
}
return status()
}
private fun status(notification: Notification?): Map<String, Any> {
val supportsPromotion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA
val promotable = supportsPromotion && notification?.hasPromotableCharacteristics() == true
val promoted = supportsPromotion &&
notification != null &&
notification.flags.and(Notification.FLAG_PROMOTED_ONGOING) != 0
val channelImportance = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.getNotificationChannel(CHANNEL_ID)?.importance
?: NotificationManager.IMPORTANCE_UNSPECIFIED
} else {
NotificationManager.IMPORTANCE_UNSPECIFIED
}
return mapOf(
"apiLevel" to Build.VERSION.SDK_INT,
"supportsPromotion" to supportsPromotion,
"notificationsEnabled" to notificationManagerCompat.areNotificationsEnabled(),
"canPostPromotedNotifications" to (
supportsPromotion && notificationManagerCompat.canPostPromotedNotifications()
),
"channelImportance" to channelImportance,
"active" to (notification != null),
"promotable" to promotable,
"promoted" to promoted,
)
}
private fun activeNotification(): Notification? = notificationManagerCompat.activeNotifications
.firstOrNull { it.tag == NOTIFICATION_TAG && it.id == NOTIFICATION_ID }
?.notification
private fun checkNotificationPermission() {
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
throw SecurityException("Notification permission is required to show an agent Live Update.")
}
}
private fun dismissPendingIntent(): PendingIntent {
val intent = Intent(context, AgentLiveUpdateDismissReceiver::class.java).apply {
action = ACTION_DISMISS
}
return PendingIntent.getBroadcast(
context,
DISMISS_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
private fun contentPendingIntent(): PendingIntent? {
val intent =
context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return PendingIntent.getActivity(
context,
CONTENT_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
private fun appNotificationSettingsIntent(): Intent =
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
private companion object {
const val CHANNEL_ID = "t3_agent_live_updates"
const val NOTIFICATION_TAG = "t3-agent-live-update"
const val NOTIFICATION_ID = 44_001
const val ACTION_DISMISS = "com.t3tools.agentliveupdate.action.DISMISS"
const val DISMISS_REQUEST_CODE = 44_002
const val CONTENT_REQUEST_CODE = 44_003
const val MAX_VISIBLE_LINES = 3
const val MAX_TITLE_LENGTH = 80
const val MAX_SHORT_CRITICAL_TEXT_LENGTH = 7
}
}
@@ -0,0 +1,18 @@
package expo.modules.t3agentliveupdate
import expo.modules.kotlin.records.Field
import expo.modules.kotlin.records.Record
internal class LiveUpdateSnapshot : Record {
@Field
val title: String = ""
@Field
val summary: String = ""
@Field
val lines: List<String> = emptyList()
@Field
val shortCriticalText: String = ""
}
@@ -0,0 +1,38 @@
package expo.modules.t3agentliveupdate
import android.content.Context
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3AgentLiveUpdateModule : Module() {
private val context: Context
get() = requireNotNull(appContext.reactContext) {
"T3AgentLiveUpdate requires an active React context."
}
override fun definition() = ModuleDefinition {
Name("T3AgentLiveUpdate")
AsyncFunction("ensureChannel") {
manager().apply { ensureChannel() }.status()
}
AsyncFunction("getStatus") {
manager().status()
}
AsyncFunction("show") { snapshot: LiveUpdateSnapshot ->
manager().show(snapshot)
}
AsyncFunction("cancel") {
manager().cancel()
}
AsyncFunction("openPromotionSettings") {
manager().openPromotionSettings()
}
}
private fun manager() = AgentLiveUpdateManager(context.applicationContext)
}
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M8,5.5L1.5,12 8,18.5 9.4,17.1 4.3,12 9.4,6.9zM16,5.5L14.6,6.9 19.7,12 14.6,17.1 16,18.5 22.5,12z" />
</vector>
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"]
}
}
@@ -0,0 +1,12 @@
{
"name": "@t3tools/mobile-agent-live-update-native",
"version": "0.0.0",
"private": true,
"expo-module": {
"android": {
"modules": [
"expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"
]
}
}
}
@@ -0,0 +1,36 @@
const { withProjectBuildGradle } = require("expo/config-plugins");
const BLOCK_START = "// @generated by withAndroidUnifiedNdk";
const BLOCK_END = "// @end withAndroidUnifiedNdk";
const BLOCK = `${BLOCK_START}
// Expo libraries that do not declare an NDK version otherwise fall back to
// Android Gradle Plugin's default. React Native declares a newer revision,
// which makes clean local builds download and retain both multi-gigabyte NDKs.
subprojects { subproject ->
subproject.plugins.withId("com.android.application") {
subproject.android.ndkVersion = rootProject.ext.ndkVersion
}
subproject.plugins.withId("com.android.library") {
subproject.android.ndkVersion = rootProject.ext.ndkVersion
}
}
${BLOCK_END}`;
module.exports = function withAndroidUnifiedNdk(config) {
return withProjectBuildGradle(config, (nextConfig) => {
if (nextConfig.modResults.language !== "groovy") {
throw new Error("withAndroidUnifiedNdk requires a Groovy Android project build file.");
}
const generatedBlock = new RegExp(
`${BLOCK_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${BLOCK_END.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
)}\\n?`,
"g",
);
const contents = nextConfig.modResults.contents.replace(generatedBlock, "").trimEnd();
nextConfig.modResults.contents = `${contents}\n\n${BLOCK}\n`;
return nextConfig;
});
};
@@ -0,0 +1,96 @@
import { requireOptionalNativeModule } from "expo";
import { Platform } from "react-native";
const MODULE_NAME = "T3AgentLiveUpdate";
export interface AndroidLiveUpdateStatus {
readonly apiLevel: number;
readonly supportsPromotion: boolean;
readonly notificationsEnabled: boolean;
readonly canPostPromotedNotifications: boolean;
readonly channelImportance: number;
readonly active: boolean;
readonly promotable: boolean;
readonly promoted: boolean;
}
interface AndroidLiveUpdateSnapshot {
readonly title: string;
readonly summary: string;
readonly lines: ReadonlyArray<string>;
readonly shortCriticalText: string;
}
interface AndroidLiveUpdateNativeModule {
readonly ensureChannel: () => Promise<AndroidLiveUpdateStatus>;
readonly getStatus: () => Promise<AndroidLiveUpdateStatus>;
readonly show: (snapshot: AndroidLiveUpdateSnapshot) => Promise<AndroidLiveUpdateStatus>;
readonly cancel: () => Promise<AndroidLiveUpdateStatus>;
readonly openPromotionSettings: () => Promise<AndroidLiveUpdateStatus>;
}
export type AndroidLiveUpdateMockKind = "working" | "attention";
const MOCK_SNAPSHOTS: Record<AndroidLiveUpdateMockKind, AndroidLiveUpdateSnapshot> = {
working: {
title: "3 agents working",
summary: "T3 Code is making progress",
lines: [
"● Implementing Android Live Updates",
"● Running the mobile typecheck",
"◌ Reviewing recent agent changes",
],
shortCriticalText: "3",
},
attention: {
title: "1 agent needs attention",
summary: "Approval is required to continue",
lines: [
"! Waiting for your approval",
"● Android validation is still running",
"● Two agents continue in the background",
],
shortCriticalText: "Action",
},
};
function resolveNativeModule(): AndroidLiveUpdateNativeModule | null {
if (Platform.OS !== "android") return null;
try {
return requireOptionalNativeModule<AndroidLiveUpdateNativeModule>(MODULE_NAME);
} catch {
return null;
}
}
function requireNativeLiveUpdateModule(): AndroidLiveUpdateNativeModule {
const module = resolveNativeModule();
if (module) return module;
throw new Error("Rebuild the Android development client to install the Live Update module.");
}
export function hasAndroidLiveUpdateModule(): boolean {
return resolveNativeModule() !== null;
}
export async function ensureAndroidLiveUpdateChannel(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().ensureChannel();
}
export async function getAndroidLiveUpdateStatus(): Promise<AndroidLiveUpdateStatus | null> {
return resolveNativeModule()?.getStatus() ?? null;
}
export async function showAndroidLiveUpdateMock(
kind: AndroidLiveUpdateMockKind,
): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().show(MOCK_SNAPSHOTS[kind]);
}
export async function cancelAndroidLiveUpdateMock(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().cancel();
}
export async function openAndroidLiveUpdatePromotionSettings(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().openPromotionSettings();
}
@@ -0,0 +1,130 @@
import * as Notifications from "expo-notifications";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, AppState, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import {
cancelAndroidLiveUpdateMock,
ensureAndroidLiveUpdateChannel,
getAndroidLiveUpdateStatus,
hasAndroidLiveUpdateModule,
openAndroidLiveUpdatePromotionSettings,
showAndroidLiveUpdateMock,
type AndroidLiveUpdateMockKind,
type AndroidLiveUpdateStatus,
} from "../agent-awareness/androidLiveUpdate";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
export function AndroidLiveUpdatePreviewSection() {
const [status, setStatus] = useState<AndroidLiveUpdateStatus | null>(null);
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const moduleAvailable = hasAndroidLiveUpdateModule();
const refreshStatus = useCallback(async () => {
const nextStatus = await getAndroidLiveUpdateStatus();
setStatus(nextStatus);
}, []);
useEffect(() => {
void refreshStatus();
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") void refreshStatus();
});
return () => subscription.remove();
}, [refreshStatus]);
const run = useCallback(async (operation: () => Promise<AndroidLiveUpdateStatus>) => {
if (busyRef.current) return;
busyRef.current = true;
setBusy(true);
try {
setStatus(await operation());
} catch (cause) {
Alert.alert(
"Live Update preview unavailable",
cause instanceof Error ? cause.message : "Could not update the mock notification.",
);
} finally {
busyRef.current = false;
setBusy(false);
}
}, []);
const showMock = useCallback(
(kind: AndroidLiveUpdateMockKind) => {
void run(async () => {
await ensureAndroidLiveUpdateChannel();
const currentPermission = await Notifications.getPermissionsAsync();
const permission = currentPermission.granted
? currentPermission
: await Notifications.requestPermissionsAsync();
if (!permission.granted) {
throw new Error("Allow notifications to display the Android Live Update preview.");
}
return showAndroidLiveUpdateMock(kind);
});
},
[run],
);
const statusLabel = useMemo(
() => formatStatus(status, moduleAvailable),
[moduleAvailable, status],
);
const settingsValue = status?.canPostPromotedNotifications ? "Allowed" : "Review";
return (
<View className="gap-3">
<SettingsSection title="Android Live Update · Mock">
<SettingsRow
disabled={busy || !moduleAvailable}
icon="bolt.circle"
label="Show Active Agents"
onPress={() => showMock("working")}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="exclamationmark.triangle"
label="Show Needs Attention"
onPress={() => showMock("attention")}
/>
<SettingsRow
disabled={busy || !moduleAvailable || !status?.active}
icon="stop.fill"
label="End Mock Update"
onPress={() => void run(cancelAndroidLiveUpdateMock)}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="gearshape"
label="Promotion Settings"
value={settingsValue}
onPress={() => void run(openAndroidLiveUpdatePromotionSettings)}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
{statusLabel} Mock data only; relay and FCM delivery are intentionally deferred.
</Text>
</View>
);
}
function formatStatus(status: AndroidLiveUpdateStatus | null, moduleAvailable: boolean): string {
if (!moduleAvailable) return "Rebuild the Android development client to enable this preview.";
if (!status) return "Checking Android notification capabilities.";
if (!status.notificationsEnabled) return "Notification access is currently disabled.";
if (status.active && status.promoted) return "A promoted Live Update is active.";
if (status.active && status.promotable) {
return status.canPostPromotedNotifications
? "A promotable ongoing notification is active."
: "The ongoing notification is active, but promotion access is disabled.";
}
if (!status.supportsPromotion) {
return "This device will use the standard ongoing-notification fallback.";
}
return status.canPostPromotedNotifications
? "This device allows promoted Live Updates."
: "Open Promotion Settings to allow promoted Live Updates.";
}
@@ -38,6 +38,7 @@ import { runtime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { AndroidLiveUpdatePreviewSection } from "./AndroidLiveUpdatePreviewSection";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
@@ -125,6 +126,8 @@ function LocalSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>
@@ -508,6 +511,8 @@ function ConfiguredSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>
@@ -65,9 +65,6 @@ export interface ThreadDetailScreenProps {
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
readonly activeThreadBusy: boolean;
readonly hasMoreOlderActivities: boolean;
readonly loadingOlderActivities: boolean;
readonly onLoadOlderActivities: () => void;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -425,9 +422,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
hasMoreOlder={props.hasMoreOlderActivities}
loadingOlder={props.loadingOlderActivities}
onLoadOlder={props.onLoadOlderActivities}
/>
</View>
) : (
@@ -139,10 +139,6 @@ export interface ThreadFeedProps {
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Older history beyond the live activity window can be lazy-loaded on scroll-up. */
readonly hasMoreOlder?: boolean;
readonly loadingOlder?: boolean;
readonly onLoadOlder?: () => void;
}
function MessageAttachmentImage(props: {
@@ -1463,15 +1459,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
? props.latestTurn.turnId
: null;
// Reaching the top (oldest) lazy-loads older history. The hook keys an
// in-flight guard by thread, so repeated fires during scroll coalesce.
const { hasMoreOlder, loadingOlder, onLoadOlder } = props;
const onStartReachedOlderHistory = useCallback(() => {
if (hasMoreOlder && !loadingOlder) {
onLoadOlder?.();
}
}, [hasMoreOlder, loadingOlder, onLoadOlder]);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = props.latestTurn;
@@ -1764,15 +1751,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
onStartReached={onStartReachedOlderHistory}
onStartReachedThreshold={0.5}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets && !loadingOlder ? null : (
<View style={{ height: usesNativeAutomaticInsets ? undefined : topContentInset }}>
{loadingOlder ? <ActivityIndicator style={{ marginTop: 8 }} /> : null}
</View>
)
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
}
contentContainerStyle={{
paddingTop: 12,
@@ -1780,24 +1761,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
/>
</View>
{props.feed.length === 0 && hasMoreOlder ? (
// The window can derive zero visible entries while older history
// exists — without scrollable content `onStartReached` can never
// fire, so give the user an explicit affordance instead of the
// empty-state placeholder.
<View style={StyleSheet.absoluteFill}>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
{loadingOlder ? (
<ActivityIndicator />
) : (
<TouchableOpacity accessibilityRole="button" onPress={() => onLoadOlder?.()}>
<Text className="text-sm text-muted-foreground">Load older history</Text>
</TouchableOpacity>
)}
</View>
</View>
) : null}
{props.feed.length === 0 && !hasMoreOlder && props.contentPresentation.kind === "ready" ? (
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
title="No conversation yet"
@@ -194,9 +194,7 @@ function ThreadRouteContent(
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
// Derive pending requests from the FULL loaded set (older pages + live
// window) so a prompt the user scrolled back to load still surfaces.
const requests = useSelectedThreadRequests(composer.mergedActivities);
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const navigation = useNavigation();
const params = props.route.params;
@@ -769,9 +767,6 @@ function ThreadRouteContent(
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
activeThreadBusy={composer.activeThreadBusy}
hasMoreOlderActivities={composer.hasMoreOlderActivities}
loadingOlderActivities={composer.loadingOlderActivities}
onLoadOlderActivities={composer.onLoadOlderActivities}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -1,11 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import {
ApprovalRequestId,
type OrchestrationThreadActivity,
type ProviderApprovalDecision,
} from "@t3tools/contracts";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -57,18 +53,7 @@ function setUserInputDraftCustomAnswer(
});
}
/**
* Pending approval / user-input requests for the selected thread.
*
* `activities` should be the FULL loaded set (lazy-loaded older pages + the
* windowed live view, i.e. `useThreadComposerState().mergedActivities`): the
* detail snapshot windows activities to the most recent page, so deriving from
* `selectedThread.activities` alone would hide a prompt the user scrolled back
* to load. Falls back to the live window when not provided. Deriving from the
* merged set is sound — resolutions are always newer than their requests, so a
* loaded request whose resolution exists always has that resolution loaded too.
*/
export function useSelectedThreadRequests(activities?: ReadonlyArray<OrchestrationThreadActivity>) {
export function useSelectedThreadRequests() {
const respondToApproval = useAtomCommand(
threadEnvironment.respondToApproval,
"thread approval response",
@@ -85,20 +70,16 @@ export function useSelectedThreadRequests(activities?: ReadonlyArray<Orchestrati
null,
);
const requestActivities = activities ?? selectedThread?.activities ?? null;
const activePendingApprovals = useMemo(
() => (requestActivities ? derivePendingApprovals(requestActivities) : []),
[requestActivities],
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
[selectedThread],
);
// The derivations sort ascending by createdAt; surface the NEWEST open
// request. With lazy-loaded older pages in the set, index 0 could be an
// ancient dangling request hijacking the prompt for the current one.
const activePendingApproval = activePendingApprovals.at(-1) ?? null;
const activePendingApproval = activePendingApprovals[0] ?? null;
const activePendingUserInputs = useMemo(
() => (requestActivities ? derivePendingUserInputs(requestActivities) : []),
[requestActivities],
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
[selectedThread],
);
const activePendingUserInput = activePendingUserInputs.at(-1) ?? null;
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
? (userInputDraftsByRequestKey[
@@ -6,17 +6,11 @@ import {
MessageId,
type EnvironmentId,
type ModelSelection,
type OrchestrationThreadActivity,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import {
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
@@ -42,15 +36,11 @@ import {
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
import { orchestrationEnvironment } from "../state/orchestration";
import { useSelectedThreadDetail } from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
export function appendReviewCommentToDraft(input: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -99,56 +89,9 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
// ── Older-history lazy-load (shared engine; see useOlderThreadActivities) ──
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities`); older pages are fetched on demand and prepended.
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const selectedEnvironmentIdForActivities = selectedThreadShell?.environmentId ?? null;
const selectedThreadIdForActivities = selectedThreadShell?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (selectedEnvironmentIdForActivities === null || selectedThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: selectedEnvironmentIdForActivities,
input: { threadId: selectedThreadIdForActivities, ...cursor },
});
if (result._tag !== "Success") {
// Surface real failures (a spinner that quietly gives up reads as
// missing history); keep `hasMore` so scrolling back retries.
if (!isAtomCommandInterrupted(result)) {
setPendingConnectionError("Could not load older thread history.");
}
return null;
}
return result.value;
},
[selectedEnvironmentIdForActivities, selectedThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities,
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: onLoadOlderActivities,
} = useOlderThreadActivities({
threadKey: selectedThreadShell
? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}`
: null,
liveActivities: selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: selectedThreadDetail?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const selectedThreadFeed = useMemo(
() =>
selectedThreadDetail
? buildThreadFeed({ ...selectedThreadDetail, activities: mergedActivities })
: [],
[selectedThreadDetail, mergedActivities],
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
@@ -356,13 +299,6 @@ export function useThreadComposerState() {
runtimeMode,
interactionMode,
activeThreadBusy,
// Lazy-loaded older pages + the live window — the full loaded activity set.
// Request derivations must run over this (not the windowed live set alone)
// so prompts pulled in by scroll-up still surface, matching web.
mergedActivities,
hasMoreOlderActivities,
loadingOlderActivities,
onLoadOlderActivities,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,
@@ -77,8 +77,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -187,8 +185,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -272,8 +268,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -342,8 +336,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -397,8 +389,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
+1 -3
View File
@@ -337,9 +337,7 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
// Project resolution only reads `.projects`; the command read model returns the
// same shape without loading the heavy per-thread activity/message tables.
return yield* projectionSnapshotQuery.getCommandReadModel();
return yield* projectionSnapshotQuery.getSnapshot();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
@@ -201,7 +201,6 @@ describe("OrchestrationEngine", () => {
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provide(
@@ -342,7 +342,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
createdAt: "2026-02-24T00:00:06.000Z",
},
],
hasMoreActivities: false,
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -975,8 +974,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
// Well under the window — nothing older to lazy-load.
assert.equal(threadDetail.value.hasMoreActivities, false);
}
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
@@ -1156,254 +1153,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect(
"windows thread-detail activities to the most recent 500 and pages older on demand",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
)
VALUES (
'project-1', 'Project 1', '/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
)
VALUES (
'thread-1', 'project-1', 'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 0, 0, 0,
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
)
`;
// 600 activities (sequence 1..600); the detail load must return only the
// most recent 500 (sequence 101..600), re-sorted ascending for display.
const total = 600;
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`activity-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`act-${seq}`}, '{}', ${seq},
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
const activities = threadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "act-101");
assert.equal(activities[0]?.sequence, 101);
assert.equal(activities.at(-1)?.summary, "act-600");
// 600 > window, so the client is told older history can be lazy-loaded.
assert.equal(threadDetail.value.hasMoreActivities, true);
}
// Lazy-load the page immediately older than the windowed view (cursor =
// oldest loaded sequence, 101): sequences 1..100, ascending, no more left.
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 101,
limit: 500,
});
assert.equal(olderPage.activities.length, 100);
assert.equal(olderPage.activities[0]?.summary, "act-1");
assert.equal(olderPage.activities.at(-1)?.summary, "act-100");
assert.equal(olderPage.hasMore, false);
// A bounded page returns the newest `limit` of the older set and reports
// that more remain (sequences 401..600, with 1..400 still older).
const boundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 601,
limit: 200,
});
assert.equal(boundedPage.activities.length, 200);
assert.equal(boundedPage.activities[0]?.summary, "act-401");
assert.equal(boundedPage.activities.at(-1)?.summary, "act-600");
assert.equal(boundedPage.hasMore, true);
yield* sql`DELETE FROM projection_thread_activities`;
// Legacy rows may not have a sequence. They are still windowed in the
// detail load and must remain pageable by the deterministic created/id
// ordering used by the snapshot query.
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`unsequenced-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`legacy-act-${seq}`}, '{}', NULL,
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const legacyThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
assert.equal(legacyThreadDetail._tag, "Some");
if (legacyThreadDetail._tag === "Some") {
const activities = legacyThreadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "legacy-act-101");
assert.equal(activities[0]?.sequence, undefined);
assert.equal(activities.at(-1)?.summary, "legacy-act-600");
const legacyOlderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: activities[0]?.createdAt ?? "2026-04-01T00:01:00.000Z",
beforeActivityId: activities[0]?.id ?? asEventId("unsequenced-0101"),
limit: 500,
});
assert.equal(legacyOlderPage.activities.length, 100);
assert.equal(legacyOlderPage.activities[0]?.summary, "legacy-act-1");
assert.equal(legacyOlderPage.activities.at(-1)?.summary, "legacy-act-100");
assert.equal(legacyOlderPage.hasMore, false);
}
const legacyBoundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: "2026-04-01T00:01:00.000Z",
beforeActivityId: asEventId("unsequenced-0601"),
limit: 200,
});
assert.equal(legacyBoundedPage.activities.length, 200);
assert.equal(legacyBoundedPage.activities[0]?.summary, "legacy-act-401");
assert.equal(legacyBoundedPage.activities.at(-1)?.summary, "legacy-act-600");
assert.equal(legacyBoundedPage.hasMore, true);
}),
);
it.effect("unsequenced cursor reaches all older rows without stranding sequenced ones", () =>
// Regression for the "unsequenced cursor hides sequenced history" concern:
// sequenced rows always sort newer than NULL-sequence (legacy) rows, so when
// the oldest loaded row is unsequenced every sequenced row is already in the
// window — the `sequence IS NULL` cursor can't strand sequenced rows.
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
) VALUES (
'project-1', 'Project 1', '/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
) VALUES (
'thread-1', 'project-1', 'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 0, 0, 0,
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
)
`;
// 600 legacy unsequenced rows (older) + 3 sequenced rows (newer). The
// window keeps the 3 sequenced + the most-recent 497 unsequenced, so the
// oldest loaded row is unsequenced and 103 older unsequenced remain.
yield* Effect.forEach(
Array.from({ length: 600 }, (_u, index) => index + 1),
(n) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
) VALUES (
${`unseq-${String(n).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`unseq-${n}`}, '{}', NULL,
${`2026-04-01T00:00:01.${String(n).padStart(3, "0")}Z`}
)
`,
{ discard: true },
);
yield* Effect.forEach(
[1, 2, 3],
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
) VALUES (
${`seq-${seq}`}, 'thread-1', NULL, 'info', 'runtime.note',
${`seq-${seq}`}, '{}', ${seq}, ${`2026-04-01T09:00:0${seq}.000Z`}
)
`,
{ discard: true },
);
const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(detail._tag, "Some");
if (detail._tag !== "Some") return;
const windowed = detail.value.activities;
assert.equal(windowed.length, 500);
// Sequenced rows are the newest (end of the ascending window); the oldest
// loaded row is unsequenced — exactly the case the concern is about.
assert.equal(windowed.at(-1)?.summary, "seq-3");
assert.equal(windowed[0]?.sequence, undefined);
// The client pages with the unsequenced cursor of the oldest loaded row.
const oldest = windowed[0];
assert.ok(oldest);
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: oldest.createdAt,
beforeActivityId: oldest.id,
limit: 500,
});
// The 103 older unsequenced rows come back, none are sequenced, and no
// sequenced row was stranded (all 3 are already in the window).
assert.equal(olderPage.activities.length, 103);
assert.equal(olderPage.hasMore, false);
assert.ok(olderPage.activities.every((a) => a.sequence === undefined));
}),
);
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1,7 +1,6 @@
import {
ChatAttachment,
CheckpointRef,
EventId,
IsoDateTime,
MessageId,
NonNegativeInt,
@@ -118,31 +117,6 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
/**
* Maximum number of most-recent activities loaded into a thread-detail snapshot.
* Bounds peak memory when opening a long-lived thread; older activities are
* fetched on demand (lazy-load, planned) and live ones stream in via events.
*/
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
// `beforeSequence`/`limit` are NonNegativeInt (not bare Number) to match the
// contract: the WHERE clause `(sequence < beforeSequence OR sequence IS NULL)`
// is only equivalent to the old `COALESCE(sequence, -1) < beforeSequence` when
// `beforeSequence` is non-negative — a negative cursor would silently match no
// sequenced rows and return only unsequenced ones. Validating here (not just at
// the RPC boundary) keeps any future non-RPC caller honest.
const ThreadActivitiesBeforeSequenceInput = Schema.Struct({
threadId: ThreadId,
beforeSequence: NonNegativeInt,
limit: NonNegativeInt,
});
const ThreadActivitiesBeforeActivityInput = Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: NonNegativeInt,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -280,23 +254,6 @@ function mapProposedPlanRow(
};
}
function mapThreadActivityRow(
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
): OrchestrationThreadActivity {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
// `sequence` is the pagination cursor; omit it when the (legacy) row is
// unsequenced so the optional contract field stays absent.
return row.sequence !== null ? Object.assign(activity, { sequence: row.sequence }) : activity;
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProjectionRepositoryError =>
Schema.isSchemaError(cause)
@@ -851,11 +808,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// The thread-detail timeline loads only the most recent window of activities so a
// long-lived thread (tens of thousands of activities, hundreds of MB of payload)
// can't blow the server heap. New activities still stream in live via the event
// subscription; older history will be fetched on demand once lazy-load lands.
// Select the most recent N (sequence DESC) then re-sort ascending for display.
const listThreadActivityRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
@@ -871,17 +823,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM (
SELECT *
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
-- One extra beyond the window so the caller can report hasMoreActivities.
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
)
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence ASC,
created_at ASC,
@@ -889,81 +832,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Older-than-cursor page for lazy-load. Returns rows newest-first (DESC) so a
// simple LIMIT yields the page adjacent to the cursor; the caller reverses to
// ascending. `sequence IS NULL` (legacy unsequenced) rows sort last under
// `sequence DESC` (SQLite orders NULLs last in DESC) — the very oldest — so
// paging eventually reaches them. `beforeSequence` is a NonNegativeInt, so
// `(sequence < beforeSequence OR sequence IS NULL)` is equivalent to the old
// `COALESCE(sequence, -1) < beforeSequence` but lets the
// (thread_id, sequence, created_at, activity_id) index satisfy the ORDER BY
// directly instead of forcing a filesort over the whole thread.
const listThreadActivityRowsBeforeSequence = SqlSchema.findAll({
Request: ThreadActivitiesBeforeSequenceInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeSequence, limit }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND (sequence < ${beforeSequence} OR sequence IS NULL)
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
// Legacy unsequenced (sequence NULL) rows are paged by a (created_at,
// activity_id) cursor. created_at is compared lexicographically as TEXT, which
// equals chronological order only because timestamps are canonical ISO-8601
// (always UTC `Z`, fixed millisecond precision) — the same invariant every
// `ORDER BY created_at` in this layer (including the detail window above)
// already relies on, so the cursor stays consistent with how rows are
// displayed. activity_id breaks created_at ties; its ordering is arbitrary but
// matches the window's `activity_id` tiebreak, so pages never skip or repeat.
const listUnsequencedThreadActivityRowsBeforeActivity = SqlSchema.findAll({
Request: ThreadActivitiesBeforeActivityInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeCreatedAt, beforeActivityId, limit }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND sequence IS NULL
AND (
created_at < ${beforeCreatedAt}
OR (
created_at = ${beforeCreatedAt}
AND activity_id < ${beforeActivityId}
)
)
ORDER BY
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
const getThreadSessionRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadSessionDbRowSchema,
@@ -1208,7 +1076,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
for (const row of activityRows) {
updatedAt = maxIso(updatedAt, row.createdAt);
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
threadActivities.push(mapThreadActivityRow(row));
threadActivities.push({
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
@@ -1313,8 +1190,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
// The full snapshot is unwindowed, so there is never more to load.
hasMoreActivities: false,
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -2123,14 +1998,21 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
// The query fetches WINDOW+1 ascending rows; if it returned the extra
// one, older activities exist beyond the window — drop that oldest row
// and flag it so clients can lazy-load older history.
activities: (activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
: activityRows
).map(mapThreadActivityRow),
hasMoreActivities: activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW,
activities: activityRows.map((row) => {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
if (row.sequence !== null) {
return Object.assign(activity, { sequence: row.sequence });
}
return activity;
}),
checkpoints: checkpointRows.map((row) => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
@@ -2181,43 +2063,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
const getThreadActivitiesPage: ProjectionSnapshotQueryShape["getThreadActivitiesPage"] = (
input,
) =>
Effect.gen(function* () {
const limit = Math.min(
Math.max(1, input.limit ?? THREAD_DETAIL_ACTIVITY_WINDOW),
THREAD_DETAIL_ACTIVITY_WINDOW,
);
// Fetch one extra to detect whether older activities remain.
const rowsEffect =
"beforeSequence" in input
? listThreadActivityRowsBeforeSequence({
threadId: input.threadId,
beforeSequence: input.beforeSequence,
limit: limit + 1,
})
: listUnsequencedThreadActivityRowsBeforeActivity({
threadId: input.threadId,
beforeCreatedAt: input.beforeCreatedAt,
beforeActivityId: input.beforeActivityId,
limit: limit + 1,
});
const rows = yield* rowsEffect.pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadActivitiesPage:query",
"ProjectionSnapshotQuery.getThreadActivitiesPage:decodeRows",
),
),
);
const hasMore = rows.length > limit;
// Rows are newest-first; keep the page closest to the cursor, then reverse
// to ascending for display.
const page = (hasMore ? rows.slice(0, limit) : rows).map(mapThreadActivityRow).toReversed();
return { activities: page, hasMore };
});
return {
getCommandReadModel,
getSnapshot,
@@ -2233,7 +2078,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getThreadShellById,
getThreadDetailById,
getThreadDetailSnapshot,
getThreadActivitiesPage,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -27,8 +27,9 @@ export interface OrchestrationEngineShape {
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to read. Defaults to the event
* store's page-bounded default. Callers must keep this bounded; use a
* projection snapshot instead of replaying an arbitrarily stale cursor.
* store's page-bounded default; pass a higher value when the caller must
* read every event after the cursor (e.g. per-thread catch-up that filters
* a small subset out of a potentially larger global range).
* @returns Stream containing ordered events.
*/
readonly readEvents: (
@@ -9,8 +9,6 @@
import type {
CheckpointRef,
OrchestrationCheckpointSummary,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetThreadActivitiesResult,
OrchestrationProject,
OrchestrationProjectShell,
OrchestrationReadModel,
@@ -170,16 +168,6 @@ export interface ProjectionSnapshotQueryShape {
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
/**
* Cursor-paginated load of a thread's older activities (lazy-load / infinite
* scroll). Returns the page of activities immediately older than the provided
* sequence or unsequenced activity cursor, ascending, plus whether older ones
* remain.
*/
readonly getThreadActivitiesPage: (
input: OrchestrationGetThreadActivitiesInput,
) => Effect.Effect<OrchestrationGetThreadActivitiesResult, ProjectionRepositoryError>;
}
/**
+1 -5
View File
@@ -31,12 +31,8 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.snapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
// The only consumer (the `t3` CLI project resolver) reads just
// `.projects`, so use the command read model — it returns the same
// OrchestrationReadModel shape but never materialises the per-thread
// activity/message/checkpoint tables (490MB+ on a busy DB → heap OOM).
return yield* projectionSnapshotQuery
.getCommandReadModel()
.getSnapshot()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
@@ -27,7 +27,6 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3045,7 +3172,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3270,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -2590,6 +2585,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2702,6 +2708,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -2746,6 +2757,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +2822,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +2944,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
@@ -210,7 +210,6 @@ describe("ProviderSessionReaper", () => {
),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provideMerge(NodeServices.layer),
-46
View File
@@ -5877,52 +5877,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeThread replaces a stale cursor with a fresh snapshot", () =>
Effect.gen(function* () {
const snapshotSequence = 5_000;
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
let replayCalls = 0;
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence }),
getThreadDetailSnapshot: () =>
Effect.succeed(
Option.some({
snapshotSequence,
thread,
}),
),
},
orchestrationEngine: {
readEvents: () => {
replayCalls += 1;
return Stream.empty;
},
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 1,
}).pipe(Stream.take(1), Stream.runCollect),
),
);
assert.equal(replayCalls, 0);
assert.equal(result[0]?.kind, "snapshot");
if (result[0]?.kind === "snapshot") {
assert.equal(result[0].snapshot.snapshotSequence, snapshotSequence);
assert.equal(result[0].snapshot.thread.id, defaultThreadId);
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeShell coalesces a per-thread burst without stalling other threads", () =>
Effect.gen(function* () {
const busyThreadId = ThreadId.make("thread-busy");
@@ -97,7 +97,6 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(AnalyticsService.AnalyticsService, {
record: () => Effect.void,
@@ -161,7 +160,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -206,7 +204,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -257,7 +254,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
+5 -78
View File
@@ -34,7 +34,6 @@ import {
type OrchestrationThreadStreamItem,
OrchestrationGetFullThreadDiffError,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_WS_METHODS,
type ProjectId,
@@ -116,24 +115,6 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT = 1_000;
const subscriptionReplayLimit = (
afterSequence: number,
snapshotSequence: number,
): number | null => {
const eventCount = snapshotSequence - afterSequence;
if (
!Number.isSafeInteger(eventCount) ||
eventCount < 0 ||
eventCount > ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT
) {
return null;
}
return eventCount;
};
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
@@ -306,7 +287,6 @@ const SHELL_RESUME_MAX_GAP = 1_000;
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getThreadActivities, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
@@ -1203,20 +1183,6 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getThreadActivities]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getThreadActivities,
projectionSnapshotQuery.getThreadActivitiesPage(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetThreadActivitiesError({
message: "Failed to load thread activities page",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
@@ -1416,53 +1382,14 @@ const makeWsRpcLayer = (
// catch-up followed by the buffered/ongoing live events. Overlapping
// events are deduped by sequence on the client.
//
// A recent cursor replays the exact global range through the
// per-thread filter. A stale cursor receives a current thread
// snapshot instead, keeping catch-up bounded even when the global
// event log is very large.
// Read the full range after the cursor (not the store's default
// page-bounded limit): the range is normally tiny (a fresh HTTP
// snapshot sequence) and the per-thread filter runs after reading,
// so a global cap could otherwise omit this thread's events.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const { snapshotSequence } = yield* projectionSnapshotQuery
.getSnapshotSequence()
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot sequence",
cause,
}),
),
);
const replayLimit = subscriptionReplayLimit(afterSequence, snapshotSequence);
if (replayLimit === null) {
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to load thread ${input.threadId}`,
cause,
}),
),
);
if (Option.isNone(snapshot)) {
return yield* new OrchestrationGetSnapshotError({
message: `Thread ${input.threadId} was not found`,
cause: input.threadId,
});
}
return Stream.concat(
Stream.make({ kind: "snapshot" as const, snapshot: snapshot.value }),
bufferedLiveStream,
);
}
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, replayLimit)
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+2 -52
View File
@@ -63,10 +63,6 @@ import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { isElectron } from "../env";
@@ -194,7 +190,6 @@ import {
primaryServerKeybindingsAtom,
serverEnvironment,
} from "../state/server";
import { orchestrationEnvironment } from "../state/orchestration";
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
@@ -1865,45 +1860,7 @@ function ChatViewContent(props: ChatViewProps) {
);
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const phase = derivePhase(activeThread?.session ?? null);
// ── Older-history lazy-load ────────────────────────────────────────────────
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities` when older ones exist); older pages are fetched on
// demand (infinite scroll-up) and prepended by the shared engine. Messages
// aren't windowed server-side, so this just back-fills the older tool
// activity.
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const activeThreadEnvironmentIdForActivities = activeThread?.environmentId ?? null;
const activeThreadIdForActivities = activeThread?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (activeThreadEnvironmentIdForActivities === null || activeThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: activeThreadEnvironmentIdForActivities,
input: { threadId: activeThreadIdForActivities, ...cursor },
});
// Failures stay silent on web (the "Load older history" affordance itself
// is the retry surface); returning null keeps `hasMore` for the retry.
return result._tag === "Success" ? result.value : null;
},
[activeThreadEnvironmentIdForActivities, activeThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities: threadActivities,
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: loadOlderActivities,
} = useOlderThreadActivities({
threadKey: activeThread ? `${activeThread.environmentId}\u0000${activeThread.id}` : null,
liveActivities: activeThread?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: activeThread?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
@@ -5299,9 +5256,6 @@ function ChatViewContent(props: ChatViewProps) {
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
hasMoreOlder={hasMoreOlderActivities}
loadingOlder={loadingOlderActivities}
onLoadOlder={loadOlderActivities}
latestTurn={activeLatestTurn}
runningTurnId={
activeThread.session?.status === "running"
@@ -5450,11 +5404,7 @@ function ChatViewContent(props: ChatViewProps) {
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
// Merged set (older pages + live window), not the windowed
// live slice: the context meter scans for the latest
// context-window.updated event, which can sit in a
// lazy-loaded page on long threads.
activeThreadActivities={threadActivities}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
+8 -12
View File
@@ -1159,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1697,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1706,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1892,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2101,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2144,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2502,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
@@ -5,68 +5,8 @@ import {
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveOlderHistoryAutoLoad,
} from "./MessagesTimeline.logic";
describe("resolveOlderHistoryAutoLoad", () => {
it("dispatches only once while a failed or successful load leaves the viewport at the top", () => {
const first = resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: false,
});
expect(first).toEqual({ requestedAtStart: true, shouldLoad: true });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: first.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: true,
requestedAtStart: first.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
});
it("rearms automatic loading only after leaving the top", () => {
const away = resolveOlderHistoryAutoLoad({
isAtStart: false,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: true,
});
expect(away).toEqual({ requestedAtStart: false, shouldLoad: false });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: away.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: true });
});
it("does not reset the latch before list state is available", () => {
expect(
resolveOlderHistoryAutoLoad({
isAtStart: undefined,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: true,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
});
});
describe("computeMessageDurationStart", () => {
it("returns message createdAt when there is no preceding user message", () => {
const result = computeMessageDurationStart([
@@ -21,42 +21,6 @@ export interface TimelineEndState {
readonly isNearEnd?: boolean;
}
export interface OlderHistoryAutoLoadInput {
readonly isAtStart: boolean | undefined;
readonly hasMoreOlder: boolean;
readonly loadingOlder: boolean;
readonly requestedAtStart: boolean;
}
export interface OlderHistoryAutoLoadResult {
readonly requestedAtStart: boolean;
readonly shouldLoad: boolean;
}
/**
* Permit at most one automatic older-history request per visit to the top.
* Loading completion and prepended rows both retrigger timeline measurements;
* neither should recursively request another page while the viewport remains
* pinned at the start. Leaving the top rearms automatic loading, while the
* explicit header control remains available for an immediate retry.
*/
export function resolveOlderHistoryAutoLoad(
input: OlderHistoryAutoLoadInput,
): OlderHistoryAutoLoadResult {
if (input.isAtStart === false) {
return { requestedAtStart: false, shouldLoad: false };
}
if (
input.isAtStart !== true ||
input.requestedAtStart ||
!input.hasMoreOlder ||
input.loadingOlder
) {
return { requestedAtStart: input.requestedAtStart, shouldLoad: false };
}
return { requestedAtStart: true, shouldLoad: true };
}
export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
return state?.isNearEnd ?? state?.isAtEnd;
}
@@ -640,37 +640,4 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("lucide-x");
expect(markup).toContain('aria-label="Tool call failed"');
});
it("offers a 'Load older history' control when older activity remains", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Hi")]}
hasMoreOlder
/>,
);
expect(markup).toContain("Load older history");
});
it("shows a loading indicator while older history is being fetched", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Hi")]}
hasMoreOlder
loadingOlder
/>,
);
expect(markup).toContain("Loading older history");
});
it("renders no older-history control when none remains", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[buildUserTimelineEntry("Hi")]} />,
);
expect(markup).not.toContain("older history");
});
});
@@ -73,7 +73,6 @@ import {
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveOlderHistoryAutoLoad,
resolveTimelineIsAtEnd,
resolveTimelineMinimapHasPersistentGutter,
resolveTimelineMinimapHeightStyle,
@@ -186,10 +185,6 @@ interface MessagesTimelineProps {
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
/** Older history beyond the live activity window can be lazy-loaded. */
hasMoreOlder?: boolean;
loadingOlder?: boolean;
onLoadOlder?: () => void;
}
// ---------------------------------------------------------------------------
@@ -224,9 +219,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onIsAtEndChange,
onManualNavigation,
hideEmptyPlaceholder = false,
hasMoreOlder = false,
loadingOlder = false,
onLoadOlder,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -338,14 +330,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
);
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
const olderHistoryRequestedAtStartRef = useRef(false);
useEffect(() => {
olderHistoryRequestedAtStartRef.current = false;
}, [routeThreadKey]);
const requestOlderHistoryAtStart = useCallback(() => {
olderHistoryRequestedAtStartRef.current = true;
onLoadOlder?.();
}, [onLoadOlder]);
const handleAnchorReady = useCallback(
(info: { anchorIndex: number | undefined }) => {
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
@@ -377,20 +361,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
if (isAtEnd !== undefined) {
onIsAtEndChange(isAtEnd);
}
// Reaching the top lazy-loads one older page. Measurements rerun when the
// request settles and when rows prepend, so keep the visit latched until
// the user leaves the top; otherwise failures retry forever and successful
// pages chain-load the whole history back into memory.
const olderHistoryAutoLoad = resolveOlderHistoryAutoLoad({
isAtStart: state?.isAtStart,
hasMoreOlder: hasMoreOlder && onLoadOlder !== undefined,
loadingOlder,
requestedAtStart: olderHistoryRequestedAtStartRef.current,
});
olderHistoryRequestedAtStartRef.current = olderHistoryAutoLoad.requestedAtStart;
if (olderHistoryAutoLoad.shouldLoad) {
requestOlderHistoryAtStart();
}
if (!state || minimapItems.length === 0) {
return;
}
@@ -413,16 +383,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
strip.dataset.inView = inView ? "true" : "false";
}
}, [
listRef,
minimapItems,
minimapStripMap,
onIsAtEndChange,
hasMoreOlder,
loadingOlder,
onLoadOlder,
requestOlderHistoryAtStart,
]);
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
useEffect(() => {
const frame = requestAnimationFrame(handleScroll);
@@ -454,28 +415,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [timelineViewportElement, rows.length]);
const listHeader = useMemo(() => {
if (loadingOlder) {
return (
<div className="flex items-center justify-center py-2 text-xs text-muted-foreground">
Loading older history…
</div>
);
}
if (hasMoreOlder) {
return (
<button
type="button"
onClick={requestOlderHistoryAtStart}
className="flex w-full cursor-pointer items-center justify-center py-2 text-xs text-muted-foreground transition-colors hover:text-foreground"
>
Load older history
</button>
);
}
return TIMELINE_LIST_HEADER;
}, [loadingOlder, hasMoreOlder, requestOlderHistoryAtStart]);
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
timestampFormat,
@@ -527,11 +466,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
[],
);
// Only short-circuit to the empty state when there is genuinely nothing to
// fetch: the window can derive zero VISIBLE rows (e.g. only tool-neutral work
// entries) while older history still exists — the list must render then so
// its "Load older history" header stays reachable.
if (rows.length === 0 && !isWorking && !hasMoreOlder && !loadingOlder) {
if (rows.length === 0 && !isWorking) {
if (hideEmptyPlaceholder) {
return null;
}
@@ -576,7 +511,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={listHeader}
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
-18
View File
@@ -123,14 +123,6 @@
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
},
"./state/thread-reducer": {
"types": "./src/state/threadReducer.ts",
"default": "./src/state/threadReducer.ts"
},
"./state/older-thread-activities": {
"types": "./src/state/olderThreadActivities.ts",
"default": "./src/state/olderThreadActivities.ts"
},
"./state/thread-sort": {
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
@@ -151,16 +143,6 @@
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/react": "~19.2.14",
"react": "19.2.6",
"vite-plus": "catalog:"
},
"peerDependencies": {
"react": "^19.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
}
}
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
@@ -1,270 +0,0 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { liveWindowOldestActivityId, oldestActivityByChronology } from "./threadReducer.ts";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
/**
* Pagination cursor for a thread's older activities. Sequenced rows page by
* `beforeSequence`; legacy/unsequenced rows (the common case — `sequence` is
* absent on most real rows) page by the `(createdAt, activityId)` keyset.
*/
export type OlderActivitiesCursor =
| { readonly beforeSequence: number }
| {
readonly beforeCreatedAt: OrchestrationThreadActivity["createdAt"];
readonly beforeActivityId: OrchestrationThreadActivity["id"];
};
export interface OlderActivitiesPage {
readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
readonly hasMore: boolean;
}
export interface UseOlderThreadActivitiesOptions {
/**
* Identity of the thread the live window belongs to (e.g.
* `${environmentId}\0${threadId}`); null when no thread is selected.
* Changing it resets the lazy-loaded pages.
*/
readonly threadKey: string | null;
/** The server-windowed live activity set from the thread detail. */
readonly liveActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** The server's `hasMoreActivities` flag from the detail snapshot. */
readonly hasMoreLiveActivities: boolean;
/**
* Fetch the page immediately older than the cursor. Resolve `null` to skip
* the page silently (a failure the caller already surfaced, or an
* interrupted command) — `hasMore` is left true so the user can retry.
* MUST be referentially stable (useCallback) for the load callback to be.
*/
readonly loadPage: (cursor: OlderActivitiesCursor) => Promise<OlderActivitiesPage | null>;
}
export interface UseOlderThreadActivitiesResult {
/** Lazy-loaded older pages + the live window, oldest first. */
readonly mergedActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** Whether older history exists beyond everything loaded. */
readonly hasMoreOlder: boolean;
readonly loadingOlder: boolean;
/** Dispatch a load of the next older page (no-op while one is in flight). */
readonly loadOlder: () => void;
}
// ── Pure decision kernel (exported for unit tests) ──────────────────────────
export interface LiveWindowShape {
readonly key: string | null;
/** Chronological-oldest activity id (an identity sentinel, not a lookup key). */
readonly oldest: string | null;
readonly count: number;
}
/**
* Whether the live window was RESHAPED rather than purely appended-to: a
* different thread, a re-snapshot (reconnect) that changes the window's
* chronological-oldest row, or a checkpoint revert that shrinks it. A pure
* append (same thread, same oldest, count not smaller) is NOT a reshape.
*/
export function didLiveWindowReshape(previous: LiveWindowShape, next: LiveWindowShape): boolean {
return (
next.key !== previous.key || next.oldest !== previous.oldest || next.count < previous.count
);
}
/**
* The cursor for the page immediately older than `oldest`: sequenced rows page
* by `beforeSequence`; unsequenced rows (the common case) by the
* `(createdAt, activityId)` keyset.
*/
export function olderActivitiesCursorFor(
oldest: OrchestrationThreadActivity,
): OlderActivitiesCursor {
return oldest.sequence !== undefined
? { beforeSequence: oldest.sequence }
: { beforeCreatedAt: oldest.createdAt, beforeActivityId: oldest.id };
}
/**
* The row the NEXT load should cursor from: the explicit cursor row already
* paged past when one exists (so an all-overlap page keeps advancing), else
* the chronologically-oldest loaded row — never index 0, which the reducer
* can fill with a newer row (unsequenced rows sort to the end).
*/
export function nextOlderActivitiesCursorRow(
pagedPast: OrchestrationThreadActivity | null,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity | null {
return pagedPast ?? oldestActivityByChronology(merged);
}
/**
* The page rows not already present in the loaded set (older pages + live
* window) — boundary overlap and mid-flight appends must never produce
* duplicate ids in the merged timeline.
*/
export function freshOlderActivities(
page: OlderActivitiesPage,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const seen = new Set(merged.map((activity) => activity.id));
return page.activities.filter((activity) => !seen.has(activity.id));
}
/**
* The older-history lazy-load engine, shared by every client (web ChatView,
* the mobile composer, the TUI ChatView). The thread-detail snapshot windows
* activities to the most recent page; older pages are fetched on demand and
* prepended.
*
* One implementation holds all the hardening the per-client copies kept
* drifting on:
* - reset on live-window RESHAPE, not just thread switch: a reconnect
* re-snapshot changes the window's chronological-oldest row and a checkpoint
* revert shrinks it, but a plain append does neither (the reducer re-sorts
* unsequenced rows, so index 0 is not a stable boundary — the sentinel is
* {@link liveWindowOldestActivityId});
* - a generation guard so a load resolving after a reset can't repopulate the
* cleared state;
* - a synchronous in-flight key so scroll-triggered duplicate dispatches
* coalesce before the loading state commits;
* - an explicit advancing cursor (the oldest row paged PAST), so an
* all-overlap page keeps paging instead of dead-ending while the server
* still reports more — the server cursor is strict, so it strictly
* decreases and paging cannot loop;
* - dedup against the LATEST merged set via a ref, so a live append or a
* prior prepend settling mid-flight can't produce duplicate ids;
* - `hasMore` stays true on a failed/skipped page (the history still exists;
* scrolling back retries).
*/
export function useOlderThreadActivities(
options: UseOlderThreadActivitiesOptions,
): UseOlderThreadActivitiesResult {
const { threadKey, liveActivities, hasMoreLiveActivities, loadPage } = options;
const [olderActivities, setOlderActivities] = useState<
ReadonlyArray<OrchestrationThreadActivity>
>([]);
const [olderLoaded, setOlderLoaded] = useState(false);
const [olderHasMore, setOlderHasMore] = useState(false);
const [loadingOlder, setLoadingOlder] = useState(false);
// Order-independent oldest boundary: `liveActivities[0]` shifts when the
// reducer re-sorts unsequenced rows on the first live append, which would
// otherwise make a plain append look like a window reshape.
const liveOldestActivityId = useMemo(
() => liveWindowOldestActivityId(liveActivities),
[liveActivities],
);
const liveActivityCount = liveActivities.length;
// Bumps on every reset so a late in-flight load can't repopulate the
// freshly-cleared state (the thread key alone doesn't change on a
// same-thread window reshape).
const generationRef = useRef(0);
// The thread key of an in-flight load — coalesces the duplicate dispatches a
// fast scroll fires before the loading state updates.
const inFlightKeyRef = useRef<string | null>(null);
// The oldest row we've paged past; advances even when a page dedupes to
// nothing. Reset on reshape.
const cursorRef = useRef<OrchestrationThreadActivity | null>(null);
const windowRef = useRef({
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
});
// useLayoutEffect (not useEffect) so the cleared state commits before paint:
// otherwise a thread switch renders one frame with the previous thread's
// lazy-loaded pages still merged in, flashing stale rows.
useLayoutEffect(() => {
const previous = windowRef.current;
windowRef.current = {
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
};
if (!didLiveWindowReshape(previous, windowRef.current)) {
return;
}
generationRef.current += 1;
inFlightKeyRef.current = null;
cursorRef.current = null;
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlder(false);
}, [threadKey, liveOldestActivityId, liveActivityCount]);
const mergedActivities = useMemo(
() => (olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities),
[olderActivities, liveActivities],
);
// Latest merged set, read inside the async load handler so dedup runs
// against current state, not the snapshot captured at dispatch time.
const mergedActivitiesRef = useRef(mergedActivities);
useLayoutEffect(() => {
mergedActivitiesRef.current = mergedActivities;
}, [mergedActivities]);
// Before any page is loaded the server flag is authoritative; afterwards
// the latest page's `hasMore` is.
const hasMoreOlder = olderLoaded ? olderHasMore : threadKey !== null && hasMoreLiveActivities;
const loadOlder = useCallback(() => {
if (threadKey === null || !hasMoreOlder) {
return;
}
const oldest = nextOlderActivitiesCursorRow(cursorRef.current, mergedActivitiesRef.current);
if (!oldest) {
return;
}
if (inFlightKeyRef.current === threadKey) {
return; // a load for this thread is already in flight
}
const cursor = olderActivitiesCursorFor(oldest);
const generation = generationRef.current;
inFlightKeyRef.current = threadKey;
setLoadingOlder(true);
void loadPage(cursor)
.then((page) => {
// The window/thread was reset while this was in flight — drop the page
// so it can't repopulate state cleared by the reset.
if (generationRef.current !== generation) {
return;
}
if (page === null) {
// Failed or interrupted (already surfaced by the caller). Keep
// `hasMore` — the history still exists and retrying is valid.
return;
}
// Advance the cursor even when every row dedupes away — the server
// cursor is strict, so it strictly decreases and paging can't loop.
const pageOldest = page.activities[0];
if (pageOldest) {
cursorRef.current = pageOldest;
}
const fresh = freshOlderActivities(page, mergedActivitiesRef.current);
if (fresh.length > 0) {
setOlderActivities((previous) => [...fresh, ...previous]);
}
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (generationRef.current === generation) {
inFlightKeyRef.current = null;
setLoadingOlder(false);
}
});
}, [threadKey, hasMoreOlder, loadPage]);
return {
mergedActivities: threadKey === null ? EMPTY_ACTIVITIES : mergedActivities,
hasMoreOlder,
loadingOlder,
loadOlder,
};
}
@@ -1,7 +1,7 @@
import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
export function createOrchestrationEnvironmentAtoms<R, E>(
@@ -12,11 +12,6 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
}),
// Imperative lazy-load of older thread activities (infinite scroll-up).
loadThreadActivities: createEnvironmentRpcCommand(runtime, {
label: "environment-data:orchestration:thread-activities",
tag: ORCHESTRATION_WS_METHODS.getThreadActivities,
}),
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:full-thread-diff",
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
@@ -9,25 +9,9 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import type { OrchestrationThread, OrchestrationThreadActivity } from "@t3tools/contracts";
import type { OrchestrationThread } from "@t3tools/contracts";
import {
applyThreadDetailEvent,
liveWindowOldestActivityId,
oldestActivityByChronology,
} from "./threadReducer.ts";
const activity = (id: string, createdAt: string, sequence?: number): OrchestrationThreadActivity =>
({
id,
tone: "tool",
kind: "command",
summary: id,
payload: {},
turnId: TurnId.make("turn-1"),
createdAt,
...(sequence !== undefined ? { sequence } : {}),
}) as unknown as OrchestrationThreadActivity;
import { applyThreadDetailEvent } from "./threadReducer.ts";
const baseEventFields = {
eventId: EventId.make("event-1"),
@@ -713,61 +697,4 @@ describe("applyThreadDetailEvent", () => {
expect(result.kind).toBe("unchanged");
});
});
describe("liveWindowOldestActivityId", () => {
it("returns null for an empty window", () => {
expect(liveWindowOldestActivityId([])).toBeNull();
});
it("returns the chronologically-oldest id regardless of array position", () => {
// Reducer order places the unsequenced legacy row (oldest) LAST while the
// server snapshot would list it first; the helper picks it either way.
const window = [
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
activity("seq-2", "2026-04-01T10:00:02.000Z", 2),
activity("legacy", "2026-04-01T09:00:00.000Z"),
];
expect(liveWindowOldestActivityId(window)).toBe("legacy");
});
it("breaks createdAt ties by id", () => {
const window = [
activity("b", "2026-04-01T10:00:00.000Z", 2),
activity("a", "2026-04-01T10:00:00.000Z", 1),
];
expect(liveWindowOldestActivityId(window)).toBe("a");
});
it("is stable when a newer activity is appended (no false reshape)", () => {
const before = [
activity("legacy", "2026-04-01T09:00:00.000Z"),
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
];
// A live append is the newest activity and is unsequenced in the payload;
// it must not change the detected oldest boundary.
const after = [...before, activity("appended", "2026-04-01T11:00:00.000Z")];
expect(liveWindowOldestActivityId(after)).toBe(liveWindowOldestActivityId(before));
expect(liveWindowOldestActivityId(after)).toBe("legacy");
});
});
describe("oldestActivityByChronology", () => {
it("returns null for an empty set", () => {
expect(oldestActivityByChronology([])).toBeNull();
});
it("returns the unsequenced legacy row so the pagination cursor agrees with the sentinel", () => {
// The reducer placed the legacy (unsequenced, oldest) row at the END; paging
// must cursor from it (createdAt cursor), not from index 0's sequenced row.
const merged = [
activity("seq-5", "2026-04-01T10:00:05.000Z", 5),
activity("seq-6", "2026-04-01T10:00:06.000Z", 6),
activity("legacy", "2026-04-01T09:00:00.000Z"),
];
const oldest = oldestActivityByChronology(merged);
expect(oldest?.id).toBe("legacy");
expect(oldest?.sequence).toBeUndefined(); // → drives the unsequenced cursor
expect(liveWindowOldestActivityId(merged)).toBe(oldest?.id); // sentinel agrees
});
});
});
@@ -35,45 +35,6 @@ const activityOrder = O.combineAll<OrchestrationThreadActivity>([
O.mapInput(O.String, (a) => a.id),
]);
/**
* The oldest activity in a set, by chronology (`createdAt`, then `id`) rather
* than array position.
*
* `activities[0]` is not a stable "oldest": {@link activityOrder} sorts
* unsequenced rows to the end (a missing `sequence` is treated as newest) while
* the server snapshot lists legacy unsequenced rows first, so the first live
* append re-sorts the array and shifts index 0. Both the lazy-load *reshape*
* sentinel ({@link liveWindowOldestActivityId}) and the lazy-load *pagination
* cursor* derive from this so they agree on which row is oldest regardless of
* the reducer's placement of unsequenced rows. Returns `null` when empty.
*/
export function oldestActivityByChronology(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity | null {
let oldest: OrchestrationThreadActivity | null = null;
for (const activity of activities) {
if (
oldest === null ||
activity.createdAt < oldest.createdAt ||
(activity.createdAt === oldest.createdAt && activity.id < oldest.id)
) {
oldest = activity;
}
}
return oldest;
}
/**
* The id of {@link oldestActivityByChronology}, used as the lazy-load reshape
* sentinel (a reconnect re-snapshot or checkpoint revert changes it; a plain
* append does not). Returns `null` when empty.
*/
export function liveWindowOldestActivityId(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity["id"] | null {
return oldestActivityByChronology(activities)?.id ?? null;
}
/**
* Apply a single orchestration event to an `OrchestrationThread`, returning
* the updated thread, a deletion signal, or an "unchanged" marker when the
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
-48
View File
@@ -25,7 +25,6 @@ import { ProviderInstanceId } from "./providerInstance.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
getTurnDiff: "orchestration.getTurnDiff",
getThreadActivities: "orchestration.getThreadActivities",
getFullThreadDiff: "orchestration.getFullThreadDiff",
replayEvents: "orchestration.replayEvents",
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
@@ -363,10 +362,6 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
activities: Schema.Array(OrchestrationThreadActivity),
// The detail snapshot windows `activities` to the most recent page; this is
// true when older activities exist beyond the window and can be lazy-loaded
// via the getThreadActivities RPC. Absent on lightweight (shell) threads.
hasMoreActivities: Schema.optional(Schema.Boolean),
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
session: Schema.NullOr(OrchestrationSession),
});
@@ -1243,37 +1238,6 @@ export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput
export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
/**
* Cursor-paginated load of a thread's OLDER activities (lazy-load / infinite
* scroll). Sequenced activity uses `beforeSequence`, the `sequence` of the
* oldest activity the client currently holds. Legacy unsequenced activity uses
* the `(beforeCreatedAt, beforeActivityId)` pair from the oldest loaded
* activity. The server returns the page of activities immediately older than the
* cursor (chronological ascending) plus whether any remain beyond that.
*/
export const OrchestrationGetThreadActivitiesInput = Schema.Union([
Schema.Struct({
threadId: ThreadId,
beforeSequence: NonNegativeInt,
limit: Schema.optional(NonNegativeInt),
}),
Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: Schema.optional(NonNegativeInt),
}),
]);
export type OrchestrationGetThreadActivitiesInput =
typeof OrchestrationGetThreadActivitiesInput.Type;
export const OrchestrationGetThreadActivitiesResult = Schema.Struct({
activities: Schema.Array(OrchestrationThreadActivity),
hasMore: Schema.Boolean,
});
export type OrchestrationGetThreadActivitiesResult =
typeof OrchestrationGetThreadActivitiesResult.Type;
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
threadId: ThreadId,
toTurnCount: NonNegativeInt,
@@ -1301,10 +1265,6 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationGetTurnDiffInput,
output: OrchestrationGetTurnDiffResult,
},
getThreadActivities: {
input: OrchestrationGetThreadActivitiesInput,
output: OrchestrationGetThreadActivitiesResult,
},
getFullThreadDiff: {
input: OrchestrationGetFullThreadDiffInput,
output: OrchestrationGetFullThreadDiffResult,
@@ -1351,14 +1311,6 @@ export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<Orche
},
) {}
export class OrchestrationGetThreadActivitiesError extends Schema.TaggedErrorClass<OrchestrationGetThreadActivitiesError>()(
"OrchestrationGetThreadActivitiesError",
{
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect()),
},
) {}
export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
"OrchestrationGetFullThreadDiffError",
{
-12
View File
@@ -52,8 +52,6 @@ import {
OrchestrationGetFullThreadDiffError,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetTurnDiffError,
OrchestrationGetTurnDiffInput,
OrchestrationReplayEventsError,
@@ -614,15 +612,6 @@ export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.g
error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),
});
export const WsOrchestrationGetThreadActivitiesRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getThreadActivities,
{
payload: OrchestrationGetThreadActivitiesInput,
success: OrchestrationRpcSchemas.getThreadActivities.output,
error: Schema.Union([OrchestrationGetThreadActivitiesError, EnvironmentAuthorizationError]),
},
);
export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
{
@@ -764,7 +753,6 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeAuthAccessRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetThreadActivitiesRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationReplayEventsRpc,
WsOrchestrationGetArchivedShellSnapshotRpc,
+1
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(
-6
View File
@@ -746,12 +746,6 @@ importers:
'@effect/vitest':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=42b87cc47e70d74e62496e7a8261b3fd298ecad4464d209348ab04b96f853a5f)([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
'@types/react':
specifier: ~19.2.14
version: 19.2.16
react:
specifier: 19.2.6
version: 19.2.6
vite-plus:
specifier: 'catalog:'
version: 0.2.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])