Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc525cda50 | ||
|
|
d995d1004b | ||
|
|
0dedf82dea | ||
|
|
6f34ad3e87 | ||
|
|
62cf461759 | ||
|
|
23c18fda7a | ||
|
|
c0bb237345 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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>
|
||||
+11
@@ -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()
|
||||
}
|
||||
}
|
||||
+194
@@ -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
|
||||
}
|
||||
}
|
||||
+18
@@ -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 = ""
|
||||
}
|
||||
+38
@@ -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)
|
||||
}
|
||||
+10
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -342,7 +342,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
refreshChangeRequestStatus: () => Effect.succeed(null),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
|
||||
@@ -895,13 +895,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -927,13 +925,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1315,7 +1311,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status reports provider availability failures without leaking diagnostics", () =>
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1337,39 +1333,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("feature/status-no-gh");
|
||||
expect(status.pr).toBeNull();
|
||||
expect(status.changeRequestLookup).toEqual({
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "provider_unavailable",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status reports source control authentication failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-auth"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-auth"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("private authentication output"),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.changeRequestLookup).toEqual({
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "authentication_required",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
GitStackedAction,
|
||||
VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusChangeRequestLookup,
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
ModelSelection,
|
||||
@@ -50,7 +49,7 @@ import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import type { ChangeRequest, SourceControlProviderError } from "@t3tools/contracts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
@@ -104,32 +103,6 @@ function isNotGitRepositoryError(error: GitCommandError): boolean {
|
||||
return error.message.toLowerCase().includes("not a git repository");
|
||||
}
|
||||
|
||||
function lookupFailureReason(error: SourceControlProviderError): VcsStatusChangeRequestLookup {
|
||||
const tags = new Set<string>();
|
||||
let current: unknown = error;
|
||||
for (let depth = 0; depth < 6 && current !== null && typeof current === "object"; depth += 1) {
|
||||
if ("_tag" in current && typeof current._tag === "string") {
|
||||
tags.add(current._tag);
|
||||
}
|
||||
if ("status" in current && (current.status === 401 || current.status === 403)) {
|
||||
return {
|
||||
_tag: "failed",
|
||||
provider: error.provider,
|
||||
reason: "authentication_required",
|
||||
};
|
||||
}
|
||||
current = "cause" in current ? current.cause : null;
|
||||
}
|
||||
|
||||
const hasTagSuffix = (suffix: string) => [...tags].some((tag) => tag.endsWith(suffix));
|
||||
const reason = hasTagSuffix("AuthenticationError")
|
||||
? "authentication_required"
|
||||
: hasTagSuffix("UnavailableError") || tags.has("VcsProcessSpawnError")
|
||||
? "provider_unavailable"
|
||||
: "lookup_failed";
|
||||
return { _tag: "failed", provider: error.provider, reason };
|
||||
}
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -806,36 +779,29 @@ export const make = Effect.gen(function* () {
|
||||
return null;
|
||||
}
|
||||
|
||||
let pr: VcsStatusRemoteResult["pr"] = null;
|
||||
let changeRequestLookup: VcsStatusChangeRequestLookup = { _tag: "succeeded" };
|
||||
if (details.branch !== null) {
|
||||
const lookup = yield* findLatestPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ error }),
|
||||
onSuccess: (latest) => ({ latest }),
|
||||
}),
|
||||
);
|
||||
if ("error" in lookup) {
|
||||
changeRequestLookup = lookupFailureReason(lookup.error);
|
||||
} else {
|
||||
const latest = lookup.latest;
|
||||
if (latest && (!details.isDefaultBranch || latest.state === "open")) {
|
||||
pr = toStatusPr(latest);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.map((latest) => {
|
||||
if (!latest) return null;
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null;
|
||||
|
||||
return {
|
||||
statusRefName: details.branch,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr,
|
||||
changeRequestLookup,
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {
|
||||
|
||||
@@ -66,13 +66,11 @@ describe("GitWorkflowService", () => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
|
||||
@@ -112,13 +112,11 @@ function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
||||
function nonRepositoryStatus(): VcsStatusResult {
|
||||
return {
|
||||
...nonRepositoryLocalStatus(),
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/* oxlint-disable t3code/no-manual-effect-runtime-in-tests */
|
||||
// This integration harness owns a ManagedRuntime and exercises its Promise boundary directly.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
@@ -16,7 +14,6 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
GitManagerError,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -200,16 +197,6 @@ async function waitForEvent(
|
||||
return poll();
|
||||
}
|
||||
|
||||
async function waitForCondition(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
|
||||
throw new Error("Timed out waiting for condition.");
|
||||
}
|
||||
await Effect.runPromise(Effect.sleep("10 millis"));
|
||||
}
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return NodeChildProcess.execFileSync("git", args, {
|
||||
cwd,
|
||||
@@ -293,10 +280,6 @@ describe("CheckpointReactor", () => {
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderDriverKind;
|
||||
readonly gitStatusRefreshCalls?: Array<string>;
|
||||
readonly changeRequestStatusRefreshCalls?: Array<string>;
|
||||
readonly failGitStatusRefresh?: boolean;
|
||||
readonly failChangeRequestStatusRefresh?: boolean;
|
||||
readonly gitStatusRefreshWait?: Promise<void>;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -328,45 +311,14 @@ describe("CheckpointReactor", () => {
|
||||
Effect.sync(() => {
|
||||
options?.gitStatusRefreshCalls?.push(cwd);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
options?.gitStatusRefreshWait
|
||||
? Effect.promise(() => options.gitStatusRefreshWait!)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(
|
||||
options?.failGitStatusRefresh
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "refreshLocalStatus",
|
||||
cwd,
|
||||
detail: "test failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
isRepo: true as const,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
),
|
||||
),
|
||||
refreshChangeRequestStatus: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
options?.changeRequestStatusRefreshCalls?.push(cwd);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
options?.failChangeRequestStatusRefresh
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "refreshChangeRequestStatus",
|
||||
cwd,
|
||||
detail: "test failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(null),
|
||||
),
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
@@ -544,13 +496,11 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("refreshes local and change request status on turn completion using the session cwd", async () => {
|
||||
it("refreshes local git status state on turn completion using the session cwd", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
@@ -566,105 +516,10 @@ describe("CheckpointReactor", () => {
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it("falls back to the thread worktree when no provider session is available", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-refresh-fallback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-refresh-fallback"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "local", failGitStatusRefresh: true, failChangeRequestStatusRefresh: false },
|
||||
{ name: "change request", failGitStatusRefresh: false, failChangeRequestStatusRefresh: true },
|
||||
])("runs both completion refreshes when the $name refresh fails", async (failure) => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
failGitStatusRefresh: failure.failGitStatusRefresh,
|
||||
failChangeRequestStatusRefresh: failure.failChangeRequestStatusRefresh,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(`evt-turn-completed-${failure.name}-refresh-failure`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId(`turn-${failure.name}-refresh-failure`),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it("starts change request refresh without waiting for local refresh", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
let releaseLocalRefresh: (() => void) | undefined;
|
||||
const gitStatusRefreshWait = new Promise<void>((resolve) => {
|
||||
releaseLocalRefresh = resolve;
|
||||
});
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
gitStatusRefreshWait,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-independent-refreshes"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-independent-refreshes"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
const draining = harness.drain();
|
||||
await waitForCondition(
|
||||
() => gitStatusRefreshCalls.length === 1 && changeRequestStatusRefreshCalls.length === 1,
|
||||
);
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
releaseLocalRefresh?.();
|
||||
await draining;
|
||||
});
|
||||
|
||||
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -716,20 +571,6 @@ describe("CheckpointReactor", () => {
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
expect(gitStatusRefreshCalls).toEqual([]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([]);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-missing-id"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
expect(gitStatusRefreshCalls).toEqual([]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([]);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
|
||||
@@ -526,73 +526,25 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const refreshGitStatusFromTurnCompletion = Effect.fn("refreshGitStatusFromTurnCompletion")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (
|
||||
thread?.session?.activeTurnId &&
|
||||
(!turnId || !sameId(thread.session.activeTurnId, turnId))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const refreshLocalGitStatusFromTurnCompletion = Effect.fn(
|
||||
"refreshLocalGitStatusFromTurnCompletion",
|
||||
)(function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
let cwd = Option.getOrUndefined(sessionRuntime)?.cwd;
|
||||
if (!cwd) {
|
||||
if (thread) {
|
||||
cwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects: yield* resolveThreadProjects(thread.projectId),
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
vcsStatusBroadcaster.refreshLocalStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(undefined)),
|
||||
),
|
||||
),
|
||||
vcsStatusBroadcaster.refreshChangeRequestStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh change request status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(undefined)),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (local && remote && remote.statusRefName !== local.refName) {
|
||||
yield* vcsStatusBroadcaster.refreshChangeRequestStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to reconcile change request status after branch change", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
|
||||
"ensurePreTurnBaselineFromDomainTurnStart",
|
||||
@@ -838,7 +790,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
yield* refreshGitStatusFromTurnCompletion(event);
|
||||
yield* refreshLocalGitStatusFromTurnCompletion(event);
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.flatMap(nowIso, (createdAt) =>
|
||||
|
||||
@@ -262,12 +262,10 @@ describe("ProviderCommandReactor", () => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "renamed-branch",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
@@ -360,8 +358,6 @@ describe("ProviderCommandReactor", () => {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshChangeRequestStatus: () =>
|
||||
Effect.die("refreshChangeRequestStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
}),
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -4823,12 +4823,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.succeed({
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
@@ -4838,12 +4836,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
runStackedAction: (input, options) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -4957,12 +4953,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
},
|
||||
reviewService: {
|
||||
@@ -5151,12 +5145,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.sync(() => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
status: () =>
|
||||
@@ -5169,12 +5161,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -5232,12 +5222,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.sync(() => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
status: () =>
|
||||
@@ -5250,12 +5238,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
runStackedAction: () => Effect.fail(gitError),
|
||||
@@ -5307,12 +5293,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
},
|
||||
@@ -5355,12 +5339,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
runStackedAction: () =>
|
||||
@@ -5438,12 +5420,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
runStackedAction: () =>
|
||||
@@ -6764,12 +6744,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "t3code/bootstrap-refName",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
);
|
||||
const fetchRemote = vi.fn(
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1521,13 +1521,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
refName: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
statusRefName: details.branch,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" as const },
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -2219,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) {
|
||||
@@ -2234,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,7 +5,6 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -40,12 +39,10 @@ const baseLocalStatus: VcsStatusLocalResult = {
|
||||
};
|
||||
|
||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
||||
statusRefName: "feature/status-broadcast",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
const remoteStatusWithPr: VcsStatusRemoteResult = {
|
||||
@@ -148,7 +145,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
statusRefName: "feature/updated-status",
|
||||
aheadCount: 2,
|
||||
};
|
||||
const refreshed = yield* broadcaster.refreshStatus("/repo");
|
||||
@@ -170,44 +166,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"retains a same-branch cached PR across lookup failure and clears it on recovery",
|
||||
() => {
|
||||
const state: Parameters<typeof makeTestLayer>[0] = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: remoteStatusWithPr,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
};
|
||||
|
||||
const failed = yield* broadcaster.refreshChangeRequestStatus("/repo");
|
||||
assert.deepStrictEqual(failed, {
|
||||
...state.currentRemoteStatus,
|
||||
pr: remoteStatusWithPr.pr,
|
||||
});
|
||||
|
||||
state.currentRemoteStatus = baseRemoteStatus;
|
||||
const recovered = yield* broadcaster.refreshChangeRequestStatus("/repo");
|
||||
assert.deepStrictEqual(recovered, baseRemoteStatus);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("keeps a successful local refresh when the remote refresh fails", () => {
|
||||
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
@@ -269,17 +228,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.isTrue(Exit.isFailure(refreshExit));
|
||||
assert.deepStrictEqual(cached, {
|
||||
...baseStatus,
|
||||
...state.currentLocalStatus,
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
assert.deepStrictEqual(cached, baseStatus);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
@@ -310,13 +259,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
...baseRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
@@ -426,7 +369,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("keeps lightweight change request polling when Git fetches are disabled", () => {
|
||||
it.effect("loads remote status once when periodic refreshes are disabled", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: remoteStatusWithPr,
|
||||
@@ -475,15 +418,8 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(2));
|
||||
assert.equal(state.remoteStatusCalls, 5);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
]);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
@@ -640,74 +576,17 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(59));
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(state.remoteStatusCalls, 3);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
});
|
||||
|
||||
it.effect("retries a failed upstream refresh after the failure backoff", () => {
|
||||
const refreshUpstreamValues: Array<boolean | undefined> = [];
|
||||
let failedUpstreamRefresh = false;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
remoteStatus: (_input, options) => {
|
||||
refreshUpstreamValues.push(options?.refreshUpstream);
|
||||
if (options?.refreshUpstream && !failedUpstreamRefresh) {
|
||||
failedUpstreamRefresh = true;
|
||||
return Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "VcsStatusBroadcaster.test",
|
||||
cwd: "/repo",
|
||||
detail: "upstream refresh failure",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(baseRemoteStatus);
|
||||
},
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const scope = yield* Scope.make();
|
||||
const snapshotDeferred = yield* Deferred.make<void>();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(5)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(snapshotDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Deferred.await(snapshotDeferred);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(5));
|
||||
assert.isTrue(failedUpstreamRefresh);
|
||||
assert.equal(refreshUpstreamValues.at(-1), true);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(30));
|
||||
assert.deepStrictEqual(refreshUpstreamValues.slice(-2), [true, true]);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
|
||||
});
|
||||
|
||||
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
|
||||
@@ -752,104 +631,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("coalesces concurrent lightweight refreshes for the same worktree", () => {
|
||||
let calls = 0;
|
||||
return Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
calls += 1;
|
||||
return calls;
|
||||
}).pipe(
|
||||
Effect.flatMap((call) =>
|
||||
call === 1
|
||||
? Effect.succeed(baseRemoteStatus)
|
||||
: Deferred.succeed(started, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(Deferred.await(release)),
|
||||
Effect.as(baseRemoteStatus),
|
||||
),
|
||||
),
|
||||
),
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const firstRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Deferred.await(started);
|
||||
const secondRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(10));
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(firstRefresh);
|
||||
yield* Fiber.join(secondRefresh);
|
||||
|
||||
assert.equal(calls, 2);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does not let an old branch lookup satisfy a queued new branch lookup", () => {
|
||||
let calls = 0;
|
||||
let currentRefName = baseLocalStatus.refName;
|
||||
return Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed({ ...baseLocalStatus, refName: currentRefName }),
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
remoteStatus: () => {
|
||||
calls += 1;
|
||||
const status = { ...baseRemoteStatus, statusRefName: currentRefName };
|
||||
return calls === 2
|
||||
? Deferred.succeed(started, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(Deferred.await(release)),
|
||||
Effect.as(status),
|
||||
)
|
||||
: Effect.succeed(status);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const oldBranchRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Deferred.await(started);
|
||||
currentRefName = "feature/new-branch";
|
||||
yield* broadcaster.refreshLocalStatus("/repo");
|
||||
const newBranchRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(10));
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(oldBranchRefresh);
|
||||
const refreshed = yield* Fiber.join(newBranchRefresh);
|
||||
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(refreshed?.statusRefName, "feature/new-branch");
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -9,7 +8,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
@@ -134,11 +133,6 @@ interface ActiveRemotePoller {
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
interface RefreshLock {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
readonly users: number;
|
||||
}
|
||||
|
||||
interface StreamStatusOptions {
|
||||
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
|
||||
}
|
||||
@@ -166,9 +160,6 @@ export class VcsStatusBroadcaster extends Context.Service<
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshChangeRequestStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: VcsStatusInput,
|
||||
@@ -199,51 +190,6 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
const refreshLocksRef = yield* Ref.make(new Map<string, RefreshLock>());
|
||||
const refreshLocksGuard = yield* Semaphore.make(1);
|
||||
const backgroundRefreshSemaphore = yield* Semaphore.make(4);
|
||||
const lastRemoteRefreshRef = yield* Ref.make(
|
||||
new Map<string, { readonly completionId: number; readonly refreshUpstream: boolean }>(),
|
||||
);
|
||||
const refreshCompletionCounterRef = yield* Ref.make(0);
|
||||
|
||||
const withCwdRefreshLock = <A, E, R>(
|
||||
cwd: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.acquireUseRelease(
|
||||
refreshLocksGuard.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const locks = yield* Ref.get(refreshLocksRef);
|
||||
const existing = locks.get(cwd);
|
||||
if (existing) {
|
||||
yield* Ref.set(
|
||||
refreshLocksRef,
|
||||
new Map(locks).set(cwd, { ...existing, users: existing.users + 1 }),
|
||||
);
|
||||
return existing.semaphore;
|
||||
}
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
yield* Ref.set(refreshLocksRef, new Map(locks).set(cwd, { semaphore, users: 1 }));
|
||||
return semaphore;
|
||||
}),
|
||||
),
|
||||
(lock) => lock.withPermits(1)(effect),
|
||||
(lock) =>
|
||||
refreshLocksGuard.withPermits(1)(
|
||||
Ref.update(refreshLocksRef, (locks) => {
|
||||
const existing = locks.get(cwd);
|
||||
if (!existing || existing.semaphore !== lock) return locks;
|
||||
const next = new Map(locks);
|
||||
if (existing.users === 1) {
|
||||
next.delete(cwd);
|
||||
} else {
|
||||
next.set(cwd, { ...existing, users: existing.users - 1 });
|
||||
}
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
@@ -283,18 +229,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
|
||||
function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
const previousRemote = cached?.remote?.value ?? null;
|
||||
const resolvedRemote =
|
||||
remote?.changeRequestLookup._tag === "failed" &&
|
||||
remote.pr === null &&
|
||||
previousRemote?.statusRefName === remote.statusRefName &&
|
||||
previousRemote.pr !== null
|
||||
? { ...remote, pr: previousRemote.pr }
|
||||
: remote;
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(resolvedRemote),
|
||||
value: resolvedRemote,
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
@@ -311,12 +248,12 @@ export const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "remoteUpdated",
|
||||
remote: resolvedRemote,
|
||||
remote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return resolvedRemote;
|
||||
return remote;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -392,9 +329,7 @@ export const make = Effect.gen(function* () {
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
|
||||
cached?.remote
|
||||
? Effect.succeed(cached.remote.value)
|
||||
: refreshRemoteStatus(cwd, { refreshUpstream: false }),
|
||||
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
@@ -420,57 +355,26 @@ export const make = Effect.gen(function* () {
|
||||
cwd: string,
|
||||
options?: { readonly refreshUpstream?: boolean },
|
||||
) {
|
||||
const wantsUpstream = options?.refreshUpstream !== false;
|
||||
const observedCompletionId = (yield* Ref.get(lastRemoteRefreshRef)).get(cwd)?.completionId ?? 0;
|
||||
return yield* withCwdRefreshLock(
|
||||
cwd,
|
||||
backgroundRefreshSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const previousRefresh = (yield* Ref.get(lastRemoteRefreshRef)).get(cwd);
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
const cachedRemoteMatchesLocal =
|
||||
cached?.local?.value.refName === cached?.remote?.value?.statusRefName;
|
||||
if (
|
||||
previousRefresh &&
|
||||
previousRefresh.completionId > observedCompletionId &&
|
||||
(!wantsUpstream || previousRefresh.refreshUpstream) &&
|
||||
cachedRemoteMatchesLocal
|
||||
) {
|
||||
return cached?.remote?.value ?? null;
|
||||
}
|
||||
if (wantsUpstream) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
const completionId = yield* Ref.updateAndGet(
|
||||
refreshCompletionCounterRef,
|
||||
(current) => current + 1,
|
||||
);
|
||||
yield* Ref.update(lastRemoteRefreshRef, (refreshes) =>
|
||||
new Map(refreshes).set(cwd, { completionId, refreshUpstream: wantsUpstream }),
|
||||
);
|
||||
return updated;
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
});
|
||||
|
||||
const refreshChangeRequestStatus: VcsStatusBroadcaster["Service"]["refreshChangeRequestStatus"] =
|
||||
Effect.fn("VcsStatusBroadcaster.refreshChangeRequestStatus")(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
return yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
|
||||
});
|
||||
|
||||
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[refreshLocalStatusCore(cwd), refreshRemoteStatus(cwd)],
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
|
||||
});
|
||||
|
||||
const makeRemoteRefreshLoop = (
|
||||
@@ -481,39 +385,23 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.gen(function* () {
|
||||
const consecutiveFailuresRef = yield* Ref.make(0);
|
||||
const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lastLightweightRefreshRef = yield* Ref.make(now);
|
||||
const lastUpstreamRefreshRef = yield* Ref.make(now);
|
||||
const runOnce = Effect.fn("VcsStatusBroadcaster.remoteRefreshLoop.runOnce")(function* () {
|
||||
const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
const activeInterval = Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval;
|
||||
const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
|
||||
const currentTime = yield* Clock.currentTimeMillis;
|
||||
const nextLightweightAt =
|
||||
(yield* Ref.get(lastLightweightRefreshRef)) +
|
||||
Duration.toMillis(DEFAULT_VCS_STATUS_REFRESH_INTERVAL);
|
||||
const nextUpstreamAt = Duration.isZero(configuredInterval)
|
||||
? Number.POSITIVE_INFINITY
|
||||
: (yield* Ref.get(lastUpstreamRefreshRef)) + Duration.toMillis(configuredInterval);
|
||||
if (!needsInitialRefresh) {
|
||||
yield* Effect.sleep(
|
||||
Duration.millis(Math.max(0, Math.min(nextLightweightAt, nextUpstreamAt) - currentTime)),
|
||||
);
|
||||
if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
const refreshTime = yield* Clock.currentTimeMillis;
|
||||
const refreshUpstream =
|
||||
!Duration.isZero(configuredInterval) &&
|
||||
(needsInitialRefresh || refreshTime >= nextUpstreamAt);
|
||||
|
||||
const exit = yield* refreshRemoteStatus(cwd, {
|
||||
refreshUpstream,
|
||||
refreshUpstream: !Duration.isZero(configuredInterval),
|
||||
}).pipe(Effect.exit);
|
||||
yield* Ref.set(lastLightweightRefreshRef, refreshTime);
|
||||
if (Exit.isSuccess(exit)) {
|
||||
if (refreshUpstream) yield* Ref.set(lastUpstreamRefreshRef, refreshTime);
|
||||
yield* Ref.set(needsInitialRefreshRef, false);
|
||||
yield* Ref.set(consecutiveFailuresRef, 0);
|
||||
return;
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
|
||||
@@ -525,19 +413,33 @@ export const make = Effect.gen(function* () {
|
||||
consecutiveFailuresRef,
|
||||
(count) => count + 1,
|
||||
);
|
||||
const nextDelay = remoteRefreshFailureDelay(
|
||||
consecutiveFailures,
|
||||
DEFAULT_VCS_STATUS_REFRESH_INTERVAL,
|
||||
);
|
||||
const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
|
||||
yield* Effect.logWarning("VCS remote status refresh failed", {
|
||||
cwdLength: cwd.length,
|
||||
...remoteRefreshFailureDiagnostics(exit.cause),
|
||||
consecutiveFailures,
|
||||
nextDelayMs: Duration.toMillis(nextDelay),
|
||||
});
|
||||
yield* Effect.sleep(nextDelay);
|
||||
return nextDelay;
|
||||
});
|
||||
return yield* runOnce().pipe(Effect.forever);
|
||||
|
||||
if (!refreshImmediately) {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
yield* Effect.sleep(
|
||||
Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval,
|
||||
);
|
||||
}
|
||||
|
||||
return yield* refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.repeat(
|
||||
Schedule.identity<Duration.Duration>().pipe(
|
||||
Schedule.addDelay((delay) => Effect.succeed(delay)),
|
||||
),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -633,7 +535,6 @@ export const make = Effect.gen(function* () {
|
||||
return VcsStatusBroadcaster.of({
|
||||
getStatus,
|
||||
refreshLocalStatus,
|
||||
refreshChangeRequestStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
});
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -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 ? (
|
||||
|
||||
@@ -24,58 +24,14 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "feature/test",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("when: change request lookup is not confirmed", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" as const },
|
||||
{
|
||||
_tag: "failed" as const,
|
||||
provider: "github" as const,
|
||||
reason: "authentication_required" as const,
|
||||
},
|
||||
])("never offers PR creation for $._tag lookup", (changeRequestLookup) => {
|
||||
const gitStatus = status({ aheadCount: 2, changeRequestLookup });
|
||||
|
||||
assert.equal(resolveQuickAction(gitStatus, false).action, "push");
|
||||
const prItem = buildMenuItems(gitStatus, false).find((item) => item.id === "pr");
|
||||
assert.equal(prItem?.disabled, true);
|
||||
assert.notEqual(prItem?.label, "Create PR");
|
||||
});
|
||||
|
||||
it("keeps an existing PR actionable when a refresh fails", () => {
|
||||
const gitStatus = status({
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(resolveQuickAction(gitStatus, false).kind, "open_pr");
|
||||
assert.equal(
|
||||
buildMenuItems(gitStatus, false).find((item) => item.id === "pr")?.label,
|
||||
"View PR",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
|
||||
@@ -3,11 +3,7 @@ import type {
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
canCreateChangeRequest,
|
||||
getChangeRequestAvailability,
|
||||
isTemporaryWorktreeBranch,
|
||||
} from "@t3tools/shared/git";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
import {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
getChangeRequestTerminology,
|
||||
@@ -105,9 +101,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
|
||||
@@ -122,7 +116,7 @@ export function buildMenuItems(
|
||||
!isBusy &&
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
canCreateChangeRequest(gitStatus) &&
|
||||
!hasOpenPr &&
|
||||
hasDefaultBranchDelta &&
|
||||
!isBehind &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
@@ -161,11 +155,7 @@ export function buildMenuItems(
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: lookupSucceeded
|
||||
? `Create ${terminology.shortLabel}`
|
||||
: changeRequestAvailability === "pending"
|
||||
? `Checking ${terminology.shortLabel} status`
|
||||
: `${terminology.shortLabel} status unavailable`,
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -195,9 +185,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
@@ -217,7 +205,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -250,7 +238,7 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -284,7 +272,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -304,21 +292,6 @@ export function resolveQuickAction(
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
if (!lookupSucceeded) {
|
||||
return {
|
||||
label:
|
||||
changeRequestAvailability === "pending"
|
||||
? `Checking ${terminology.shortLabel} status`
|
||||
: `${terminology.shortLabel} status unavailable`,
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint:
|
||||
changeRequestAvailability === "pending"
|
||||
? `Checking for an existing ${terminology.singular}.`
|
||||
: `${terminology.shortLabel} status could not be checked.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasDefaultBranchDelta && !isDefaultRef) {
|
||||
return {
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
ThreadStatusLabel,
|
||||
ThreadWorktreeIndicator,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { autoAnimate } from "@formkit/auto-animate";
|
||||
@@ -471,7 +470,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const lookupWarning = changeRequestLookupWarning(thread.branch, gitStatus.data);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
@@ -713,22 +711,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{lookupWarning && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label={lookupWarning}
|
||||
className="inline-flex items-center justify-center text-amber-600/70 dark:text-amber-300/70"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TriangleAlertIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{lookupWarning}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
{renamingThreadKey === threadKey ? (
|
||||
<input
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
|
||||
export function changeRequestLookupWarning(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): string | null {
|
||||
if (
|
||||
threadBranch === null ||
|
||||
gitStatus === null ||
|
||||
gitStatus.refName !== threadBranch ||
|
||||
gitStatus.changeRequestLookup._tag !== "failed"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const presentation = resolveChangeRequestPresentation(gitStatus.sourceControlProvider);
|
||||
switch (gitStatus.changeRequestLookup.reason) {
|
||||
case "authentication_required":
|
||||
return `${presentation.shortName} status unavailable: authentication required.`;
|
||||
case "provider_unavailable":
|
||||
return `${presentation.shortName} status unavailable: provider integration unavailable.`;
|
||||
case "lookup_failed":
|
||||
return `${presentation.shortName} status unavailable: lookup failed.`;
|
||||
}
|
||||
}
|
||||
@@ -1,58 +1,9 @@
|
||||
import { ThreadId, type VcsStatusResult } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import { ThreadWorktreeIndicator } from "./ThreadStatusIndicators";
|
||||
|
||||
const failedStatus: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
sourceControlProvider: { kind: "github", name: "GitHub", baseUrl: "https://github.com" },
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/sidebar-indicator",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/sidebar-indicator",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "authentication_required",
|
||||
},
|
||||
};
|
||||
|
||||
describe("changeRequestLookupWarning", () => {
|
||||
it("returns actionable provider copy for the matching thread branch", () => {
|
||||
expect(changeRequestLookupWarning("feature/sidebar-indicator", failedStatus)).toBe(
|
||||
"PR status unavailable: authentication required.",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not leak warnings across branches", () => {
|
||||
expect(changeRequestLookupWarning("feature/other", failedStatus)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the refresh warning when a cached open PR remains actionable", () => {
|
||||
expect(
|
||||
changeRequestLookupWarning("feature/sidebar-indicator", {
|
||||
...failedStatus,
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Cached open PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/sidebar-indicator",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
).toBe("PR status unavailable: authentication required.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ThreadWorktreeIndicator", () => {
|
||||
it("renders the worktree folder and branch in an accessible label", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -4,13 +4,7 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import {
|
||||
CloudIcon,
|
||||
FolderGit2Icon,
|
||||
GitPullRequestIcon,
|
||||
TerminalIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProject } from "../state/entities";
|
||||
@@ -20,7 +14,6 @@ import { vcsEnvironment } from "../state/vcs";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { formatWorktreePathForDisplay } from "../worktreeCleanup";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -215,7 +208,6 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
);
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const lookupWarning = changeRequestLookupWarning(thread.branch, gitStatus.data);
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -223,7 +215,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
},
|
||||
});
|
||||
|
||||
if (!prStatus && !lookupWarning && !threadStatus) {
|
||||
if (!prStatus && !threadStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -244,21 +236,6 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{lookupWarning ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={lookupWarning}
|
||||
className="inline-flex items-center justify-center text-amber-600/70 dark:text-amber-300/70"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TriangleAlertIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{lookupWarning}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -329,8 +329,7 @@ function GitFetchIntervalSettings() {
|
||||
</div>
|
||||
<p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
|
||||
or security keys should only be prompted by explicit Git actions. Lightweight pull or
|
||||
merge request status checks continue without fetching Git remotes.
|
||||
or security keys should only be prompted by explicit Git actions.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
|
||||
@@ -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
|
||||
);
|
||||
|
||||
@@ -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] ??
|
||||
|
||||
@@ -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,64 +0,0 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildMenuItems, resolveQuickAction } from "./gitActions.ts";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/test",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/test",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("change request certainty", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" as const },
|
||||
{
|
||||
_tag: "failed" as const,
|
||||
provider: "github" as const,
|
||||
reason: "lookup_failed" as const,
|
||||
},
|
||||
])("never creates a PR while lookup is $._tag", (changeRequestLookup) => {
|
||||
const ahead = status({ aheadCount: 1, changeRequestLookup });
|
||||
const dirty = status({ hasWorkingTreeChanges: true, changeRequestLookup });
|
||||
|
||||
expect(resolveQuickAction(ahead, false).action).toBe("push");
|
||||
expect(resolveQuickAction(dirty, false).action).toBe("commit_push");
|
||||
expect(buildMenuItems(ahead, false).find((item) => item.id === "pr")?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("allows creation after a successful lookup confirms absence", () => {
|
||||
expect(resolveQuickAction(status({ aheadCount: 1 }), false).action).toBe("create_pr");
|
||||
});
|
||||
|
||||
it("keeps a cached open PR actionable when lookup fails", () => {
|
||||
const gitStatus = status({
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveQuickAction(gitStatus, false).kind).toBe("open_pr");
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,7 @@ import type {
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
canCreateChangeRequest,
|
||||
getChangeRequestAvailability,
|
||||
isTemporaryWorktreeBranch,
|
||||
} from "@t3tools/shared/git";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -95,9 +91,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
@@ -112,7 +106,7 @@ export function buildMenuItems(
|
||||
!isBusy &&
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
canCreateChangeRequest(gitStatus) &&
|
||||
!hasOpenPr &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
!isBehind &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
@@ -145,11 +139,7 @@ export function buildMenuItems(
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: lookupSucceeded
|
||||
? "Create PR"
|
||||
: changeRequestAvailability === "pending"
|
||||
? "Checking PR status"
|
||||
: "PR status unavailable",
|
||||
label: "Create PR",
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -179,9 +169,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
@@ -199,7 +187,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -233,7 +221,7 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -267,7 +255,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -287,19 +275,6 @@ export function resolveQuickAction(
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
if (!lookupSucceeded) {
|
||||
return {
|
||||
label:
|
||||
changeRequestAvailability === "pending" ? "Checking PR status" : "PR status unavailable",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint:
|
||||
changeRequestAvailability === "pending"
|
||||
? "Checking for an existing PR."
|
||||
: "PR status could not be checked.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
GitRunStackedActionResult,
|
||||
GitRunStackedActionInput,
|
||||
GitResolvePullRequestResult,
|
||||
VcsStatusChangeRequestLookup,
|
||||
} from "./git.ts";
|
||||
|
||||
const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput);
|
||||
@@ -17,19 +16,6 @@ const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
|
||||
const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput);
|
||||
const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActionResult);
|
||||
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
|
||||
const decodeChangeRequestLookup = Schema.decodeUnknownSync(VcsStatusChangeRequestLookup);
|
||||
|
||||
describe("VcsStatusChangeRequestLookup", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" },
|
||||
{ _tag: "succeeded" },
|
||||
{ _tag: "failed", provider: "github", reason: "authentication_required" },
|
||||
{ _tag: "failed", provider: "gitlab", reason: "provider_unavailable" },
|
||||
{ _tag: "failed", provider: "bitbucket", reason: "lookup_failed" },
|
||||
])("decodes provider-neutral lookup state $._tag", (lookup) => {
|
||||
expect(decodeChangeRequestLookup(lookup)).toEqual(lookup);
|
||||
});
|
||||
});
|
||||
|
||||
describe("VcsCreateWorktreeInput", () => {
|
||||
it("accepts omitted newRefName for existing-refName worktrees", () => {
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import {
|
||||
SourceControlProviderError,
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
} from "./sourceControl.ts";
|
||||
import { SourceControlProviderError, SourceControlProviderInfo } from "./sourceControl.ts";
|
||||
import { VcsDriverKind } from "./vcs.ts";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
@@ -202,16 +198,6 @@ const VcsStatusChangeRequest = Schema.Struct({
|
||||
state: VcsStatusChangeRequestState,
|
||||
});
|
||||
|
||||
export const VcsStatusChangeRequestLookup = Schema.Union([
|
||||
Schema.TaggedStruct("pending", {}),
|
||||
Schema.TaggedStruct("succeeded", {}),
|
||||
Schema.TaggedStruct("failed", {
|
||||
provider: SourceControlProviderKind,
|
||||
reason: Schema.Literals(["authentication_required", "provider_unavailable", "lookup_failed"]),
|
||||
}),
|
||||
]);
|
||||
export type VcsStatusChangeRequestLookup = typeof VcsStatusChangeRequestLookup.Type;
|
||||
|
||||
const VcsStatusLocalShape = {
|
||||
isRepo: Schema.Boolean,
|
||||
sourceControlProvider: Schema.optional(SourceControlProviderInfo),
|
||||
@@ -233,13 +219,11 @@ const VcsStatusLocalShape = {
|
||||
};
|
||||
|
||||
const VcsStatusRemoteShape = {
|
||||
statusRefName: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
aheadOfDefaultCount: Schema.optional(NonNegativeInt),
|
||||
pr: Schema.NullOr(VcsStatusChangeRequest),
|
||||
changeRequestLookup: VcsStatusChangeRequestLookup,
|
||||
};
|
||||
|
||||
export const VcsStatusLocalResult = Schema.Struct(VcsStatusLocalShape);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -79,38 +79,12 @@ describe("isTemporaryWorktreeBranch", () => {
|
||||
});
|
||||
|
||||
describe("applyGitStatusStreamEvent", () => {
|
||||
const localStatus = {
|
||||
isRepo: true as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
it("keeps an initial snapshot pending until remote lookup completes", () => {
|
||||
expect(
|
||||
applyGitStatusStreamEvent(null, {
|
||||
_tag: "snapshot",
|
||||
local: localStatus,
|
||||
remote: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
refName: "feature/demo",
|
||||
statusRefName: null,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a remote-only update as a repository when local state is missing", () => {
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
statusRefName: null,
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
@@ -120,12 +94,10 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: null,
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -146,21 +118,17 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
insertions: 1,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(applyGitStatusStreamEvent(current, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
@@ -169,77 +137,6 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
});
|
||||
|
||||
it("clears remote state when a local update switches branches", () => {
|
||||
const current: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/old",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/old",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Old branch PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseRef: "main",
|
||||
headRef: "feature/old",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(
|
||||
applyGitStatusStreamEvent(current, {
|
||||
_tag: "localUpdated",
|
||||
local: { ...current, refName: "feature/new" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
refName: "feature/new",
|
||||
statusRefName: null,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores a late remote update calculated for a previous branch", () => {
|
||||
const current: VcsStatusResult = {
|
||||
...localStatus,
|
||||
refName: "feature/new",
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
};
|
||||
|
||||
expect(
|
||||
applyGitStatusStreamEvent(current, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: {
|
||||
statusRefName: "feature/old",
|
||||
hasUpstream: true,
|
||||
aheadCount: 1,
|
||||
behindCount: 0,
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Old branch PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseRef: "main",
|
||||
headRef: "feature/old",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
},
|
||||
}),
|
||||
).toEqual(current);
|
||||
});
|
||||
});
|
||||
@@ -203,37 +203,25 @@ export function detectSourceControlProviderFromGitRemoteUrl(
|
||||
}
|
||||
|
||||
const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
};
|
||||
|
||||
function remoteStatusForLocal(
|
||||
local: VcsStatusLocalResult,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
): VcsStatusRemoteResult {
|
||||
return remote !== null && remote.statusRefName === local.refName
|
||||
? remote
|
||||
: EMPTY_GIT_STATUS_REMOTE;
|
||||
}
|
||||
|
||||
export function mergeGitStatusParts(
|
||||
local: VcsStatusLocalResult,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
): VcsStatusResult {
|
||||
return {
|
||||
...local,
|
||||
...remoteStatusForLocal(local, remote),
|
||||
...(remote ?? EMPTY_GIT_STATUS_REMOTE),
|
||||
};
|
||||
}
|
||||
|
||||
function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
return {
|
||||
statusRefName: status.statusRefName,
|
||||
hasUpstream: status.hasUpstream,
|
||||
aheadCount: status.aheadCount,
|
||||
behindCount: status.behindCount,
|
||||
@@ -241,7 +229,6 @@ function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
? {}
|
||||
: { aheadOfDefaultCount: status.aheadOfDefaultCount }),
|
||||
pr: status.pr,
|
||||
changeRequestLookup: status.changeRequestLookup,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -282,22 +269,6 @@ export function applyGitStatusStreamEvent(
|
||||
event.remote,
|
||||
);
|
||||
}
|
||||
if (event.remote?.statusRefName !== current.refName) {
|
||||
return current;
|
||||
}
|
||||
return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
|
||||
}
|
||||
}
|
||||
|
||||
export type ChangeRequestAvailability = "pending" | "failed" | "open" | "available";
|
||||
|
||||
export function getChangeRequestAvailability(status: VcsStatusResult): ChangeRequestAvailability {
|
||||
if (status.pr?.state === "open") return "open";
|
||||
if (status.changeRequestLookup._tag === "pending") return "pending";
|
||||
if (status.changeRequestLookup._tag === "failed") return "failed";
|
||||
return "available";
|
||||
}
|
||||
|
||||
export function canCreateChangeRequest(status: VcsStatusResult): boolean {
|
||||
return getChangeRequestAvailability(status) === "available";
|
||||
}
|
||||
Reference in new issue
Block a user