Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d31b1c810f | ||
|
|
e4061d41b4 | ||
|
|
233e0b45ce | ||
|
|
590103ee7f |
No files matched your search
@@ -20,6 +20,7 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
projectThreadEnvModeOverrides: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
@@ -23,54 +23,46 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
const DEVELOPMENT_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-dev.png",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
|
||||
androidAdaptiveBackgroundColor: "#00639B",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#00639B",
|
||||
} as const;
|
||||
|
||||
const RELEASE_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-prod.png",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-mark.png",
|
||||
androidAdaptiveBackgroundColor: "#000000",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#FFFFFF",
|
||||
} as const;
|
||||
|
||||
const VARIANT_CONFIG = {
|
||||
const VARIANT_CONFIG: Record<
|
||||
AppVariant,
|
||||
{
|
||||
readonly appName: string;
|
||||
readonly scheme: string;
|
||||
readonly iosIcon: string;
|
||||
readonly splashIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
}
|
||||
> = {
|
||||
development: {
|
||||
appName: "T3 Code Dev",
|
||||
scheme: "t3code-dev",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: DEVELOPMENT_ASSETS,
|
||||
},
|
||||
preview: {
|
||||
appName: "T3 Code Preview",
|
||||
scheme: "t3code-preview",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
scheme: "t3code",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
} as const;
|
||||
};
|
||||
|
||||
function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
switch (value) {
|
||||
@@ -129,7 +121,7 @@ const config: ExpoConfig = {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: variant.assets.appIcon,
|
||||
icon: "./assets/icon.png",
|
||||
userInterfaceStyle: "automatic",
|
||||
updates: {
|
||||
enabled: true,
|
||||
@@ -138,7 +130,7 @@ const config: ExpoConfig = {
|
||||
fallbackToCacheTimeout: 0,
|
||||
},
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
@@ -159,12 +151,13 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
android: {
|
||||
icon: variant.assets.appIcon,
|
||||
icon: "./assets/icon.png",
|
||||
package: variant.androidPackage,
|
||||
adaptiveIcon: {
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
monochromeImage: variant.assets.androidMonochromeIcon,
|
||||
backgroundColor: "#E6F4FE",
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundImage: "./assets/android-icon-background.png",
|
||||
monochromeImage: "./assets/android-icon-monochrome.png",
|
||||
},
|
||||
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
|
||||
// JS back handling survives it via react-native's Android 16 shim plus
|
||||
@@ -172,7 +165,7 @@ const config: ExpoConfig = {
|
||||
predictiveBackGestureEnabled: true,
|
||||
},
|
||||
web: {
|
||||
favicon: variant.assets.appIcon,
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-asset",
|
||||
@@ -202,14 +195,6 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
icon: variant.assets.androidNotificationIcon,
|
||||
color: variant.assets.androidNotificationColor,
|
||||
mode: APP_VARIANT === "development" ? "development" : "production",
|
||||
},
|
||||
],
|
||||
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
|
||||
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
|
||||
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
|
||||
@@ -221,8 +206,8 @@ const config: ExpoConfig = {
|
||||
// the shortcut items set in src/features/shortcuts.
|
||||
androidIcons: {
|
||||
shortcut_icon: {
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundColor: "#E6F4FE",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -232,18 +217,17 @@ const config: ExpoConfig = {
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
image: variant.assets.splashIcon,
|
||||
image: variant.splashIcon,
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#ffffff",
|
||||
imageWidth: 220,
|
||||
dark: {
|
||||
image: variant.assets.splashIcon,
|
||||
image: variant.splashIcon,
|
||||
backgroundColor: "#0a0a0a",
|
||||
},
|
||||
},
|
||||
|
||||
|
Before Width: | Height: | Size: 323 KiB After Width: | Height: | Size: 323 KiB |
|
After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 733 B |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 2.0 MiB |
@@ -1,315 +0,0 @@
|
||||
package expo.modules.t3reviewdiff
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
internal class ReviewDiffCanvasDrawing(context: Context) {
|
||||
private val density = context.resources.displayMetrics.density
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
|
||||
val backgroundPaint = Paint()
|
||||
val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
|
||||
private val italicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
|
||||
}
|
||||
private val boldItalicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
|
||||
}
|
||||
|
||||
init {
|
||||
textPaint.typeface = ReviewDiffTypefaces.regular
|
||||
uiPaint.typeface = Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val left = style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
|
||||
}
|
||||
|
||||
fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val chevron = fileHeaderChevronRect(top, bottom, style)
|
||||
return RectF(
|
||||
chevron.right + 8f * density,
|
||||
chevron.top,
|
||||
chevron.right + 28f * density,
|
||||
chevron.bottom,
|
||||
)
|
||||
}
|
||||
|
||||
fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val right = width - style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(
|
||||
right - 20f * density,
|
||||
centerY - 10f * density,
|
||||
right,
|
||||
centerY + 10f * density,
|
||||
)
|
||||
}
|
||||
|
||||
fun drawDisclosureChevron(
|
||||
canvas: Canvas,
|
||||
rect: RectF,
|
||||
color: Int,
|
||||
collapsed: Boolean
|
||||
) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path()
|
||||
if (collapsed) {
|
||||
path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
|
||||
path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
|
||||
path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
|
||||
} else {
|
||||
path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
|
||||
path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
|
||||
val color = when (changeType) {
|
||||
"new" -> theme.addText
|
||||
"deleted" -> theme.deleteText
|
||||
else -> theme.hunkText
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
|
||||
if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
|
||||
drawRenameChevronIcon(canvas, rect, color)
|
||||
} else {
|
||||
backgroundPaint.color = color
|
||||
canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
|
||||
if (checked) {
|
||||
backgroundPaint.color = theme.hunkText
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = if (checked) theme.hunkText else theme.mutedText
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
if (checked) {
|
||||
borderPaint.color = theme.background
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path().apply {
|
||||
moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
|
||||
lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
|
||||
lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.7f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
canvas.drawOval(rect, borderPaint)
|
||||
canvas.drawLine(
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.3f,
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.58f,
|
||||
borderPaint,
|
||||
)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
|
||||
}
|
||||
|
||||
fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
|
||||
paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
||||
configureTextPaint(paint, color, size)
|
||||
}
|
||||
|
||||
fun configureMonospacePaint(color: Int, size: Float, weight: String) {
|
||||
textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
|
||||
configureTextPaint(textPaint, color, size)
|
||||
}
|
||||
|
||||
fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
|
||||
val tokenBold = fontStyle and 2 != 0
|
||||
val italic = fontStyle and 1 != 0
|
||||
textPaint.typeface = when {
|
||||
tokenBold && italic -> boldItalicCodeTypeface
|
||||
tokenBold -> ReviewDiffTypefaces.bold
|
||||
italic -> italicCodeTypeface
|
||||
else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
|
||||
}
|
||||
configureTextPaint(textPaint, color, style.codeFontSizePx)
|
||||
textPaint.isUnderlineText = fontStyle and 4 != 0
|
||||
}
|
||||
|
||||
fun lineNumberColor(change: String): Int = when (change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.mutedText
|
||||
}
|
||||
|
||||
fun drawDeleteStripes(
|
||||
canvas: Canvas,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
width: Float,
|
||||
color: Int
|
||||
) {
|
||||
backgroundPaint.color = color
|
||||
var y = top.toFloat()
|
||||
while (y < bottom) {
|
||||
canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
|
||||
y += 2f * density
|
||||
}
|
||||
}
|
||||
|
||||
fun drawWordDiffRanges(
|
||||
canvas: Canvas,
|
||||
row: DiffRow,
|
||||
codeX: Float,
|
||||
top: Int,
|
||||
bottom: Int
|
||||
) {
|
||||
if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
|
||||
val color = if (row.change == "add") theme.addBar else theme.deleteBar
|
||||
backgroundPaint.color = withAlpha(color, 71)
|
||||
val characterWidth = textPaint.measureText("M")
|
||||
val fontHeight = textPaint.fontMetrics.run { descent - ascent }
|
||||
val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
|
||||
val highlightTop = (top + bottom - highlightHeight) / 2f
|
||||
row.wordDiffRanges.forEach { range ->
|
||||
val left = codeX + range.start * characterWidth
|
||||
val right = max(left + 2f * density, codeX + range.end * characterWidth)
|
||||
canvas.drawRoundRect(
|
||||
RectF(left, highlightTop, right, highlightTop + highlightHeight),
|
||||
3f * density,
|
||||
3f * density,
|
||||
backgroundPaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun drawFileHeaderPathScrollFades(
|
||||
canvas: Canvas,
|
||||
pathRect: RectF,
|
||||
horizontalOffset: Int,
|
||||
maxOffset: Int
|
||||
) {
|
||||
if (maxOffset <= 0 || pathRect.width() <= 0f) return
|
||||
val fadeWidth = min(28f * density, pathRect.width() / 3f)
|
||||
if (horizontalOffset > 0) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
|
||||
fadesToRight = false,
|
||||
)
|
||||
}
|
||||
if (horizontalOffset < maxOffset) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
|
||||
fadesToRight = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val chevronWidth = 3.6f * density
|
||||
val chevronHeight = 8f * density
|
||||
val gap = 2.4f * density
|
||||
val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
|
||||
val path = Path()
|
||||
for (x in listOf(startX, startX + chevronWidth + gap)) {
|
||||
path.moveTo(x, rect.centerY() - chevronHeight / 2f)
|
||||
path.lineTo(x + chevronWidth, rect.centerY())
|
||||
path.lineTo(x, rect.centerY() + chevronHeight / 2f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
|
||||
private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
|
||||
paint.textSize = size
|
||||
paint.color = color
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.textAlign = Paint.Align.LEFT
|
||||
paint.isUnderlineText = false
|
||||
paint.isFakeBoldText = false
|
||||
paint.clearShadowLayer()
|
||||
}
|
||||
|
||||
private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
|
||||
val opaque = theme.headerBackground
|
||||
val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
|
||||
backgroundPaint.shader = LinearGradient(
|
||||
rect.left,
|
||||
rect.centerY(),
|
||||
rect.right,
|
||||
rect.centerY(),
|
||||
if (fadesToRight) transparent else opaque,
|
||||
if (fadesToRight) opaque else transparent,
|
||||
Shader.TileMode.CLAMP,
|
||||
)
|
||||
canvas.drawRect(rect, backgroundPaint)
|
||||
backgroundPaint.shader = null
|
||||
}
|
||||
|
||||
private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
|
||||
}
|
||||
|
||||
private object ReviewDiffTypefaces {
|
||||
val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
|
||||
private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
|
||||
val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
|
||||
|
||||
fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold" -> medium
|
||||
"bold", "heavy", "black" -> bold
|
||||
else -> regular
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Typeface
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.VelocityTracker
|
||||
@@ -19,7 +19,6 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
@@ -50,13 +49,12 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
private val verticalScroller = OverScroller(context)
|
||||
private val horizontalScroller = OverScroller(context)
|
||||
private var dragAxis: DragAxis? = null
|
||||
private var horizontalDragTarget: HorizontalPanTarget? = null
|
||||
private var lastTouchX = 0f
|
||||
private var lastTouchY = 0f
|
||||
private var velocityTracker: VelocityTracker? = null
|
||||
|
||||
init {
|
||||
canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }
|
||||
canvasView.onRowTap = { row, gesture -> handleRowTap(row, gesture) }
|
||||
canvasView.onVisibleRowsChanged = { first, last ->
|
||||
onDebug(
|
||||
mapOf(
|
||||
@@ -88,13 +86,12 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
lastVisibleFileId = null
|
||||
pendingInitialScroll = true
|
||||
canvasView.setVerticalOffset(0)
|
||||
canvasView.resetHorizontalOffsets()
|
||||
canvasView.setHorizontalOffset(0)
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
fun setCollapsedFileIdsJson(value: String) {
|
||||
collapsedFileIds = parseStringSet(value)
|
||||
canvasView.collapsedFileIds = collapsedFileIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -110,7 +107,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
|
||||
fun setCollapsedCommentIdsJson(value: String) {
|
||||
collapsedCommentIds = parseStringSet(value)
|
||||
canvasView.collapsedCommentIds = collapsedCommentIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -206,7 +202,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
verticalScroller.forceFinished(true)
|
||||
horizontalScroller.forceFinished(true)
|
||||
dragAxis = null
|
||||
horizontalDragTarget = canvasView.horizontalPanTarget(event.y)
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
parent?.requestDisallowInterceptTouchEvent(true)
|
||||
@@ -217,13 +212,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
val deltaX = event.x - lastTouchX
|
||||
val deltaY = event.y - lastTouchY
|
||||
if (max(abs(deltaX), abs(deltaY)) > touchSlop) {
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) {
|
||||
DragAxis.VERTICAL
|
||||
} else {
|
||||
horizontalDragTarget
|
||||
?.takeIf { canvasView.maxHorizontalOffset(it) > 0 }
|
||||
?.let { DragAxis.HORIZONTAL }
|
||||
}
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) DragAxis.VERTICAL else DragAxis.HORIZONTAL
|
||||
}
|
||||
}
|
||||
return dragAxis != null
|
||||
@@ -249,7 +238,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
) {
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
horizontalDragTarget = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
}
|
||||
return handled
|
||||
@@ -265,7 +253,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
if (axis == DragAxis.VERTICAL) {
|
||||
canvasView.scrollByVertical(deltaY)
|
||||
} else {
|
||||
horizontalDragTarget?.let { canvasView.scrollByHorizontal(deltaX, it) }
|
||||
canvasView.scrollByHorizontal(deltaX)
|
||||
}
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
@@ -288,7 +276,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
)
|
||||
postInvalidateOnAnimation()
|
||||
}
|
||||
} else if (horizontalDragTarget?.kind == HorizontalPanKind.CODE) {
|
||||
} else {
|
||||
val velocity = -(velocityTracker?.xVelocity ?: 0f).toInt()
|
||||
if (abs(velocity) >= minimumFlingVelocity) {
|
||||
horizontalScroller.fling(
|
||||
@@ -306,7 +294,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
dragAxis = null
|
||||
horizontalDragTarget = null
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
@@ -338,7 +325,11 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
|
||||
filtered.add(row)
|
||||
} else if (!currentFileCollapsed) {
|
||||
filtered.add(row)
|
||||
if (row.kind != "comment" || !collapsedCommentIds.contains(row.id)) {
|
||||
filtered.add(row)
|
||||
} else {
|
||||
filtered.add(row.copy(commentText = "Comment collapsed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
visibleRows = filtered
|
||||
@@ -348,11 +339,10 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) {
|
||||
private fun handleRowTap(row: DiffRow, gesture: String) {
|
||||
when (row.kind) {
|
||||
"file" -> {
|
||||
if (gesture != "tap") return
|
||||
if (target == RowTapTarget.VIEWED_CHECKBOX) {
|
||||
if (gesture == "longPress") {
|
||||
onToggleViewedFile(mapOf("fileId" to row.resolvedFileId))
|
||||
} else {
|
||||
onToggleFile(mapOf("fileId" to row.resolvedFileId))
|
||||
@@ -418,22 +408,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
|
||||
private enum class RowTapTarget {
|
||||
ROW,
|
||||
VIEWED_CHECKBOX
|
||||
}
|
||||
|
||||
private enum class HorizontalPanKind {
|
||||
CODE,
|
||||
FILE_HEADER_PATH
|
||||
}
|
||||
|
||||
private data class HorizontalPanTarget(
|
||||
val fileId: String,
|
||||
val kind: HorizontalPanKind
|
||||
)
|
||||
|
||||
internal data class DiffRow(
|
||||
private data class DiffRow(
|
||||
val kind: String,
|
||||
val id: String,
|
||||
val fileId: String,
|
||||
@@ -447,7 +422,6 @@ internal data class DiffRow(
|
||||
val change: String,
|
||||
val oldLineNumber: Int?,
|
||||
val newLineNumber: Int?,
|
||||
val wordDiffRanges: List<DiffWordDiffRange>,
|
||||
val commentText: String,
|
||||
val commentRangeLabel: String,
|
||||
val commentSectionTitle: String
|
||||
@@ -455,18 +429,13 @@ internal data class DiffRow(
|
||||
val resolvedFileId: String get() = fileId.ifEmpty { id }
|
||||
}
|
||||
|
||||
internal data class DiffWordDiffRange(
|
||||
val start: Int,
|
||||
val end: Int
|
||||
)
|
||||
|
||||
private data class DiffToken(
|
||||
val content: String,
|
||||
val color: Int?,
|
||||
val fontStyle: Int
|
||||
)
|
||||
|
||||
internal data class DiffTheme(
|
||||
private data class DiffTheme(
|
||||
val background: Int,
|
||||
val text: Int,
|
||||
val mutedText: Int,
|
||||
@@ -542,25 +511,14 @@ internal data class DiffTheme(
|
||||
}
|
||||
}
|
||||
|
||||
internal data class DiffStyle(
|
||||
private data class DiffStyle(
|
||||
val rowHeightPx: Float,
|
||||
val gutterWidthPx: Float,
|
||||
val codePaddingPx: Float,
|
||||
val changeBarWidthPx: Float,
|
||||
val fileHeaderHeightPx: Float,
|
||||
val fileHeaderHorizontalPaddingPx: Float,
|
||||
val codeFontSizePx: Float,
|
||||
val codeFontWeight: String,
|
||||
val lineNumberFontSizePx: Float,
|
||||
val lineNumberFontWeight: String,
|
||||
val hunkFontSizePx: Float,
|
||||
val hunkFontWeight: String,
|
||||
val fileHeaderFontSizePx: Float,
|
||||
val fileHeaderFontWeight: String,
|
||||
val fileHeaderMetaFontSizePx: Float,
|
||||
val fileHeaderMetaFontWeight: String,
|
||||
val fileHeaderSubtextFontSizePx: Float,
|
||||
val fileHeaderSubtextFontWeight: String
|
||||
val lineNumberFontSizePx: Float
|
||||
) {
|
||||
companion object {
|
||||
fun defaults(density: Float): DiffStyle = DiffStyle(
|
||||
@@ -569,19 +527,8 @@ internal data class DiffStyle(
|
||||
codePaddingPx = 10f * density,
|
||||
changeBarWidthPx = 3f * density,
|
||||
fileHeaderHeightPx = 44f * density,
|
||||
fileHeaderHorizontalPaddingPx = 10f * density,
|
||||
codeFontSizePx = 12f * density,
|
||||
codeFontWeight = "regular",
|
||||
lineNumberFontSizePx = 10f * density,
|
||||
lineNumberFontWeight = "regular",
|
||||
hunkFontSizePx = 11f * density,
|
||||
hunkFontWeight = "medium",
|
||||
fileHeaderFontSizePx = 11f * density,
|
||||
fileHeaderFontWeight = "semibold",
|
||||
fileHeaderMetaFontSizePx = 10f * density,
|
||||
fileHeaderMetaFontWeight = "semibold",
|
||||
fileHeaderSubtextFontSizePx = 11f * density,
|
||||
fileHeaderSubtextFontWeight = "medium",
|
||||
)
|
||||
|
||||
fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try {
|
||||
@@ -592,50 +539,11 @@ internal data class DiffStyle(
|
||||
codePaddingPx = json.floatDp("codePadding", fallback.codePaddingPx, density),
|
||||
changeBarWidthPx = json.floatDp("changeBarWidth", fallback.changeBarWidthPx, density),
|
||||
fileHeaderHeightPx = json.floatDp("fileHeaderHeight", fallback.fileHeaderHeightPx, density),
|
||||
fileHeaderHorizontalPaddingPx = json.floatDp(
|
||||
"fileHeaderHorizontalPadding",
|
||||
fallback.fileHeaderHorizontalPaddingPx,
|
||||
density,
|
||||
),
|
||||
codeFontSizePx = json.floatSp("codeFontSize", fallback.codeFontSizePx, density),
|
||||
codeFontWeight = json.optString("codeFontWeight", fallback.codeFontWeight),
|
||||
lineNumberFontSizePx = json.floatSp(
|
||||
"lineNumberFontSize",
|
||||
fallback.lineNumberFontSizePx,
|
||||
density,
|
||||
),
|
||||
lineNumberFontWeight = json.optString(
|
||||
"lineNumberFontWeight",
|
||||
fallback.lineNumberFontWeight,
|
||||
),
|
||||
hunkFontSizePx = json.floatSp("hunkFontSize", fallback.hunkFontSizePx, density),
|
||||
hunkFontWeight = json.optString("hunkFontWeight", fallback.hunkFontWeight),
|
||||
fileHeaderFontSizePx = json.floatSp(
|
||||
"fileHeaderFontSize",
|
||||
fallback.fileHeaderFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderFontWeight = json.optString(
|
||||
"fileHeaderFontWeight",
|
||||
fallback.fileHeaderFontWeight,
|
||||
),
|
||||
fileHeaderMetaFontSizePx = json.floatSp(
|
||||
"fileHeaderMetaFontSize",
|
||||
fallback.fileHeaderMetaFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderMetaFontWeight = json.optString(
|
||||
"fileHeaderMetaFontWeight",
|
||||
fallback.fileHeaderMetaFontWeight,
|
||||
),
|
||||
fileHeaderSubtextFontSizePx = json.floatSp(
|
||||
"fileHeaderSubtextFontSize",
|
||||
fallback.fileHeaderSubtextFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderSubtextFontWeight = json.optString(
|
||||
"fileHeaderSubtextFontWeight",
|
||||
fallback.fileHeaderSubtextFontWeight,
|
||||
density
|
||||
),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
@@ -646,54 +554,35 @@ internal data class DiffStyle(
|
||||
|
||||
private class DiffCanvasView(context: Context) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
private val drawing = ReviewDiffCanvasDrawing(context)
|
||||
private val backgroundPaint = drawing.backgroundPaint
|
||||
private val borderPaint = drawing.borderPaint
|
||||
private val textPaint = drawing.textPaint
|
||||
private val boldTextPaint = drawing.uiPaint
|
||||
private val backgroundPaint = Paint()
|
||||
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = Typeface.MONOSPACE }
|
||||
private val boldTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
private val gestureDetector = GestureDetector(
|
||||
context,
|
||||
object : GestureDetector.SimpleOnGestureListener() {
|
||||
override fun onDown(event: MotionEvent): Boolean = true
|
||||
|
||||
override fun onSingleTapUp(event: MotionEvent): Boolean {
|
||||
rowHitAt(event.y)?.let { hit ->
|
||||
val target = if (
|
||||
hit.row.kind == "file" &&
|
||||
drawing.fileHeaderCheckboxRect(
|
||||
hit.top,
|
||||
hit.bottom,
|
||||
width,
|
||||
style
|
||||
).contains(event.x, event.y)
|
||||
) {
|
||||
RowTapTarget.VIEWED_CHECKBOX
|
||||
} else {
|
||||
RowTapTarget.ROW
|
||||
}
|
||||
onRowTap?.invoke(hit.row, "tap", target)
|
||||
}
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "tap") }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onLongPress(event: MotionEvent) {
|
||||
rowHitAt(event.y)?.row
|
||||
?.takeIf { it.kind == "line" }
|
||||
?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) }
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "longPress") }
|
||||
}
|
||||
},
|
||||
)
|
||||
private var rowOffsets = intArrayOf(0)
|
||||
private var verticalOffset = 0
|
||||
private var horizontalOffset = 0
|
||||
private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()
|
||||
private var lastVisibleRange: Pair<Int, Int>? = null
|
||||
|
||||
var rows: List<DiffRow> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
headerPathOffsetsByFileId.keys.retainAll(
|
||||
value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),
|
||||
)
|
||||
rebuildOffsets()
|
||||
}
|
||||
var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()
|
||||
@@ -706,16 +595,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedFileIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedCommentIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
rebuildOffsets()
|
||||
}
|
||||
var selectedRowIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -724,7 +603,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
set(value) {
|
||||
field = value
|
||||
drawing.theme = value
|
||||
invalidate()
|
||||
}
|
||||
var style: DiffStyle = DiffStyle.defaults(density)
|
||||
@@ -736,10 +614,9 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
set(value) {
|
||||
field = max(value, suggestedMinimumWidth)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
invalidate()
|
||||
}
|
||||
var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null
|
||||
var onRowTap: ((DiffRow, String) -> Unit)? = null
|
||||
var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
@@ -753,7 +630,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
super.onSizeChanged(width, height, oldWidth, oldHeight)
|
||||
setVerticalOffset(verticalOffset)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -805,63 +681,27 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun scrollByHorizontal(delta: Int, target: HorizontalPanTarget) {
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
setHeaderPathOffset(
|
||||
target.fileId,
|
||||
(headerPathOffsetsByFileId[target.fileId] ?: 0) + delta,
|
||||
)
|
||||
} else {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
}
|
||||
fun scrollByHorizontal(delta: Int) {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
}
|
||||
|
||||
fun horizontalOffset(): Int = horizontalOffset
|
||||
|
||||
fun maxHorizontalOffset(): Int = max(0, contentWidthPx - width)
|
||||
|
||||
fun maxHorizontalOffset(target: HorizontalPanTarget): Int =
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
maxHeaderPathOffset(target.fileId)
|
||||
} else {
|
||||
maxHorizontalOffset()
|
||||
}
|
||||
|
||||
fun horizontalPanTarget(y: Float): HorizontalPanTarget? {
|
||||
val row = rowHitAt(y)?.row ?: return null
|
||||
return HorizontalPanTarget(
|
||||
fileId = row.resolvedFileId,
|
||||
kind = if (row.kind == "file") HorizontalPanKind.FILE_HEADER_PATH else HorizontalPanKind.CODE,
|
||||
)
|
||||
}
|
||||
|
||||
fun resetHorizontalOffsets() {
|
||||
setHorizontalOffset(0)
|
||||
if (headerPathOffsetsByFileId.isNotEmpty()) {
|
||||
headerPathOffsetsByFileId.clear()
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private fun rebuildOffsets() {
|
||||
rowOffsets = IntArray(rows.size + 1)
|
||||
rows.forEachIndexed { index, row ->
|
||||
rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)
|
||||
}
|
||||
setVerticalOffset(verticalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
requestLayout()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun rowHeight(row: DiffRow): Int = when (row.kind) {
|
||||
"file" -> style.fileHeaderHeightPx.toInt()
|
||||
"notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt())
|
||||
"comment" -> if (collapsedCommentIds.contains(row.id)) {
|
||||
(44 * density).toInt()
|
||||
} else {
|
||||
(124 * density).toInt()
|
||||
}
|
||||
"comment" -> max((style.rowHeightPx * 3.2f).toInt(), (56 * density).toInt())
|
||||
else -> style.rowHeightPx.toInt()
|
||||
}.coerceAtLeast(1)
|
||||
|
||||
@@ -881,20 +721,13 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
return low.coerceIn(0, rows.lastIndex)
|
||||
}
|
||||
|
||||
private fun rowHitAt(y: Float): RowHit? {
|
||||
private fun rowAt(y: Float): DiffRow? {
|
||||
stickyFileHeader(firstVisibleRow())?.let { sticky ->
|
||||
if (y >= max(0, sticky.top).toFloat() && y < sticky.bottom.toFloat()) {
|
||||
return rows.getOrNull(sticky.index)?.let { RowHit(it, sticky.top, sticky.bottom) }
|
||||
return rows.getOrNull(sticky.index)
|
||||
}
|
||||
}
|
||||
val index = rowIndexAt(verticalOffset + y.toInt())
|
||||
return rows.getOrNull(index)?.let {
|
||||
RowHit(
|
||||
row = it,
|
||||
top = rowOffsets[index] - verticalOffset,
|
||||
bottom = rowOffsets[index + 1] - verticalOffset,
|
||||
)
|
||||
}
|
||||
return rows.getOrNull(rowIndexAt(verticalOffset + y.toInt()))
|
||||
}
|
||||
|
||||
private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)
|
||||
@@ -921,140 +754,23 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
|
||||
private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
|
||||
val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.drawDisclosureChevron(
|
||||
canvas,
|
||||
chevronRect,
|
||||
theme.mutedText,
|
||||
collapsed = collapsedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
drawing.drawFileIcon(canvas, iconRect, row.changeType)
|
||||
drawing.drawViewedCheckbox(
|
||||
canvas,
|
||||
checkboxRect,
|
||||
viewedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val deleteText = "-${row.deletions}"
|
||||
val deleteWidth = boldTextPaint.measureText(deleteText)
|
||||
val addText = "+${row.additions}"
|
||||
val addWidth = boldTextPaint.measureText(addText)
|
||||
val countGap = 4f * density
|
||||
val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint)
|
||||
canvas.drawText(deleteText, countsX, baseline, boldTextPaint)
|
||||
boldTextPaint.color = theme.addText
|
||||
canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint)
|
||||
|
||||
val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX)
|
||||
val maxPathOffset = maxHeaderPathOffset(pathLayout)
|
||||
val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0)
|
||||
.coerceIn(0, maxPathOffset)
|
||||
canvas.save()
|
||||
canvas.clipRect(pathLayout.rect)
|
||||
canvas.drawText(
|
||||
pathLayout.displayPath,
|
||||
pathLayout.rect.left - pathOffset,
|
||||
centeredBaseline(top, bottom, boldTextPaint),
|
||||
boldTextPaint,
|
||||
)
|
||||
canvas.restore()
|
||||
drawing.drawFileHeaderPathScrollFades(
|
||||
canvas,
|
||||
pathLayout.rect,
|
||||
pathOffset,
|
||||
maxPathOffset,
|
||||
)
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint.apply { textSize = 13f * density })
|
||||
boldTextPaint.color = theme.text
|
||||
val marker = if (viewedFileIds.contains(row.resolvedFileId)) "[x] " else "[ ] "
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 11f * density
|
||||
val stats = "+${row.additions} -${row.deletions}"
|
||||
val statsX = max(12f * density, width - textPaint.measureText(stats) - 16f * density)
|
||||
val title = ellipsize(marker + row.filePath, boldTextPaint, statsX - 28f * density)
|
||||
canvas.drawText(title, 12f * density, baseline, boldTextPaint)
|
||||
canvas.drawText(stats, statsX, baseline, textPaint)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
private fun fileHeaderPathLayout(
|
||||
row: DiffRow,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
iconRect: RectF,
|
||||
countsX: Float
|
||||
): FileHeaderPathLayout {
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.text,
|
||||
size = style.fileHeaderFontSizePx,
|
||||
weight = style.fileHeaderFontWeight,
|
||||
)
|
||||
val pathX = iconRect.right + 10f * density
|
||||
val pathWidth = max(24f * density, countsX - pathX - 12f * density)
|
||||
val centerY = (top + bottom) / 2f
|
||||
val displayPath = if (
|
||||
!row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath
|
||||
) {
|
||||
"${row.previousPath} -> ${row.filePath}"
|
||||
} else {
|
||||
row.filePath
|
||||
}
|
||||
return FileHeaderPathLayout(
|
||||
displayPath = displayPath,
|
||||
rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density),
|
||||
)
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(fileId: String): Int {
|
||||
val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0
|
||||
val top = 0
|
||||
val bottom = rowHeight(row)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val countsX = checkboxRect.left - 10f * density -
|
||||
boldTextPaint.measureText("-${row.deletions}") - 4f * density -
|
||||
boldTextPaint.measureText("+${row.additions}")
|
||||
return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX))
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max(
|
||||
0,
|
||||
ceil(boldTextPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(),
|
||||
)
|
||||
|
||||
private fun setHeaderPathOffset(fileId: String, value: Int) {
|
||||
val nextOffset = value.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if ((headerPathOffsetsByFileId[fileId] ?: 0) == nextOffset) return
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun clampHeaderPathOffsets() {
|
||||
headerPathOffsetsByFileId.keys.toList().forEach { fileId ->
|
||||
val nextOffset = (headerPathOffsetsByFileId[fileId] ?: 0)
|
||||
.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if (nextOffset == 0) {
|
||||
headerPathOffsetsByFileId.remove(fileId)
|
||||
} else {
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
drawing.configureMonospacePaint(
|
||||
color = theme.hunkText,
|
||||
size = style.hunkFontSizePx,
|
||||
weight = style.hunkFontWeight,
|
||||
)
|
||||
textPaint.color = theme.hunkText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(
|
||||
row.text.ifEmpty { row.content },
|
||||
@@ -1066,82 +782,36 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val iconSize = 16f * density
|
||||
val iconRect = RectF(
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density,
|
||||
(top + bottom - iconSize) / 2f,
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
|
||||
(top + bottom + iconSize) / 2f,
|
||||
)
|
||||
drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val textX = iconRect.right + 10f * density
|
||||
canvas.drawText(
|
||||
ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx),
|
||||
textX,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(row.text, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val cardRect = RectF(
|
||||
8f * density,
|
||||
top + 5f * density,
|
||||
width - 8f * density,
|
||||
bottom - 5f * density,
|
||||
fill(
|
||||
canvas,
|
||||
theme.headerBackground,
|
||||
style.gutterWidthPx,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat()
|
||||
)
|
||||
backgroundPaint.color = theme.headerBackground
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint)
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = withAlpha(theme.border, 217)
|
||||
borderPaint.strokeWidth = density
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
|
||||
val collapsed = collapsedCommentIds.contains(row.id)
|
||||
val chevronRect = RectF(
|
||||
cardRect.left + 10f * density,
|
||||
cardRect.top + 11f * density,
|
||||
cardRect.left + 26f * density,
|
||||
cardRect.top + 27f * density,
|
||||
)
|
||||
drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}"
|
||||
canvas.drawText(
|
||||
ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density),
|
||||
chevronRect.right + 10f * density,
|
||||
cardRect.top + 22f * density,
|
||||
textPaint,
|
||||
)
|
||||
if (!collapsed) {
|
||||
textPaint.color = theme.text
|
||||
val bodyX = cardRect.left + 18f * density
|
||||
boldTextPaint.color = theme.text
|
||||
boldTextPaint.textSize = 12f * density
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(
|
||||
ellipsize(
|
||||
row.commentText.ifEmpty { "Comment" },
|
||||
textPaint,
|
||||
cardRect.right - bodyX - 18f * density
|
||||
),
|
||||
bodyX,
|
||||
cardRect.top + 58f * density,
|
||||
textPaint,
|
||||
row.commentSectionTitle.ifEmpty { row.commentRangeLabel.ifEmpty { "Comment" } },
|
||||
codeX,
|
||||
top + 20f * density,
|
||||
boldTextPaint,
|
||||
)
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 12f * density
|
||||
canvas.drawText(row.commentText, codeX, top + 42f * density, textPaint)
|
||||
}
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
@Suppress("CyclomaticComplexMethod")
|
||||
@@ -1152,79 +822,65 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
else -> theme.background
|
||||
}
|
||||
fill(canvas, background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
if (style.changeBarWidthPx > 0) {
|
||||
when (row.change) {
|
||||
"add" -> fill(
|
||||
canvas,
|
||||
theme.addBar,
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
"delete" -> drawing.drawDeleteStripes(
|
||||
canvas,
|
||||
top,
|
||||
bottom,
|
||||
style.changeBarWidthPx,
|
||||
theme.deleteBar,
|
||||
)
|
||||
}
|
||||
}
|
||||
val selected = selectedRowIds.contains(row.id)
|
||||
if (selected) {
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, 56),
|
||||
withAlpha(theme.hunkText, if (theme.background == Color.WHITE) 54 else 76),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat(),
|
||||
)
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, 242),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
}
|
||||
val barColor = when (row.change) {
|
||||
"add" -> theme.addBar
|
||||
"delete" -> theme.deleteBar
|
||||
else -> Color.TRANSPARENT
|
||||
}
|
||||
if (barColor != Color.TRANSPARENT && style.changeBarWidthPx > 0) {
|
||||
fill(canvas, barColor, 0f, top.toFloat(), style.changeBarWidthPx, bottom.toFloat())
|
||||
}
|
||||
|
||||
val tokens = tokensByRowId[row.id]
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
drawing.configureCodePaint(theme.text, 0, style)
|
||||
drawing.drawWordDiffRanges(canvas, row, codeX, top, bottom)
|
||||
if (tokens.isNullOrEmpty()) {
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = when (row.change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.text
|
||||
}
|
||||
canvas.drawText(row.content, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
} else {
|
||||
var x = codeX
|
||||
tokens.forEach { token ->
|
||||
drawing.configureCodePaint(token.color ?: theme.text, token.fontStyle, style)
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = token.color ?: theme.text
|
||||
textPaint.typeface = when {
|
||||
token.fontStyle and 1 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.ITALIC)
|
||||
token.fontStyle and 2 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
|
||||
else -> Typeface.MONOSPACE
|
||||
}
|
||||
canvas.drawText(token.content, x, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
x += textPaint.measureText(token.content)
|
||||
}
|
||||
textPaint.typeface = Typeface.MONOSPACE
|
||||
}
|
||||
}
|
||||
|
||||
drawLineNumber(canvas, row, top, bottom)
|
||||
}
|
||||
|
||||
private fun drawLineNumber(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
val lineNumber = row.newLineNumber ?: row.oldLineNumber ?: return
|
||||
drawing.configureMonospacePaint(
|
||||
color = drawing.lineNumberColor(row.change),
|
||||
size = style.lineNumberFontSizePx,
|
||||
weight = style.lineNumberFontWeight,
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.RIGHT
|
||||
textPaint.textSize = style.lineNumberFontSizePx
|
||||
textPaint.color = if (selected) theme.text else theme.mutedText
|
||||
val oldNumber = row.oldLineNumber?.toString().orEmpty()
|
||||
val newNumber = row.newLineNumber?.toString().orEmpty()
|
||||
val baseline = centeredBaseline(top, bottom, textPaint)
|
||||
canvas.drawText(oldNumber, style.changeBarWidthPx + 6f * density, baseline, textPaint)
|
||||
canvas.drawText(
|
||||
lineNumber.toString(),
|
||||
style.changeBarWidthPx + style.gutterWidthPx - style.codePaddingPx,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
newNumber,
|
||||
style.changeBarWidthPx + style.gutterWidthPx / 2f,
|
||||
baseline,
|
||||
textPaint
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.LEFT
|
||||
}
|
||||
|
||||
private fun drawScrollableCode(
|
||||
@@ -1316,17 +972,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class RowHit(
|
||||
val row: DiffRow,
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class FileHeaderPathLayout(
|
||||
val displayPath: String,
|
||||
val rect: RectF
|
||||
)
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
@@ -1350,7 +995,6 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
change = row.optString("change", "context"),
|
||||
oldLineNumber = row.optNullableInt("oldLineNumber"),
|
||||
newLineNumber = row.optNullableInt("newLineNumber"),
|
||||
wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
|
||||
commentText = row.optString("commentText"),
|
||||
commentRangeLabel = row.optString("commentRangeLabel"),
|
||||
commentSectionTitle = row.optString("commentSectionTitle"),
|
||||
@@ -1360,17 +1004,6 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {
|
||||
for (index in 0 until value.length()) {
|
||||
val range = value.optJSONObject(index) ?: continue
|
||||
val start = range.optInt("start", -1)
|
||||
val end = range.optInt("end", -1)
|
||||
if (start >= 0 && end > start) {
|
||||
add(DiffWordDiffRange(start = start, end = end))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTokensObject(value: String): Map<String, List<DiffToken>> = try {
|
||||
parseTokensObject(JSONObject(value))
|
||||
} catch (_: Exception) {
|
||||
@@ -1387,7 +1020,7 @@ private fun parseTokensObject(value: JSONObject): Map<String, List<DiffToken>> {
|
||||
val token = array.getJSONObject(index)
|
||||
DiffToken(
|
||||
content = token.optString("content"),
|
||||
color = token.optNullableString("color")?.let(::parseColorOrNull),
|
||||
color = token.optNullableString("color")?.let { parseColor(it, Color.TRANSPARENT) },
|
||||
fontStyle = token.optInt("fontStyle"),
|
||||
)
|
||||
}
|
||||
@@ -1410,12 +1043,6 @@ private fun parseColor(value: String, fallback: Int): Int = try {
|
||||
fallback
|
||||
}
|
||||
|
||||
private fun parseColorOrNull(value: String): Int? = try {
|
||||
Color.parseColor(value)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun JSONObject.optNullableString(key: String): String? =
|
||||
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
|
||||
|
||||
|
||||
@@ -440,9 +440,9 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
options: {
|
||||
// A root-level Android formSheet does not host the native stack bar;
|
||||
// the route renders an embedded AndroidSheetHeader instead.
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
// Root screenOptions hide headers; formSheets that want the native
|
||||
// title bar opt back in with the sheet header preset.
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
|
||||
@@ -51,7 +51,6 @@ export function AndroidScreenHeader(props: {
|
||||
readonly actions?: ReadonlyArray<AndroidHeaderAction>;
|
||||
readonly trailing?: ReactNode;
|
||||
readonly onBack?: () => void;
|
||||
readonly embedded?: boolean;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
@@ -60,7 +59,7 @@ export function AndroidScreenHeader(props: {
|
||||
<View
|
||||
className="border-b border-header-border bg-header px-3 pb-2.5"
|
||||
style={{
|
||||
paddingTop: props.embedded ? 8 : Math.max(insets.top, 12),
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
}}
|
||||
>
|
||||
<View className="min-h-12 flex-row items-center gap-2">
|
||||
@@ -109,9 +108,3 @@ export function AndroidScreenHeader(props: {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function AndroidSheetHeader(
|
||||
props: Omit<Parameters<typeof AndroidScreenHeader>[0], "embedded">,
|
||||
) {
|
||||
return <AndroidScreenHeader {...props} embedded />;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { Image } from "expo-image";
|
||||
import { useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
|
||||
@@ -25,12 +24,11 @@ export function ProjectFavicon(props: {
|
||||
? null
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={faviconUrl}
|
||||
faviconUrl={renderableFaviconUrl}
|
||||
faviconUrl={faviconUrl}
|
||||
open={props.open}
|
||||
projectTitle={props.projectTitle}
|
||||
size={size}
|
||||
|
||||
@@ -2,11 +2,10 @@ import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
@@ -82,16 +81,9 @@ function ConfiguredConnectOnboardingRouteScreen() {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader
|
||||
title="Set up T3 Connect"
|
||||
actions={[{ accessibilityLabel: "Close", icon: "xmark", onPress: handleClose }]}
|
||||
/>
|
||||
) : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
<ScrollView
|
||||
alwaysBounceVertical
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useState } from "react";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -58,125 +57,115 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
|
||||
const disabledExistingBranches = new Set(disabledExistingBranchNames);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Branches & worktrees" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy ||
|
||||
worktreeBaseBranch.trim().length === 0 ||
|
||||
worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">Loading branches...</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
Loading branches...
|
||||
</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
</Text>
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -66,168 +65,160 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
|
||||
);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Commit changes" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
</Text>
|
||||
</View>
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
</Text>
|
||||
</View>
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">
|
||||
-{file.deletions}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -4,11 +4,10 @@ import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Platform, View } from "react-native";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
@@ -103,11 +102,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Confirm action" onBack={() => navigation.goBack()} />
|
||||
) : (
|
||||
<View className="min-h-4 pt-2" />
|
||||
)}
|
||||
<View className="min-h-4 pt-2" />
|
||||
|
||||
<View className="items-center gap-1 px-5 pb-3 pt-4">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
|
||||
@@ -5,12 +5,7 @@ import {
|
||||
requiresDefaultBranchConfirmation,
|
||||
} from "@t3tools/client-runtime/state/vcs";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommonActions,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
@@ -19,7 +14,6 @@ import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-scree
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../../native/StackHeader";
|
||||
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
|
||||
@@ -29,7 +23,6 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
|
||||
import { vcsEnvironment } from "../../../state/vcs";
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -262,14 +255,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
title="Review changes"
|
||||
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
|
||||
disabled={busy || !isRepo}
|
||||
onPress={() => {
|
||||
const params = { environmentId, threadId };
|
||||
navigation.dispatch(
|
||||
resolveGitOverviewReviewNavigationAction(presentation) === "replace"
|
||||
? StackActions.replace("ThreadReview", params)
|
||||
: CommonActions.navigate("ThreadReview", params),
|
||||
);
|
||||
}}
|
||||
onPress={() => navigation.navigate("ThreadReview", { environmentId, threadId })}
|
||||
/>
|
||||
<View className="ml-12 h-px bg-border" />
|
||||
<SheetListRow
|
||||
@@ -362,14 +348,12 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
collapsable={false}
|
||||
className={isInspector ? "flex-1 border-l border-border bg-sheet" : "flex-1 bg-sheet"}
|
||||
>
|
||||
{isInspector ? (
|
||||
<View
|
||||
style={{
|
||||
minHeight: props.headerInset ?? 0,
|
||||
paddingTop: props.headerInset ?? 0,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={{
|
||||
minHeight: isInspector ? (props.headerInset ?? 0) : 16,
|
||||
paddingTop: isInspector ? (props.headerInset ?? 0) : 8,
|
||||
}}
|
||||
/>
|
||||
|
||||
{isInspector ? (
|
||||
<View className="gap-1 border-b border-border px-4 pb-4 pt-3">
|
||||
@@ -399,19 +383,24 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<AndroidSheetHeader
|
||||
title={currentBranchLabel}
|
||||
subtitle={currentStatusSummary}
|
||||
onBack={() => navigation.goBack()}
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Refresh repository status",
|
||||
disabled: busy,
|
||||
icon: "arrow.clockwise",
|
||||
onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
// Compact header row: labeled branch on the left, status summary at
|
||||
// the trailing end. Horizontal padding lines the text up with the
|
||||
// rows' icon column inside the card below (20 screen + 16 card + 4
|
||||
// row). The sheet relies on pull-to-refresh instead of a corner
|
||||
// refresh button.
|
||||
<View className="flex-row items-end justify-between gap-3 px-10 pb-4 pt-4">
|
||||
<View className="shrink gap-0.5">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
Branch
|
||||
</Text>
|
||||
<Text className="text-xl font-t3-bold" numberOfLines={1}>
|
||||
{currentBranchLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-foreground-secondary pb-0.5 text-sm font-medium" numberOfLines={1}>
|
||||
{currentStatusSummary}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{content}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
|
||||
describe("resolveGitOverviewReviewNavigationAction", () => {
|
||||
it("replaces the sheet so Back returns directly to the thread", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("sheet")).toBe("replace");
|
||||
});
|
||||
|
||||
it("pushes Review normally when Git is a persistent inspector", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("inspector")).toBe("navigate");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
export function resolveGitOverviewReviewNavigationAction(
|
||||
presentation: "sheet" | "inspector",
|
||||
): "replace" | "navigate" {
|
||||
return presentation === "sheet" ? "replace" : "navigate";
|
||||
}
|
||||
@@ -12,9 +12,11 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
|
||||
@@ -345,10 +347,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
// Mobile is a detached surface — there is no local checkout in front of
|
||||
// the user — so surface derivation (the default) resolves to an isolated
|
||||
// worktree pinned to the latest remote base. An explicit
|
||||
// defaultThreadEnvMode in the environment settings still applies, and
|
||||
// "Local" remains an explicit per-draft exception.
|
||||
const environmentSettings = selectedEnvironmentServerConfig?.settings;
|
||||
const defaultWorkspaceMode = resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface:
|
||||
environmentSettings?.deriveThreadEnvModeFromSurface ??
|
||||
DEFAULT_SERVER_SETTINGS.deriveThreadEnvModeFromSurface,
|
||||
configuredMode:
|
||||
environmentSettings?.defaultThreadEnvMode ?? DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
|
||||
surface: "detached",
|
||||
});
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const startFromOrigin =
|
||||
selectedProjectDraft.workspaceSelection?.startFromOrigin ??
|
||||
(workspaceMode === "worktree" &&
|
||||
(environmentSettings?.newWorktreesStartFromOrigin ??
|
||||
DEFAULT_SERVER_SETTINGS.newWorktreesStartFromOrigin));
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -597,6 +617,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
// Wait for the environment's settings before auto-writing a workspace
|
||||
// selection: selectBranch persists the current mode into the draft, and
|
||||
// doing that against the pre-config fallback would freeze the wrong
|
||||
// default once the real settings arrive.
|
||||
if (environmentSettings === undefined) {
|
||||
return;
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
@@ -604,7 +631,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
}, [availableBranches, environmentSettings, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
@@ -667,7 +694,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
return null;
|
||||
}
|
||||
const workspaceSelection = draft.workspaceSelection;
|
||||
const mode = workspaceSelection?.mode ?? "local";
|
||||
const mode = workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const pendingStartFromOrigin =
|
||||
workspaceSelection?.startFromOrigin ?? (mode === "worktree" && startFromOrigin);
|
||||
// When the selection is the stand-in built from the queued snapshot,
|
||||
// persist the original (possibly absent) snapshot values — the
|
||||
// stand-in's placeholder title/workspaceRoot must never be written back
|
||||
@@ -696,17 +725,19 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
...(pendingStartFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
},
|
||||
[
|
||||
defaultWorkspaceMode,
|
||||
editingPendingProject,
|
||||
editingPendingTask,
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { buildThreadWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -74,7 +74,7 @@ export function useCreateProjectThread() {
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
startFromOrigin: input.startFromOrigin ?? false,
|
||||
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
|
||||
worktreeBranchName: buildThreadWorktreeBranchName(metadata.threadId, randomHex),
|
||||
}),
|
||||
});
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type MessageId,
|
||||
} from "@t3tools/contracts";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { buildThreadWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -269,7 +269,7 @@ export function useThreadOutboxDrain(): void {
|
||||
branch: creation.branch,
|
||||
worktreePath: creation.worktreePath,
|
||||
startFromOrigin: creation.startFromOrigin ?? false,
|
||||
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
|
||||
worktreeBranchName: buildThreadWorktreeBranchName(queuedMessage.threadId, randomHex),
|
||||
}),
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -229,7 +228,6 @@ describe("AssetAccess", () => {
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -237,7 +235,7 @@ describe("AssetAccess", () => {
|
||||
fallbackSuffix.slice(0, fallbackSeparatorIndex),
|
||||
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
|
||||
),
|
||||
).toBeNull();
|
||||
).toEqual({ kind: "project-favicon-fallback" });
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -41,6 +40,7 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
@@ -91,7 +91,9 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
|
||||
export type ResolvedAsset =
|
||||
| { readonly kind: "file"; readonly path: string }
|
||||
| { readonly kind: "project-favicon-fallback" };
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -324,7 +326,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -389,7 +391,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
if (claims.relativePath === null) return null;
|
||||
if (claims.relativePath === null) {
|
||||
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
|
||||
}
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
|
||||
@@ -42,6 +42,7 @@ export interface ServerDerivedPaths {
|
||||
readonly anonymousIdPath: string;
|
||||
readonly environmentIdPath: string;
|
||||
readonly serverRuntimeStatePath: string;
|
||||
readonly worktreeRegistryPath: string;
|
||||
readonly secretsDir: string;
|
||||
}
|
||||
|
||||
@@ -116,6 +117,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
anonymousIdPath: join(stateDir, "anonymous-id"),
|
||||
environmentIdPath: join(stateDir, "environment-id"),
|
||||
serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
|
||||
worktreeRegistryPath: join(stateDir, "worktree-registry.json"),
|
||||
secretsDir: join(stateDir, "secrets"),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import {
|
||||
GitCommandError,
|
||||
WORKTREE_BASE_FRESHNESS_WINDOW,
|
||||
WORKTREE_BASE_USABLE_HORIZON,
|
||||
type WorktreeBaseProvenance,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 Layer from "effect/Layer";
|
||||
|
||||
import * as GitWorkflowService from "./GitWorkflowService.ts";
|
||||
|
||||
export interface WorktreeBasePin {
|
||||
/** Commit SHA the new worktree is created from. */
|
||||
readonly commitSha: string;
|
||||
/** Remote-tracking ref the SHA was resolved from. */
|
||||
readonly remoteRefName: string;
|
||||
readonly provenance: WorktreeBaseProvenance;
|
||||
/** Time of the successful fetch backing this pin (null when unknown). */
|
||||
readonly fetchedAt: string | null;
|
||||
}
|
||||
|
||||
export interface EnsureFreshRemoteResult {
|
||||
readonly fetchedAt: string | null;
|
||||
readonly fetchSucceeded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans the base commit for new worktree threads.
|
||||
*
|
||||
* Freshness ladder ("always current" without a blocking fetch on every send):
|
||||
* 1. A fetch of the repo's primary remote within {@link WORKTREE_BASE_FRESHNESS_WINDOW}
|
||||
* counts as fresh — pin the remote-tracking commit immediately.
|
||||
* 2. Otherwise fetch now (deduped per repository: concurrent sends and the
|
||||
* composer-open prefetch share one in-flight fetch).
|
||||
* 3. If that fetch fails but the last successful fetch is within
|
||||
* {@link WORKTREE_BASE_USABLE_HORIZON}, proceed on the last-known remote
|
||||
* commit with `provenance: "stale"` (fail-visible).
|
||||
* 4. With no usable fetch, fail closed — the caller surfaces the error and
|
||||
* never silently falls back to a local ref.
|
||||
*/
|
||||
export class WorktreeBasePlanner extends Context.Service<
|
||||
WorktreeBasePlanner,
|
||||
{
|
||||
/**
|
||||
* Fetch the repository's primary remote unless a successful fetch is
|
||||
* already within the freshness window. Never fails: fetch failures are
|
||||
* reported through `fetchSucceeded` so composer-open prefetches are
|
||||
* fire-and-forget.
|
||||
*/
|
||||
readonly ensureFreshRemote: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<EnsureFreshRemoteResult>;
|
||||
|
||||
/**
|
||||
* Resolve the pinned base commit for a new worktree from `baseRef`,
|
||||
* applying the freshness ladder above.
|
||||
*/
|
||||
readonly pinRemoteBase: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseRef: string;
|
||||
}) => Effect.Effect<WorktreeBasePin, GitCommandError>;
|
||||
}
|
||||
>()("t3/git/WorktreeBasePlanner") {}
|
||||
|
||||
interface RepoFetchState {
|
||||
/** Completion time of the last successful fetch (ISO). */
|
||||
lastSuccessAt: string | null;
|
||||
/** Shared in-flight fetch so concurrent callers coalesce. */
|
||||
inFlight: Deferred.Deferred<boolean> | null;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
|
||||
// Keyed by cwd. Bootstraps and the composer-open prefetch always pass the
|
||||
// project root, so a per-cwd key deduplicates the flows that matter.
|
||||
const fetchStateByCwd = new Map<string, RepoFetchState>();
|
||||
|
||||
const getState = (cwd: string): RepoFetchState => {
|
||||
const existing = fetchStateByCwd.get(cwd);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const created: RepoFetchState = { lastSuccessAt: null, inFlight: null };
|
||||
fetchStateByCwd.set(cwd, created);
|
||||
return created;
|
||||
};
|
||||
|
||||
const isWithin = (isoTime: string | null, window: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
if (isoTime === null) {
|
||||
return false;
|
||||
}
|
||||
const at = Date.parse(isoTime);
|
||||
if (Number.isNaN(at)) {
|
||||
return false;
|
||||
}
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
return now - at <= Duration.toMillis(window);
|
||||
});
|
||||
|
||||
const runDedupedFetch = (cwd: string): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const state = getState(cwd);
|
||||
const existingInFlight = state.inFlight;
|
||||
if (existingInFlight) {
|
||||
return yield* Deferred.await(existingInFlight);
|
||||
}
|
||||
// Claim the slot synchronously (no suspension between the check above
|
||||
// and this assignment) so concurrent callers can't both start a fetch.
|
||||
const inFlight = Deferred.makeUnsafe<boolean>();
|
||||
state.inFlight = inFlight;
|
||||
return yield* gitWorkflow.fetchRemote({ cwd, remoteName: "origin" }).pipe(
|
||||
Effect.flatMap(() =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((now) => {
|
||||
state.lastSuccessAt = DateTime.formatIso(now);
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("worktree base fetch failed", {
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.map(() => false)),
|
||||
),
|
||||
Effect.onExit((exit) => {
|
||||
state.inFlight = null;
|
||||
return Deferred.done(inFlight, Exit.isSuccess(exit) ? exit : Exit.succeed(false)).pipe(
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const ensureFreshRemote: WorktreeBasePlanner["Service"]["ensureFreshRemote"] = Effect.fn(
|
||||
"WorktreeBasePlanner.ensureFreshRemote",
|
||||
)(function* (input) {
|
||||
const state = getState(input.cwd);
|
||||
if (yield* isWithin(state.lastSuccessAt, WORKTREE_BASE_FRESHNESS_WINDOW)) {
|
||||
return { fetchedAt: state.lastSuccessAt, fetchSucceeded: true };
|
||||
}
|
||||
const fetchSucceeded = yield* runDedupedFetch(input.cwd);
|
||||
return { fetchedAt: state.lastSuccessAt, fetchSucceeded };
|
||||
});
|
||||
|
||||
const pinRemoteBase: WorktreeBasePlanner["Service"]["pinRemoteBase"] = Effect.fn(
|
||||
"WorktreeBasePlanner.pinRemoteBase",
|
||||
)(function* (input) {
|
||||
const { fetchedAt, fetchSucceeded } = yield* ensureFreshRemote({ cwd: input.cwd });
|
||||
|
||||
const resolvePin = (provenance: WorktreeBaseProvenance) =>
|
||||
gitWorkflow
|
||||
.resolveRemoteTrackingCommit({
|
||||
cwd: input.cwd,
|
||||
refName: input.baseRef,
|
||||
fallbackRemoteName: "origin",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(resolved): WorktreeBasePin => ({
|
||||
commitSha: resolved.commitSha,
|
||||
remoteRefName: resolved.remoteRefName,
|
||||
provenance,
|
||||
fetchedAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (fetchSucceeded) {
|
||||
return yield* resolvePin("fresh");
|
||||
}
|
||||
|
||||
// Fail-visible: the remote is unreachable, but a recent fetch means the
|
||||
// remote-tracking ref is still a sane base. Proceed with stale provenance.
|
||||
if (yield* isWithin(fetchedAt, WORKTREE_BASE_USABLE_HORIZON)) {
|
||||
return yield* resolvePin("stale");
|
||||
}
|
||||
|
||||
// Fail closed: no usable remote data. The caller must not silently fall
|
||||
// back to a local ref — surfacing this error is the contract.
|
||||
return yield* new GitCommandError({
|
||||
operation: "WorktreeBasePlanner.pinRemoteBase",
|
||||
command: "fetch",
|
||||
cwd: input.cwd,
|
||||
detail: `Couldn't prepare a fresh worktree from ${input.baseRef}: the remote could not be reached and no recent fetch is available. Nothing has started and your checkout was not modified.`,
|
||||
});
|
||||
});
|
||||
|
||||
return WorktreeBasePlanner.of({
|
||||
ensureFreshRemote,
|
||||
pinRemoteBase,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(WorktreeBasePlanner, make);
|
||||
@@ -0,0 +1,154 @@
|
||||
import { ThreadId, WorktreeBaseProvenance } from "@t3tools/contracts";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
export const WorktreeRegistryStatus = Schema.Literals(["active", "thread-deleted"]);
|
||||
export type WorktreeRegistryStatus = typeof WorktreeRegistryStatus.Type;
|
||||
|
||||
/**
|
||||
* One record per worktree this server created for a thread. The registry is
|
||||
* the durable worktree ↔ thread association: attribution never depends on
|
||||
* scanning paths or parsing branch names, which makes lifecycle/GC tooling
|
||||
* cheap to build later.
|
||||
*/
|
||||
export const WorktreeRegistryRecord = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
worktreePath: Schema.String,
|
||||
branch: Schema.String,
|
||||
projectCwd: Schema.String,
|
||||
baseRefName: Schema.NullOr(Schema.String),
|
||||
baseCommitSha: Schema.NullOr(Schema.String),
|
||||
baseProvenance: Schema.NullOr(WorktreeBaseProvenance),
|
||||
createdAt: Schema.String,
|
||||
status: WorktreeRegistryStatus,
|
||||
});
|
||||
export type WorktreeRegistryRecord = typeof WorktreeRegistryRecord.Type;
|
||||
|
||||
const WorktreeRegistryFile = Schema.Struct({
|
||||
version: Schema.Number.pipe(Schema.withDecodingDefault(Effect.succeed(1))),
|
||||
worktrees: Schema.Array(WorktreeRegistryRecord).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed([])),
|
||||
),
|
||||
});
|
||||
type WorktreeRegistryFile = typeof WorktreeRegistryFile.Type;
|
||||
|
||||
const decodeRegistryExit = Schema.decodeUnknownExit(fromLenientJson(WorktreeRegistryFile));
|
||||
const encodeRegistryJson = Schema.encodeEffect(fromJsonStringPretty(WorktreeRegistryFile));
|
||||
|
||||
const EMPTY_REGISTRY: WorktreeRegistryFile = { version: 1, worktrees: [] };
|
||||
|
||||
export class WorktreeRegistry extends Context.Service<
|
||||
WorktreeRegistry,
|
||||
{
|
||||
/** Record (or refresh) the worktree created for a thread. Never fails. */
|
||||
readonly register: (record: Omit<WorktreeRegistryRecord, "status">) => Effect.Effect<void>;
|
||||
/** Mark all records for a thread as belonging to a deleted thread. Never fails. */
|
||||
readonly markThreadDeleted: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
/** Remove records whose worktree path was removed from disk. Never fails. */
|
||||
readonly unregisterPath: (worktreePath: string) => Effect.Effect<void>;
|
||||
readonly list: Effect.Effect<ReadonlyArray<WorktreeRegistryRecord>>;
|
||||
}
|
||||
>()("t3/git/WorktreeRegistry") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const { worktreeRegistryPath } = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const writeSemaphore = yield* Semaphore.make(1);
|
||||
const loadedRef = yield* Ref.make<WorktreeRegistryFile | null>(null);
|
||||
|
||||
const loadFromDisk = Effect.gen(function* () {
|
||||
const exists = yield* fs.exists(worktreeRegistryPath);
|
||||
if (!exists) {
|
||||
return EMPTY_REGISTRY;
|
||||
}
|
||||
const raw = yield* fs.readFileString(worktreeRegistryPath);
|
||||
const decoded = decodeRegistryExit(raw);
|
||||
if (decoded._tag === "Failure") {
|
||||
yield* Effect.logWarning("failed to parse worktree registry, starting fresh", {
|
||||
path: worktreeRegistryPath,
|
||||
});
|
||||
return EMPTY_REGISTRY;
|
||||
}
|
||||
return decoded.value;
|
||||
});
|
||||
|
||||
// All reads and writes take the semaphore so a first-access disk load can
|
||||
// never overwrite in-memory state that a concurrent mutation just wrote.
|
||||
const getRegistryLocked = Effect.gen(function* () {
|
||||
const loaded = yield* Ref.get(loadedRef);
|
||||
if (loaded !== null) {
|
||||
return loaded;
|
||||
}
|
||||
const fromDisk = yield* loadFromDisk;
|
||||
yield* Ref.set(loadedRef, fromDisk);
|
||||
return fromDisk;
|
||||
});
|
||||
|
||||
const getRegistry = Semaphore.withPermit(writeSemaphore)(getRegistryLocked);
|
||||
|
||||
const mutate = (
|
||||
update: (current: WorktreeRegistryFile) => WorktreeRegistryFile,
|
||||
): Effect.Effect<void> =>
|
||||
Semaphore.withPermit(writeSemaphore)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getRegistryLocked;
|
||||
const next = update(current);
|
||||
const contents = yield* encodeRegistryJson(next);
|
||||
yield* writeFileStringAtomically({
|
||||
filePath: worktreeRegistryPath,
|
||||
contents,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
// Memory reflects disk only after the persist succeeds, so `list`
|
||||
// never reports an association that was never durably recorded.
|
||||
yield* Ref.set(loadedRef, next);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to persist worktree registry", { cause }),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return WorktreeRegistry.of({
|
||||
register: (record) =>
|
||||
mutate((current) => ({
|
||||
...current,
|
||||
worktrees: [
|
||||
...current.worktrees.filter((entry) => entry.worktreePath !== record.worktreePath),
|
||||
{ ...record, status: "active" },
|
||||
],
|
||||
})),
|
||||
markThreadDeleted: (threadId) =>
|
||||
mutate((current) => ({
|
||||
...current,
|
||||
worktrees: current.worktrees.map((entry) =>
|
||||
entry.threadId === threadId ? { ...entry, status: "thread-deleted" as const } : entry,
|
||||
),
|
||||
})),
|
||||
unregisterPath: (worktreePath) =>
|
||||
mutate((current) => ({
|
||||
...current,
|
||||
worktrees: current.worktrees.filter((entry) => entry.worktreePath !== worktreePath),
|
||||
})),
|
||||
list: getRegistry.pipe(
|
||||
Effect.map((registry) => registry.worktrees),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(WorktreeRegistry, make);
|
||||
@@ -25,7 +25,11 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import {
|
||||
ASSET_ROUTE_PREFIX,
|
||||
FALLBACK_PROJECT_FAVICON_SVG,
|
||||
resolveAsset,
|
||||
} from "./assets/AssetAccess.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
@@ -192,6 +196,17 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
if (!asset) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
if (asset.kind === "project-favicon-fallback") {
|
||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
||||
status: 200,
|
||||
contentType: "image/svg+xml",
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: {
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as WorktreeRegistry from "../../git/WorktreeRegistry.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -40,6 +41,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
const worktreeRegistry = yield* WorktreeRegistry.WorktreeRegistry;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
@@ -61,6 +63,8 @@ const make = Effect.gen(function* () {
|
||||
const { threadId } = event.payload;
|
||||
yield* stopProviderSession(threadId);
|
||||
yield* closeThreadTerminals(threadId);
|
||||
// Keep the record for future GC tooling; just mark it unowned.
|
||||
yield* worktreeRegistry.markThreadDeleted(threadId);
|
||||
});
|
||||
|
||||
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
|
||||
|
||||
@@ -137,7 +137,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
|
||||
});
|
||||
|
||||
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
|
||||
it("does not publish streaming content or non-awareness activity events", () => {
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const base = {
|
||||
sequence: 1,
|
||||
@@ -191,16 +191,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
streaming: false,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
|
||||
|
||||
@@ -67,13 +67,7 @@ export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
|
||||
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent":
|
||||
case "thread.turn-start-requested":
|
||||
// These events express intent to start work, but the shell still contains
|
||||
// the previous turn's terminal state until the provider acknowledges the
|
||||
// new turn. Publishing that snapshot can queue a fresh "Done" alert just
|
||||
// before the real running state arrives. Provider lifecycle events publish
|
||||
// the authoritative starting/running state instead.
|
||||
return false;
|
||||
return !event.payload.streaming;
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.runtime-mode-set":
|
||||
case "thread.interaction-mode-set":
|
||||
|
||||
@@ -103,6 +103,8 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as WorktreeBasePlanner from "./git/WorktreeBasePlanner.ts";
|
||||
import * as WorktreeRegistry from "./git/WorktreeRegistry.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
@@ -503,6 +505,10 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provideMerge(gitManagerLayer),
|
||||
);
|
||||
const worktreeBasePlannerLayer = WorktreeBasePlanner.layer.pipe(
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
);
|
||||
const worktreeRegistryLayer = WorktreeRegistry.layer;
|
||||
const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
@@ -628,7 +634,9 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(gitWorkflowLayer, worktreeBasePlannerLayer, worktreeRegistryLayer),
|
||||
),
|
||||
Layer.provide(reviewLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
@@ -6224,7 +6232,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 5);
|
||||
assert.equal(response.sequence, 6);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
[
|
||||
@@ -6232,6 +6240,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"thread.meta.update",
|
||||
"thread.activity.append",
|
||||
"thread.activity.append",
|
||||
"thread.activity.append",
|
||||
"thread.turn.start",
|
||||
],
|
||||
);
|
||||
@@ -6241,6 +6250,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
newRefName: "t3code/bootstrap-refName",
|
||||
baseRefName: "main",
|
||||
path: null,
|
||||
uniquifyNewRefName: true,
|
||||
});
|
||||
assert.deepEqual(fetchRemote.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
@@ -6270,9 +6280,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.deepEqual(
|
||||
setupActivities.map((command) => command.activity.kind),
|
||||
["setup-script.requested", "setup-script.started"],
|
||||
["worktree.base-pinned", "setup-script.requested", "setup-script.started"],
|
||||
);
|
||||
const finalCommand = dispatchedCommands[4];
|
||||
const basePinnedActivity = setupActivities[0];
|
||||
assert.deepEqual(basePinnedActivity?.activity.payload, {
|
||||
branch: "t3code/bootstrap-refName",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: fetchedOriginCommit,
|
||||
baseProvenance: "fresh",
|
||||
baseFetchedAt: basePinnedActivity
|
||||
? (basePinnedActivity.activity.payload as { baseFetchedAt: string | null })
|
||||
.baseFetchedAt
|
||||
: null,
|
||||
});
|
||||
const finalCommand = dispatchedCommands[5];
|
||||
assertTrue(finalCommand?.type === "thread.turn.start");
|
||||
if (finalCommand?.type === "thread.turn.start") {
|
||||
assert.equal(finalCommand.bootstrap, undefined);
|
||||
@@ -6367,14 +6389,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 4);
|
||||
assert.equal(response.sequence, 5);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
|
||||
[
|
||||
"thread.create",
|
||||
"thread.meta.update",
|
||||
"thread.activity.append",
|
||||
"thread.activity.append",
|
||||
"thread.turn.start",
|
||||
],
|
||||
);
|
||||
const setupFailureActivity = dispatchedCommands.find(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
command.type === "thread.activity.append",
|
||||
command.type === "thread.activity.append" &&
|
||||
command.activity.kind.startsWith("setup-script."),
|
||||
);
|
||||
assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed");
|
||||
assert.deepEqual(setupFailureActivity?.activity.payload, {
|
||||
@@ -6488,14 +6517,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 4);
|
||||
assert.equal(response.sequence, 5);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
|
||||
[
|
||||
"thread.create",
|
||||
"thread.meta.update",
|
||||
"thread.activity.append",
|
||||
"thread.activity.append",
|
||||
"thread.turn.start",
|
||||
],
|
||||
);
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
command.type === "thread.activity.append",
|
||||
command.type === "thread.activity.append" &&
|
||||
command.activity.kind.startsWith("setup-script."),
|
||||
);
|
||||
assert.deepEqual(
|
||||
setupActivities.map((command) => command.activity.kind),
|
||||
|
||||
@@ -65,6 +65,8 @@ import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as WorktreeBasePlanner from "./git/WorktreeBasePlanner.ts";
|
||||
import * as WorktreeRegistry from "./git/WorktreeRegistry.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
@@ -161,6 +163,10 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProviderRuntimeIngestionLive),
|
||||
Layer.provideMerge(ProviderCommandReactorLive),
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
// WorktreeRegistry is deliberately NOT provided here: the reactor must
|
||||
// share the single instance from VcsLayerLive (provided downstream in
|
||||
// RuntimeCoreDependenciesLive) so bootstrap registrations and deletion
|
||||
// markings see the same in-memory state.
|
||||
Layer.provideMerge(ThreadDeletionReactorLive),
|
||||
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
@@ -212,6 +218,10 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
);
|
||||
|
||||
const WorktreeBasePlannerLayerLive = WorktreeBasePlanner.layer.pipe(
|
||||
Layer.provide(GitWorkflowLayerLive),
|
||||
);
|
||||
|
||||
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
@@ -227,6 +237,8 @@ const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(WorktreeBasePlannerLayerLive),
|
||||
Layer.provideMerge(WorktreeRegistry.layer),
|
||||
Layer.provideMerge(ReviewLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
|
||||
@@ -2242,22 +2242,48 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
},
|
||||
);
|
||||
|
||||
const resolveAvailableWorktreeBranchName = Effect.fn("resolveAvailableWorktreeBranchName")(
|
||||
function* (cwd: string, desiredBranch: string) {
|
||||
if (!(yield* branchExists(cwd, desiredBranch))) {
|
||||
return desiredBranch;
|
||||
}
|
||||
for (let suffix = 2; suffix <= 100; suffix += 1) {
|
||||
const candidate = `${desiredBranch}-${suffix}`;
|
||||
if (!(yield* branchExists(cwd, candidate))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.createWorktree",
|
||||
cwd,
|
||||
args: ["worktree", "add", "-b", desiredBranch],
|
||||
}),
|
||||
detail: `Could not find an available worktree branch name for '${desiredBranch}'.`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const createWorktree: GitVcsDriver.GitVcsDriver["Service"]["createWorktree"] = Effect.fn(
|
||||
"createWorktree",
|
||||
)(function* (input) {
|
||||
const targetBranch = input.newRefName ?? input.refName;
|
||||
const newRefName =
|
||||
input.newRefName !== undefined && input.uniquifyNewRefName
|
||||
? yield* resolveAvailableWorktreeBranchName(input.cwd, input.newRefName)
|
||||
: input.newRefName;
|
||||
const targetBranch = newRefName ?? input.refName;
|
||||
const sanitizedBranch = targetBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
|
||||
const args = input.newRefName
|
||||
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
|
||||
const args = newRefName
|
||||
? ["worktree", "add", "-b", newRefName, worktreePath, input.refName]
|
||||
: ["worktree", "add", worktreePath, input.refName];
|
||||
|
||||
yield* executeGit("GitVcsDriver.createWorktree", input.cwd, args, {
|
||||
fallbackErrorDetail: "git worktree add failed",
|
||||
});
|
||||
|
||||
if (input.newRefName && input.baseRefName) {
|
||||
if (newRefName && input.baseRefName) {
|
||||
const remoteNames = yield* listRemoteNames(input.cwd).pipe(Effect.orElseSucceed(() => []));
|
||||
const parsedBaseRef = parseRemoteRefWithRemoteNames(
|
||||
input.baseRefName,
|
||||
@@ -2266,7 +2292,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const baseBranch = parsedBaseRef?.branchName ?? input.baseRefName;
|
||||
yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
|
||||
"config",
|
||||
`branch.${input.newRefName}.gh-merge-base`,
|
||||
`branch.${newRefName}.gh-merge-base`,
|
||||
baseBranch,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as WorktreeBasePlanner from "./git/WorktreeBasePlanner.ts";
|
||||
import * as WorktreeRegistry from "./git/WorktreeRegistry.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
@@ -310,6 +312,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPrefetchRemote, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.gitRunStackedAction, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.gitResolvePullRequest, AuthOrchestrationOperateScope],
|
||||
@@ -401,6 +404,8 @@ const makeWsRpcLayer = (
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const worktreeBasePlanner = yield* WorktreeBasePlanner.WorktreeBasePlanner;
|
||||
const worktreeRegistry = yield* WorktreeRegistry.WorktreeRegistry;
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
@@ -527,7 +532,11 @@ const makeWsRpcLayer = (
|
||||
|
||||
const appendSetupScriptActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
|
||||
readonly kind:
|
||||
| "setup-script.requested"
|
||||
| "setup-script.started"
|
||||
| "setup-script.failed"
|
||||
| "worktree.base-pinned";
|
||||
readonly summary: string;
|
||||
readonly createdAt: string;
|
||||
readonly payload: Record<string, unknown>;
|
||||
@@ -556,6 +565,53 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Record where a new worktree thread's base came from as a thread
|
||||
* activity — the durable, user-visible provenance ("pinned at <sha>",
|
||||
* and a warning when the remote was unreachable and the last-known
|
||||
* commit was used instead). Never fails the bootstrap.
|
||||
*/
|
||||
const appendWorktreeBaseActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly branch: string;
|
||||
readonly worktreePath: string;
|
||||
readonly baseRefName: string;
|
||||
readonly basePin: WorktreeBasePlanner.WorktreeBasePin | null;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = yield* nowIso;
|
||||
const shortSha = input.basePin?.commitSha.slice(0, 7);
|
||||
const summary =
|
||||
input.basePin === null
|
||||
? `Created worktree from local ${input.baseRefName}`
|
||||
: input.basePin.provenance === "stale"
|
||||
? `Remote unreachable — created worktree from last-known ${input.baseRefName} (${shortSha})`
|
||||
: `Created worktree from ${input.baseRefName} (${shortSha})`;
|
||||
yield* appendSetupScriptActivity({
|
||||
threadId: input.threadId,
|
||||
kind: "worktree.base-pinned",
|
||||
summary,
|
||||
createdAt,
|
||||
payload: {
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
baseRefName: input.baseRefName,
|
||||
baseCommitSha: input.basePin?.commitSha ?? null,
|
||||
baseProvenance: input.basePin?.provenance ?? "local",
|
||||
baseFetchedAt: input.basePin?.fetchedAt ?? null,
|
||||
},
|
||||
tone: input.basePin?.provenance === "stale" ? "error" : "info",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to record worktree base provenance activity", {
|
||||
threadId: input.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
|
||||
const error = Cause.squash(cause);
|
||||
return isOrchestrationDispatchCommandError(error)
|
||||
@@ -836,25 +892,28 @@ const makeWsRpcLayer = (
|
||||
}
|
||||
|
||||
if (bootstrap?.prepareWorktree) {
|
||||
let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;
|
||||
if (bootstrap.prepareWorktree.startFromOrigin) {
|
||||
yield* gitWorkflow.fetchRemote({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
remoteName: "origin",
|
||||
const prepareWorktree = bootstrap.prepareWorktree;
|
||||
let worktreeBaseRef = prepareWorktree.baseBranch;
|
||||
let basePin: WorktreeBasePlanner.WorktreeBasePin | null = null;
|
||||
if (prepareWorktree.startFromOrigin) {
|
||||
// Pin the base to a remote commit via the freshness ladder:
|
||||
// fresh fetch → recent fetch (stale, fail-visible) → fail
|
||||
// closed. Never silently falls back to the local ref.
|
||||
basePin = yield* worktreeBasePlanner.pinRemoteBase({
|
||||
cwd: prepareWorktree.projectCwd,
|
||||
baseRef: prepareWorktree.baseBranch,
|
||||
});
|
||||
const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
refName: bootstrap.prepareWorktree.baseBranch,
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
worktreeBaseRef = resolvedRemoteBase.commitSha;
|
||||
worktreeBaseRef = basePin.commitSha;
|
||||
}
|
||||
const worktree = yield* gitWorkflow.createWorktree({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
cwd: prepareWorktree.projectCwd,
|
||||
refName: worktreeBaseRef,
|
||||
newRefName: bootstrap.prepareWorktree.branch,
|
||||
baseRefName: bootstrap.prepareWorktree.baseBranch,
|
||||
newRefName: prepareWorktree.branch,
|
||||
baseRefName: prepareWorktree.baseBranch,
|
||||
path: null,
|
||||
// Branch names derive from the thread id, so a resend after a
|
||||
// partial failure may find the branch already exists.
|
||||
uniquifyNewRefName: true,
|
||||
});
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
yield* orchestrationEngine.dispatch({
|
||||
@@ -864,6 +923,24 @@ const makeWsRpcLayer = (
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* worktreeRegistry.register({
|
||||
threadId: command.threadId,
|
||||
worktreePath: targetWorktreePath,
|
||||
branch: worktree.worktree.refName,
|
||||
projectCwd: prepareWorktree.projectCwd,
|
||||
baseRefName: basePin?.remoteRefName ?? prepareWorktree.baseBranch,
|
||||
baseCommitSha: basePin?.commitSha ?? null,
|
||||
baseProvenance:
|
||||
basePin?.provenance ?? (prepareWorktree.startFromOrigin ? null : "local"),
|
||||
createdAt: yield* nowIso,
|
||||
});
|
||||
yield* appendWorktreeBaseActivity({
|
||||
threadId: command.threadId,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: targetWorktreePath,
|
||||
baseRefName: basePin?.remoteRefName ?? prepareWorktree.baseBranch,
|
||||
basePin,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
}
|
||||
|
||||
@@ -1537,6 +1614,12 @@ const makeWsRpcLayer = (
|
||||
"rpc.aggregate": "vcs",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.vcsPrefetchRemote]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsPrefetchRemote,
|
||||
worktreeBasePlanner.ensureFreshRemote({ cwd: input.cwd }),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsPull]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsPull,
|
||||
|
||||
@@ -7,14 +7,14 @@
|
||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"
|
||||
/>
|
||||
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#000000" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="theme-color" content="#161616" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="theme-color" content="#161616" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<script>
|
||||
(() => {
|
||||
const LIGHT_BACKGROUND = "#ffffff";
|
||||
const DARK_BACKGROUND = "#000000";
|
||||
const DARK_BACKGROUND = "#161616";
|
||||
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
|
||||
try {
|
||||
const storedTheme = window.localStorage.getItem("t3code:theme");
|
||||
@@ -58,7 +58,7 @@
|
||||
}
|
||||
|
||||
html.dark body {
|
||||
background: #000000;
|
||||
background: #161616;
|
||||
color: #f5f5f5;
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="app-sidebar-surface border-r border-border text-foreground"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
derivePinnedWorktreeBase,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveEnvironmentOptionLabel,
|
||||
resolveBranchSelectionTarget,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePinnedBaseTitle,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
@@ -166,6 +168,75 @@ describe("resolveLockedWorkspaceLabel", () => {
|
||||
it("uses a shorter label for an attached worktree", () => {
|
||||
expect(resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Worktree");
|
||||
});
|
||||
|
||||
it("turns the label into the pinned fact once the base is known", () => {
|
||||
expect(
|
||||
resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a", {
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: "0123456789abcdef",
|
||||
baseProvenance: "fresh",
|
||||
}),
|
||||
).toBe("Worktree · 0123456");
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePinnedWorktreeBase", () => {
|
||||
it("reads the latest worktree.base-pinned activity payload", () => {
|
||||
expect(
|
||||
derivePinnedWorktreeBase([
|
||||
{ kind: "setup-script.started", payload: {} },
|
||||
{
|
||||
kind: "worktree.base-pinned",
|
||||
payload: {
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: "0123456789abcdef",
|
||||
baseProvenance: "stale",
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toEqual({
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: "0123456789abcdef",
|
||||
baseProvenance: "stale",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null when no pin activity exists", () => {
|
||||
expect(derivePinnedWorktreeBase([{ kind: "tool.started", payload: {} }])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePinnedBaseTitle", () => {
|
||||
it("describes fresh pins", () => {
|
||||
expect(
|
||||
resolvePinnedBaseTitle({
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: "0123456789abcdef",
|
||||
baseProvenance: "fresh",
|
||||
}),
|
||||
).toBe("Pinned at 0123456 from latest origin/main");
|
||||
});
|
||||
|
||||
it("discloses stale pins", () => {
|
||||
expect(
|
||||
resolvePinnedBaseTitle({
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: "0123456789abcdef",
|
||||
baseProvenance: "stale",
|
||||
}),
|
||||
).toContain("remote was unreachable");
|
||||
});
|
||||
|
||||
it("returns null without a pinned commit", () => {
|
||||
expect(
|
||||
resolvePinnedBaseTitle({
|
||||
baseRefName: "origin/main",
|
||||
baseCommitSha: null,
|
||||
baseProvenance: "local",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(resolvePinnedBaseTitle(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
|
||||
@@ -50,8 +50,66 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
|
||||
}
|
||||
|
||||
export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
/**
|
||||
* Provenance of a worktree thread's pinned base, derived from the
|
||||
* `worktree.base-pinned` activity the server records during bootstrap.
|
||||
*/
|
||||
export interface WorktreePinnedBase {
|
||||
readonly baseRefName: string;
|
||||
readonly baseCommitSha: string | null;
|
||||
readonly baseProvenance: "fresh" | "stale" | "local";
|
||||
}
|
||||
|
||||
export function derivePinnedWorktreeBase(
|
||||
activities: ReadonlyArray<{ kind: string; payload: unknown }>,
|
||||
): WorktreePinnedBase | null {
|
||||
for (let index = activities.length - 1; index >= 0; index -= 1) {
|
||||
const activity = activities[index];
|
||||
if (activity?.kind !== "worktree.base-pinned") continue;
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const baseRefName = typeof payload.baseRefName === "string" ? payload.baseRefName : null;
|
||||
if (!baseRefName) return null;
|
||||
const baseCommitSha = typeof payload.baseCommitSha === "string" ? payload.baseCommitSha : null;
|
||||
const baseProvenance =
|
||||
payload.baseProvenance === "fresh" ||
|
||||
payload.baseProvenance === "stale" ||
|
||||
payload.baseProvenance === "local"
|
||||
? payload.baseProvenance
|
||||
: "local";
|
||||
return { baseRefName, baseCommitSha, baseProvenance };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locked (post-send) workspace label. Once the base pin is known the promise
|
||||
* becomes a fact: "Worktree · a1b2c3f" instead of just "Worktree".
|
||||
*/
|
||||
export function resolveLockedWorkspaceLabel(
|
||||
activeWorktreePath: string | null,
|
||||
pinnedBase?: WorktreePinnedBase | null,
|
||||
): string {
|
||||
if (!activeWorktreePath) {
|
||||
return "Local checkout";
|
||||
}
|
||||
const shortSha = pinnedBase?.baseCommitSha?.slice(0, 7);
|
||||
return shortSha ? `Worktree · ${shortSha}` : "Worktree";
|
||||
}
|
||||
|
||||
export function resolvePinnedBaseTitle(pinnedBase: WorktreePinnedBase | null): string | null {
|
||||
if (!pinnedBase?.baseCommitSha) {
|
||||
return null;
|
||||
}
|
||||
const shortSha = pinnedBase.baseCommitSha.slice(0, 7);
|
||||
return pinnedBase.baseProvenance === "stale"
|
||||
? `Pinned at ${shortSha} from ${pinnedBase.baseRefName} (remote was unreachable — last-known commit)`
|
||||
: pinnedBase.baseProvenance === "fresh"
|
||||
? `Pinned at ${shortSha} from latest ${pinnedBase.baseRefName}`
|
||||
: `Pinned at ${shortSha} from local ${pinnedBase.baseRefName}`;
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { useIsMobile } from "../hooks/useMediaQuery";
|
||||
import {
|
||||
type EnvMode,
|
||||
type EnvironmentOption,
|
||||
derivePinnedWorktreeBase,
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
@@ -48,6 +49,12 @@ interface BranchToolbarProps {
|
||||
startFromOrigin: boolean;
|
||||
onStartFromOriginChange: (startFromOrigin: boolean) => void;
|
||||
envLocked: boolean;
|
||||
/** The project checkout has uncommitted changes (pre-send disclosure). */
|
||||
workingTreeDirty?: boolean;
|
||||
/** Mode this project's new threads currently default to. */
|
||||
projectDefaultEnvMode?: EnvMode | null;
|
||||
/** Persist the current mode as this project's default (explicit write). */
|
||||
onSetProjectDefaultEnvMode?: (mode: EnvMode) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
availableEnvironments?: readonly EnvironmentOption[];
|
||||
@@ -201,6 +208,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
startFromOrigin,
|
||||
onStartFromOriginChange,
|
||||
envLocked,
|
||||
workingTreeDirty,
|
||||
projectDefaultEnvMode,
|
||||
onSetProjectDefaultEnvMode,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
availableEnvironments,
|
||||
@@ -222,6 +232,10 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const activeProject = useProject(activeProjectRef);
|
||||
const hasActiveThread = serverThread !== null || draftThread !== null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const pinnedBase = useMemo(
|
||||
() => (serverThread ? derivePinnedWorktreeBase(serverThread.activities) : null),
|
||||
[serverThread],
|
||||
);
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
@@ -238,56 +252,92 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
// Dirty-state disclosure runs both directions and only while the choice is
|
||||
// still editable: in checkout mode the agent's edits will mix with the
|
||||
// user's uncommitted work; in worktree mode those uncommitted changes won't
|
||||
// be included. Each hint offers the one-click switch to the other mode.
|
||||
const dirtyDisclosure =
|
||||
!envModeLocked && workingTreeDirty && serverThread === null
|
||||
? effectiveEnvMode === "local"
|
||||
? {
|
||||
text: "This checkout has uncommitted changes — the agent will work alongside them.",
|
||||
action: "Use a fresh worktree",
|
||||
nextMode: "worktree" as const,
|
||||
}
|
||||
: {
|
||||
text: "Uncommitted changes in this checkout won't be included in the fresh worktree.",
|
||||
action: "Use current checkout",
|
||||
nextMode: "local" as const,
|
||||
}
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
envModeLocked={envModeLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
showEnvironmentPicker={showEnvironmentPicker}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
|
||||
<>
|
||||
<BranchToolbarEnvironmentSelector
|
||||
envLocked={envLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
</>
|
||||
)}
|
||||
<BranchToolbarEnvModeSelector
|
||||
envLocked={envModeLocked}
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col px-2.5 pb-3 pt-1 sm:px-3">
|
||||
{dirtyDisclosure ? (
|
||||
<div className="flex items-center gap-1.5 px-1 pb-1 text-xs text-muted-foreground/80">
|
||||
<span className="min-w-0 truncate">{dirtyDisclosure.text}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 font-medium text-foreground/70 underline-offset-2 hover:underline"
|
||||
onClick={() => onEnvModeChange(dirtyDisclosure.nextMode)}
|
||||
>
|
||||
{dirtyDisclosure.action}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex w-full items-center gap-2">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
envModeLocked={envModeLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
showEnvironmentPicker={showEnvironmentPicker}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
|
||||
<>
|
||||
<BranchToolbarEnvironmentSelector
|
||||
envLocked={envLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
</>
|
||||
)}
|
||||
<BranchToolbarEnvModeSelector
|
||||
envLocked={envModeLocked}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
pinnedBase={pinnedBase}
|
||||
projectDefaultEnvMode={projectDefaultEnvMode ?? null}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
{...(onSetProjectDefaultEnvMode ? { onSetProjectDefaultEnvMode } : {})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<BranchToolbarBranchSelector
|
||||
className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
|
||||
environmentId={environmentId}
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
<BranchToolbarBranchSelector
|
||||
className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
|
||||
environmentId={environmentId}
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -38,6 +38,8 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
import {
|
||||
ChangeRequestStatusIcon,
|
||||
prStatusIndicator,
|
||||
@@ -107,6 +109,7 @@ export function BranchToolbarBranchSelector({
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
const startFromOriginSwitchId = useId();
|
||||
const settings = useEnvironmentSettings(environmentId);
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
@@ -191,6 +194,16 @@ export function BranchToolbarBranchSelector({
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: nextDraftEnvMode,
|
||||
// Mode changes re-derive the origin pin from settings so a draft
|
||||
// flipped into worktree mode here doesn't silently skip the fetch.
|
||||
...(nextDraftEnvMode !== effectiveEnvMode
|
||||
? {
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: nextDraftEnvMode,
|
||||
newWorktreesStartFromOrigin: settings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
projectRef: scopeProjectRef(environmentId, activeProject.id),
|
||||
});
|
||||
},
|
||||
@@ -202,6 +215,7 @@ export function BranchToolbarBranchSelector({
|
||||
hasServerThread,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
setDraftThreadContext,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
draftId,
|
||||
threadRef,
|
||||
environmentId,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon, PinIcon } from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import {
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePinnedBaseTitle,
|
||||
type EnvMode,
|
||||
type WorktreePinnedBase,
|
||||
} from "./BranchToolbar.logic";
|
||||
import {
|
||||
Select,
|
||||
@@ -17,18 +19,36 @@ import {
|
||||
SelectValue,
|
||||
} from "./ui/select";
|
||||
|
||||
/**
|
||||
* Sentinel select value for the "Always for this project" action. Selecting
|
||||
* it never becomes the control's value — it's intercepted in onValueChange
|
||||
* and routed to an explicit settings write instead.
|
||||
*/
|
||||
const SET_PROJECT_DEFAULT_VALUE = "__set_project_default__";
|
||||
|
||||
interface BranchToolbarEnvModeSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
pinnedBase?: WorktreePinnedBase | null;
|
||||
/**
|
||||
* Mode the project's new threads default to today (after overrides). Used
|
||||
* to decide whether the "Always for this project" action is meaningful.
|
||||
*/
|
||||
projectDefaultEnvMode?: EnvMode | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
/** Persist the current mode as this project's default (explicit write). */
|
||||
onSetProjectDefaultEnvMode?: (mode: EnvMode) => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
|
||||
envLocked,
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
pinnedBase,
|
||||
projectDefaultEnvMode,
|
||||
onEnvModeChange,
|
||||
onSetProjectDefaultEnvMode,
|
||||
}: BranchToolbarEnvModeSelectorProps) {
|
||||
const envModeItems = useMemo(
|
||||
() => [
|
||||
@@ -37,19 +57,29 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
],
|
||||
[activeWorktreePath],
|
||||
);
|
||||
const showSetProjectDefault =
|
||||
onSetProjectDefaultEnvMode !== undefined &&
|
||||
projectDefaultEnvMode != null &&
|
||||
effectiveEnvMode !== projectDefaultEnvMode;
|
||||
|
||||
if (envLocked) {
|
||||
// Post-send the label states the outcome, not the intent: the pinned
|
||||
// base commit (and, on hover, its provenance) replaces "New worktree".
|
||||
const lockedTitle = resolvePinnedBaseTitle(pinnedBase ?? null);
|
||||
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">
|
||||
<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"
|
||||
{...(lockedTitle ? { title: lockedTitle } : {})}
|
||||
>
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath, pinnedBase)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath, pinnedBase)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
@@ -60,7 +90,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
<Select
|
||||
modal={false}
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
onValueChange={(value) => {
|
||||
const selected = value as string;
|
||||
if (selected === SET_PROJECT_DEFAULT_VALUE) {
|
||||
onSetProjectDefaultEnvMode?.(effectiveEnvMode);
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(selected as EnvMode);
|
||||
}}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
|
||||
@@ -75,7 +112,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectGroup>
|
||||
<SelectGroupLabel>Workspace</SelectGroupLabel>
|
||||
<SelectGroupLabel>Workspace · this draft only</SelectGroupLabel>
|
||||
<SelectItem value="local">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{activeWorktreePath ? (
|
||||
@@ -93,6 +130,16 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
{showSetProjectDefault ? (
|
||||
<SelectGroup>
|
||||
<SelectItem hideIndicator value={SET_PROJECT_DEFAULT_VALUE}>
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
||||
<PinIcon className="size-3" />
|
||||
Always {resolveEnvModeLabel(effectiveEnvMode).toLowerCase()} for this project
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
) : null}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
);
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
@@ -112,7 +113,7 @@ import {
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { buildThreadWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
|
||||
import {
|
||||
@@ -150,7 +151,13 @@ import {
|
||||
} from "~/projectScripts";
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
useClientSettings,
|
||||
useEnvironmentSettings,
|
||||
useUpdateClientSettings,
|
||||
} from "../hooks/useSettings";
|
||||
import { useEnvironmentPresentation } from "../state/presentation";
|
||||
import { resolveSurfaceThreadEnvMode } from "../lib/threadSurface";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
@@ -2120,6 +2127,43 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
input: { cwd: gitCwd },
|
||||
}),
|
||||
);
|
||||
const prefetchRemote = useAtomCommand(vcsEnvironment.prefetchRemote, { reportFailure: false });
|
||||
// Prefetch the remote the moment a worktree-mode draft composer is open, so
|
||||
// the send-time freshness check almost always hits the fresh window and the
|
||||
// user never waits on a blocking fetch. Fire-and-forget; the server dedupes
|
||||
// concurrent fetches per repository.
|
||||
const prefetchedDraftCwdRef = useRef<string | null>(null);
|
||||
const draftEnvModeForPrefetch = isLocalDraftThread ? draftThread?.envMode : undefined;
|
||||
const draftStartFromOriginForPrefetch = isLocalDraftThread
|
||||
? draftThread?.startFromOrigin
|
||||
: undefined;
|
||||
useEffect(() => {
|
||||
const projectCwd = activeProject?.workspaceRoot ?? null;
|
||||
if (
|
||||
!isLocalDraftThread ||
|
||||
draftEnvModeForPrefetch !== "worktree" ||
|
||||
draftStartFromOriginForPrefetch !== true ||
|
||||
projectCwd === null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const prefetchKey = `${environmentId}:${projectCwd}`;
|
||||
if (prefetchedDraftCwdRef.current === prefetchKey) {
|
||||
return;
|
||||
}
|
||||
prefetchedDraftCwdRef.current = prefetchKey;
|
||||
void prefetchRemote({
|
||||
environmentId,
|
||||
input: { cwd: projectCwd },
|
||||
});
|
||||
}, [
|
||||
activeProject?.workspaceRoot,
|
||||
draftEnvModeForPrefetch,
|
||||
draftStartFromOriginForPrefetch,
|
||||
environmentId,
|
||||
isLocalDraftThread,
|
||||
prefetchRemote,
|
||||
]);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
|
||||
// Prefer an instance-id match so a custom Codex instance (e.g.
|
||||
@@ -4154,7 +4198,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
prepareWorktree: {
|
||||
projectCwd: activeProject.workspaceRoot,
|
||||
baseBranch: baseBranchForWorktree,
|
||||
branch: buildTemporaryWorktreeBranchName(randomHex),
|
||||
branch: buildThreadWorktreeBranchName(threadIdForSend, randomHex),
|
||||
...(startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
runSetupScript: true,
|
||||
@@ -4867,6 +4911,34 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
],
|
||||
);
|
||||
|
||||
const projectThreadEnvModeOverrides = useClientSettings(
|
||||
(clientSettings) => clientSettings.projectThreadEnvModeOverrides,
|
||||
);
|
||||
const updateClientSettings = useUpdateClientSettings();
|
||||
const { presentation: activeEnvironmentPresentation } = useEnvironmentPresentation(environmentId);
|
||||
const envModeOverrideProjectKey = activeProjectRef ? scopedProjectKey(activeProjectRef) : null;
|
||||
const projectDefaultEnvMode: DraftThreadEnvMode | null = envModeOverrideProjectKey
|
||||
? (projectThreadEnvModeOverrides[envModeOverrideProjectKey] ??
|
||||
resolveSurfaceThreadEnvMode({
|
||||
settings,
|
||||
target: activeEnvironmentPresentation?.entry.target ?? null,
|
||||
}))
|
||||
: null;
|
||||
// "Always for this project": the only sanctioned way a composer choice
|
||||
// becomes a default, and it goes through an explicit settings write.
|
||||
const onSetProjectDefaultEnvMode = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
if (!envModeOverrideProjectKey) return;
|
||||
updateClientSettings({
|
||||
projectThreadEnvModeOverrides: {
|
||||
...projectThreadEnvModeOverrides,
|
||||
[envModeOverrideProjectKey]: mode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[envModeOverrideProjectKey, projectThreadEnvModeOverrides, updateClientSettings],
|
||||
);
|
||||
|
||||
const onStartFromOriginChange = (nextStartFromOrigin: boolean) => {
|
||||
if (canOverrideServerThreadEnvMode && activeThread) {
|
||||
setPendingServerThreadStartFromOriginByThreadId((current) =>
|
||||
@@ -5232,6 +5304,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
workingTreeDirty={Boolean(gitStatusQuery.data?.hasWorkingTreeChanges)}
|
||||
projectDefaultEnvMode={projectDefaultEnvMode}
|
||||
onSetProjectDefaultEnvMode={onSetProjectDefaultEnvMode}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
|
||||
@@ -1621,7 +1621,7 @@ function ComposerPromptEditorInner({
|
||||
}
|
||||
placeholder={
|
||||
terminalContexts.length > 0 ? null : (
|
||||
<div className="pointer-events-none absolute inset-0 text-[16px] leading-relaxed text-muted-foreground/75 sm:text-[14px]">
|
||||
<div className="pointer-events-none absolute inset-0 text-[16px] leading-relaxed text-muted-foreground/35 sm:text-[14px]">
|
||||
{placeholder}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
@@ -16,7 +15,7 @@ export function ProjectFavicon(input: {
|
||||
cwd: input.cwd,
|
||||
});
|
||||
|
||||
if (!src || isProjectFaviconFallbackUrl(src)) {
|
||||
if (!src) {
|
||||
return <ProjectFaviconFallback className={input.className} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -261,90 +261,22 @@ describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
it("prefers the default worktree mode over active thread context", () => {
|
||||
it("always starts from the resolved default mode — active thread and draft context never leak in", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the active draft thread context when it matches the target project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default env mode when there is no matching active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-2",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
|
||||
@@ -184,50 +184,17 @@ export function resolveSidebarNewThreadEnvMode(input: {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* New threads always start from the resolved default workspace mode.
|
||||
* Mode/branch/worktree choices on the active thread or draft are draft-only
|
||||
* exceptions and are deliberately NOT inherited — a one-off "use current
|
||||
* checkout" must never retrain what the next new thread does.
|
||||
*/
|
||||
export function resolveSidebarNewThreadSeedContext(input: {
|
||||
projectId: string;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
activeThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
} | null;
|
||||
activeDraftThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
} | null;
|
||||
}): {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
worktreePath: input.activeDraftThread.worktreePath,
|
||||
envMode: input.activeDraftThread.envMode,
|
||||
startFromOrigin: input.activeDraftThread.startFromOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeThread.branch,
|
||||
worktreePath: input.activeThread.worktreePath,
|
||||
envMode: input.activeThread.worktreePath ? "worktree" : "local",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
envMode: input.defaultEnvMode,
|
||||
};
|
||||
|
||||
@@ -43,7 +43,6 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
type ContextMenuItem,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProjectId,
|
||||
type ScopedThreadRef,
|
||||
type ResolvedKeybindingsConfig,
|
||||
@@ -79,10 +78,8 @@ import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import {
|
||||
readThreadShell,
|
||||
useProject,
|
||||
useProjects,
|
||||
useServerConfigs,
|
||||
useThreadShells,
|
||||
useThreadShellsForProjectRefs,
|
||||
} from "../state/entities";
|
||||
@@ -118,11 +115,7 @@ import { useEnvironmentQuery } from "../state/query";
|
||||
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import {
|
||||
buildThreadRouteParams,
|
||||
resolveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "../threadRoutes";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
@@ -189,8 +182,6 @@ import {
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
@@ -1109,7 +1100,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
(settings) => settings.confirmThreadArchive,
|
||||
);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const serverConfigs = useServerConfigs();
|
||||
const deleteProject = useAtomCommand(projectEnvironment.delete, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1836,61 +1826,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const createThreadForProjectMember = useCallback(
|
||||
(member: SidebarProjectGroupMember) => {
|
||||
const currentRouteParams =
|
||||
router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
const currentRouteTarget = resolveThreadRouteTarget(currentRouteParams);
|
||||
const currentActiveThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? readThreadShell(currentRouteTarget.threadRef)
|
||||
: null;
|
||||
const draftStore = useComposerDraftStore.getState();
|
||||
const currentActiveDraftThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? (draftStore.getDraftThread(currentRouteTarget.threadRef) ?? null)
|
||||
: currentRouteTarget?.kind === "draft"
|
||||
? (draftStore.getDraftSession(currentRouteTarget.draftId) ?? null)
|
||||
: null;
|
||||
const seedContext = resolveSidebarNewThreadSeedContext({
|
||||
projectId: member.id,
|
||||
defaultEnvMode: resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode:
|
||||
serverConfigs.get(member.environmentId)?.settings.defaultThreadEnvMode ??
|
||||
DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
|
||||
}),
|
||||
activeThread:
|
||||
currentActiveThread && currentActiveThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveThread.projectId,
|
||||
branch: currentActiveThread.branch,
|
||||
worktreePath: currentActiveThread.worktreePath,
|
||||
}
|
||||
: null,
|
||||
activeDraftThread:
|
||||
currentActiveDraftThread && currentActiveDraftThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveDraftThread.projectId,
|
||||
branch: currentActiveDraftThread.branch,
|
||||
worktreePath: currentActiveDraftThread.worktreePath,
|
||||
envMode: currentActiveDraftThread.envMode,
|
||||
startFromOrigin: currentActiveDraftThread.startFromOrigin,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void (async () => {
|
||||
// No seed context: new threads always start from the resolved
|
||||
// default workspace mode (useNewThreadHandler derives it from the
|
||||
// surface). The active thread's mode/branch is a draft-only
|
||||
// exception and must not leak into the next thread.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
|
||||
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
|
||||
...(seedContext.worktreePath !== undefined
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -1904,7 +1849,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
})();
|
||||
},
|
||||
[handleNewThread, isMobile, router, serverConfigs, setOpenMobile],
|
||||
[handleNewThread, isMobile, setOpenMobile],
|
||||
);
|
||||
|
||||
const handleCreateThreadClick = useCallback(
|
||||
|
||||
@@ -2061,10 +2061,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-foreground/20",
|
||||
isDragOverComposer
|
||||
? "border-primary/70 bg-accent/45"
|
||||
: "border-border dark:border-white/7",
|
||||
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
environmentUnavailable ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
|
||||
@@ -405,7 +405,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
|
||||
? ["Automatic Git fetch interval"]
|
||||
: []),
|
||||
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
|
||||
...(settings.deriveThreadEnvModeFromSurface !==
|
||||
DEFAULT_UNIFIED_SETTINGS.deriveThreadEnvModeFromSurface ||
|
||||
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
|
||||
? ["New thread mode"]
|
||||
: []),
|
||||
...(settings.newWorktreesStartFromOrigin !==
|
||||
@@ -430,6 +432,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.confirmThreadDelete,
|
||||
settings.addProjectBaseDirectory,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.deriveThreadEnvModeFromSurface,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.automaticGitFetchInterval,
|
||||
@@ -460,6 +463,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
deriveThreadEnvModeFromSurface: DEFAULT_UNIFIED_SETTINGS.deriveThreadEnvModeFromSurface,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
@@ -723,8 +727,10 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="New threads"
|
||||
description="Pick the default workspace mode for newly created draft threads."
|
||||
description="Pick the default workspace mode for newly created draft threads. Auto uses the current checkout when you're on the same machine as the environment and a fresh worktree everywhere else."
|
||||
resetAction={
|
||||
settings.deriveThreadEnvModeFromSurface !==
|
||||
DEFAULT_UNIFIED_SETTINGS.deriveThreadEnvModeFromSurface ||
|
||||
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ||
|
||||
settings.newWorktreesStartFromOrigin !==
|
||||
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin ? (
|
||||
@@ -732,6 +738,8 @@ export function GeneralSettingsPanel() {
|
||||
label="new threads"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
deriveThreadEnvModeFromSurface:
|
||||
DEFAULT_UNIFIED_SETTINGS.deriveThreadEnvModeFromSurface,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
newWorktreesStartFromOrigin:
|
||||
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
|
||||
@@ -742,19 +750,35 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={settings.defaultThreadEnvMode}
|
||||
value={
|
||||
settings.deriveThreadEnvModeFromSurface ? "surface" : settings.defaultThreadEnvMode
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
if (value === "surface") {
|
||||
updateSettings({ deriveThreadEnvModeFromSurface: true });
|
||||
return;
|
||||
}
|
||||
if (value === "local" || value === "worktree") {
|
||||
updateSettings({ defaultThreadEnvMode: value });
|
||||
updateSettings({
|
||||
deriveThreadEnvModeFromSurface: false,
|
||||
defaultThreadEnvMode: value,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Default thread mode">
|
||||
<SelectValue>
|
||||
{settings.defaultThreadEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||
{settings.deriveThreadEnvModeFromSurface
|
||||
? "Auto"
|
||||
: settings.defaultThreadEnvMode === "worktree"
|
||||
? "New worktree"
|
||||
: "Local"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="surface">
|
||||
Auto
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="local">
|
||||
Local
|
||||
</SelectItem>
|
||||
@@ -766,7 +790,7 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
{settings.defaultThreadEnvMode === "worktree" ? (
|
||||
{settings.deriveThreadEnvModeFromSurface || settings.defaultThreadEnvMode !== "local" ? (
|
||||
<SettingsRow
|
||||
className="bg-muted/20 sm:pl-9"
|
||||
title="Start from origin"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopeProjectRef,
|
||||
@@ -10,6 +11,9 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { useParams, useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { environmentPresentations } from "../state/presentation";
|
||||
import { resolveSurfaceThreadEnvMode } from "../lib/threadSurface";
|
||||
import {
|
||||
markPromotedDraftThreadByRef,
|
||||
type DraftThreadEnvMode,
|
||||
@@ -32,7 +36,11 @@ import { useClientSettings } from "./useSettings";
|
||||
export function useNewThreadHandler() {
|
||||
const projects = useProjects();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const environmentPresentationById = useAtomValue(environmentPresentations.presentationsAtom);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projectThreadEnvModeOverrides = useClientSettings(
|
||||
(settings) => settings.projectThreadEnvModeOverrides,
|
||||
);
|
||||
const router = useRouter();
|
||||
const getCurrentRouteTarget = useCallback(() => {
|
||||
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
@@ -72,6 +80,17 @@ export function useNewThreadHandler() {
|
||||
const hasWorktreePathOption = options?.worktreePath !== undefined;
|
||||
const hasEnvModeOption = options?.envMode !== undefined;
|
||||
const hasStartFromOriginOption = options?.startFromOrigin !== undefined;
|
||||
// The default mode derives from the surface (attached checkout →
|
||||
// local, detached → worktree) unless a project override or an explicit
|
||||
// setting pins a mode. Draft exceptions never retrain this default —
|
||||
// only the project override ("Always for this project") does, and only
|
||||
// through an explicit settings write.
|
||||
const resolveDefaultEnvMode = (): DraftThreadEnvMode =>
|
||||
projectThreadEnvModeOverrides[scopedProjectKey(projectRef)] ??
|
||||
resolveSurfaceThreadEnvMode({
|
||||
settings: environmentSettings,
|
||||
target: environmentPresentationById.get(projectRef.environmentId)?.entry.target ?? null,
|
||||
});
|
||||
const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
||||
const storedDraftThreadRef = storedDraftThread
|
||||
? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId)
|
||||
@@ -88,6 +107,14 @@ export function useNewThreadHandler() {
|
||||
? getDraftThread(currentRouteTarget.threadRef)
|
||||
: getDraftSession(currentRouteTarget.draftId)
|
||||
: null;
|
||||
// Reusing a stored draft for a different project member must re-derive
|
||||
// the mode from that member's default — otherwise the store's
|
||||
// project-changed reset hard-codes "local" regardless of surface.
|
||||
const storedDraftProjectChanged =
|
||||
reusableStoredDraftThread !== null &&
|
||||
reusableStoredDraftThread !== undefined &&
|
||||
(reusableStoredDraftThread.environmentId !== projectRef.environmentId ||
|
||||
reusableStoredDraftThread.projectId !== projectRef.projectId);
|
||||
if (reusableStoredDraftThread) {
|
||||
return (async () => {
|
||||
if (
|
||||
@@ -109,6 +136,22 @@ export function useNewThreadHandler() {
|
||||
reusableStoredDraftThread.draftId,
|
||||
{
|
||||
threadId: reusableStoredDraftThread.threadId,
|
||||
// Independently re-derive whichever values the caller didn't
|
||||
// pin, so the store's project-changed reset (hard-coded
|
||||
// "local"/false) never overrides the target's surface default.
|
||||
...(storedDraftProjectChanged && !hasEnvModeOption
|
||||
? { envMode: resolveDefaultEnvMode() }
|
||||
: {}),
|
||||
...(storedDraftProjectChanged && !hasStartFromOriginOption
|
||||
? {
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: hasEnvModeOption
|
||||
? (options?.envMode ?? resolveDefaultEnvMode())
|
||||
: resolveDefaultEnvMode(),
|
||||
newWorktreesStartFromOrigin: environmentSettings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
if (
|
||||
@@ -159,7 +202,7 @@ export function useNewThreadHandler() {
|
||||
const draftId = newDraftId();
|
||||
const threadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const initialEnvMode = options?.envMode ?? environmentSettings.defaultThreadEnvMode;
|
||||
const initialEnvMode = options?.envMode ?? resolveDefaultEnvMode();
|
||||
return (async () => {
|
||||
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
|
||||
threadId,
|
||||
@@ -183,7 +226,15 @@ export function useNewThreadHandler() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[getCurrentRouteTarget, projectGroupingSettings, projects, router, serverConfigs],
|
||||
[
|
||||
environmentPresentationById,
|
||||
getCurrentRouteTarget,
|
||||
projectGroupingSettings,
|
||||
projects,
|
||||
projectThreadEnvModeOverrides,
|
||||
router,
|
||||
serverConfigs,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -146,11 +146,6 @@
|
||||
@apply flex h-10 min-h-10 shrink-0 items-center border-b border-border/60 bg-background;
|
||||
}
|
||||
|
||||
.app-sidebar-surface,
|
||||
.app-sidebar-surface [data-slot="sidebar-inner"] {
|
||||
background: var(--sidebar-surface);
|
||||
}
|
||||
|
||||
.chat-composer-horizontal-inset {
|
||||
padding-inline-start: calc(env(safe-area-inset-left) + 0.75rem);
|
||||
padding-inline-end: calc(env(safe-area-inset-right) + 0.75rem);
|
||||
@@ -172,18 +167,15 @@
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass {
|
||||
background: var(--composer-surface);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.dark .chat-composer-glass,
|
||||
.dark .chat-composer-lower-chrome {
|
||||
background: var(--background);
|
||||
background: color-mix(in srgb, var(--card) 45%, transparent);
|
||||
}
|
||||
|
||||
.dark .chat-composer-shared-blur {
|
||||
-webkit-backdrop-filter: none;
|
||||
backdrop-filter: none;
|
||||
.dark .chat-composer-glass {
|
||||
box-shadow:
|
||||
0 18px 48px -20px rgb(0 0 0 / 60%),
|
||||
0 4px 14px -7px rgb(0 0 0 / 40%);
|
||||
}
|
||||
|
||||
.chat-composer-lower-chrome {
|
||||
@@ -237,8 +229,6 @@
|
||||
--radius: 0.625rem;
|
||||
--background: var(--color-white);
|
||||
--app-chrome-background: var(--background);
|
||||
--sidebar-surface: var(--card);
|
||||
--composer-surface: var(--card);
|
||||
--foreground: var(--color-neutral-800);
|
||||
--card: var(--color-white);
|
||||
--card-foreground: var(--color-neutral-800);
|
||||
@@ -266,22 +256,20 @@
|
||||
|
||||
@variant dark {
|
||||
color-scheme: dark;
|
||||
--background: var(--color-black);
|
||||
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
|
||||
--app-chrome-background: var(--background);
|
||||
--sidebar-surface: color-mix(in srgb, var(--color-black) 97.5%, var(--color-white));
|
||||
--composer-surface: color-mix(in srgb, var(--color-black) 95.5%, var(--color-white));
|
||||
--foreground: var(--color-neutral-100);
|
||||
--card: color-mix(in srgb, var(--color-black) 97%, var(--color-white));
|
||||
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
|
||||
--card-foreground: var(--color-neutral-100);
|
||||
--popover: color-mix(in srgb, var(--color-black) 93%, var(--color-white));
|
||||
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
|
||||
--popover-foreground: var(--color-neutral-100);
|
||||
--primary: oklch(0.588 0.217 264);
|
||||
--primary-foreground: var(--color-white);
|
||||
--secondary: --alpha(var(--color-white) / 3%);
|
||||
--secondary: --alpha(var(--color-white) / 4%);
|
||||
--secondary-foreground: var(--color-neutral-100);
|
||||
--muted: --alpha(var(--color-white) / 3%);
|
||||
--muted-foreground: var(--color-neutral-400);
|
||||
--accent: --alpha(var(--color-white) / 5%);
|
||||
--muted: --alpha(var(--color-white) / 4%);
|
||||
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
|
||||
--accent: --alpha(var(--color-white) / 4%);
|
||||
--accent-foreground: var(--color-neutral-100);
|
||||
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
|
||||
--border: --alpha(var(--color-white) / 6%);
|
||||
@@ -343,10 +331,6 @@ body::after {
|
||||
background-size: 256px 256px;
|
||||
}
|
||||
|
||||
.dark body::after {
|
||||
content: none;
|
||||
}
|
||||
|
||||
pre,
|
||||
code {
|
||||
font-family:
|
||||
|
||||
@@ -66,7 +66,7 @@ describe("chatThreadActions", () => {
|
||||
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
});
|
||||
|
||||
it("starts a contextual new thread from the active draft thread", async () => {
|
||||
it("starts a new thread with only the project carried over — draft workspace choices never leak in", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
const didStart = await startNewThreadFromContext(
|
||||
@@ -84,40 +84,10 @@ describe("chatThreadActions", () => {
|
||||
);
|
||||
|
||||
expect(didStart).toBe(true);
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
});
|
||||
|
||||
it("preserves an explicitly disabled origin base in contextual thread options", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
await startNewThreadFromContext(
|
||||
createContext({
|
||||
activeDraftThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: false,
|
||||
},
|
||||
handleNewThread,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("delegates the target environment defaults to the new-thread handler", async () => {
|
||||
it("starts an explicit current-checkout thread via the local action", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
const didStart = await startNewLocalThreadFromContext(
|
||||
@@ -128,7 +98,9 @@ describe("chatThreadActions", () => {
|
||||
);
|
||||
|
||||
expect(didStart).toBe(true);
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
|
||||
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
|
||||
envMode: "local",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not start a thread when there is no project context", async () => {
|
||||
|
||||
@@ -26,8 +26,6 @@ interface NewThreadHandler {
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
type NewThreadOptions = NonNullable<Parameters<NewThreadHandler>[1]>;
|
||||
|
||||
export interface ChatThreadActionContext {
|
||||
readonly activeDraftThread: DraftThreadContextLike | null;
|
||||
readonly activeThread: ThreadContextLike | undefined;
|
||||
@@ -57,25 +55,15 @@ export function resolveThreadActionProjectRef(
|
||||
return context.defaultProjectRef;
|
||||
}
|
||||
|
||||
function buildContextualThreadOptions(context: ChatThreadActionContext): NewThreadOptions {
|
||||
return {
|
||||
branch: context.activeThread?.branch ?? context.activeDraftThread?.branch ?? null,
|
||||
worktreePath:
|
||||
context.activeThread?.worktreePath ?? context.activeDraftThread?.worktreePath ?? null,
|
||||
envMode:
|
||||
context.activeDraftThread?.envMode ??
|
||||
(context.activeThread?.worktreePath ? "worktree" : "local"),
|
||||
...(context.activeDraftThread
|
||||
? { startFromOrigin: context.activeDraftThread.startFromOrigin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function startNewThreadInProjectFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
projectRef: ScopedProjectRef,
|
||||
): Promise<void> {
|
||||
await context.handleNewThread(projectRef, buildContextualThreadOptions(context));
|
||||
// Only the project carries over from the active thread. Workspace mode,
|
||||
// branch, and worktree choices are draft-only exceptions — a new thread
|
||||
// always starts from the resolved default so exceptions never become
|
||||
// sticky.
|
||||
await context.handleNewThread(projectRef);
|
||||
}
|
||||
|
||||
export async function startNewThreadFromContext(
|
||||
@@ -98,6 +86,7 @@ export async function startNewLocalThreadFromContext(
|
||||
return false;
|
||||
}
|
||||
|
||||
await context.handleNewThread(projectRef);
|
||||
// chat.newLocal is the explicit current-checkout exception (draft-only).
|
||||
await context.handleNewThread(projectRef, { envMode: "local" });
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
|
||||
import type { ThreadEnvMode, UnifiedSettings } from "@t3tools/contracts";
|
||||
import { resolveDefaultThreadEnvMode, type ThreadSurface } from "@t3tools/shared/threadEnvMode";
|
||||
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { isElectron } from "../env";
|
||||
|
||||
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
||||
|
||||
function isLoopbackBrowser(): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
return LOOPBACK_HOSTNAMES.has(window.location.hostname.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify an environment by whether the user's attention is attached to a
|
||||
* local checkout they can see. Two conditions must both hold: the
|
||||
* environment is host-managed (the primary server or a desktop-local
|
||||
* backend, not a saved remote/relay/SSH environment), and the client itself
|
||||
* runs on that host (desktop app, or a browser served from loopback). A
|
||||
* browser reaching the primary server over LAN or a domain is detached —
|
||||
* the checkout lives on another machine the user cannot see, so isolation
|
||||
* is the only coherent default.
|
||||
*/
|
||||
export function resolveEnvironmentThreadSurface(
|
||||
target: ConnectionTarget | null | undefined,
|
||||
): ThreadSurface {
|
||||
if (!target) {
|
||||
return "detached";
|
||||
}
|
||||
const hostManaged =
|
||||
target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target);
|
||||
if (!hostManaged) {
|
||||
return "detached";
|
||||
}
|
||||
return isElectron || isLoopbackBrowser() ? "attached-checkout" : "detached";
|
||||
}
|
||||
|
||||
export function resolveSurfaceThreadEnvMode(input: {
|
||||
readonly settings: Pick<
|
||||
UnifiedSettings,
|
||||
"deriveThreadEnvModeFromSurface" | "defaultThreadEnvMode"
|
||||
>;
|
||||
readonly target: ConnectionTarget | null | undefined;
|
||||
}): ThreadEnvMode {
|
||||
return resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface: input.settings.deriveThreadEnvModeFromSurface,
|
||||
configuredMode: input.settings.defaultThreadEnvMode,
|
||||
surface: resolveEnvironmentThreadSurface(input.target),
|
||||
});
|
||||
}
|
||||
@@ -64,7 +64,6 @@ function makeAgentActivityRows(
|
||||
remove: () => Effect.void,
|
||||
pruneTerminal: () => Effect.void,
|
||||
listForUser: () => Effect.succeed([state]),
|
||||
getForUserThread: () => Effect.succeed(state),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -75,15 +75,6 @@ describe("AgentActivityRows", () => {
|
||||
const listError = yield* rows.listForUser({ userId: "user-2" }).pipe(Effect.flip);
|
||||
expect(listError).toMatchObject({ userId: "user-2", cause });
|
||||
expect(listError.message).toBe("Failed to list agent activity state for user user-2.");
|
||||
|
||||
const getError = yield* rows
|
||||
.getForUserThread({
|
||||
userId: "user-2",
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
expect(getError).toMatchObject({ userId: "user-2", cause });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, failingDb))),
|
||||
|
||||
@@ -83,11 +83,6 @@ export class AgentActivityRows extends Context.Service<
|
||||
ReadonlyArray<RelayAgentActivityState>,
|
||||
AgentActivityRowListPersistenceError
|
||||
>;
|
||||
readonly getForUserThread: (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
}) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;
|
||||
}
|
||||
>()("t3code-relay/agentActivity/AgentActivityRows") {}
|
||||
|
||||
@@ -246,54 +241,6 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {
|
||||
return yield* db
|
||||
.select({ stateJson: relayAgentActivityRows.stateJson })
|
||||
.from(relayAgentActivityRows)
|
||||
.innerJoin(
|
||||
relayEnvironmentLinks,
|
||||
and(
|
||||
eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
|
||||
eq(
|
||||
relayEnvironmentLinks.environmentPublicKey,
|
||||
relayAgentActivityRows.environmentPublicKey,
|
||||
),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.userId, input.userId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
eq(relayAgentActivityRows.environmentId, input.environmentId),
|
||||
eq(relayAgentActivityRows.threadId, input.threadId),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(relayAgentActivityRows.updatedAt))
|
||||
.pipe(
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
|
||||
concurrency: "unbounded",
|
||||
}),
|
||||
),
|
||||
Effect.map((rows) => {
|
||||
for (const row of rows) {
|
||||
const decoded = decodeRelayAgentActivityStateJson(row);
|
||||
if (Option.isSome(decoded)) {
|
||||
return decoded.value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AgentActivityRowListPersistenceError({
|
||||
userId: input.userId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -160,13 +161,10 @@ function makeLayer(input: {
|
||||
>;
|
||||
readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;
|
||||
readonly config?: RelayConfiguration.RelayConfiguration["Service"];
|
||||
// Live agent-activity rows returned by delivery-time state rechecks.
|
||||
// Defaults to the fixture row so queued updates match unless a test is
|
||||
// explicitly exercising stale-state behavior.
|
||||
// Live agent-activity rows returned by the delivery-time start recheck.
|
||||
// Defaults to one freshly-updated running thread so queued starts stay
|
||||
// deliverable in tests that don't care about the recheck.
|
||||
readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;
|
||||
// Current per-thread rows used to reject queued updates/notifications that
|
||||
// have been superseded before APNs delivery.
|
||||
readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;
|
||||
readonly execute?: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
|
||||
@@ -184,14 +182,9 @@ function makeLayer(input: {
|
||||
listForUser: () =>
|
||||
input.activityStates !== undefined
|
||||
? Effect.succeed([...input.activityStates])
|
||||
: Effect.succeed([state]),
|
||||
getForUserThread: ({ environmentId, threadId }) =>
|
||||
Effect.succeed(
|
||||
(input.currentActivityStates ?? input.activityStates ?? [state]).find(
|
||||
(current) =>
|
||||
current.environmentId === environmentId && current.threadId === threadId,
|
||||
) ?? null,
|
||||
),
|
||||
: DateTime.now.pipe(
|
||||
Effect.map((now) => [{ ...state, updatedAt: DateTime.formatIso(now) }]),
|
||||
),
|
||||
} satisfies AgentActivityRows.AgentActivityRows["Service"]),
|
||||
Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
|
||||
send: (body) =>
|
||||
@@ -681,8 +674,6 @@ describe("ApnsDeliveries", () => {
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/",
|
||||
phase: "waiting_for_input",
|
||||
updatedAt: state.updatedAt,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -787,30 +778,6 @@ describe("ApnsDeliveries", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("does not queue a push notification when a thread starts working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.sendForTarget({
|
||||
target: {
|
||||
...target,
|
||||
push_token: "apns-device-token",
|
||||
push_to_start_token: null,
|
||||
activity_push_token: null,
|
||||
remote_started_at: null,
|
||||
},
|
||||
aggregate,
|
||||
nowMs: 5_000,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(queuedJobs).toEqual([]);
|
||||
expect(attempts).toEqual([]);
|
||||
}).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));
|
||||
});
|
||||
|
||||
it.effect("queues bounded alert notification payloads", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
|
||||
@@ -1209,150 +1176,6 @@ describe("ApnsDeliveries", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
const completedAt = "1970-01-01T00:00:01.000Z";
|
||||
const completedAggregate: RelayAgentActivityAggregateState = {
|
||||
...aggregate,
|
||||
activeCount: 0,
|
||||
updatedAt: completedAt,
|
||||
activities: [
|
||||
{
|
||||
...aggregate.activities[0]!,
|
||||
phase: "completed",
|
||||
status: "Done",
|
||||
updatedAt: completedAt,
|
||||
},
|
||||
],
|
||||
};
|
||||
const payload = makeApnsDeliveryJobPayload({
|
||||
kind: "live_activity_update",
|
||||
userId: target.user_id,
|
||||
deviceId: target.device_id,
|
||||
token: target.activity_push_token ?? "activity-token",
|
||||
aggregate: completedAggregate,
|
||||
alert: { title: "Thread", body: "Done: Project" },
|
||||
createdAt: completedAt,
|
||||
expiresAt: "1970-01-01T00:10:00.000Z",
|
||||
jobId: "job-update-superseded-by-running",
|
||||
});
|
||||
const signed = signApnsDeliveryJob({
|
||||
secret: config.apnsDeliveryJobSigningSecret,
|
||||
payload,
|
||||
});
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
executeCount += 1;
|
||||
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.processSignedJob(signed);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: "live_activity_update",
|
||||
ok: true,
|
||||
apnsStatus: null,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
expect(executeCount).toBe(0);
|
||||
expect(attempts).toMatchObject([
|
||||
{
|
||||
sourceJobId: "job-update-superseded-by-running",
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
activityStates: [
|
||||
{
|
||||
...state,
|
||||
phase: "running",
|
||||
headline: "Running",
|
||||
updatedAt: "1970-01-01T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips a queued Done notification after the thread resumes working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
const completedAt = "1970-01-01T00:00:01.000Z";
|
||||
const payload = makeApnsDeliveryJobPayload({
|
||||
kind: "push_notification",
|
||||
userId: target.user_id,
|
||||
deviceId: target.device_id,
|
||||
token: "apns-device-token",
|
||||
aggregate: null,
|
||||
notification: {
|
||||
title: "Thread",
|
||||
body: "Done: Project",
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/",
|
||||
phase: "completed",
|
||||
updatedAt: completedAt,
|
||||
},
|
||||
createdAt: completedAt,
|
||||
expiresAt: "1970-01-01T00:10:00.000Z",
|
||||
jobId: "job-push-superseded-by-running",
|
||||
});
|
||||
const signed = signApnsDeliveryJob({
|
||||
secret: config.apnsDeliveryJobSigningSecret,
|
||||
payload,
|
||||
});
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
executeCount += 1;
|
||||
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.processSignedJob(signed);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: "push_notification",
|
||||
ok: true,
|
||||
apnsStatus: null,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
expect(executeCount).toBe(0);
|
||||
expect(attempts).toMatchObject([
|
||||
{
|
||||
sourceJobId: "job-push-superseded-by-running",
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
currentTargets: [{ ...target, push_token: "apns-device-token" }],
|
||||
currentActivityStates: [
|
||||
{
|
||||
...state,
|
||||
phase: "running",
|
||||
headline: "Running",
|
||||
updatedAt: "1970-01-01T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries signed queue jobs that are already claimed but not completed", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
@@ -1504,15 +1327,7 @@ describe("ApnsDeliveries", () => {
|
||||
deviceId: target.device_id,
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
clearedStarts,
|
||||
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(makeLayer({ attempts, clearedStarts })));
|
||||
});
|
||||
|
||||
it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => {
|
||||
@@ -1558,15 +1373,7 @@ describe("ApnsDeliveries", () => {
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
invalidatedTokens,
|
||||
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -369,8 +369,6 @@ function notificationForAggregate(input: {
|
||||
environmentId: activity.environmentId,
|
||||
threadId: activity.threadId,
|
||||
deepLink: activity.deepLink,
|
||||
phase: activity.phase,
|
||||
updatedAt: activity.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -724,87 +722,6 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];
|
||||
readonly updatedAt: string;
|
||||
}) {
|
||||
return yield* activityRows
|
||||
.getForUserThread({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(current) =>
|
||||
current !== null &&
|
||||
current.phase === input.phase &&
|
||||
current.updatedAt === input.updatedAt,
|
||||
),
|
||||
// A transient persistence failure must not permanently discard a
|
||||
// legitimate alert. Fail open and let the signed job's retry/dedupe
|
||||
// protections handle transport failures as usual.
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {
|
||||
cause,
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
}).pipe(Effect.as(true)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly aggregate: RelayAgentActivityAggregateState;
|
||||
}) {
|
||||
return yield* activityRows.listForUser({ userId: input.userId }).pipe(
|
||||
Effect.map((currentStates) => {
|
||||
const currentByThread = new Map(
|
||||
currentStates.map((current) => [
|
||||
`${current.environmentId}\u0000${current.threadId}`,
|
||||
current,
|
||||
]),
|
||||
);
|
||||
return input.aggregate.activities.every((row) => {
|
||||
const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);
|
||||
return (
|
||||
current !== undefined &&
|
||||
current.phase === row.phase &&
|
||||
current.updatedAt === row.updatedAt
|
||||
);
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {
|
||||
cause,
|
||||
userId: input.userId,
|
||||
}).pipe(Effect.as(true)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly notification: ApnsNotificationPayload;
|
||||
}) {
|
||||
// Jobs from older relay versions do not carry a state identity. Preserve
|
||||
// backwards compatibility and only revalidate newly queued jobs.
|
||||
if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {
|
||||
return true;
|
||||
}
|
||||
return yield* stateIdentityIsCurrent({
|
||||
userId: input.userId,
|
||||
environmentId: input.notification.environmentId,
|
||||
threadId: input.notification.threadId,
|
||||
phase: input.notification.phase,
|
||||
updatedAt: input.notification.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
|
||||
readonly target: LiveActivityDeliveryTarget;
|
||||
readonly kind: RelayDeliveryKind;
|
||||
@@ -874,20 +791,6 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
if (
|
||||
input.kind !== "live_activity_start" &&
|
||||
aggregate !== null &&
|
||||
!(yield* aggregateRowsAreCurrent({
|
||||
userId: input.target.user_id,
|
||||
aggregate,
|
||||
}))
|
||||
) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
}
|
||||
if (
|
||||
input.kind === "live_activity_start" &&
|
||||
@@ -1027,21 +930,6 @@ export const make = Effect.gen(function* () {
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
if (
|
||||
!(yield* notificationStateIsCurrent({
|
||||
userId: input.target.user_id,
|
||||
notification,
|
||||
}))
|
||||
) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
});
|
||||
return staleJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
}
|
||||
const result = yield* apns
|
||||
.sendPushNotificationRequest({
|
||||
|
||||
@@ -86,7 +86,6 @@ function makeAgentActivityRows(
|
||||
};
|
||||
return Effect.succeed([activeState]);
|
||||
},
|
||||
getForUserThread: () => Effect.succeed(null),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import {
|
||||
RelayAgentActivityAggregateState,
|
||||
RelayAgentAwarenessPhase,
|
||||
type RelayDeliveryKind,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -42,11 +38,6 @@ export const ApnsNotificationPayload = Schema.Struct({
|
||||
environmentId: Schema.String,
|
||||
threadId: Schema.String,
|
||||
deepLink: Schema.String,
|
||||
// Optional so delivery jobs queued by older relay builds still decode.
|
||||
// New jobs use these fields to avoid delivering a stale Done/attention
|
||||
// notification after the thread has moved to another phase.
|
||||
phase: Schema.optional(RelayAgentAwarenessPhase),
|
||||
updatedAt: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
|
||||
|
||||
|
||||
@@ -188,6 +188,12 @@ export function createVcsEnvironmentAtoms<R, E>(
|
||||
scheduler: vcsCommandScheduler,
|
||||
concurrency: vcsCommandConcurrency,
|
||||
}),
|
||||
prefetchRemote: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:vcs:prefetch-remote",
|
||||
tag: WS_METHODS.vcsPrefetchRemote,
|
||||
scheduler: vcsCommandScheduler,
|
||||
concurrency: vcsCommandConcurrency,
|
||||
}),
|
||||
createWorktree: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:vcs:create-worktree",
|
||||
tag: WS_METHODS.vcsCreateWorktree,
|
||||
|
||||
@@ -139,9 +139,31 @@ export const VcsCreateWorktreeInput = Schema.Struct({
|
||||
newRefName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
baseRefName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
path: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
/**
|
||||
* When `newRefName` already exists (e.g. a resend after a partially failed
|
||||
* bootstrap reusing the deterministic thread-derived branch name), append a
|
||||
* numeric suffix instead of failing.
|
||||
*/
|
||||
uniquifyNewRefName: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type;
|
||||
|
||||
export const VcsPrefetchRemoteInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type VcsPrefetchRemoteInput = typeof VcsPrefetchRemoteInput.Type;
|
||||
|
||||
/**
|
||||
* Result of a composer-open prefetch. `fetchedAt` is the time of the last
|
||||
* successful fetch of the repository's primary remote (`null` when the fetch
|
||||
* failed and no earlier fetch succeeded this session).
|
||||
*/
|
||||
export const VcsPrefetchRemoteResult = Schema.Struct({
|
||||
fetchedAt: Schema.NullOr(Schema.String),
|
||||
fetchSucceeded: Schema.Boolean,
|
||||
});
|
||||
export type VcsPrefetchRemoteResult = typeof VcsPrefetchRemoteResult.Type;
|
||||
|
||||
export const GitPullRequestRefInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
reference: GitPullRequestReference,
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
GitManagerServiceError,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
VcsPrefetchRemoteInput,
|
||||
VcsPrefetchRemoteResult,
|
||||
VcsPullInput,
|
||||
GitPullRequestRefInput,
|
||||
VcsPullResult,
|
||||
@@ -164,6 +166,7 @@ export const WS_METHODS = {
|
||||
// VCS methods
|
||||
vcsPull: "vcs.pull",
|
||||
vcsRefreshStatus: "vcs.refreshStatus",
|
||||
vcsPrefetchRemote: "vcs.prefetchRemote",
|
||||
vcsListRefs: "vcs.listRefs",
|
||||
vcsCreateWorktree: "vcs.createWorktree",
|
||||
vcsRemoveWorktree: "vcs.removeWorktree",
|
||||
@@ -414,6 +417,12 @@ export const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, {
|
||||
error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsVcsPrefetchRemoteRpc = Rpc.make(WS_METHODS.vcsPrefetchRemote, {
|
||||
payload: VcsPrefetchRemoteInput,
|
||||
success: VcsPrefetchRemoteResult,
|
||||
error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, {
|
||||
payload: GitRunStackedActionInput,
|
||||
success: GitActionProgressEvent,
|
||||
@@ -709,6 +718,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeVcsStatusRpc,
|
||||
WsVcsPullRpc,
|
||||
WsVcsRefreshStatusRpc,
|
||||
WsVcsPrefetchRemoteRpc,
|
||||
WsGitRunStackedActionRpc,
|
||||
WsGitResolvePullRequestRpc,
|
||||
WsGitPreparePullRequestThreadRpc,
|
||||
|
||||
@@ -88,14 +88,31 @@ 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 so new worktrees pin the latest remote base", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults to surface-derived thread env mode resolution", () => {
|
||||
const decoded = decodeServerSettings({});
|
||||
expect(decoded.deriveThreadEnvModeFromSurface).toBe(true);
|
||||
// The wire value stays within the legacy literal set so pre-surface
|
||||
// clients can still decode the server config snapshot.
|
||||
expect(decoded.defaultThreadEnvMode).toBe("local");
|
||||
});
|
||||
|
||||
it("accepts explicit env modes for legacy configs", () => {
|
||||
expect(decodeServerSettings({ defaultThreadEnvMode: "worktree" }).defaultThreadEnvMode).toBe(
|
||||
"worktree",
|
||||
);
|
||||
expect(decodeServerSettings({ defaultThreadEnvMode: "local" }).defaultThreadEnvMode).toBe(
|
||||
"local",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts start-from-origin updates", () => {
|
||||
expect(
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
|
||||
).toBe(true);
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@ import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.t
|
||||
|
||||
// ── Client Settings (local-only) ───────────────────────────────
|
||||
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
|
||||
|
||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
@@ -75,6 +78,12 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
|
||||
),
|
||||
// Per-project default workspace mode, keyed by scoped project key. This is
|
||||
// the sanctioned way to retrain the new-thread default for one project —
|
||||
// the composer's draft-only exceptions never write here implicitly.
|
||||
projectThreadEnvModeOverrides: Schema.Record(TrimmedNonEmptyString, ThreadEnvMode).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed({})),
|
||||
),
|
||||
sidebarProjectGroupingOverrides: Schema.Record(
|
||||
TrimmedNonEmptyString,
|
||||
SidebarProjectGroupingMode,
|
||||
@@ -99,9 +108,6 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
|
||||
|
||||
// ── Server Settings (server-authoritative) ────────────────────
|
||||
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
|
||||
|
||||
const makeBinaryPathSetting = (fallback: string) =>
|
||||
TrimmedString.pipe(
|
||||
Schema.decodeTo(
|
||||
@@ -363,6 +369,28 @@ export type ObservabilitySettings = typeof ObservabilitySettings.Type;
|
||||
|
||||
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
/**
|
||||
* A remote fetch younger than this window counts as "fresh": worktree
|
||||
* creation pins the remote-tracking commit without fetching again.
|
||||
*/
|
||||
export const WORKTREE_BASE_FRESHNESS_WINDOW = Duration.seconds(30);
|
||||
|
||||
/**
|
||||
* Fail-visible horizon: when a send-time fetch fails but the last successful
|
||||
* fetch is within this horizon, worktree creation proceeds on the last-known
|
||||
* remote commit and reports stale provenance instead of failing.
|
||||
*/
|
||||
export const WORKTREE_BASE_USABLE_HORIZON = Duration.hours(1);
|
||||
|
||||
/**
|
||||
* Provenance of the commit a worktree thread was pinned to.
|
||||
* - `fresh`: pinned from a remote fetch within the freshness window
|
||||
* - `stale`: remote unreachable; pinned from the last-known remote commit
|
||||
* - `local`: pinned from a local ref without consulting the remote
|
||||
*/
|
||||
export const WorktreeBaseProvenance = Schema.Literals(["fresh", "stale", "local"]);
|
||||
export type WorktreeBaseProvenance = typeof WorktreeBaseProvenance.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
@@ -371,11 +399,23 @@ export const ServerSettings = Schema.Struct({
|
||||
Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
|
||||
),
|
||||
),
|
||||
/**
|
||||
* When true (the default), the workspace mode for new threads derives from
|
||||
* the surface the client runs on: attached to a visible local checkout
|
||||
* (desktop app, CLI-launched local browser) → current checkout; detached
|
||||
* (remote browser, mobile, relay/SSH environments) → fresh worktree.
|
||||
* `defaultThreadEnvMode` only applies when this is false. A separate
|
||||
* boolean (rather than a third `defaultThreadEnvMode` literal) keeps the
|
||||
* wire value decodable by clients that predate surface derivation.
|
||||
*/
|
||||
deriveThreadEnvModeFromSurface: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
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(
|
||||
@@ -506,6 +546,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
|
||||
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
deriveThreadEnvModeFromSurface: Schema.optionalKey(Schema.Boolean),
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
|
||||
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
|
||||
@@ -559,6 +600,9 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
}),
|
||||
),
|
||||
),
|
||||
projectThreadEnvModeOverrides: Schema.optionalKey(
|
||||
Schema.Record(TrimmedNonEmptyString, ThreadEnvMode),
|
||||
),
|
||||
sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
|
||||
sidebarProjectGroupingOverrides: Schema.optionalKey(
|
||||
Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
|
||||
|
||||
@@ -3,10 +3,6 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./projectFavicon": {
|
||||
"types": "./src/projectFavicon.ts",
|
||||
"import": "./src/projectFavicon.ts"
|
||||
},
|
||||
"./model": {
|
||||
"types": "./src/model.ts",
|
||||
"import": "./src/model.ts"
|
||||
@@ -23,6 +19,10 @@
|
||||
"types": "./src/git.ts",
|
||||
"import": "./src/git.ts"
|
||||
},
|
||||
"./threadEnvMode": {
|
||||
"types": "./src/threadEnvMode.ts",
|
||||
"import": "./src/threadEnvMode.ts"
|
||||
},
|
||||
"./sourceControl": {
|
||||
"types": "./src/sourceControl.ts",
|
||||
"import": "./src/sourceControl.ts"
|
||||
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
applyGitStatusStreamEvent,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
buildThreadWorktreeBranchName,
|
||||
isTemporaryWorktreeBranch,
|
||||
normalizeGitRemoteUrl,
|
||||
parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
|
||||
@@ -71,6 +72,11 @@ describe("isTemporaryWorktreeBranch", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches uniquified retry suffixes on thread-derived branches", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-2`)).toBe(true);
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-10`)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects non-temporary refName names", () => {
|
||||
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false);
|
||||
expect(isTemporaryWorktreeBranch("main")).toBe(false);
|
||||
@@ -78,6 +84,32 @@ describe("isTemporaryWorktreeBranch", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadWorktreeBranchName", () => {
|
||||
const failRandomHex = (): string => {
|
||||
throw new Error("randomness must not be used for UUID thread ids");
|
||||
};
|
||||
|
||||
it("derives a deterministic branch from the thread id's UUID prefix", () => {
|
||||
expect(
|
||||
buildThreadWorktreeBranchName("A1B2C3D4-0000-4000-8000-000000000000", failRandomHex),
|
||||
).toBe(`${WORKTREE_BRANCH_PREFIX}/a1b2c3d4`);
|
||||
});
|
||||
|
||||
it("produces a valid temporary worktree branch shape", () => {
|
||||
expect(
|
||||
isTemporaryWorktreeBranch(
|
||||
buildThreadWorktreeBranchName("deadbeef-1111-4222-8333-444455556666", failRandomHex),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("falls back to randomness for non-UUID thread ids", () => {
|
||||
expect(buildThreadWorktreeBranchName("thread-1", () => "CAFEF00D")).toBe(
|
||||
`${WORKTREE_BRANCH_PREFIX}/cafef00d`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyGitStatusStreamEvent", () => {
|
||||
it("treats a remote-only update as a repository when local state is missing", () => {
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
|
||||
@@ -11,7 +11,11 @@ import * as Result from "effect/Result";
|
||||
import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
|
||||
|
||||
export const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
// Optional `-N` suffix: bootstrap retries uniquify a taken thread-derived
|
||||
// branch name (t3code/a1b2c3d4-2), and those are still temporary branches.
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
|
||||
`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}(-\\d+)?$`,
|
||||
);
|
||||
|
||||
/**
|
||||
* Sanitize an arbitrary string into a valid, lowercase git refName fragment.
|
||||
@@ -93,6 +97,24 @@ export function buildTemporaryWorktreeBranchName(
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic worktree branch name derived from the thread id (the first
|
||||
* UUID segment), so every worktree is attributable to its thread by
|
||||
* construction and resends of the same thread reuse one branch name.
|
||||
* Falls back to the caller-supplied randomness when the id has no usable
|
||||
* hex prefix (non-UUID ids from older clients).
|
||||
*/
|
||||
export function buildThreadWorktreeBranchName(
|
||||
threadId: string,
|
||||
randomHex: (byteLength: number) => string,
|
||||
): string {
|
||||
const token = threadId.trim().toLowerCase().slice(0, 8);
|
||||
if (/^[0-9a-f]{8}$/.test(token)) {
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
return buildTemporaryWorktreeBranchName(randomHex);
|
||||
}
|
||||
|
||||
export function isTemporaryWorktreeBranch(refName: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isProjectFaviconFallbackUrl, PROJECT_FAVICON_FALLBACK_MARKER } from "./projectFavicon.ts";
|
||||
|
||||
describe("project favicon", () => {
|
||||
it("identifies fallback asset URLs by their dedicated filename", () => {
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(
|
||||
`https://environment.example/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(`/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not mistake real favicons or query parameters for fallbacks", () => {
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl("https://environment.example/api/assets/token/favicon.svg"),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(
|
||||
`https://environment.example/api/assets/token/favicon.svg?name=${PROJECT_FAVICON_FALLBACK_MARKER}`,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(isProjectFaviconFallbackUrl(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
export const PROJECT_FAVICON_FALLBACK_MARKER = "project-favicon-missing";
|
||||
|
||||
export function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {
|
||||
if (!url) return false;
|
||||
|
||||
try {
|
||||
const pathname = new URL(url, "https://t3.invalid").pathname;
|
||||
return pathname.slice(pathname.lastIndexOf("/") + 1) === PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveDefaultThreadEnvMode, surfaceDefaultThreadEnvMode } from "./threadEnvMode.ts";
|
||||
|
||||
describe("surfaceDefaultThreadEnvMode", () => {
|
||||
it("uses the current checkout when the user's attention is attached to it", () => {
|
||||
expect(surfaceDefaultThreadEnvMode("attached-checkout")).toBe("local");
|
||||
});
|
||||
|
||||
it("isolates in a worktree on detached surfaces", () => {
|
||||
expect(surfaceDefaultThreadEnvMode("detached")).toBe("worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultThreadEnvMode", () => {
|
||||
it("derives from the surface when surface derivation is on", () => {
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface: true,
|
||||
configuredMode: "worktree",
|
||||
surface: "attached-checkout",
|
||||
}),
|
||||
).toBe("local");
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface: true,
|
||||
configuredMode: "local",
|
||||
surface: "detached",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("pins the configured mode on every surface when derivation is off", () => {
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface: false,
|
||||
configuredMode: "worktree",
|
||||
surface: "attached-checkout",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
deriveFromSurface: false,
|
||||
configuredMode: "local",
|
||||
surface: "detached",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ThreadEnvMode } from "@t3tools/contracts/settings";
|
||||
|
||||
/**
|
||||
* Surfaces a client can run on, for deriving the default workspace mode of a
|
||||
* new thread. The deciding question is whether the user's attention is
|
||||
* attached to a local checkout they can see:
|
||||
*
|
||||
* - `attached-checkout`: the user is looking at the checkout (desktop app on
|
||||
* a local project, browser opened on the same machine as the server). The
|
||||
* agent working elsewhere would be invisible to them, so the default is
|
||||
* the current checkout.
|
||||
* - `detached`: no local checkout in front of the user (remote browser,
|
||||
* mobile, relay/SSH environments). Isolation in a fresh worktree is the
|
||||
* only coherent default.
|
||||
*/
|
||||
export type ThreadSurface = "attached-checkout" | "detached";
|
||||
|
||||
export function surfaceDefaultThreadEnvMode(surface: ThreadSurface): ThreadEnvMode {
|
||||
return surface === "attached-checkout" ? "local" : "worktree";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effective workspace mode for a new thread.
|
||||
* `deriveFromSurface` (the default) derives the mode from where the client
|
||||
* runs; otherwise the explicit `configuredMode` applies everywhere.
|
||||
*/
|
||||
export function resolveDefaultThreadEnvMode(input: {
|
||||
readonly deriveFromSurface: boolean;
|
||||
readonly configuredMode: ThreadEnvMode;
|
||||
readonly surface: ThreadSurface;
|
||||
}): ThreadEnvMode {
|
||||
return input.deriveFromSurface
|
||||
? surfaceDefaultThreadEnvMode(input.surface)
|
||||
: input.configuredMode;
|
||||
}
|
||||