Compare commits

..
69 changed files with 1225 additions and 1503 deletions

No files matched your search

+44
View File
@@ -28,6 +28,50 @@ Start Metro for the dev client:
vp run dev:client
```
### Android
Local Android builds require Android Studio, JDK 17, and an Android SDK. On an Apple Silicon Mac,
the following setup installs the API 36.1 emulator used to exercise promoted ongoing notifications
(Android Live Updates):
```bash
brew install --cask android-studio android-commandlinetools
brew install openjdk@17
export JAVA_HOME="/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"
export ANDROID_HOME="$HOME/Library/Android/sdk"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/emulator:$ANDROID_HOME/platform-tools:$PATH"
yes | sdkmanager --sdk_root="$ANDROID_HOME" --licenses
sdkmanager --sdk_root="$ANDROID_HOME" \
"platform-tools" \
"emulator" \
"platforms;android-36" \
"build-tools;36.0.0" \
"system-images;android-36.1;google_apis;arm64-v8a"
echo no | avdmanager create avd \
--name T3Code_API_36_1 \
--package "system-images;android-36.1;google_apis;arm64-v8a" \
--device pixel_9
```
Add the four exports to your shell profile, start `T3Code_API_36_1` from Android Studio's Device
Manager, then build and run the development client:
```bash
vp run android:dev
```
The first native build may need roughly 20 GB of free space for SDK, NDK, Gradle, and emulator
caches. In a development build on Android, Settings includes an **Android Live Update · Mock**
section for exercising the active-agents and needs-attention states without the relay.
The mock preview is entirely local. It does not require T3 Connect, a hosted relay, Clerk
configuration, Firebase/FCM credentials, or a connected T3 Code server. Remote delivery and
background reconciliation require the separate T3 Connect infrastructure.
Build and run the local iOS dev client:
```bash
+1
View File
@@ -315,6 +315,7 @@ const config: ExpoConfig = {
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
"./plugins/withAndroidGradleHeap.cjs",
"./plugins/withAndroidUnifiedNdk.cjs",
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
@@ -0,0 +1,20 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.agentliveupdate'
version = '0.0.0'
android {
namespace 'expo.modules.t3agentliveupdate'
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
implementation 'androidx.core:core:1.17.0'
}
@@ -0,0 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
<application>
<receiver
android:name="expo.modules.t3agentliveupdate.AgentLiveUpdateDismissReceiver"
android:exported="false" />
</application>
</manifest>
@@ -0,0 +1,11 @@
package expo.modules.t3agentliveupdate
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
internal class AgentLiveUpdateDismissReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
AgentLiveUpdateManager(context.applicationContext).cancel()
}
}
@@ -0,0 +1,194 @@
package expo.modules.t3agentliveupdate
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
internal class AgentLiveUpdateManager(private val context: Context) {
private val notificationManager = context.getSystemService(NotificationManager::class.java)
private val notificationManagerCompat = NotificationManagerCompat.from(context)
fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
CHANNEL_ID,
"Agent live updates",
NotificationManager.IMPORTANCE_LOW,
).apply {
description = "Ongoing status for active T3 Code agents"
enableVibration(false)
lockscreenVisibility = Notification.VISIBILITY_PRIVATE
setShowBadge(false)
setSound(null, null)
}
notificationManager.createNotificationChannel(channel)
}
fun show(snapshot: LiveUpdateSnapshot): Map<String, Any> {
ensureChannel()
checkNotificationPermission()
val title = snapshot.title.trim().ifEmpty { "T3 Code agents" }.take(MAX_TITLE_LENGTH)
val summary = snapshot.summary.trim().ifEmpty { "Agent activity is in progress" }
val expandedText = snapshot.lines
.asSequence()
.map(String::trim)
.filter(String::isNotEmpty)
.take(MAX_VISIBLE_LINES)
.joinToString("\n")
.ifEmpty { summary }
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.t3_agent_live_update)
.setContentTitle(title)
.setContentText(summary)
.setStyle(NotificationCompat.BigTextStyle().bigText(expandedText))
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setColorized(false)
.setRequestPromotedOngoing(true)
.setWhen(System.currentTimeMillis())
.setShowWhen(true)
.setDeleteIntent(dismissPendingIntent())
.addAction(
NotificationCompat.Action.Builder(
0,
"Stop",
dismissPendingIntent(),
).build(),
)
contentPendingIntent()?.let(builder::setContentIntent)
snapshot.shortCriticalText
.trim()
.take(MAX_SHORT_CRITICAL_TEXT_LENGTH)
.takeIf(String::isNotEmpty)
?.let(builder::setShortCriticalText)
val notification = builder.build()
notificationManagerCompat.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification)
return status()
}
fun cancel(): Map<String, Any> {
notificationManagerCompat.cancel(NOTIFICATION_TAG, NOTIFICATION_ID)
return status(null)
}
fun status(): Map<String, Any> = status(activeNotification())
fun openPromotionSettings(): Map<String, Any> {
val promotionIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
Intent(Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS)
} else {
appNotificationSettingsIntent()
}
promotionIntent
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(promotionIntent)
} catch (_: ActivityNotFoundException) {
context.startActivity(appNotificationSettingsIntent())
}
return status()
}
private fun status(notification: Notification?): Map<String, Any> {
val supportsPromotion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA
val promotable = supportsPromotion && notification?.hasPromotableCharacteristics() == true
val promoted = supportsPromotion &&
notification != null &&
notification.flags.and(Notification.FLAG_PROMOTED_ONGOING) != 0
val channelImportance = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.getNotificationChannel(CHANNEL_ID)?.importance
?: NotificationManager.IMPORTANCE_UNSPECIFIED
} else {
NotificationManager.IMPORTANCE_UNSPECIFIED
}
return mapOf(
"apiLevel" to Build.VERSION.SDK_INT,
"supportsPromotion" to supportsPromotion,
"notificationsEnabled" to notificationManagerCompat.areNotificationsEnabled(),
"canPostPromotedNotifications" to (
supportsPromotion && notificationManagerCompat.canPostPromotedNotifications()
),
"channelImportance" to channelImportance,
"active" to (notification != null),
"promotable" to promotable,
"promoted" to promoted,
)
}
private fun activeNotification(): Notification? = notificationManagerCompat.activeNotifications
.firstOrNull { it.tag == NOTIFICATION_TAG && it.id == NOTIFICATION_ID }
?.notification
private fun checkNotificationPermission() {
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
throw SecurityException("Notification permission is required to show an agent Live Update.")
}
}
private fun dismissPendingIntent(): PendingIntent {
val intent = Intent(context, AgentLiveUpdateDismissReceiver::class.java).apply {
action = ACTION_DISMISS
}
return PendingIntent.getBroadcast(
context,
DISMISS_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
private fun contentPendingIntent(): PendingIntent? {
val intent =
context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return PendingIntent.getActivity(
context,
CONTENT_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
private fun appNotificationSettingsIntent(): Intent =
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
private companion object {
const val CHANNEL_ID = "t3_agent_live_updates"
const val NOTIFICATION_TAG = "t3-agent-live-update"
const val NOTIFICATION_ID = 44_001
const val ACTION_DISMISS = "com.t3tools.agentliveupdate.action.DISMISS"
const val DISMISS_REQUEST_CODE = 44_002
const val CONTENT_REQUEST_CODE = 44_003
const val MAX_VISIBLE_LINES = 3
const val MAX_TITLE_LENGTH = 80
const val MAX_SHORT_CRITICAL_TEXT_LENGTH = 7
}
}
@@ -0,0 +1,18 @@
package expo.modules.t3agentliveupdate
import expo.modules.kotlin.records.Field
import expo.modules.kotlin.records.Record
internal class LiveUpdateSnapshot : Record {
@Field
val title: String = ""
@Field
val summary: String = ""
@Field
val lines: List<String> = emptyList()
@Field
val shortCriticalText: String = ""
}
@@ -0,0 +1,38 @@
package expo.modules.t3agentliveupdate
import android.content.Context
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3AgentLiveUpdateModule : Module() {
private val context: Context
get() = requireNotNull(appContext.reactContext) {
"T3AgentLiveUpdate requires an active React context."
}
override fun definition() = ModuleDefinition {
Name("T3AgentLiveUpdate")
AsyncFunction("ensureChannel") {
manager().apply { ensureChannel() }.status()
}
AsyncFunction("getStatus") {
manager().status()
}
AsyncFunction("show") { snapshot: LiveUpdateSnapshot ->
manager().show(snapshot)
}
AsyncFunction("cancel") {
manager().cancel()
}
AsyncFunction("openPromotionSettings") {
manager().openPromotionSettings()
}
}
private fun manager() = AgentLiveUpdateManager(context.applicationContext)
}
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M8,5.5L1.5,12 8,18.5 9.4,17.1 4.3,12 9.4,6.9zM16,5.5L14.6,6.9 19.7,12 14.6,17.1 16,18.5 22.5,12z" />
</vector>
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"]
}
}
@@ -0,0 +1,12 @@
{
"name": "@t3tools/mobile-agent-live-update-native",
"version": "0.0.0",
"private": true,
"expo-module": {
"android": {
"modules": [
"expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"
]
}
}
}
@@ -0,0 +1,36 @@
const { withProjectBuildGradle } = require("expo/config-plugins");
const BLOCK_START = "// @generated by withAndroidUnifiedNdk";
const BLOCK_END = "// @end withAndroidUnifiedNdk";
const BLOCK = `${BLOCK_START}
// Expo libraries that do not declare an NDK version otherwise fall back to
// Android Gradle Plugin's default. React Native declares a newer revision,
// which makes clean local builds download and retain both multi-gigabyte NDKs.
subprojects { subproject ->
subproject.plugins.withId("com.android.application") {
subproject.android.ndkVersion = rootProject.ext.ndkVersion
}
subproject.plugins.withId("com.android.library") {
subproject.android.ndkVersion = rootProject.ext.ndkVersion
}
}
${BLOCK_END}`;
module.exports = function withAndroidUnifiedNdk(config) {
return withProjectBuildGradle(config, (nextConfig) => {
if (nextConfig.modResults.language !== "groovy") {
throw new Error("withAndroidUnifiedNdk requires a Groovy Android project build file.");
}
const generatedBlock = new RegExp(
`${BLOCK_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${BLOCK_END.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
)}\\n?`,
"g",
);
const contents = nextConfig.modResults.contents.replace(generatedBlock, "").trimEnd();
nextConfig.modResults.contents = `${contents}\n\n${BLOCK}\n`;
return nextConfig;
});
};
@@ -0,0 +1,96 @@
import { requireOptionalNativeModule } from "expo";
import { Platform } from "react-native";
const MODULE_NAME = "T3AgentLiveUpdate";
export interface AndroidLiveUpdateStatus {
readonly apiLevel: number;
readonly supportsPromotion: boolean;
readonly notificationsEnabled: boolean;
readonly canPostPromotedNotifications: boolean;
readonly channelImportance: number;
readonly active: boolean;
readonly promotable: boolean;
readonly promoted: boolean;
}
interface AndroidLiveUpdateSnapshot {
readonly title: string;
readonly summary: string;
readonly lines: ReadonlyArray<string>;
readonly shortCriticalText: string;
}
interface AndroidLiveUpdateNativeModule {
readonly ensureChannel: () => Promise<AndroidLiveUpdateStatus>;
readonly getStatus: () => Promise<AndroidLiveUpdateStatus>;
readonly show: (snapshot: AndroidLiveUpdateSnapshot) => Promise<AndroidLiveUpdateStatus>;
readonly cancel: () => Promise<AndroidLiveUpdateStatus>;
readonly openPromotionSettings: () => Promise<AndroidLiveUpdateStatus>;
}
export type AndroidLiveUpdateMockKind = "working" | "attention";
const MOCK_SNAPSHOTS: Record<AndroidLiveUpdateMockKind, AndroidLiveUpdateSnapshot> = {
working: {
title: "3 agents working",
summary: "T3 Code is making progress",
lines: [
"● Implementing Android Live Updates",
"● Running the mobile typecheck",
"◌ Reviewing recent agent changes",
],
shortCriticalText: "3",
},
attention: {
title: "1 agent needs attention",
summary: "Approval is required to continue",
lines: [
"! Waiting for your approval",
"● Android validation is still running",
"● Two agents continue in the background",
],
shortCriticalText: "Action",
},
};
function resolveNativeModule(): AndroidLiveUpdateNativeModule | null {
if (Platform.OS !== "android") return null;
try {
return requireOptionalNativeModule<AndroidLiveUpdateNativeModule>(MODULE_NAME);
} catch {
return null;
}
}
function requireNativeLiveUpdateModule(): AndroidLiveUpdateNativeModule {
const module = resolveNativeModule();
if (module) return module;
throw new Error("Rebuild the Android development client to install the Live Update module.");
}
export function hasAndroidLiveUpdateModule(): boolean {
return resolveNativeModule() !== null;
}
export async function ensureAndroidLiveUpdateChannel(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().ensureChannel();
}
export async function getAndroidLiveUpdateStatus(): Promise<AndroidLiveUpdateStatus | null> {
return resolveNativeModule()?.getStatus() ?? null;
}
export async function showAndroidLiveUpdateMock(
kind: AndroidLiveUpdateMockKind,
): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().show(MOCK_SNAPSHOTS[kind]);
}
export async function cancelAndroidLiveUpdateMock(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().cancel();
}
export async function openAndroidLiveUpdatePromotionSettings(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().openPromotionSettings();
}
@@ -0,0 +1,130 @@
import * as Notifications from "expo-notifications";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, AppState, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import {
cancelAndroidLiveUpdateMock,
ensureAndroidLiveUpdateChannel,
getAndroidLiveUpdateStatus,
hasAndroidLiveUpdateModule,
openAndroidLiveUpdatePromotionSettings,
showAndroidLiveUpdateMock,
type AndroidLiveUpdateMockKind,
type AndroidLiveUpdateStatus,
} from "../agent-awareness/androidLiveUpdate";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
export function AndroidLiveUpdatePreviewSection() {
const [status, setStatus] = useState<AndroidLiveUpdateStatus | null>(null);
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const moduleAvailable = hasAndroidLiveUpdateModule();
const refreshStatus = useCallback(async () => {
const nextStatus = await getAndroidLiveUpdateStatus();
setStatus(nextStatus);
}, []);
useEffect(() => {
void refreshStatus();
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") void refreshStatus();
});
return () => subscription.remove();
}, [refreshStatus]);
const run = useCallback(async (operation: () => Promise<AndroidLiveUpdateStatus>) => {
if (busyRef.current) return;
busyRef.current = true;
setBusy(true);
try {
setStatus(await operation());
} catch (cause) {
Alert.alert(
"Live Update preview unavailable",
cause instanceof Error ? cause.message : "Could not update the mock notification.",
);
} finally {
busyRef.current = false;
setBusy(false);
}
}, []);
const showMock = useCallback(
(kind: AndroidLiveUpdateMockKind) => {
void run(async () => {
await ensureAndroidLiveUpdateChannel();
const currentPermission = await Notifications.getPermissionsAsync();
const permission = currentPermission.granted
? currentPermission
: await Notifications.requestPermissionsAsync();
if (!permission.granted) {
throw new Error("Allow notifications to display the Android Live Update preview.");
}
return showAndroidLiveUpdateMock(kind);
});
},
[run],
);
const statusLabel = useMemo(
() => formatStatus(status, moduleAvailable),
[moduleAvailable, status],
);
const settingsValue = status?.canPostPromotedNotifications ? "Allowed" : "Review";
return (
<View className="gap-3">
<SettingsSection title="Android Live Update · Mock">
<SettingsRow
disabled={busy || !moduleAvailable}
icon="bolt.circle"
label="Show Active Agents"
onPress={() => showMock("working")}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="exclamationmark.triangle"
label="Show Needs Attention"
onPress={() => showMock("attention")}
/>
<SettingsRow
disabled={busy || !moduleAvailable || !status?.active}
icon="stop.fill"
label="End Mock Update"
onPress={() => void run(cancelAndroidLiveUpdateMock)}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="gearshape"
label="Promotion Settings"
value={settingsValue}
onPress={() => void run(openAndroidLiveUpdatePromotionSettings)}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
{statusLabel} Mock data only; relay and FCM delivery are intentionally deferred.
</Text>
</View>
);
}
function formatStatus(status: AndroidLiveUpdateStatus | null, moduleAvailable: boolean): string {
if (!moduleAvailable) return "Rebuild the Android development client to enable this preview.";
if (!status) return "Checking Android notification capabilities.";
if (!status.notificationsEnabled) return "Notification access is currently disabled.";
if (status.active && status.promoted) return "A promoted Live Update is active.";
if (status.active && status.promotable) {
return status.canPostPromotedNotifications
? "A promotable ongoing notification is active."
: "The ongoing notification is active, but promotion access is disabled.";
}
if (!status.supportsPromotion) {
return "This device will use the standard ongoing-notification fallback.";
}
return status.canPostPromotedNotifications
? "This device allows promoted Live Updates."
: "Open Promotion Settings to allow promoted Live Updates.";
}
@@ -38,6 +38,7 @@ import { runtime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { AndroidLiveUpdatePreviewSection } from "./AndroidLiveUpdatePreviewSection";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
@@ -125,6 +126,8 @@ function LocalSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>
@@ -508,6 +511,8 @@ function ConfiguredSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -1,20 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
describe("buildAssetResponseHeaders", () => {
it("forces non-image assets to download without overriding the client filename", () => {
expect(buildAssetResponseHeaders({ download: true })).toEqual({
"Cache-Control": "private, max-age=3600",
"Content-Disposition": "attachment",
"X-Content-Type-Options": "nosniff",
});
});
it("does not force image assets to download", () => {
expect(buildAssetResponseHeaders({ download: false })).toEqual({
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
});
});
});
-7
View File
@@ -1,7 +0,0 @@
export function buildAssetResponseHeaders(input: { readonly download?: boolean }) {
return {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
...(input.download ? { "Content-Disposition": "attachment" } : {}),
};
}
@@ -198,32 +198,6 @@ describe("AssetAccess", () => {
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
kind: "file",
path: attachmentPath,
download: false,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("marks non-image attachment capabilities for download", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002";
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
const result = yield* issueAssetUrl({
resource: { _tag: "attachment", attachmentId },
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({
kind: "file",
path: attachmentPath,
download: true,
});
}).pipe(Effect.provide(testLayer)),
);
+4 -17
View File
@@ -36,7 +36,6 @@ import {
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import { SAFE_IMAGE_FILE_EXTENSIONS } from "../imageMime.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -92,11 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = {
readonly kind: "file";
readonly path: string;
readonly download?: boolean;
};
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -388,17 +383,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
),
Effect.orElseSucceed(() => Option.none()),
);
if (!Option.isSome(info) || info.value.type !== "File") {
return null;
}
// Non-image attachments are downloaded rather than rendered inline so the
// same-origin asset route never interprets uploaded content (e.g. HTML/XML).
const extension = attachmentPath.slice(attachmentPath.lastIndexOf(".")).toLowerCase();
return {
kind: "file",
path: attachmentPath,
download: !SAFE_IMAGE_FILE_EXTENSIONS.has(extension),
} satisfies ResolvedAsset;
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "project-favicon") {
-97
View File
@@ -1,97 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts";
const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt");
describe("attachmentPrompt", () => {
it("appends a prompt line for file attachments", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 2048,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000001.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`,
);
});
it("returns text unchanged when only image attachments are present", () => {
expect(
appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "image",
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
},
],
}),
).toBe("hello");
});
it("returns only the prompt lines when the text is empty", () => {
const result = appendFileAttachmentPromptText({
text: "",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000003",
name: "data.csv",
mimeType: "text/csv",
sizeBytes: 12,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.csv",
);
expect(result).toBe(
`[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`,
);
});
it("strips control characters, brackets, and parentheses from attachment names", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000004",
name: "a(b)\u0001[c].txt",
mimeType: "text/plain",
sizeBytes: 5,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000004.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`,
);
});
});
-55
View File
@@ -1,55 +0,0 @@
import type { ChatAttachment } from "@t3tools/contracts";
import { resolveAttachmentPath } from "./attachmentStore.ts";
const SIZE_LABEL_UNITS = ["B", "KB", "MB"] as const;
function formatSizeLabel(sizeBytes: number): string {
let value = sizeBytes;
let unitIndex = 0;
while (value >= 1024 && unitIndex < SIZE_LABEL_UNITS.length - 1) {
value /= 1024;
unitIndex += 1;
}
const rounded = unitIndex === 0 ? String(value) : value.toFixed(1);
return `${rounded} ${SIZE_LABEL_UNITS[unitIndex]}`;
}
function sanitizePromptFileName(name: string): string {
// eslint-disable-next-line no-control-regex
return name.replace(/[\u0000-\u001f\u007f()[\]]+/gu, " ").trim();
}
/**
* Non-image attachments are delivered by reference: the file already lives on
* the server's disk, so the provider agent reads it with its own tools. Images
* keep their native content-block path and are not mentioned here.
*/
export function appendFileAttachmentPromptText(input: {
readonly text: string;
readonly attachmentsDir: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
}): string {
const lines: Array<string> = [];
for (const attachment of input.attachments) {
if (attachment.type !== "file") {
continue;
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: input.attachmentsDir,
attachment,
});
if (!attachmentPath) {
continue;
}
const name = sanitizePromptFileName(attachment.name);
lines.push(
`[Attached file: ${attachmentPath} (${name}, ${attachment.mimeType}, ${formatSizeLabel(attachment.sizeBytes)}). Read it from disk when needed.]`,
);
}
if (lines.length === 0) {
return input.text;
}
const joined = lines.join("\n");
return input.text.trim().length > 0 ? `${input.text}\n\n${joined}` : joined;
}
-32
View File
@@ -6,7 +6,6 @@ import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import {
attachmentRelativePath,
createAttachmentId,
parseThreadSegmentFromAttachmentId,
resolveAttachmentPathById,
@@ -45,37 +44,6 @@ describe("attachmentStore", () => {
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
});
it("builds file attachment relative paths with the inferred file extension", () => {
expect(
attachmentRelativePath({
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
}),
).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf");
});
it("resolves attachment path by id for a written file attachment extension", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const attachmentId = "thread-1-attachment";
const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`);
NodeFS.writeFileSync(pdfPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId,
});
expect(resolved).toBe(pdfPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+2 -16
View File
@@ -8,16 +8,9 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import {
inferFileExtension,
inferImageExtension,
SAFE_FILE_EXTENSIONS,
SAFE_IMAGE_FILE_EXTENSIONS,
} from "./imageMime.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [
...new Set([...SAFE_IMAGE_FILE_EXTENSIONS, ...SAFE_FILE_EXTENSIONS, ".bin"]),
];
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -70,13 +63,6 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
});
return `${attachment.id}${extension}`;
}
case "file": {
const extension = inferFileExtension({
mimeType: attachment.mimeType,
fileName: attachment.name,
});
return `${attachment.id}${extension}`;
}
}
}
+4 -2
View File
@@ -25,7 +25,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -195,7 +194,10 @@ export const assetRouteLayer = HttpRouter.add(
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: buildAssetResponseHeaders(asset),
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
+1 -36
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
@@ -92,39 +92,4 @@ describe("imageMime", () => {
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
it("infers file extension from an allowlisted file name extension", () => {
expect(
inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }),
).toBe(".pdf");
});
it("infers file extension from the last segment of a multi-dot file name", () => {
expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe(
".csv",
);
});
it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => {
expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf");
});
it("falls back to an allowlisted mime extension when the file name has no extension", () => {
expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt");
});
it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe(
".bin",
);
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe(
".bin",
);
});
it("defaults dotfile names without an allowlisted mime to .bin", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe(
".bin",
);
});
});
-42
View File
@@ -112,48 +112,6 @@ export function parseBase64DataUrl(
return { mimeType, base64 };
}
export const SAFE_FILE_EXTENSIONS = new Set([
".csv",
".diff",
".docx",
".gz",
".json",
".jsonl",
".log",
".md",
".patch",
".pdf",
".pptx",
".tar",
".toml",
".tsv",
".txt",
".xlsx",
".xml",
".yaml",
".yml",
".zip",
]);
export function inferFileExtension(input: { mimeType: string; fileName?: string }): string {
const fileName = input.fileName?.trim() ?? "";
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
if (SAFE_FILE_EXTENSIONS.has(fileNameExtension)) {
return fileNameExtension;
}
// Mime.getExtension returns dot-less extensions ("pdf"), the sets hold
// dotted ones (".pdf").
const fromMimeExtension = Mime.getExtension(input.mimeType);
const dottedMimeExtension = fromMimeExtension ? `.${fromMimeExtension}` : null;
if (dottedMimeExtension && SAFE_FILE_EXTENSIONS.has(dottedMimeExtension)) {
return dottedMimeExtension;
}
return ".bin";
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -928,214 +928,6 @@ it.layer(
);
});
it.layer(
Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")),
)("OrchestrationProjectionPipeline", (it) => {
it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const { attachmentsDir } = yield* ServerConfig;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("Thread Revert.Docs");
const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001";
const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002";
const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003";
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-revert-docs-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-revert-docs"),
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-revert-docs"),
title: "Project Revert Docs",
workspaceRoot: "/tmp/project-revert-docs",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-revert-docs-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-revert-docs"),
title: "Thread Revert Docs",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-3"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-keep"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-keep"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-4"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-keep"),
role: "assistant",
text: "Keep",
attachments: [
{
type: "file",
id: keepAttachmentId,
name: "keep.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-5"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-5"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-remove"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-remove"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-6"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-6"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-remove"),
role: "assistant",
text: "Remove",
attachments: [
{
type: "file",
id: removeAttachmentId,
name: "remove.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`);
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`);
const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`);
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
yield* fileSystem.writeFileString(keepPath, "keep");
yield* fileSystem.writeFileString(removePath, "remove");
yield* fileSystem.writeFileString(orphanPath, "orphan");
assert.isTrue(yield* exists(keepPath));
assert.isTrue(yield* exists(removePath));
assert.isTrue(yield* exists(orphanPath));
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.make("evt-revert-docs-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-7"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-7"),
metadata: {},
payload: {
threadId,
turnCount: 1,
},
});
assert.isTrue(yield* exists(keepPath));
assert.isFalse(yield* exists(removePath));
assert.isFalse(yield* exists(orphanPath));
}),
);
});
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))(
"OrchestrationProjectionPipeline",
(it) => {
@@ -338,6 +338,9 @@ function collectThreadAttachmentRelativePaths(
const relativePaths = new Set<string>();
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
continue;
@@ -466,58 +466,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect(
"sends only image attachments to the provider and appends file attachment prompt text",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const imageAttachment = {
type: "image" as const,
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
};
const fileAttachment = {
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 5,
};
const attachmentsDir = NodePath.join(harness.stateDir, "attachments");
const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`);
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
NodeFS.writeFileSync(fileAttachmentPath, "notes");
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-file-attachments"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-file-attachments"),
role: "user",
text: "hello with attachments",
attachments: [imageAttachment, fileAttachment],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
const request = harness.sendTurn.mock.calls[0]?.[0] as {
readonly input?: string;
readonly attachments?: ReadonlyArray<unknown>;
};
expect(request.attachments).toEqual([imageAttachment]);
expect(request.input).toBe(
`hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`,
);
}),
);
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -25,9 +25,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { appendFileAttachmentPromptText } from "../../attachmentPrompt.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
@@ -198,7 +196,6 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const serverCommandId = (tag: string) =>
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
@@ -608,18 +605,8 @@ const make = Effect.gen(function* () {
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(
appendFileAttachmentPromptText({
text: input.messageText,
attachmentsDir: serverConfig.attachmentsDir,
attachments: input.attachments ?? [],
}),
);
// Only image attachments go to the provider as content blocks; file
// attachments are delivered by path in the prompt text above.
const normalizedAttachments = (input.attachments ?? []).filter(
(attachment) => attachment.type === "image",
);
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
.pipe(
@@ -1,53 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "vite-plus/test";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ClientOrchestrationCommand,
MessageId,
ProjectId,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProviderInstanceId,
ThreadId,
type ClientOrchestrationCommand,
type UploadChatAttachment,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
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 ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }),
WorkspacePaths.layer,
).pipe(Layer.provideMerge(NodeServices.layer));
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
const now = "2026-01-01T00:00:00.000Z";
const turnStartCommand = (
attachments: ReadonlyArray<UploadChatAttachment>,
): ClientOrchestrationCommand => ({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("user-message-1"),
role: "user",
text: "hello normalizer",
attachments,
},
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
createdAt: now,
});
const asDataUrl = (mimeType: string, bytes: Buffer) =>
`data:${mimeType};base64,${bytes.toString("base64")}`;
describe("canonicalizeClientCommandTimestamps", () => {
it("replaces a client command timestamp with the server receipt timestamp", () => {
@@ -107,86 +71,3 @@ describe("canonicalizeClientCommandTimestamps", () => {
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
});
});
describe("Normalizer", () => {
it.effect("persists file attachments and writes their bytes to the attachments dir", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("hello world");
const normalized = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
);
expect(normalized.type).toBe("thread.turn.start");
if (normalized.type !== "thread.turn.start") {
return;
}
const attachment = normalized.message.attachments[0];
expect(attachment).toMatchObject({
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
});
expect(attachment?.id).toMatch(
/^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
if (!attachment) {
return;
}
const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`);
expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects image attachments with a non-image data URL mime type", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "image",
name: "fake.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: asDataUrl("text/plain", Buffer.from("hello")),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Invalid image attachment payload for 'fake.png'.");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects file attachments over the maximum attachment size", () =>
Effect.gen(function* () {
const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a");
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "big.txt",
mimeType: "text/plain",
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Attachment 'big.txt' is empty or too large.");
}).pipe(Effect.provide(testLayer)),
);
});
+4 -4
View File
@@ -109,16 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' is empty or too large.`,
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
@@ -130,7 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
}
const persistedAttachment = {
type: attachment.type,
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3045,7 +3172,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3270,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -2590,6 +2585,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2702,6 +2708,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -2746,6 +2757,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +2822,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +2944,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+2 -81
View File
@@ -6,9 +6,9 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import type { ChatMessage, Thread } from "../types";
import type { Thread } from "../types";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -20,10 +20,6 @@ import {
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
collectUserMessageBlobPreviewUrls,
normalizeDataUrlMimeType,
resolveComposerAttachmentMimeType,
revokeUserMessagePreviewUrls,
resolveSendEnvMode,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -81,81 +77,6 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};
function makeAttachmentMessage(): ChatMessage {
return {
id: MessageId.make("message-with-attachments"),
role: "user",
text: "Inspect these files",
turnId: null,
createdAt: now,
updatedAt: now,
streaming: false,
attachments: [
{
type: "image",
id: "image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 10,
previewUrl: "blob:image-preview",
},
{
type: "file",
id: "file-1",
name: "debug.log",
mimeType: "text/plain",
sizeBytes: 20,
previewUrl: "blob:file-preview",
},
],
};
}
describe("attachment preview lifecycle", () => {
it("collects and revokes blob previews for images and files", () => {
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
const message = makeAttachmentMessage();
expect(collectUserMessageBlobPreviewUrls(message)).toEqual([
"blob:image-preview",
"blob:file-preview",
]);
revokeUserMessagePreviewUrls(message);
expect(revokeObjectURL).toHaveBeenCalledTimes(2);
expect(revokeObjectURL).toHaveBeenNthCalledWith(1, "blob:image-preview");
expect(revokeObjectURL).toHaveBeenNthCalledWith(2, "blob:file-preview");
revokeObjectURL.mockRestore();
});
});
describe("composer attachment MIME types", () => {
it("recovers image MIME types from names when the browser reports a generic type", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.PNG", type: "" })).toBe("image/png");
expect(
resolveComposerAttachmentMimeType({
name: "capture.webp",
type: "application/octet-stream",
}),
).toBe("image/webp");
});
it("preserves a specific browser MIME type and keeps unknown files generic", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.png", type: "text/plain" })).toBe(
"text/plain",
);
expect(resolveComposerAttachmentMimeType({ name: "payload.bin", type: "" })).toBe(
"application/octet-stream",
);
});
it("rewrites a FileReader data URL with the resolved attachment MIME type", () => {
expect(
normalizeDataUrlMimeType("data:application/octet-stream;base64,iVBORw0KGgo=", "image/png"),
).toBe("data:image/png;base64,iVBORw0KGgo=");
});
});
describe("buildThreadTurnInterruptInput", () => {
it("targets the session's active running turn", () => {
const activeTurnId = TurnId.make("turn-running");
+12 -55
View File
@@ -10,7 +10,7 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
@@ -144,6 +144,9 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
@@ -154,78 +157,30 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
const FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
".avif": "image/avif",
".bmp": "image/bmp",
".gif": "image/gif",
".heic": "image/heic",
".heif": "image/heif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".tif": "image/tiff",
".tiff": "image/tiff",
".webp": "image/webp",
};
const GENERIC_BINARY_MIME_TYPES = new Set([
"",
"application/octet-stream",
"application/unknown",
"application/x-unknown",
"binary/octet-stream",
]);
export function resolveComposerAttachmentMimeType(file: {
readonly name: string;
readonly type: string;
}): string {
const declaredMimeType = file.type.trim().toLowerCase();
if (!GENERIC_BINARY_MIME_TYPES.has(declaredMimeType)) {
return declaredMimeType;
}
const normalizedName = file.name.trim().toLowerCase();
const extensionIndex = normalizedName.lastIndexOf(".");
const extension = extensionIndex >= 0 ? normalizedName.slice(extensionIndex) : "";
return (
FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION[extension] ||
declaredMimeType ||
"application/octet-stream"
);
}
export function normalizeDataUrlMimeType(dataUrl: string, mimeType: string): string {
const separatorIndex = dataUrl.indexOf(",");
if (!dataUrl.startsWith("data:") || separatorIndex < 0) {
return dataUrl;
}
return `data:${mimeType};base64,${dataUrl.slice(separatorIndex + 1)}`;
}
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
export function readFileAsDataUrl(file: File, mimeType?: string): Promise<string> {
export function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(mimeType ? normalizeDataUrlMimeType(reader.result, mimeType) : reader.result);
resolve(reader.result);
return;
}
reject(new Error("Could not read attachment data."));
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read attachment."));
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
@@ -238,7 +193,9 @@ export function resolveSendEnvMode(input: {
return input.isGitRepo ? input.requestedEnvMode : "local";
}
export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment {
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
+9 -9
View File
@@ -162,7 +162,7 @@ import {
} from "../logicalProject";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerAttachment,
type ComposerImageAttachment,
type DraftThreadEnvMode,
useComposerDraftStore,
type DraftId,
@@ -261,8 +261,8 @@ import {
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -1190,7 +1190,7 @@ function ChatViewContent(props: ChatViewProps) {
: null,
);
const promptRef = useRef("");
const composerImagesRef = useRef<ComposerAttachment[]>([]);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
@@ -4179,19 +4179,19 @@ function ChatViewContent(props: ChatViewProps) {
model: ctxSelectedModel,
models: ctxSelectedProviderModels,
effort: ctxSelectedPromptEffort,
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
});
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => ({
type: image.type,
type: "image" as const,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file, image.mimeType),
dataUrl: await readFileAsDataUrl(image.file),
})),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: image.type,
type: "image" as const,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -4253,7 +4253,7 @@ function ChatViewContent(props: ChatViewProps) {
let titleSeed = trimmed;
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
titleSeed = `Image: ${firstComposerImageName}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
+32 -61
View File
@@ -43,17 +43,13 @@ import {
replaceTextRange,
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import {
deriveComposerSendState,
readFileAsDataUrl,
resolveComposerAttachmentMimeType,
} from "../ChatView.logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerAttachment,
type ComposerImageAttachment,
type DraftId,
type PersistedComposerImageAttachment,
useComposerDraftStore,
@@ -105,7 +101,6 @@ import {
BotIcon,
CheckIcon,
CircleAlertIcon,
FileTextIcon,
ListTodoIcon,
PencilRulerIcon,
type LucideIcon,
@@ -135,7 +130,6 @@ import {
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { formatAttachmentSizeLabel } from "../../lib/attachmentSize";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -431,7 +425,7 @@ export interface ChatComposerHandle {
/** Get the current prompt/effort/model state for use in send. */
getSendContext: () => {
prompt: string;
images: ComposerAttachment[];
images: ComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
@@ -522,7 +516,7 @@ export interface ChatComposerProps {
// Refs the parent needs kept in sync
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerAttachment[]>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
@@ -1165,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1181,14 +1176,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const addComposerImage = useCallback(
(image: ComposerAttachment) => {
(image: ComposerImageAttachment) => {
addComposerDraftImage(composerDraftTarget, image);
},
[composerDraftTarget, addComposerDraftImage],
);
const addComposerImagesToDraft = useCallback(
(images: ComposerAttachment[]) => {
(images: ComposerImageAttachment[]) => {
addComposerDraftImages(composerDraftTarget, images);
},
[composerDraftTarget, addComposerDraftImages],
@@ -1396,9 +1391,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
await Promise.all(
composerImages.map(async (image) => {
try {
const dataUrl = await readFileAsDataUrl(image.file, image.mimeType);
const dataUrl = await readFileAsDataUrl(image.file);
stagedAttachmentById.set(image.id, {
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -1704,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1713,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1799,30 +1796,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (pendingUserInputs.length > 0) {
toastManager.add({
type: "error",
title: "Attach files after answering plan questions.",
title: "Attach images after answering plan questions.",
});
return;
}
const nextImages: ComposerAttachment[] = [];
const nextImages: ComposerImageAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
continue;
}
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
}
const mimeType = resolveComposerAttachmentMimeType(file);
const isImage = mimeType.startsWith("image/");
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: isImage ? "image" : "file",
type: "image",
id: randomUUID(),
name: file.name || (isImage ? "image" : "file"),
mimeType,
name: file.name || "image",
mimeType: file.type,
sizeBytes: file.size,
previewUrl,
file,
@@ -1847,8 +1846,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) return;
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
if (imageFiles.length === 0) return;
event.preventDefault();
addComposerImages(files);
addComposerImages(imageFiles);
};
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
@@ -1895,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2104,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2147,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2355,10 +2353,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
imageId,
);
const preview = buildExpandedImagePreview(composerImages, imageId);
if (preview) onExpandImage(preview);
}}
className="mb-3"
@@ -2409,34 +2404,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
.map((image) => (
<div
key={image.id}
className={
image.type === "file"
? "relative flex h-16 w-40 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background px-2"
: "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.type === "file" ? (
<>
<FileTextIcon className="size-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 pr-5">
<div className="truncate text-xs" title={image.name}>
{image.name}
</div>
<div className="text-[10px] text-muted-foreground/70">
{formatAttachmentSizeLabel(image.sizeBytes)}
</div>
</div>
</>
) : image.previewUrl ? (
{image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
image.id,
);
const preview = buildExpandedImagePreview(composerImages, image.id);
if (!preview) return;
onExpandImage(preview);
}}
@@ -2527,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
@@ -2,13 +2,13 @@ import type { PreviewAnnotationPayload } from "@t3tools/contracts";
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
import type { ReactNode } from "react";
import type { ComposerAttachment } from "~/composerDraftStore";
import type { ComposerImageAttachment } from "~/composerDraftStore";
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
import { cn } from "~/lib/utils";
interface ComposerPreviewAnnotationCardsProps {
annotations: ReadonlyArray<PreviewAnnotationPayload>;
images: ReadonlyArray<ComposerAttachment>;
images: ReadonlyArray<ComposerImageAttachment>;
onRemove: (annotationId: string) => void;
onExpandImage: (imageId: string) => void;
className?: string;
@@ -381,88 +381,6 @@ describe("MessagesTimeline", () => {
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders file attachments as chips with name and size instead of images", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Please review the attached report."),
message: {
...buildUserTimelineEntry("Please review the attached report.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain("report.pdf");
expect(markup).toContain("2.0 KB");
expect(markup).toContain("lucide-file-text");
expect(markup).not.toContain("<img");
});
it("renders downloadable file attachment chips when a preview URL is available", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Here is the file."),
message: {
...buildUserTimelineEntry("Here is the file.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-2",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 512,
previewUrl: "data:text/plain;base64,aGVsbG8=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('download="notes.txt"');
expect(markup).toContain('href="data:text/plain;base64,aGVsbG8="');
expect(markup).toContain("512 B");
});
it("renders image attachments in the image grid without file chips", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Take a look."),
message: {
...buildUserTimelineEntry("Take a look.").message,
attachments: [
{
type: "image" as const,
id: "attachment-image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1,
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('src="data:image/png;base64,iVBORw0KGgo="');
expect(markup).toContain('alt="screenshot.png"');
expect(markup).not.toContain("lucide-file-text");
expect(markup).not.toContain("download=");
});
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -49,7 +49,6 @@ import {
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
FileTextIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -65,7 +64,6 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { formatAttachmentSizeLabel } from "~/lib/attachmentSize";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
@@ -883,10 +881,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
...elementContextState.contexts,
];
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter(
(image) => image.type === "image" && !image.name.startsWith("preview-annotation-"),
);
const fileAttachments = userImages.filter((attachment) => attachment.type === "file");
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
@@ -925,38 +920,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
{fileAttachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1.5">
{fileAttachments.map((attachment) => {
const chipContent = (
<>
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="max-w-48 truncate">{attachment.name}</span>
<span className="text-muted-foreground/70">
{formatAttachmentSizeLabel(attachment.sizeBytes)}
</span>
</>
);
const chipClassName =
"inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-background/70 px-2 py-1 text-[11px]";
return attachment.previewUrl ? (
<a
key={attachment.id}
href={attachment.previewUrl}
download={attachment.name}
className={`${chipClassName} hover:bg-background`}
aria-label={`Download ${attachment.name}`}
>
{chipContent}
</a>
) : (
<span key={attachment.id} className={chipClassName}>
{chipContent}
</span>
);
})}
</div>
)}
{previewAnnotations.map((annotation, index) => (
<UserMessagePreviewAnnotationCard
key={annotation.id}
-145
View File
@@ -65,7 +65,6 @@ import {
markPromotedDraftThreadByRef,
markPromotedDraftThreads,
markPromotedDraftThreadsByRef,
type ComposerFileAttachment,
type ComposerImageAttachment,
useComposerDraftStore,
DraftId,
@@ -105,33 +104,6 @@ function makeImage(input: {
};
}
function makeFile(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerFileAttachment {
const name = input.name ?? "report.pdf";
const mimeType = input.mimeType ?? "application/pdf";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "file",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
function makeTerminalContext(input: {
id: string;
text?: string;
@@ -373,123 +345,6 @@ describe("composerDraftStore syncPersistedAttachments", () => {
});
});
describe("composerDraftStore file attachments", () => {
const threadId = ThreadId.make("thread-file-attachments");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
beforeEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
resetComposerDraftStore();
});
afterEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
});
function mergePersistedDraft(attachment: Record<string, unknown>) {
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
) => ReturnType<typeof useComposerDraftStore.getState>;
};
};
return persistApi.getOptions().merge(
{
draftsByThreadId: {
[threadId]: {
prompt: "",
attachments: [attachment],
},
},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectKey: {},
},
useComposerDraftStore.getInitialState(),
);
}
it("hydrates persisted attachments without a type as images (legacy drafts)", () => {
const mergedState = mergePersistedDraft({
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: "data:image/png;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "image",
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
previewUrl: "data:image/png;base64,aGVsbG8=",
},
]);
});
it("hydrates persisted attachments with type file as file attachments", () => {
const mergedState = mergePersistedDraft({
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
dataUrl: "data:application/pdf;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
previewUrl: "data:application/pdf;base64,aGVsbG8=",
},
]);
});
it("persists the file type for staged file attachments (round trip)", () => {
const attachment = makeFile({
id: "file-round-trip",
previewUrl: "data:application/pdf;base64,aGVsbG8=",
});
useComposerDraftStore.getState().addImage(threadRef, attachment);
useComposerDraftStore.getState().syncPersistedAttachments(threadRef, [
{
type: "file",
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: attachment.previewUrl,
},
]);
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
};
};
const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey?: Record<string, { attachments?: Array<Record<string, unknown>> }>;
};
expect(
persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.attachments?.[0],
).toMatchObject({
type: "file",
id: "file-round-trip",
name: "report.pdf",
mimeType: "application/pdf",
});
});
});
describe("composerDraftStore terminal contexts", () => {
const threadId = ThreadId.make("thread-dedupe");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
+10 -26
View File
@@ -33,12 +33,7 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
import { useMemo } from "react";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatFileAttachment,
type ChatImageAttachment,
} from "./types";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
@@ -84,8 +79,6 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
}
export const PersistedComposerImageAttachment = Schema.Struct({
// Missing on drafts persisted before file attachments existed → "image".
type: Schema.optionalKey(Schema.Literals(["image", "file"])),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
@@ -99,13 +92,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment;
const PersistedTerminalContextDraft = Schema.Struct({
id: Schema.String,
threadId: ThreadId,
@@ -263,7 +249,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
*/
export interface ComposerThreadDraftState {
prompt: string;
images: ComposerAttachment[];
images: ComposerImageAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
@@ -448,8 +434,8 @@ interface ComposerDraftStoreState {
threadRef: ComposerThreadTarget,
interactionMode: ProviderInteractionMode | null | undefined,
) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerAttachment[]) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
insertTerminalContext: (
threadRef: ComposerThreadTarget,
@@ -565,7 +551,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
stickyActiveProvider: null,
});
const EMPTY_IMAGES: ComposerAttachment[] = [];
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
@@ -623,7 +609,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
};
}
function composerImageDedupKey(image: ComposerAttachment): string {
function composerImageDedupKey(image: ComposerImageAttachment): string {
// Keep this independent from File.lastModified so dedupe is stable for hydrated
// images reconstructed from localStorage (which get a fresh lastModified value).
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
@@ -1073,9 +1059,7 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
) {
return null;
}
const type = candidate.type;
return {
...(type === "image" || type === "file" ? { type } : {}),
id,
name,
mimeType,
@@ -2100,21 +2084,21 @@ function hydratePersistedComposerImageAttachment(
function hydrateImagesFromPersisted(
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
): ComposerAttachment[] {
): ComposerImageAttachment[] {
return attachments.flatMap((attachment) => {
const file = hydratePersistedComposerImageAttachment(attachment);
if (!file) return [];
return [
{
type: attachment.type ?? ("image" as const),
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: attachment.dataUrl,
file,
} satisfies ComposerAttachment,
} satisfies ComposerImageAttachment,
];
});
}
@@ -2872,7 +2856,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
existing.images.map((image) => composerImageDedupKey(image)),
);
const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
const dedupedIncoming: ComposerAttachment[] = [];
const dedupedIncoming: ComposerImageAttachment[] = [];
for (const image of images) {
const dedupKey = composerImageDedupKey(image);
if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
-37
View File
@@ -136,41 +136,4 @@ describe("buildBootstrapInput", () => {
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
it("captures mixed image and file attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-mixed"),
role: "user",
text: "Compare the screenshot with the report.",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
{
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
turnId: null,
updatedAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What differs?",
1_500,
);
expect(result.text).toContain("[Attached image: screenshot.png]");
expect(result.text).toContain("[Attached file: report.pdf]");
});
});
+5 -17
View File
@@ -18,30 +18,18 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummaryOfType(
message: ChatMessage,
type: "image" | "file",
label: string,
): string | null {
const typedAttachments = message.attachments?.filter((attachment) => attachment.type === type);
const count = typedAttachments?.length ?? 0;
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = typedAttachments?.slice(0, 3).map((attachment) => attachment.name) ?? [];
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached ${label}${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function attachmentSummary(message: ChatMessage): string | null {
const summaries = [
attachmentSummaryOfType(message, "image", "image"),
attachmentSummaryOfType(message, "file", "file"),
].filter((summary) => summary !== null);
return summaries.length > 0 ? summaries.join("\n") : null;
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function buildMessageBlock(message: ChatMessage): string {
-22
View File
@@ -1,22 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { formatAttachmentSizeLabel } from "./attachmentSize";
describe("formatAttachmentSizeLabel", () => {
it("formats sub-kilobyte sizes in bytes", () => {
expect(formatAttachmentSizeLabel(0)).toBe("0 B");
expect(formatAttachmentSizeLabel(512)).toBe("512 B");
expect(formatAttachmentSizeLabel(1_023)).toBe("1023 B");
});
it("formats kilobyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024)).toBe("1.0 KB");
expect(formatAttachmentSizeLabel(2_048)).toBe("2.0 KB");
expect(formatAttachmentSizeLabel(1_024 * 1_024 - 1)).toBe("1024.0 KB");
});
it("formats megabyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024 * 1_024)).toBe("1.0 MB");
expect(formatAttachmentSizeLabel(2_202_010)).toBe("2.1 MB");
});
});
-9
View File
@@ -1,9 +0,0 @@
export function formatAttachmentSizeLabel(sizeBytes: number): string {
if (sizeBytes >= 1024 * 1024) {
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
}
if (sizeBytes >= 1024) {
return `${(sizeBytes / 1024).toFixed(1)} KB`;
}
return `${sizeBytes} B`;
}
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
+1 -6
View File
@@ -1,5 +1,4 @@
import type {
ChatFileAttachment as ContractChatFileAttachment,
ChatImageAttachment as ContractChatImageAttachment,
OrchestrationCheckpointFile,
OrchestrationCheckpointSummary,
@@ -36,11 +35,7 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
readonly previewUrl?: string;
}
export interface ChatFileAttachment extends ContractChatFileAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment;
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
@@ -3,9 +3,6 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
ChatAttachment,
ChatFileAttachment,
ChatImageAttachment,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
ModelSelection,
@@ -746,80 +743,3 @@ it.effect("ModelSelection rejects malformed instance ids", () =>
assert.strictEqual(result._tag, "Failure");
}),
);
// ── ChatAttachment: image/file union ──────────────────────────────────
const decodeChatAttachment = Schema.decodeUnknownEffect(ChatAttachment);
const decodeChatAttachmentArray = Schema.decodeUnknownEffect(Schema.Array(ChatAttachment));
const decodeChatImageAttachment = Schema.decodeUnknownEffect(ChatImageAttachment);
const decodeChatFileAttachment = Schema.decodeUnknownEffect(ChatFileAttachment);
it.effect("ChatAttachment decodes a file attachment with a non-image mime type", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachment({
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
});
assert.strictEqual(parsed.type, "file");
assert.strictEqual(parsed.name, "report.pdf");
assert.strictEqual(parsed.mimeType, "application/pdf");
assert.strictEqual(parsed.sizeBytes, 2_048);
}),
);
it.effect("ChatAttachment arrays still decode legacy image-only attachments", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachmentArray([
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1_024,
},
{
type: "image",
id: "img-2",
name: "diagram.jpeg",
mimeType: "image/jpeg",
sizeBytes: 4_096,
},
]);
assert.strictEqual(parsed.length, 2);
assert.strictEqual(parsed[0]?.type, "image");
assert.strictEqual(parsed[1]?.type, "image");
}),
);
it.effect("ChatImageAttachment rejects non-image mime types", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatImageAttachment({
type: "image",
id: "img-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
it.effect("ChatFileAttachment rejects sizeBytes over the 10MB limit", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatFileAttachment({
type: "file",
id: "file-1",
name: "big.bin",
mimeType: "application/octet-stream",
sizeBytes: 10 * 1024 * 1024 + 1,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+2 -22
View File
@@ -173,29 +173,9 @@ const UploadChatImageAttachment = Schema.Struct({
});
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
export const ChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
id: ChatAttachmentId,
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
});
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
const UploadChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
dataUrl: TrimmedNonEmptyString.check(
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
),
});
export type UploadChatFileAttachment = typeof UploadChatFileAttachment.Type;
export const ChatAttachment = Schema.Union([ChatImageAttachment, ChatFileAttachment]);
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
export type ChatAttachment = typeof ChatAttachment.Type;
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment, UploadChatFileAttachment]);
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
export const ProjectScriptIcon = Schema.Literals([
+1
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(