Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92724f1509 | ||
|
|
0d0f592a54 | ||
|
|
c44c38f096 | ||
|
|
8d45b184d7 | ||
|
|
cb9719f1dc | ||
|
|
0a1bec5a98 | ||
|
|
c607b73d94 | ||
|
|
a8b175132a | ||
|
|
7bbf4b0e53 | ||
|
|
f325d1aa64 | ||
|
|
79b59d5e94 | ||
|
|
f9b4ceb463 | ||
|
|
8c12290a17 | ||
|
|
a54fe4e34d | ||
|
|
f2d2f960a6 | ||
|
|
79a4f3409d | ||
|
|
50013a2591 | ||
|
|
462742eb49 | ||
|
|
128a6134cd | ||
|
|
948eb8a1ca | ||
|
|
1af86c90ad | ||
|
|
106c208553 | ||
|
|
1c84a54a80 | ||
|
|
5f178fc567 | ||
|
|
a9068978e9 | ||
|
|
6f9cd78787 | ||
|
|
3dc38031f1 | ||
|
|
564f916cdb | ||
|
|
a1237d983a | ||
|
|
fc43823227 | ||
|
|
ce23e3bbe4 | ||
|
|
fa3ea832c6 |
No files matched your search
@@ -0,0 +1,14 @@
|
||||
# Copy this file to .env.release for local releases. Never commit .env.release.
|
||||
GITEA_TOKEN=<gitea-release-token>
|
||||
GITEA_API_URL=https://git.molberg.cloud/api/v1/repos/alex/t3code
|
||||
T3CODE_APK_REPOSITORY_URL=https://git.molberg.cloud/alex/t3code
|
||||
ANDROID_HOME=/opt/android-sdk
|
||||
ANDROID_NDK_HOME=/opt/android-sdk/ndk/27.1.12297006
|
||||
ANDROID_BUILD_TOOLS_VERSION=36.0.0
|
||||
APK_KEYSTORE_BASE64=<base64-encoded-release-keystore>
|
||||
APK_KEYSTORE_PASSWORD=<keystore-password>
|
||||
APK_KEY_ALIAS=<key-alias>
|
||||
APK_KEY_PASSWORD=<key-password>
|
||||
# Optional overrides:
|
||||
# APK_VERSION_CODE=45
|
||||
# APK_RELEASE_BODY={"schema":1,"channel":"production"}
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Fork Android APK
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- apk-*
|
||||
|
||||
concurrency:
|
||||
group: android-apk-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: android-apk
|
||||
env:
|
||||
T3CODE_APK_RELEASE_TAG: ${{ gitea.ref_name }}
|
||||
T3CODE_APK_REPOSITORY_URL: ${{ gitea.server_url }}/${{ gitea.repository }}
|
||||
T3CODE_APK_RELEASES_URL: ${{ vars.APK_RELEASES_URL }}
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Build and sign APK
|
||||
env:
|
||||
APK_KEYSTORE_BASE64: ${{ secrets.APK_KEYSTORE_BASE64 }}
|
||||
APK_KEYSTORE_PASSWORD: ${{ secrets.APK_KEYSTORE_PASSWORD }}
|
||||
APK_KEY_ALIAS: ${{ secrets.APK_KEY_ALIAS }}
|
||||
APK_KEY_PASSWORD: ${{ secrets.APK_KEY_PASSWORD }}
|
||||
run: bash scripts/build-fork-apk.sh
|
||||
- name: Publish repository release
|
||||
env:
|
||||
APK_RELEASE_TOKEN: ${{ secrets.APK_RELEASE_TOKEN }}
|
||||
APK_RELEASE_COMMIT: ${{ gitea.sha }}
|
||||
run: node scripts/publish-fork-apk.ts
|
||||
@@ -40,6 +40,7 @@ node_modules/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
!.env.release.example
|
||||
|
||||
# pnpm content-addressable store; never belongs in the repo.
|
||||
.pnpm-store/
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.40",
|
||||
"version": "0.0.41-hermes.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { ExpoConfig } from "expo/config";
|
||||
|
||||
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
|
||||
import {
|
||||
DEFAULT_ANDROID_APK_REPOSITORY_URL,
|
||||
parseAndroidApkReleaseTag,
|
||||
resolveAndroidApkRepository,
|
||||
} from "../../scripts/lib/android-apk-release.ts";
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
|
||||
|
||||
type AppVariant = "development" | "preview" | "production";
|
||||
@@ -9,6 +14,11 @@ const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
|
||||
const apkReleaseTag = repoEnv.T3CODE_APK_RELEASE_TAG;
|
||||
const apkVersionCode = apkReleaseTag ? parseAndroidApkReleaseTag(apkReleaseTag) : undefined;
|
||||
const apkRepository = resolveAndroidApkRepository(
|
||||
repoEnv.T3CODE_APK_REPOSITORY_URL || DEFAULT_ANDROID_APK_REPOSITORY_URL,
|
||||
);
|
||||
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
||||
const runtimeVersionPolicy =
|
||||
process.env.MOBILE_VERSION_POLICY ??
|
||||
@@ -225,7 +235,10 @@ const config: ExpoConfig = {
|
||||
icon: variant.assets.appIcon,
|
||||
userInterfaceStyle: "automatic",
|
||||
updates: {
|
||||
enabled: repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0",
|
||||
enabled:
|
||||
apkRepository === undefined &&
|
||||
apkVersionCode === undefined &&
|
||||
repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0",
|
||||
url: "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454",
|
||||
checkAutomatically: "ON_LOAD",
|
||||
fallbackToCacheTimeout: 0,
|
||||
@@ -274,8 +287,10 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
android: {
|
||||
...(apkVersionCode === undefined ? {} : { versionCode: apkVersionCode }),
|
||||
icon: variant.assets.appIcon,
|
||||
package: variant.androidPackage,
|
||||
...(apkRepository ? { permissions: ["android.permission.REQUEST_INSTALL_PACKAGES"] } : {}),
|
||||
...(repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE
|
||||
? { googleServicesFile: repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE }
|
||||
: {}),
|
||||
@@ -429,6 +444,7 @@ const config: ExpoConfig = {
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
apkReleaseApiUrl: apkRepository.apiUrl,
|
||||
appVariant: APP_VARIANT,
|
||||
iosPersonalTeamBuild: isIosPersonalTeamBuild,
|
||||
relay: {
|
||||
|
||||
@@ -16,4 +16,5 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
}
|
||||
+178
-4
@@ -1,15 +1,78 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.PackageInfo
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.content.FileProvider
|
||||
import expo.modules.kotlin.Promise
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import java.io.File
|
||||
import java.net.URI
|
||||
import java.security.MessageDigest
|
||||
|
||||
private const val FILE_PREVIEW_REQUEST_CODE = 7343
|
||||
private const val APK_INSTALL_REQUEST_CODE = 7344
|
||||
private const val MAX_ANDROID_VERSION_CODE = 2_100_000_000L
|
||||
private const val APK_MIME_TYPE = "application/vnd.android.package-archive"
|
||||
|
||||
internal data class ApkIdentity(
|
||||
val packageName: String,
|
||||
val versionCode: Long,
|
||||
val signerDigests: Set<String>
|
||||
)
|
||||
|
||||
internal data class InstallerCandidate(
|
||||
val packageName: String,
|
||||
val className: String,
|
||||
val applicationFlags: Int
|
||||
) {
|
||||
val componentKey = "$packageName/$className"
|
||||
}
|
||||
|
||||
internal fun validateApkIdentity(
|
||||
installed: ApkIdentity,
|
||||
archive: ApkIdentity,
|
||||
expectedVersionCode: Long
|
||||
) {
|
||||
require(expectedVersionCode in 1..MAX_ANDROID_VERSION_CODE) {
|
||||
"The expected APK version is invalid."
|
||||
}
|
||||
require(archive.packageName == installed.packageName) {
|
||||
"The downloaded APK belongs to a different app."
|
||||
}
|
||||
require(archive.versionCode == expectedVersionCode) {
|
||||
"The downloaded APK version does not match the selected update."
|
||||
}
|
||||
require(archive.versionCode > installed.versionCode) {
|
||||
"The downloaded APK is not newer than the installed app."
|
||||
}
|
||||
require(archive.signerDigests.isNotEmpty() && archive.signerDigests == installed.signerDigests) {
|
||||
"The downloaded APK signing certificate does not match the installed app."
|
||||
}
|
||||
}
|
||||
|
||||
internal fun selectTrustedInstaller(
|
||||
candidates: List<InstallerCandidate>,
|
||||
resolvedComponentKey: String?
|
||||
): InstallerCandidate? {
|
||||
val trusted = candidates
|
||||
.filter { candidate ->
|
||||
candidate.packageName.isNotBlank() &&
|
||||
candidate.className.isNotBlank() &&
|
||||
candidate.applicationFlags and
|
||||
(ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
|
||||
}
|
||||
.sortedBy(InstallerCandidate::componentKey)
|
||||
return trusted.firstOrNull { it.componentKey == resolvedComponentKey } ?: trusted.firstOrNull()
|
||||
}
|
||||
|
||||
class T3NativeControlsModule : Module() {
|
||||
private var filePreviewPromise: Promise? = null
|
||||
private var apkInstallPromise: Promise? = null
|
||||
|
||||
@Suppress("TooGenericExceptionCaught") // Clear the pending promise before rethrowing.
|
||||
override fun definition() = ModuleDefinition {
|
||||
@@ -31,17 +94,37 @@ class T3NativeControlsModule : Module() {
|
||||
}
|
||||
filePreviewPromise = promise
|
||||
try {
|
||||
activity.startActivityForResult(intent, 7343)
|
||||
activity.startActivityForResult(intent, FILE_PREVIEW_REQUEST_CODE)
|
||||
} catch (error: Exception) {
|
||||
filePreviewPromise = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
AsyncFunction("installApk") { uri: String, expectedVersionCode: Long, promise: Promise ->
|
||||
launchVerifiedApkInstaller(uri, expectedVersionCode, promise)
|
||||
}
|
||||
|
||||
Function("getInstalledVersionCode") {
|
||||
val context = appContext.reactContext ?: error("The app is not active.")
|
||||
val installedInfo = getInstalledPackageInfo(
|
||||
context.packageManager,
|
||||
context.packageName,
|
||||
0
|
||||
)
|
||||
packageVersionCode(installedInfo)
|
||||
}
|
||||
|
||||
OnActivityResult { _, (requestCode) ->
|
||||
if (requestCode == 7343) {
|
||||
filePreviewPromise?.resolve(null)
|
||||
filePreviewPromise = null
|
||||
when (requestCode) {
|
||||
FILE_PREVIEW_REQUEST_CODE -> {
|
||||
filePreviewPromise?.resolve(null)
|
||||
filePreviewPromise = null
|
||||
}
|
||||
APK_INSTALL_REQUEST_CODE -> {
|
||||
apkInstallPromise?.resolve(null)
|
||||
apkInstallPromise = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,4 +160,95 @@ class T3NativeControlsModule : Module() {
|
||||
?.writeText(scene)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION", "TooGenericExceptionCaught")
|
||||
private fun launchVerifiedApkInstaller(uri: String, expectedVersionCode: Long, promise: Promise) {
|
||||
check(apkInstallPromise == null) { "An APK installation is already open." }
|
||||
val activity = appContext.currentActivity ?: error("The app is not active.")
|
||||
val file = File(URI(uri)).canonicalFile
|
||||
require(file.isFile) { "The downloaded APK is no longer available." }
|
||||
val packageManager = activity.packageManager
|
||||
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
PackageManager.GET_SIGNING_CERTIFICATES
|
||||
} else {
|
||||
PackageManager.GET_SIGNATURES
|
||||
}
|
||||
val installedInfo = getInstalledPackageInfo(packageManager, activity.packageName, flags)
|
||||
val archiveInfo = packageManager.getPackageArchiveInfo(file.path, flags)
|
||||
?: error("Android could not parse the downloaded APK.")
|
||||
validateApkIdentity(
|
||||
packageIdentity(installedInfo),
|
||||
packageIdentity(archiveInfo),
|
||||
expectedVersionCode
|
||||
)
|
||||
|
||||
val contentUri = FileProvider.getUriForFile(
|
||||
activity,
|
||||
"${activity.packageName}.FileSystemFileProvider",
|
||||
file
|
||||
)
|
||||
val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE).apply {
|
||||
setDataAndType(contentUri, APK_MIME_TYPE)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
putExtra(Intent.EXTRA_RETURN_RESULT, true)
|
||||
}
|
||||
val resolvedComponentKey = packageManager
|
||||
.resolveActivity(installIntent, PackageManager.MATCH_DEFAULT_ONLY)
|
||||
?.activityInfo
|
||||
?.let { "${it.packageName}/${it.name}" }
|
||||
val candidates = packageManager
|
||||
.queryIntentActivities(installIntent, PackageManager.MATCH_DEFAULT_ONLY)
|
||||
.mapNotNull { resolved ->
|
||||
val info = resolved.activityInfo ?: return@mapNotNull null
|
||||
InstallerCandidate(info.packageName, info.name, info.applicationInfo.flags)
|
||||
}
|
||||
val installer = selectTrustedInstaller(candidates, resolvedComponentKey)
|
||||
?: error("No trusted Android package installer is available.")
|
||||
installIntent.component = ComponentName(installer.packageName, installer.className)
|
||||
activity.grantUriPermission(
|
||||
installer.packageName,
|
||||
contentUri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
)
|
||||
|
||||
apkInstallPromise = promise
|
||||
try {
|
||||
activity.startActivityForResult(installIntent, APK_INSTALL_REQUEST_CODE)
|
||||
} catch (error: Exception) {
|
||||
apkInstallPromise = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun getInstalledPackageInfo(
|
||||
packageManager: PackageManager,
|
||||
packageName: String,
|
||||
flags: Int
|
||||
): PackageInfo = packageManager.getPackageInfo(packageName, flags)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun packageIdentity(info: PackageInfo): ApkIdentity {
|
||||
val signatures = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
info.signingInfo?.apkContentsSigners?.toList().orEmpty()
|
||||
} else {
|
||||
info.signatures?.toList().orEmpty()
|
||||
}
|
||||
val digests = signatures.mapTo(mutableSetOf()) { signature ->
|
||||
MessageDigest
|
||||
.getInstance("SHA-256")
|
||||
.digest(signature.toByteArray())
|
||||
.joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
|
||||
}
|
||||
require(digests.isNotEmpty()) { "Android could not read the APK signing certificate." }
|
||||
return ApkIdentity(info.packageName, packageVersionCode(info), digests)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun packageVersionCode(info: PackageInfo): Long =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
info.longVersionCode
|
||||
} else {
|
||||
info.versionCode.toLong()
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.pm.ApplicationInfo
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class ApkInstallerSecurityTest {
|
||||
private val installed = ApkIdentity("com.t3tools.t3code", 50, setOf("signer-a"))
|
||||
|
||||
@Test
|
||||
fun acceptsOnlyTheExpectedNewerVersionOfTheSameSignedPackage() {
|
||||
validateApkIdentity(
|
||||
installed,
|
||||
ApkIdentity("com.t3tools.t3code", 51, setOf("signer-a")),
|
||||
51
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsPackageVersionAndSignerMismatches() {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
validateApkIdentity(installed, ApkIdentity("example.other", 51, setOf("signer-a")), 51)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
validateApkIdentity(
|
||||
installed,
|
||||
ApkIdentity("com.t3tools.t3code", 52, setOf("signer-a")),
|
||||
51
|
||||
)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
validateApkIdentity(
|
||||
installed,
|
||||
ApkIdentity("com.t3tools.t3code", 51, setOf("signer-b")),
|
||||
51
|
||||
)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
validateApkIdentity(installed, installed, 50)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectsOnlyAConfiguredSystemInstallerActivity() {
|
||||
val untrusted = InstallerCandidate("example.viewer", "ViewerActivity", 0)
|
||||
val updatedSystem = InstallerCandidate(
|
||||
"android.installer.updated",
|
||||
"InstallActivity",
|
||||
ApplicationInfo.FLAG_UPDATED_SYSTEM_APP
|
||||
)
|
||||
val system = InstallerCandidate(
|
||||
"android.installer",
|
||||
"InstallActivity",
|
||||
ApplicationInfo.FLAG_SYSTEM
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
updatedSystem,
|
||||
selectTrustedInstaller(listOf(untrusted, system, updatedSystem), updatedSystem.componentKey)
|
||||
)
|
||||
assertEquals(system, selectTrustedInstaller(listOf(untrusted, system), null))
|
||||
assertNull(selectTrustedInstaller(listOf(untrusted), untrusted.componentKey))
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,8 @@ import {
|
||||
SettingsOpenSourceLicensesRouteScreen,
|
||||
} from "./features/settings/SettingsOpenSourceLicensesRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { SettingsProvidersRouteScreen } from "./features/settings/SettingsProvidersRouteScreen";
|
||||
import { SettingsHermesRouteScreen } from "./features/settings/SettingsHermesRouteScreen";
|
||||
import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled";
|
||||
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
@@ -164,6 +166,20 @@ const SettingsContentStack = createNativeStackNavigator({
|
||||
title: "Environments",
|
||||
},
|
||||
}),
|
||||
SettingsProviders: createNativeStackScreen({
|
||||
screen: SettingsProvidersRouteScreen,
|
||||
linking: "providers",
|
||||
options: {
|
||||
title: "Providers",
|
||||
},
|
||||
}),
|
||||
SettingsHermes: createNativeStackScreen({
|
||||
screen: SettingsHermesRouteScreen,
|
||||
linking: "hermes",
|
||||
options: {
|
||||
title: "Hermes",
|
||||
},
|
||||
}),
|
||||
SettingsEnvironmentNew: createNativeStackScreen({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "environment-new",
|
||||
|
||||
@@ -53,6 +53,28 @@ export function ProviderIcon(props: ProviderIconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "hermes") {
|
||||
return (
|
||||
<Svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke={mono}
|
||||
strokeWidth={1.8}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<Path d="M12 3v18" />
|
||||
<Path d="M8.5 5.5C6 3.5 3.5 4 2 6c2.8-.2 4.8.7 6 2.5" />
|
||||
<Path d="M15.5 5.5C18 3.5 20.5 4 22 6c-2.8-.2-4.8.7-6 2.5" />
|
||||
<Path d="M8 9.5c0 2 1.7 2.5 4 3.5 2.3 1 4 1.5 4 3.5S14.3 19 12 20" />
|
||||
<Path d="M16 9.5c0 2-1.7 2.5-4 3.5-2.3 1-4 1.5-4 3.5S9.7 19 12 20" />
|
||||
<Path d="M10 3h4" />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "cursor") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "re
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
@@ -48,10 +49,11 @@ const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
readonly onPressDirectory: (path: string) => void;
|
||||
readonly onPreviewFile?: (path: string) => void;
|
||||
readonly onPressFile: (path: string) => void;
|
||||
readonly onDownloadFile: (path: string) => void;
|
||||
}) {
|
||||
const { node, depth } = props.item;
|
||||
|
||||
return (
|
||||
const row = (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={node.path}
|
||||
@@ -104,6 +106,20 @@ const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
return node.kind === "file" ? (
|
||||
<ControlPillMenu
|
||||
title={node.name}
|
||||
shouldOpenOnLongPress
|
||||
actions={[{ id: "download", title: "Download file", image: "arrow.down.to.line" }]}
|
||||
onPressAction={({ nativeEvent }) => {
|
||||
if (nativeEvent.event === "download") props.onDownloadFile(node.path);
|
||||
}}
|
||||
>
|
||||
{row}
|
||||
</ControlPillMenu>
|
||||
) : (
|
||||
row
|
||||
);
|
||||
});
|
||||
|
||||
export function FileTreeBrowser(props: {
|
||||
@@ -118,6 +134,7 @@ export function FileTreeBrowser(props: {
|
||||
readonly onPreviewFile?: (path: string) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
readonly onDownloadFile: (path: string) => void;
|
||||
}) {
|
||||
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [pendingSelection, setPendingSelection] = useState<{
|
||||
@@ -132,6 +149,7 @@ export function FileTreeBrowser(props: {
|
||||
onLoadDirectory,
|
||||
onPreviewFile,
|
||||
onSelectFile,
|
||||
onDownloadFile,
|
||||
loadedDirectories,
|
||||
selectedPath: controlledSelectedPath,
|
||||
} = props;
|
||||
@@ -222,12 +240,14 @@ export function FileTreeBrowser(props: {
|
||||
onPressDirectory={toggleDirectory}
|
||||
onPreviewFile={onPreviewFile}
|
||||
onPressFile={handleSelectFile}
|
||||
onDownloadFile={onDownloadFile}
|
||||
/>
|
||||
),
|
||||
[
|
||||
expandedPaths,
|
||||
handleSelectFile,
|
||||
onPreviewFile,
|
||||
onDownloadFile,
|
||||
loadedDirectories,
|
||||
selectedPath,
|
||||
toggleDirectory,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/co
|
||||
import { videoMimeType } from "@t3tools/shared/video";
|
||||
import {
|
||||
isWorkspaceBrowserPreviewPath,
|
||||
isDownloadOnlyFile,
|
||||
isWorkspaceImagePreviewPath,
|
||||
mediaMimeTypeFromExtension,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
@@ -48,6 +49,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
|
||||
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
|
||||
import { FileMarkdownPreview } from "./FileMarkdownPreview";
|
||||
import { FileTreeBrowser } from "./FileTreeBrowser";
|
||||
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
|
||||
import { useFileTreeEntries } from "./useFileTreeEntries";
|
||||
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
|
||||
import { SourceFileSurface } from "./SourceFileSurface";
|
||||
@@ -114,6 +116,7 @@ function FileContent(props: {
|
||||
readonly resolveVideoUri: () => Promise<string | null>;
|
||||
readonly fileContents: string | null;
|
||||
readonly fileError: string | null;
|
||||
readonly onDownload: () => void;
|
||||
readonly relativePath: string;
|
||||
readonly threadId: ThreadId | null;
|
||||
readonly initialLine: number | null;
|
||||
@@ -183,10 +186,19 @@ function FileContent(props: {
|
||||
return <WorkspaceFileWebPreview uri={props.previewUri} />;
|
||||
}
|
||||
|
||||
if (props.fileError && props.fileContents === null) {
|
||||
if (isDownloadOnlyFile(props.relativePath) || (props.fileError && props.fileContents === null)) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<EmptyState title="File unavailable" detail={props.fileError} />
|
||||
<EmptyState
|
||||
title="Preview unavailable"
|
||||
detail={
|
||||
isDownloadOnlyFile(props.relativePath)
|
||||
? "This file cannot be previewed. Would you like to download it?"
|
||||
: `${props.fileError}\nYou can download this file instead.`
|
||||
}
|
||||
actionLabel="Download file"
|
||||
onAction={props.onDownload}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -337,6 +349,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
|
||||
props.route.params,
|
||||
);
|
||||
const revealedInspectorRef = useRef(false);
|
||||
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
|
||||
const entriesQuery = useFileTreeEntries({
|
||||
environmentId,
|
||||
cwd: fileInspector.supported ? null : cwd,
|
||||
@@ -561,6 +574,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
|
||||
onPreviewFile={handlePreviewFile}
|
||||
onRefresh={entriesQuery.refresh}
|
||||
onSelectFile={handleSelectFile}
|
||||
onDownloadFile={downloadFile}
|
||||
/>
|
||||
<FilesToolbarBottomFade />
|
||||
</>
|
||||
@@ -592,6 +606,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
readonly path: string;
|
||||
readonly mode: FileViewMode;
|
||||
} | null>(null);
|
||||
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
|
||||
const [previewRevision, setPreviewRevision] = useState(0);
|
||||
const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
|
||||
const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
|
||||
@@ -674,6 +689,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
};
|
||||
const needsFileContents =
|
||||
relativePath !== null &&
|
||||
!isDownloadOnlyFile(relativePath) &&
|
||||
!isVideoFile &&
|
||||
!isAudioFile &&
|
||||
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
|
||||
@@ -742,6 +758,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
if (relativePath === null) return [];
|
||||
const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
|
||||
return [
|
||||
{
|
||||
id: "download",
|
||||
title: "Download file",
|
||||
icon: "arrow.down.to.line" as const,
|
||||
inline: false,
|
||||
onPress: () => downloadFile(relativePath),
|
||||
},
|
||||
canToggleMode
|
||||
? ({
|
||||
id: "preview",
|
||||
@@ -840,6 +863,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
].filter((action) => action !== null);
|
||||
}, [
|
||||
appearance.codeWordBreak,
|
||||
downloadFile,
|
||||
setCodeWordBreak,
|
||||
assetPreviewUri,
|
||||
assetPreview.refresh,
|
||||
@@ -1020,6 +1044,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
resolveVideoUri={assetPreview.refresh}
|
||||
fileContents={fileData?.contents ?? null}
|
||||
fileError={fileQuery.error}
|
||||
onDownload={() => downloadFile(relativePath)}
|
||||
initialLine={targetLine}
|
||||
relativePath={relativePath}
|
||||
threadId={threadId}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
isDownloadOnlyFile,
|
||||
isWorkspaceBrowserPreviewPath,
|
||||
isWorkspaceImagePreviewPath,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
@@ -30,6 +31,7 @@ export function preloadWorkspaceFileContents(input: {
|
||||
readonly theme: ReviewDiffTheme;
|
||||
}): void {
|
||||
if (
|
||||
isDownloadOnlyFile(input.relativePath) ||
|
||||
isWorkspaceBrowserPreviewPath(input.relativePath) ||
|
||||
isWorkspaceImagePreviewPath(input.relativePath) ||
|
||||
isVideoPreviewFile(input.relativePath)
|
||||
|
||||
@@ -15,6 +15,7 @@ import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
import { useUniwindTheme } from "../../lib/useUniwindTheme";
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import { FileTreeBrowser } from "./FileTreeBrowser";
|
||||
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
|
||||
import { useFileTreeEntries } from "./useFileTreeEntries";
|
||||
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
@@ -28,6 +29,7 @@ export function ThreadFileNavigatorPane(props: {
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
}) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const downloadFile = useWorkspaceFileDownload(props.environmentId, props.cwd);
|
||||
const { toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
|
||||
const { themeAppearance: highlightTheme } = useAppearancePreferences();
|
||||
const theme = useUniwindTheme();
|
||||
@@ -91,6 +93,7 @@ export function ThreadFileNavigatorPane(props: {
|
||||
onPreviewFile={handlePreviewFile}
|
||||
onRefresh={entriesQuery.refresh}
|
||||
onSelectFile={props.onSelectFile}
|
||||
onDownloadFile={downloadFile}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ export function useFileTreeEntries(input: {
|
||||
searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
|
||||
? projectEnvironment.searchEntries({
|
||||
environmentId,
|
||||
input: { cwd, query: debouncedQuery, limit: 200 },
|
||||
input: { cwd, query: debouncedQuery, limit: 200, includeIgnored: true },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { useFileDownload } from "../threads/useFileChipShare";
|
||||
import { basename } from "./filePath";
|
||||
|
||||
export function useWorkspaceFileDownload(environmentId: EnvironmentId | null, cwd: string | null) {
|
||||
const download = useFileDownload(environmentId, "workspace-file-download");
|
||||
return useCallback(
|
||||
(path: string) => {
|
||||
if (cwd === null) return;
|
||||
download({
|
||||
name: basename(path),
|
||||
mimeType: "application/octet-stream",
|
||||
resource: { _tag: "draft-workspace-file", cwd, path, download: true },
|
||||
});
|
||||
},
|
||||
[cwd, download],
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,12 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
|
||||
import { ConversationTabs, HermesMobileWorkspace } from "../hermes/HermesWorkspace";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Platform, useWindowDimensions } from "react-native";
|
||||
import { Platform, View, useWindowDimensions } from "react-native";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
@@ -26,6 +30,8 @@ import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export function HomeRouteScreen() {
|
||||
const conversationSource = useAtomValue(conversationSourceAtom);
|
||||
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { layout } = useAdaptiveWorkspaceLayout();
|
||||
const projects = useProjects();
|
||||
@@ -106,6 +112,41 @@ export function HomeRouteScreen() {
|
||||
|
||||
// In split layouts the persistent sidebar IS the thread list — Home becomes
|
||||
// an empty detail pane so selecting a thread never transitions layouts.
|
||||
if (conversationSource === "hermes" && !layout.usesSplitView) {
|
||||
const content = (
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "Hermes", headerShown: Platform.OS !== "android" }}
|
||||
/>
|
||||
{Platform.OS === "android" && (
|
||||
<AndroidScreenHeader
|
||||
title="Hermes"
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Settings",
|
||||
icon: "gearshape",
|
||||
onPress: () =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsHermes" },
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<ConversationTabs />
|
||||
<HermesMobileWorkspace />
|
||||
</View>
|
||||
);
|
||||
return Platform.OS === "android" ? (
|
||||
<AndroidHomeFabLayout onStartNewTask={() => requestHermesSession((value) => value + 1)}>
|
||||
{content}
|
||||
</AndroidHomeFabLayout>
|
||||
) : (
|
||||
content
|
||||
);
|
||||
}
|
||||
|
||||
if (layout.usesSplitView) {
|
||||
return (
|
||||
<>
|
||||
@@ -181,6 +222,7 @@ export function HomeRouteScreen() {
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
<ConversationTabs />
|
||||
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
|
||||
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
|
||||
import {
|
||||
useCallback,
|
||||
@@ -36,6 +38,8 @@ export function HardwareKeyboardCommandProvider({
|
||||
pathname,
|
||||
}: PropsWithChildren<{ readonly pathname: string }>) {
|
||||
const navigation = useNavigation();
|
||||
const conversationSource = useAtomValue(conversationSourceAtom);
|
||||
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
|
||||
const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
|
||||
const activeThread = useThreadShell(activeThreadRef);
|
||||
const copyTarget = useMemo(
|
||||
@@ -125,6 +129,11 @@ export function HardwareKeyboardCommandProvider({
|
||||
}
|
||||
|
||||
if (command === "newTask") {
|
||||
if (conversationSource === "hermes") {
|
||||
requestHermesSession((value) => value + 1);
|
||||
navigation.navigate("Home");
|
||||
return;
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
|
||||
return;
|
||||
}
|
||||
@@ -149,7 +158,7 @@ export function HardwareKeyboardCommandProvider({
|
||||
navigation.navigate("ThreadReview", thread);
|
||||
}
|
||||
},
|
||||
[copyTarget, navigation, pathname, showCopyFeedback],
|
||||
[conversationSource, copyTarget, navigation, pathname, requestHermesSession, showCopyFeedback],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,7 +3,9 @@ import type {
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
|
||||
import { ConversationTabs, HermesMobileWorkspace } from "../hermes/HermesWorkspace";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
NavigationContext,
|
||||
@@ -226,6 +228,8 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
},
|
||||
) {
|
||||
const projectGroupingMode = props.projectGroupingMode;
|
||||
const conversationSource = useAtomValue(conversationSourceAtom);
|
||||
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
|
||||
const { materialYouStyleLayoutActive } = useAppearancePreferences();
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = props.pathname;
|
||||
@@ -445,8 +449,12 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
}, [navigation]);
|
||||
|
||||
const handleStartNewTask = useCallback(() => {
|
||||
if (conversationSource === "hermes") {
|
||||
requestHermesSession((value) => value + 1);
|
||||
return;
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
|
||||
}, [navigation]);
|
||||
}, [conversationSource, navigation, requestHermesSession]);
|
||||
|
||||
// Minted here (root stack navigation) so the sidebar pane stays free of
|
||||
// navigation hooks — on iOS it renders inside an independent nav tree.
|
||||
@@ -561,21 +569,27 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
style={sidebarAnimatedStyle}
|
||||
>
|
||||
<View className="flex-1" style={{ width: layout.listPaneWidth }}>
|
||||
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
|
||||
<ThreadNavigationSidebar
|
||||
width={layout.listPaneWidth}
|
||||
visible={panes.primarySidebarVisible}
|
||||
onRequestVisibility={revealPrimarySidebar}
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onOpenSettings={handleOpenSettings}
|
||||
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
|
||||
onNewThreadInProject={handleNewThreadInProject}
|
||||
onNewThreadOnBranch={handleNewThreadOnBranch}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSearchQueryChange={setPrimarySidebarSearchQuery}
|
||||
searchQuery={primarySidebarSearchQuery}
|
||||
/>
|
||||
</AndroidHomeFabLayout>
|
||||
<ConversationTabs topInset />
|
||||
{conversationSource === "hermes" ? (
|
||||
<HermesMobileWorkspace mode="list" />
|
||||
) : (
|
||||
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
|
||||
<ThreadNavigationSidebar
|
||||
topInset={0}
|
||||
width={layout.listPaneWidth}
|
||||
visible={panes.primarySidebarVisible}
|
||||
onRequestVisibility={revealPrimarySidebar}
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onOpenSettings={handleOpenSettings}
|
||||
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
|
||||
onNewThreadInProject={handleNewThreadInProject}
|
||||
onNewThreadOnBranch={handleNewThreadOnBranch}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSearchQueryChange={setPrimarySidebarSearchQuery}
|
||||
searchQuery={primarySidebarSearchQuery}
|
||||
/>
|
||||
</AndroidHomeFabLayout>
|
||||
)}
|
||||
</View>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
@@ -596,7 +610,11 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
<WorkspaceContentWidthContext
|
||||
value={layout.usesSplitView ? renderedContentWidth : null}
|
||||
>
|
||||
{props.children}
|
||||
{layout.usesSplitView && conversationSource === "hermes" ? (
|
||||
<HermesMobileWorkspace mode="detail" />
|
||||
) : (
|
||||
props.children
|
||||
)}
|
||||
</WorkspaceContentWidthContext>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { Platform, View } from "react-native";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { HermesSettingsMobileWorkspace } from "../hermes/HermesWorkspace";
|
||||
|
||||
export function SettingsHermesRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Hermes" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<HermesSettingsMobileWorkspace />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import {
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
ProviderInstanceId,
|
||||
resolveProviderInstanceEnabled,
|
||||
type EnvironmentId,
|
||||
type ProviderInstanceConfig,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ThemedSwitch } from "../../components/ThemedSwitch";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useEnvironments } from "../../state/environments";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
import {
|
||||
addProviderCustomModel,
|
||||
buildMobileProviderInstancePatch,
|
||||
createHermesProviderInstance,
|
||||
deriveMobileProviderSettingsRows,
|
||||
HERMES_DRIVER_KIND,
|
||||
readProviderConfigString,
|
||||
readProviderCustomModels,
|
||||
readProviderEnvironmentVariable,
|
||||
removeProviderCustomModel,
|
||||
updateProviderConfigString,
|
||||
updateProviderEnvironmentVariable,
|
||||
type MobileProviderSettingsRow,
|
||||
} from "./mobile-provider-settings";
|
||||
|
||||
function providerLabel(row: MobileProviderSettingsRow): string {
|
||||
return (
|
||||
row.instance.displayName?.trim() ||
|
||||
PROVIDER_DISPLAY_NAMES[row.instance.driver] ||
|
||||
String(row.instanceId)
|
||||
);
|
||||
}
|
||||
|
||||
function providerStatus(row: MobileProviderSettingsRow): string {
|
||||
if (!resolveProviderInstanceEnabled(row.instance)) return "Disabled";
|
||||
const provider = row.liveProvider;
|
||||
if (!provider) return "Waiting for server";
|
||||
if (provider.status === "ready") {
|
||||
const count = provider.models.length;
|
||||
return `${count} advertised model${count === 1 ? "" : "s"}`;
|
||||
}
|
||||
return provider.status === "error" ? "Needs attention" : "Checking availability";
|
||||
}
|
||||
|
||||
function CommittedTextInput(props: {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly placeholder: string;
|
||||
readonly disabled: boolean;
|
||||
readonly onCommit: (value: string) => void;
|
||||
}) {
|
||||
const commit = (value: string) => {
|
||||
if (value.trim() !== props.value.trim()) props.onCommit(value);
|
||||
};
|
||||
return (
|
||||
<View className="gap-1.5">
|
||||
<Text className="text-sm font-t3-medium text-foreground-muted">{props.label}</Text>
|
||||
<TextInput
|
||||
accessibilityLabel={props.label}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="min-h-11 rounded-xl bg-sheet px-3 py-2 text-base text-foreground"
|
||||
defaultValue={props.value}
|
||||
editable={!props.disabled}
|
||||
onEndEditing={(event) => commit(event.nativeEvent.text)}
|
||||
placeholder={props.placeholder}
|
||||
returnKeyType="done"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SmallAction(props: {
|
||||
readonly label: string;
|
||||
readonly destructive?: boolean;
|
||||
readonly disabled?: boolean;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={props.disabled}
|
||||
onPress={props.onPress}
|
||||
className={
|
||||
props.disabled
|
||||
? "rounded-full bg-subtle px-4 py-2 opacity-40"
|
||||
: props.destructive
|
||||
? "rounded-full bg-subtle px-4 py-2 active:opacity-70"
|
||||
: "rounded-full bg-subtle px-4 py-2 active:opacity-70"
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
props.destructive
|
||||
? "text-sm font-t3-medium text-danger-foreground"
|
||||
: "text-sm font-t3-medium text-foreground"
|
||||
}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderCard(props: {
|
||||
readonly row: MobileProviderSettingsRow;
|
||||
readonly saving: boolean;
|
||||
readonly onCommit: (instance: ProviderInstanceConfig) => void;
|
||||
readonly onDelete: () => void;
|
||||
}) {
|
||||
const { row } = props;
|
||||
const enabled = resolveProviderInstanceEnabled(row.instance);
|
||||
const customModels = readProviderCustomModels(row.instance);
|
||||
const [modelDraft, setModelDraft] = useState("");
|
||||
const [modelError, setModelError] = useState<string | null>(null);
|
||||
const isHermes = row.instance.driver === HERMES_DRIVER_KIND;
|
||||
const customModelsSupported = row.instance.driver !== "antigravity";
|
||||
|
||||
const addModel = () => {
|
||||
const result = addProviderCustomModel(row.instance, modelDraft);
|
||||
if (!result.ok) {
|
||||
setModelError(result.message);
|
||||
return;
|
||||
}
|
||||
setModelDraft("");
|
||||
setModelError(null);
|
||||
props.onCommit(result.instance);
|
||||
};
|
||||
|
||||
return (
|
||||
<View className="gap-4 p-4">
|
||||
<View className="flex-row items-center gap-3">
|
||||
<ProviderIcon provider={row.instance.driver} size={24} />
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-lg font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{providerLabel(row)}
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">{providerStatus(row)}</Text>
|
||||
</View>
|
||||
{props.saving ? (
|
||||
<ActivityIndicator />
|
||||
) : (
|
||||
<ThemedSwitch
|
||||
accessibilityLabel={`Enable ${providerLabel(row)}`}
|
||||
disabled={props.saving}
|
||||
onValueChange={(value) => props.onCommit({ ...row.instance, enabled: value })}
|
||||
value={enabled}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{isHermes ? (
|
||||
<View className="gap-3">
|
||||
<CommittedTextInput
|
||||
key={`dashboard:${readProviderConfigString(row.instance, "dashboardUrl")}`}
|
||||
label="Dashboard URL (on the T3 server)"
|
||||
value={readProviderConfigString(row.instance, "dashboardUrl")}
|
||||
placeholder="http://127.0.0.1:9119"
|
||||
disabled={props.saving}
|
||||
onCommit={(value) =>
|
||||
props.onCommit(updateProviderConfigString(row.instance, "dashboardUrl", value))
|
||||
}
|
||||
/>
|
||||
<CommittedTextInput
|
||||
key={`binary:${readProviderConfigString(row.instance, "binaryPath")}`}
|
||||
label="Binary path"
|
||||
value={readProviderConfigString(row.instance, "binaryPath")}
|
||||
placeholder="hermes"
|
||||
disabled={props.saving}
|
||||
onCommit={(value) =>
|
||||
props.onCommit(updateProviderConfigString(row.instance, "binaryPath", value))
|
||||
}
|
||||
/>
|
||||
<CommittedTextInput
|
||||
key={`home:${readProviderEnvironmentVariable(row.instance, "HERMES_HOME")}`}
|
||||
label="HERMES_HOME (optional)"
|
||||
value={readProviderEnvironmentVariable(row.instance, "HERMES_HOME")}
|
||||
placeholder="Use the server's default Hermes profile"
|
||||
disabled={props.saving}
|
||||
onCommit={(value) =>
|
||||
props.onCommit(updateProviderEnvironmentVariable(row.instance, "HERMES_HOME", value))
|
||||
}
|
||||
/>
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Hermes runs on the selected T3 environment. Install it and run `hermes setup` on that
|
||||
machine first.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{customModelsSupported ? (
|
||||
<View className="gap-2">
|
||||
<Text className="text-sm font-t3-medium text-foreground-muted">Custom models</Text>
|
||||
{customModels.map((model) => (
|
||||
<View
|
||||
key={model.slug}
|
||||
className="flex-row items-center gap-2 rounded-xl bg-sheet px-3 py-2"
|
||||
>
|
||||
<Text className="min-w-0 flex-1 font-mono text-sm text-foreground" numberOfLines={1}>
|
||||
{model.slug}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityLabel={`Remove custom model ${model.slug}`}
|
||||
accessibilityRole="button"
|
||||
disabled={props.saving}
|
||||
hitSlop={8}
|
||||
onPress={() => props.onCommit(removeProviderCustomModel(row.instance, model.slug))}
|
||||
className="p-1 active:opacity-60"
|
||||
>
|
||||
<SymbolView
|
||||
name="trash"
|
||||
size={17}
|
||||
tintColorClassName="accent-icon-muted"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
))}
|
||||
<View className="flex-row items-center gap-2">
|
||||
<TextInput
|
||||
accessibilityLabel={`Custom model ID for ${providerLabel(row)}`}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="min-h-11 min-w-0 flex-1 rounded-xl bg-sheet px-3 py-2 font-mono text-sm text-foreground"
|
||||
editable={!props.saving}
|
||||
onChangeText={(value) => {
|
||||
setModelDraft(value);
|
||||
setModelError(null);
|
||||
}}
|
||||
onSubmitEditing={addModel}
|
||||
placeholder="provider/model-id"
|
||||
returnKeyType="done"
|
||||
value={modelDraft}
|
||||
/>
|
||||
<SmallAction label="Add" disabled={props.saving} onPress={addModel} />
|
||||
</View>
|
||||
{modelError ? <Text className="text-sm text-danger-foreground">{modelError}</Text> : null}
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Add a model ID that the provider accepts but did not advertise. It will appear in the
|
||||
thread model picker after the server refreshes.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!row.isDefault ? (
|
||||
<View className="items-start border-t border-border-subtle pt-3">
|
||||
<SmallAction
|
||||
label="Remove instance"
|
||||
destructive
|
||||
disabled={props.saving}
|
||||
onPress={props.onDelete}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AddHermesForm(props: {
|
||||
readonly saving: boolean;
|
||||
readonly onAdd: (input: {
|
||||
readonly label: string;
|
||||
readonly binaryPath: string;
|
||||
readonly hermesHome: string;
|
||||
}) => Promise<boolean>;
|
||||
readonly onCancel: () => void;
|
||||
}) {
|
||||
const [label, setLabel] = useState("");
|
||||
const [binaryPath, setBinaryPath] = useState("");
|
||||
const [hermesHome, setHermesHome] = useState("");
|
||||
return (
|
||||
<View className="gap-3 p-4">
|
||||
<Text className="text-lg font-t3-medium text-foreground">Add Hermes instance</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Hermes instance label"
|
||||
className="min-h-11 rounded-xl bg-sheet px-3 py-2 text-base text-foreground"
|
||||
editable={!props.saving}
|
||||
onChangeText={setLabel}
|
||||
placeholder="Label, for example Work"
|
||||
value={label}
|
||||
/>
|
||||
<TextInput
|
||||
accessibilityLabel="Hermes binary path"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="min-h-11 rounded-xl bg-sheet px-3 py-2 font-mono text-sm text-foreground"
|
||||
editable={!props.saving}
|
||||
onChangeText={setBinaryPath}
|
||||
placeholder="hermes"
|
||||
value={binaryPath}
|
||||
/>
|
||||
<TextInput
|
||||
accessibilityLabel="Hermes home"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="min-h-11 rounded-xl bg-sheet px-3 py-2 font-mono text-sm text-foreground"
|
||||
editable={!props.saving}
|
||||
onChangeText={setHermesHome}
|
||||
placeholder="HERMES_HOME (optional)"
|
||||
value={hermesHome}
|
||||
/>
|
||||
<View className="flex-row gap-2">
|
||||
<SmallAction label="Cancel" disabled={props.saving} onPress={props.onCancel} />
|
||||
<SmallAction
|
||||
label="Add instance"
|
||||
disabled={props.saving}
|
||||
onPress={() => void props.onAdd({ label, binaryPath, hermesHome })}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsProvidersRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { environments } = useEnvironments();
|
||||
const configurableEnvironments = useMemo(
|
||||
() => environments.filter((environment) => environment.serverConfig !== null),
|
||||
[environments],
|
||||
);
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const [savingInstanceId, setSavingInstanceId] = useState<ProviderInstanceId | null>(null);
|
||||
const [showAddHermes, setShowAddHermes] = useState(false);
|
||||
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
|
||||
label: "provider settings update",
|
||||
reportFailure: false,
|
||||
});
|
||||
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
|
||||
label: "provider refresh",
|
||||
reportFailure: false,
|
||||
});
|
||||
|
||||
const selectedEnvironment =
|
||||
configurableEnvironments.find(
|
||||
(environment) => environment.environmentId === selectedEnvironmentId,
|
||||
) ??
|
||||
configurableEnvironments[0] ??
|
||||
null;
|
||||
|
||||
const serverConfig = selectedEnvironment?.serverConfig ?? null;
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
serverConfig
|
||||
? deriveMobileProviderSettingsRows(serverConfig.settings, serverConfig.providers)
|
||||
: [],
|
||||
[serverConfig],
|
||||
);
|
||||
|
||||
const commitPatch = useCallback(
|
||||
async (patch: ServerSettingsPatch, savingId: ProviderInstanceId): Promise<boolean> => {
|
||||
if (!selectedEnvironment) return false;
|
||||
setSavingInstanceId(savingId);
|
||||
const result = await updateSettings({
|
||||
environmentId: selectedEnvironment.environmentId,
|
||||
input: { patch },
|
||||
});
|
||||
setSavingInstanceId(null);
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert(
|
||||
"Could not update provider",
|
||||
error instanceof Error ? error.message : "The T3 server rejected the settings change.",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void refreshProviders({
|
||||
environmentId: selectedEnvironment.environmentId,
|
||||
input: { refreshModels: true },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
[refreshProviders, selectedEnvironment, updateSettings],
|
||||
);
|
||||
|
||||
const commitInstance = useCallback(
|
||||
(row: MobileProviderSettingsRow, instance: ProviderInstanceConfig) => {
|
||||
if (!serverConfig) return;
|
||||
void commitPatch(
|
||||
buildMobileProviderInstancePatch({ settings: serverConfig.settings, row, instance }),
|
||||
row.instanceId,
|
||||
);
|
||||
},
|
||||
[commitPatch, serverConfig],
|
||||
);
|
||||
|
||||
const deleteInstance = useCallback(
|
||||
(row: MobileProviderSettingsRow) => {
|
||||
if (!serverConfig || row.isDefault) return;
|
||||
Alert.alert(
|
||||
"Remove provider instance?",
|
||||
`${providerLabel(row)} will no longer be available.`,
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Remove",
|
||||
style: "destructive",
|
||||
onPress: () => {
|
||||
const providerInstances = { ...serverConfig.settings.providerInstances };
|
||||
delete providerInstances[row.instanceId];
|
||||
void commitPatch({ providerInstances }, row.instanceId);
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
},
|
||||
[commitPatch, serverConfig],
|
||||
);
|
||||
|
||||
const addHermes = useCallback(
|
||||
async (input: {
|
||||
readonly label: string;
|
||||
readonly binaryPath: string;
|
||||
readonly hermesHome: string;
|
||||
}): Promise<boolean> => {
|
||||
if (!serverConfig) return false;
|
||||
const created = createHermesProviderInstance({ settings: serverConfig.settings, ...input });
|
||||
const added = await commitPatch(
|
||||
{
|
||||
providerInstances: {
|
||||
...serverConfig.settings.providerInstances,
|
||||
[created.instanceId]: created.instance,
|
||||
},
|
||||
},
|
||||
created.instanceId,
|
||||
);
|
||||
if (added) setShowAddHermes(false);
|
||||
return added;
|
||||
},
|
||||
[commitPatch, serverConfig],
|
||||
);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Providers" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-5 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
>
|
||||
{configurableEnvironments.length > 1 ? (
|
||||
<SettingsSection title="Environment" card>
|
||||
{configurableEnvironments.map((environment, index) => (
|
||||
<Pressable
|
||||
key={environment.environmentId}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{
|
||||
checked: environment.environmentId === selectedEnvironment?.environmentId,
|
||||
}}
|
||||
onPress={() => setSelectedEnvironmentId(environment.environmentId)}
|
||||
className={
|
||||
index === 0
|
||||
? "flex-row items-center gap-3 p-4"
|
||||
: "flex-row items-center gap-3 border-t border-border-subtle p-4"
|
||||
}
|
||||
>
|
||||
<Text className="min-w-0 flex-1 text-lg text-foreground" numberOfLines={1}>
|
||||
{environment.label}
|
||||
</Text>
|
||||
{environment.environmentId === selectedEnvironment?.environmentId ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={18}
|
||||
tintColorClassName="accent-icon"
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
))}
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
|
||||
{selectedEnvironment ? (
|
||||
<View className="gap-2 px-2">
|
||||
<Text className="text-sm font-t3-medium text-foreground-muted">
|
||||
Configuring {selectedEnvironment.label}
|
||||
</Text>
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Provider processes run on this environment's machine. Changes made here apply to web,
|
||||
desktop, and mobile clients connected to it.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{serverConfig ? (
|
||||
<>
|
||||
<SettingsSection title="Hermes Agent" card>
|
||||
<View className="flex-row items-center gap-3 p-4">
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<Text className="text-lg text-foreground">Add another Hermes instance</Text>
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
Use a separate binary or HERMES_HOME profile.
|
||||
</Text>
|
||||
</View>
|
||||
<SmallAction
|
||||
label={showAddHermes ? "Close" : "Add"}
|
||||
disabled={savingInstanceId !== null}
|
||||
onPress={() => setShowAddHermes((visible) => !visible)}
|
||||
/>
|
||||
</View>
|
||||
{showAddHermes ? (
|
||||
<View className="border-t border-border-subtle">
|
||||
<AddHermesForm
|
||||
saving={savingInstanceId !== null}
|
||||
onAdd={addHermes}
|
||||
onCancel={() => setShowAddHermes(false)}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
|
||||
<View className="gap-4">
|
||||
{rows.map((row) => (
|
||||
<SettingsSection key={row.instanceId} card>
|
||||
<ProviderCard
|
||||
row={row}
|
||||
saving={savingInstanceId === row.instanceId}
|
||||
onCommit={(instance) => commitInstance(row, instance)}
|
||||
onDelete={() => deleteInstance(row)}
|
||||
/>
|
||||
</SettingsSection>
|
||||
))}
|
||||
</View>
|
||||
</>
|
||||
) : (
|
||||
<SettingsSection card>
|
||||
<View className="items-center gap-3 px-6 py-8">
|
||||
<SymbolView
|
||||
name="exclamationmark.triangle"
|
||||
size={22}
|
||||
tintColorClassName="accent-icon-muted"
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Connect a T3 environment before configuring its providers.
|
||||
</Text>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
@@ -44,17 +44,12 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { SettingsRow } from "./components/SettingsRow";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
|
||||
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
|
||||
import { SoftwareUpdateSection } from "./SoftwareUpdateSection";
|
||||
import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
|
||||
|
||||
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
|
||||
@@ -132,6 +127,8 @@ function LocalSettingsRouteScreen() {
|
||||
value={`${environmentCount}`}
|
||||
target="SettingsEnvironments"
|
||||
/>
|
||||
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
|
||||
<SettingsRow icon="gearshape.2" label="Hermes" target="SettingsHermes" />
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
@@ -144,6 +141,7 @@ function LocalSettingsRouteScreen() {
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<SoftwareUpdateSection />
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -514,6 +512,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
value={`${environmentCount}`}
|
||||
target="SettingsEnvironments"
|
||||
/>
|
||||
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
|
||||
<SettingsRow icon="gearshape.2" label="Hermes" target="SettingsHermes" />
|
||||
<SettingsSwitchRow
|
||||
icon="bell.badge"
|
||||
label="Device Notifications"
|
||||
@@ -564,6 +564,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<SoftwareUpdateSection />
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -735,70 +736,12 @@ function LegacySettingsSection() {
|
||||
}
|
||||
|
||||
function AppSettingsSection() {
|
||||
const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
|
||||
const updateInFlight = useRef(false);
|
||||
const hiddenUpdateTapCount = useRef(0);
|
||||
|
||||
const version = Constants.expoConfig?.version ?? "0.0.0";
|
||||
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
|
||||
// missing variant never mislabels a production build as development.
|
||||
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
|
||||
const variantLabel = variant === "production" ? "" : capitalize(variant);
|
||||
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
|
||||
const updateCheckAvailable = isAppUpdateCheckAvailable();
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
// "Up to date" is a transient acknowledgement, not a state worth persisting —
|
||||
// return the version row to its normal, deliberately quiet state.
|
||||
useEffect(() => {
|
||||
if (updateState !== "current") return;
|
||||
const timer = setTimeout(() => setUpdateState("idle"), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [updateState]);
|
||||
|
||||
const checkForUpdate = useCallback(async () => {
|
||||
// `disabled={busy}` only takes effect on the next render, so two taps in the
|
||||
// same frame would both get through. The ref closes that window.
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
// The user asked for this restart by tapping the version row, so it may
|
||||
// apply immediately instead of prompting.
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
onFailure: (message) => Alert.alert("Update failed", message),
|
||||
onStateChange: setUpdateState,
|
||||
});
|
||||
} finally {
|
||||
updateInFlight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleVersionPress = useCallback(() => {
|
||||
if (!updateCheckAvailable || updateInFlight.current) return;
|
||||
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
|
||||
hiddenUpdateTapCount.current = tap.nextCount;
|
||||
if (tap.shouldCheck) {
|
||||
void checkForUpdate();
|
||||
}
|
||||
}, [checkForUpdate, updateCheckAvailable]);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: // "ready" appears only when this check joined an in-flight background-mode
|
||||
// check; that download installs at the next backgrounding.
|
||||
updateState === "ready"
|
||||
? "Update ready"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
@@ -809,12 +752,7 @@ function AppSettingsSection() {
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{statusLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -828,18 +766,7 @@ function AppSettingsSection() {
|
||||
target="SettingsOpenSourceLicenses"
|
||||
/>
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{updateCheckAvailable ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
disabled={busy}
|
||||
onPress={handleVersionPress}
|
||||
>
|
||||
{versionRow}
|
||||
</Pressable>
|
||||
) : (
|
||||
versionRow
|
||||
)}
|
||||
{versionRow}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import Constants from "expo-constants";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Alert, Platform, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import {
|
||||
AndroidApkUpdateError,
|
||||
type AndroidApkUpdatePhase,
|
||||
downloadTrustedAndroidApk,
|
||||
runAndroidApkUpdate,
|
||||
} from "./androidApkUpdater";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
import { SettingsRow } from "./components/SettingsRow";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
|
||||
type UpdateStatus =
|
||||
| "idle"
|
||||
| AndroidApkUpdatePhase
|
||||
| "already-in-progress"
|
||||
| "up-to-date"
|
||||
| "unavailable"
|
||||
| "installer-launched"
|
||||
| "failed";
|
||||
|
||||
const STATUS_LABEL: Record<UpdateStatus, string | undefined> = {
|
||||
idle: undefined,
|
||||
checking: "Checking…",
|
||||
downloading: "Downloading…",
|
||||
installing: "Opening installer…",
|
||||
"already-in-progress": "Update in progress",
|
||||
"up-to-date": "Up to date",
|
||||
unavailable: "No release available",
|
||||
"installer-launched": "Installer launched",
|
||||
failed: "Try again",
|
||||
};
|
||||
|
||||
const APP_UPDATE_STATUS_LABEL: Record<AppUpdateCheckState, string | undefined> = {
|
||||
idle: undefined,
|
||||
checking: "Checking…",
|
||||
downloading: "Downloading…",
|
||||
ready: "Update ready",
|
||||
restarting: "Restarting…",
|
||||
current: "Up to date",
|
||||
};
|
||||
|
||||
async function fetchReleasePage(
|
||||
apiUrl: string,
|
||||
init: { credentials: "omit"; redirect: "error"; signal: AbortSignal },
|
||||
) {
|
||||
const { fetch: expoFetch } = await import("expo/fetch");
|
||||
return expoFetch(apiUrl, { ...init, headers: { Accept: "application/json" } });
|
||||
}
|
||||
|
||||
async function downloadApk(
|
||||
downloadUrl: string,
|
||||
versionCode: number,
|
||||
expectedSize: number,
|
||||
): Promise<string> {
|
||||
const { randomUUID } = await import("expo-crypto");
|
||||
const { fetch: expoFetch } = await import("expo/fetch");
|
||||
const { Directory, File, Paths } = await import("expo-file-system");
|
||||
const cache = new Directory(Paths.cache, "t3-apk-updates");
|
||||
cache.create({ idempotent: true, intermediates: true });
|
||||
return downloadTrustedAndroidApk(downloadUrl, versionCode, expectedSize, {
|
||||
fetchApk: (url, init) => expoFetch(url, init),
|
||||
createTemporaryFile: (candidateVersionCode) => {
|
||||
const temporary = new File(cache, `t3code-apk-${candidateVersionCode}-${randomUUID()}.part`);
|
||||
temporary.create();
|
||||
return temporary;
|
||||
},
|
||||
openTemporaryFileStream: (file) => {
|
||||
const writable = file as { writableStream(): WritableStream };
|
||||
return writable.writableStream();
|
||||
},
|
||||
finalizeTemporaryFile: async (file, candidateVersionCode) => {
|
||||
const temporary = file as InstanceType<typeof File>;
|
||||
const destination = new File(cache, `t3code-apk-${candidateVersionCode}.apk`);
|
||||
await temporary.move(destination, { overwrite: true });
|
||||
return destination.uri;
|
||||
},
|
||||
deleteTemporaryFile: (file) => {
|
||||
const temporary = file as InstanceType<typeof File>;
|
||||
if (temporary.exists) temporary.delete();
|
||||
},
|
||||
pruneObsoleteFiles: (candidateVersionCode) => {
|
||||
try {
|
||||
const currentName = `t3code-apk-${candidateVersionCode}.apk`;
|
||||
for (const entry of cache.list()) {
|
||||
if (
|
||||
entry instanceof File &&
|
||||
entry.name !== currentName &&
|
||||
(/^t3code-apk-\d+\.apk$/.test(entry.name) ||
|
||||
/^t3code-apk-\d+-[0-9a-f-]+\.part$/.test(entry.name))
|
||||
) {
|
||||
entry.delete();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Cache pruning must not block an otherwise verified download from being installed.
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function getInstalledVersionCode(): Promise<number> {
|
||||
const { requireNativeModule } = await import("expo");
|
||||
return requireNativeModule<{
|
||||
getInstalledVersionCode(): number;
|
||||
}>("T3NativeControls").getInstalledVersionCode();
|
||||
}
|
||||
|
||||
async function launchPackageInstaller(
|
||||
localUri: string,
|
||||
expectedVersionCode: number,
|
||||
): Promise<void> {
|
||||
const { requireNativeModule } = await import("expo");
|
||||
await requireNativeModule<{
|
||||
installApk(uri: string, expectedVersionCode: number): Promise<void>;
|
||||
}>("T3NativeControls").installApk(localUri, expectedVersionCode);
|
||||
}
|
||||
|
||||
export function SoftwareUpdateSection() {
|
||||
const [status, setStatus] = useState<UpdateStatus>("idle");
|
||||
const [appUpdateState, setAppUpdateState] = useState<AppUpdateCheckState>("idle");
|
||||
const apiUrl = Constants.expoConfig?.extra?.apkReleaseApiUrl;
|
||||
const manifestVersionCode =
|
||||
Constants.platform?.android?.versionCode ?? Constants.expoConfig?.android?.versionCode;
|
||||
|
||||
const hasApkUpdates =
|
||||
Platform.OS === "android" && typeof apiUrl === "string" && apiUrl.length > 0;
|
||||
const hasAppUpdates = isAppUpdateCheckAvailable();
|
||||
|
||||
const checkAppUpdate = useCallback(async () => {
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
onFailure: (message) => Alert.alert("Could not update T3 Code", message),
|
||||
onStateChange: setAppUpdateState,
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!hasApkUpdates && !hasAppUpdates) return null;
|
||||
|
||||
const update = async () => {
|
||||
try {
|
||||
const result = await runAndroidApkUpdate({
|
||||
apiUrl,
|
||||
getInstalledVersionCode,
|
||||
fetchReleasePage,
|
||||
downloadApk,
|
||||
installApk: launchPackageInstaller,
|
||||
onPhase: setStatus,
|
||||
});
|
||||
if (result.kind === "already-in-progress") {
|
||||
setStatus("already-in-progress");
|
||||
Alert.alert(
|
||||
"Update already in progress",
|
||||
"Another update check, download, or installer launch is already in progress.",
|
||||
);
|
||||
} else if (result.kind === "no-compatible-release") {
|
||||
setStatus("unavailable");
|
||||
Alert.alert(
|
||||
"No APK release available",
|
||||
"The repository does not currently have a compatible published Android APK release.",
|
||||
);
|
||||
} else if (result.kind === "up-to-date") {
|
||||
setStatus("up-to-date");
|
||||
Alert.alert(
|
||||
"T3 Code is up to date",
|
||||
`Installed build ${result.installedVersionCode} is the newest available APK.`,
|
||||
);
|
||||
} else {
|
||||
setStatus("installer-launched");
|
||||
}
|
||||
} catch (error) {
|
||||
setStatus("failed");
|
||||
Alert.alert(
|
||||
error instanceof AndroidApkUpdateError && error.stage === "install"
|
||||
? "Could not open installer"
|
||||
: error instanceof AndroidApkUpdateError && error.stage === "download"
|
||||
? "Could not download update"
|
||||
: "Could not check for updates",
|
||||
error instanceof AndroidApkUpdateError
|
||||
? error.userMessage
|
||||
: "The update could not be completed. Please try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const apkBusy = status === "checking" || status === "downloading" || status === "installing";
|
||||
const appUpdateBusy =
|
||||
appUpdateState === "checking" ||
|
||||
appUpdateState === "downloading" ||
|
||||
appUpdateState === "restarting";
|
||||
|
||||
return (
|
||||
<View className="gap-2">
|
||||
<SettingsSection title="Software Update">
|
||||
<View className="flex-row items-center justify-between gap-4 p-4">
|
||||
<Text className="text-lg text-foreground">Installed version</Text>
|
||||
<Text className="text-base text-foreground-muted">
|
||||
{Constants.expoConfig?.version ?? "Unknown"}
|
||||
{manifestVersionCode ? ` (${manifestVersionCode})` : ""}
|
||||
</Text>
|
||||
</View>
|
||||
{hasApkUpdates ? (
|
||||
<SettingsRow
|
||||
icon="arrow.down.circle"
|
||||
label="Check for updates"
|
||||
value={STATUS_LABEL[status]}
|
||||
disabled={apkBusy}
|
||||
onPress={() => void update()}
|
||||
/>
|
||||
) : (
|
||||
<SettingsRow
|
||||
icon="arrow.down.circle"
|
||||
label="Check for updates"
|
||||
value={APP_UPDATE_STATUS_LABEL[appUpdateState]}
|
||||
disabled={appUpdateBusy}
|
||||
onPress={() => void checkAppUpdate()}
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
{hasApkUpdates
|
||||
? "Checks the repository, downloads a newer APK inside T3 Code, then opens Android’s installer for your confirmation. Android may require permission to install unknown apps from T3 Code. Updates must use the same signing key as your installed app."
|
||||
: "Checks for an app update, downloads it securely, and restarts T3 Code after saving pending drafts and messages. Background update checks also run automatically."}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,669 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
AndroidApkUpdateError,
|
||||
downloadTrustedAndroidApk,
|
||||
isNewerAndroidVersion,
|
||||
runAndroidApkUpdate,
|
||||
selectLatestAndroidApkRelease,
|
||||
} from "./androidApkUpdater";
|
||||
|
||||
const API_URL = "https://git.example.com/api/v1/repos/alex/t3code/releases";
|
||||
const SUBPATH_API_URL = "https://git.example.com/git/api/v1/repos/alex/t3code/releases";
|
||||
|
||||
function attachmentUuid(versionCode: number): string {
|
||||
return `00000000-0000-4000-8000-${String(versionCode).padStart(12, "0")}`;
|
||||
}
|
||||
|
||||
function release(
|
||||
versionCode: number,
|
||||
overrides: Record<string, unknown> = {},
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
id: versionCode,
|
||||
tag_name: `apk-${versionCode}`,
|
||||
name: `Android APK · build ${versionCode}`,
|
||||
draft: false,
|
||||
prerelease: false,
|
||||
assets: [
|
||||
{
|
||||
id: versionCode,
|
||||
name: `t3code-apk-${versionCode}.apk`,
|
||||
size: 4,
|
||||
browser_download_url: `https://git.example.com/attachments/${attachmentUuid(versionCode)}`,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function releasePageResponse(
|
||||
url: string,
|
||||
items: ReadonlyArray<unknown>,
|
||||
totalCount: number | string,
|
||||
overrides: Partial<{
|
||||
ok: boolean;
|
||||
status: number;
|
||||
url: string;
|
||||
redirected: boolean;
|
||||
}> = {},
|
||||
) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
url,
|
||||
redirected: false,
|
||||
headers: {
|
||||
get: (name: string) => (name.toLowerCase() === "x-total-count" ? String(totalCount) : null),
|
||||
},
|
||||
json: vi.fn().mockResolvedValue(items),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function successfulReleaseFetch(items: ReadonlyArray<unknown>) {
|
||||
return vi.fn(async (url: string) => releasePageResponse(url, items, items.length));
|
||||
}
|
||||
|
||||
function downloadResponse(
|
||||
url: string,
|
||||
chunks: ReadonlyArray<Uint8Array>,
|
||||
contentLength: string | null = null,
|
||||
) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
url,
|
||||
redirected: false,
|
||||
headers: {
|
||||
get: (name: string) => (name.toLowerCase() === "content-length" ? contentLength : null),
|
||||
},
|
||||
body: new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (const chunk of chunks) controller.enqueue(chunk);
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function downloadDependencies(response: ReturnType<typeof downloadResponse>) {
|
||||
const temporaryFile = { uri: "file:///cache/t3code-apk-51-unique.part" };
|
||||
const written: Uint8Array[] = [];
|
||||
return {
|
||||
temporaryFile,
|
||||
written,
|
||||
dependencies: {
|
||||
fetchApk: vi.fn().mockResolvedValue(response),
|
||||
createTemporaryFile: vi.fn().mockReturnValue(temporaryFile),
|
||||
openTemporaryFileStream: vi.fn().mockReturnValue(
|
||||
new WritableStream<Uint8Array>({
|
||||
write(chunk) {
|
||||
written.push(chunk);
|
||||
},
|
||||
}),
|
||||
),
|
||||
finalizeTemporaryFile: vi.fn().mockResolvedValue("file:///cache/t3code-apk-51.apk"),
|
||||
deleteTemporaryFile: vi.fn(),
|
||||
pruneObsoleteFiles: vi.fn(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("Android APK release selection", () => {
|
||||
it("selects the highest valid published release and retains its trusted size", () => {
|
||||
const selected = selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(42),
|
||||
release(105, { prerelease: true }),
|
||||
release(91),
|
||||
release(120, { draft: true }),
|
||||
release(75),
|
||||
],
|
||||
API_URL,
|
||||
);
|
||||
|
||||
expect(selected).toEqual({
|
||||
versionCode: 91,
|
||||
downloadUrl: `https://git.example.com/attachments/${attachmentUuid(91)}`,
|
||||
expectedSize: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it("requires matching release and asset identity metadata", () => {
|
||||
expect(
|
||||
selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(20, { id: 0 }),
|
||||
release(21, { tag_name: "v21" }),
|
||||
release(22, { name: "Unexpected release" }),
|
||||
release(23, { assets: [] }),
|
||||
release(24, {
|
||||
assets: [
|
||||
{
|
||||
id: 24,
|
||||
name: "t3code-apk-23.apk",
|
||||
size: 4,
|
||||
browser_download_url: `https://git.example.com/attachments/${attachmentUuid(24)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
release(25, { assets: [{ id: 0, name: "t3code-apk-25.apk", size: 4 }] }),
|
||||
],
|
||||
API_URL,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts the exact Gitea repository release download path", () => {
|
||||
const browser_download_url =
|
||||
"https://git.example.com/alex/t3code/releases/download/apk-5/t3code-apk-5.apk";
|
||||
expect(
|
||||
selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(5, {
|
||||
assets: [{ id: 5, name: "t3code-apk-5.apk", size: 4, browser_download_url }],
|
||||
}),
|
||||
],
|
||||
API_URL,
|
||||
),
|
||||
).toEqual({ versionCode: 5, downloadUrl: browser_download_url, expectedSize: 4 });
|
||||
});
|
||||
|
||||
it("rejects same-origin assets outside trusted Gitea asset paths", () => {
|
||||
for (const browser_download_url of [
|
||||
`https://git.example.com/other/t3code/releases/download/apk-5/t3code-apk-5.apk`,
|
||||
`https://git.example.com/alex/t3code/releases/download/apk-6/t3code-apk-5.apk`,
|
||||
`https://git.example.com/alex/t3code/releases/download/apk-5/other.apk`,
|
||||
`https://git.example.com/api/v1/repos/alex/t3code/releases/assets/5`,
|
||||
`https://git.example.com/other/attachments/${attachmentUuid(5)}`,
|
||||
`https://git.example.com/attachments/not-a-uuid`,
|
||||
]) {
|
||||
expect(
|
||||
selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(5, {
|
||||
assets: [
|
||||
{
|
||||
id: 5,
|
||||
name: "t3code-apk-5.apk",
|
||||
size: 4,
|
||||
browser_download_url,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
API_URL,
|
||||
),
|
||||
).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the exact configured Gitea subpath for attachments", () => {
|
||||
const valid = release(5, {
|
||||
assets: [
|
||||
{
|
||||
id: 5,
|
||||
name: "t3code-apk-5.apk",
|
||||
size: 4,
|
||||
browser_download_url: `https://git.example.com/git/attachments/${attachmentUuid(5)}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(selectLatestAndroidApkRelease([valid], SUBPATH_API_URL)?.versionCode).toBe(5);
|
||||
expect(selectLatestAndroidApkRelease([valid], API_URL)).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the exact configured Gitea subpath for release downloads", () => {
|
||||
const valid = release(5, {
|
||||
assets: [
|
||||
{
|
||||
id: 5,
|
||||
name: "t3code-apk-5.apk",
|
||||
size: 4,
|
||||
browser_download_url:
|
||||
"https://git.example.com/git/alex/t3code/releases/download/apk-5/t3code-apk-5.apk",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(selectLatestAndroidApkRelease([valid], SUBPATH_API_URL)?.versionCode).toBe(5);
|
||||
expect(selectLatestAndroidApkRelease([valid], API_URL)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects assets with invalid or excessive declared sizes", () => {
|
||||
for (const size of [0, -1, 1.5, 500 * 1024 * 1024 + 1]) {
|
||||
expect(
|
||||
selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(5, {
|
||||
assets: [
|
||||
{
|
||||
id: 5,
|
||||
name: "t3code-apk-5.apk",
|
||||
size,
|
||||
browser_download_url: `https://git.example.com/attachments/${attachmentUuid(5)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
API_URL,
|
||||
),
|
||||
).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects non-HTTPS, cross-origin, credential-bearing, and queried asset URLs", () => {
|
||||
const unsafeUrls = [
|
||||
`http://git.example.com/attachments/${attachmentUuid(5)}`,
|
||||
`https://evil.example/attachments/${attachmentUuid(5)}`,
|
||||
`https://user:[email protected]/attachments/${attachmentUuid(5)}`,
|
||||
`https://git.example.com/attachments/${attachmentUuid(5)}?token=secret`,
|
||||
];
|
||||
|
||||
for (const browser_download_url of unsafeUrls) {
|
||||
expect(
|
||||
selectLatestAndroidApkRelease(
|
||||
[
|
||||
release(5, {
|
||||
assets: [{ id: 5, name: "t3code-apk-5.apk", size: 4, browser_download_url }],
|
||||
}),
|
||||
],
|
||||
API_URL,
|
||||
),
|
||||
).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("requires a trusted unqueried HTTPS API URL", () => {
|
||||
expect(() => selectLatestAndroidApkRelease([], "http://git.example.com/releases")).toThrow(
|
||||
/HTTPS/,
|
||||
);
|
||||
expect(() =>
|
||||
selectLatestAndroidApkRelease([], "https://user:[email protected]/releases"),
|
||||
).toThrow(/credentials/);
|
||||
expect(() => selectLatestAndroidApkRelease([], `${API_URL}?token=secret`)).toThrow(/query/);
|
||||
});
|
||||
|
||||
it("compares integer Android version codes", () => {
|
||||
expect(isNewerAndroidVersion(11, 10)).toBe(true);
|
||||
expect(isNewerAndroidVersion(10, 10)).toBe(false);
|
||||
expect(isNewerAndroidVersion(9, 10)).toBe(false);
|
||||
expect(() => isNewerAndroidVersion(11, 0)).toThrow(/installed version code/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Android APK update orchestration", () => {
|
||||
it("rejects a cross-origin redirected API response before reading JSON", async () => {
|
||||
const requested = `${API_URL}?limit=50&page=1`;
|
||||
const response = releasePageResponse(requested, [release(51)], 1, {
|
||||
redirected: true,
|
||||
url: "https://evil.example/releases",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: vi.fn().mockResolvedValue(response),
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).rejects.toMatchObject({ name: "AndroidApkUpdateError", stage: "check" });
|
||||
expect(response.json).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a non-redirected API final URL mismatch before reading JSON", async () => {
|
||||
const response = releasePageResponse(`${API_URL}?limit=50&page=1`, [release(51)], 1, {
|
||||
url: "https://evil.example/api/v1/repos/alex/t3code/releases?limit=50&page=1",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: vi.fn().mockResolvedValue(response),
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: "check" });
|
||||
expect(response.json).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes redirect rejection, omitted credentials, and an abort signal to release fetches", async () => {
|
||||
const fetchReleasePage = vi.fn(async (url: string) => releasePageResponse(url, [], 0));
|
||||
await runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage,
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
});
|
||||
|
||||
expect(fetchReleasePage).toHaveBeenCalledWith(`${API_URL}?limit=50&page=1`, {
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
});
|
||||
|
||||
it("uses X-Total-Count to fetch exactly 20 full pages for 1,000 releases", async () => {
|
||||
const requestedUrls: string[] = [];
|
||||
const fetchReleasePage = vi.fn(async (url: string) => {
|
||||
requestedUrls.push(url);
|
||||
const page = Number(new URL(url).searchParams.get("page"));
|
||||
const start = (page - 1) * 50 + 1;
|
||||
return releasePageResponse(
|
||||
url,
|
||||
Array.from({ length: 50 }, (_, index) => release(start + index)),
|
||||
1_000,
|
||||
);
|
||||
});
|
||||
const downloadApk = vi.fn().mockResolvedValue("file:///cache/update.apk");
|
||||
const installApk = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage,
|
||||
downloadApk,
|
||||
installApk,
|
||||
}),
|
||||
).resolves.toEqual({ kind: "installer-launched", versionCode: 1_000 });
|
||||
expect(requestedUrls).toHaveLength(20);
|
||||
expect(new URL(requestedUrls.at(-1)!).searchParams.get("page")).toBe("20");
|
||||
expect(downloadApk).toHaveBeenCalledWith(
|
||||
`https://git.example.com/attachments/${attachmentUuid(1_000)}`,
|
||||
1_000,
|
||||
4,
|
||||
);
|
||||
expect(installApk).toHaveBeenCalledWith("file:///cache/update.apk", 1_000);
|
||||
});
|
||||
|
||||
it("validates every page length and the final aggregate count", async () => {
|
||||
const fetchReleasePage = vi.fn(async (url: string) =>
|
||||
releasePageResponse(
|
||||
url,
|
||||
Array.from({ length: 49 }, (_, index) => release(index + 1)),
|
||||
50,
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(1),
|
||||
fetchReleasePage,
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: "check" });
|
||||
});
|
||||
|
||||
it("rejects a changed X-Total-Count on a later page", async () => {
|
||||
const fetchReleasePage = vi.fn(async (url: string) => {
|
||||
const page = Number(new URL(url).searchParams.get("page"));
|
||||
const items =
|
||||
page === 1 ? Array.from({ length: 50 }, (_, index) => release(index + 1)) : [release(51)];
|
||||
return releasePageResponse(url, items, page === 1 ? 51 : 52);
|
||||
});
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(1),
|
||||
fetchReleasePage,
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: "check" });
|
||||
});
|
||||
|
||||
it("rejects a duplicate positive release ID across pages", async () => {
|
||||
const fetchReleasePage = vi.fn(async (url: string) => {
|
||||
const page = Number(new URL(url).searchParams.get("page"));
|
||||
const items =
|
||||
page === 1
|
||||
? Array.from({ length: 50 }, (_, index) => release(index + 1))
|
||||
: [release(50, { tag_name: "apk-51", name: "Android APK · build 51" })];
|
||||
return releasePageResponse(url, items, 51);
|
||||
});
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(1),
|
||||
fetchReleasePage,
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: "check" });
|
||||
});
|
||||
|
||||
it("uses the native installed version value for update selection", async () => {
|
||||
const getInstalledVersionCode = vi.fn().mockResolvedValue(51);
|
||||
const downloadApk = vi.fn();
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode,
|
||||
fetchReleasePage: successfulReleaseFetch([release(51)]),
|
||||
downloadApk,
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
kind: "up-to-date",
|
||||
installedVersionCode: 51,
|
||||
latestVersionCode: 51,
|
||||
});
|
||||
expect(getInstalledVersionCode).toHaveBeenCalledOnce();
|
||||
expect(downloadApk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports the installed build when it is newer than the latest release", async () => {
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(60),
|
||||
fetchReleasePage: successfulReleaseFetch([release(50)]),
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
kind: "up-to-date",
|
||||
installedVersionCode: 60,
|
||||
latestVersionCode: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the trusted release size to download and expected version to the installer", async () => {
|
||||
const downloadApk = vi.fn().mockResolvedValue("content://trusted/update.apk");
|
||||
const installApk = vi.fn().mockResolvedValue(undefined);
|
||||
await runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: successfulReleaseFetch([release(51)]),
|
||||
downloadApk,
|
||||
installApk,
|
||||
});
|
||||
expect(downloadApk).toHaveBeenCalledWith(
|
||||
`https://git.example.com/attachments/${attachmentUuid(51)}`,
|
||||
51,
|
||||
4,
|
||||
);
|
||||
expect(installApk).toHaveBeenCalledWith("content://trusted/update.apk", 51);
|
||||
});
|
||||
|
||||
it("aborts a stalled API request and releases the module lock", async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchReleasePage = vi.fn(
|
||||
(_url: string, init: { signal: AbortSignal }) =>
|
||||
new Promise<never>((_, reject) => {
|
||||
init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true });
|
||||
}),
|
||||
);
|
||||
const stalled = runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage,
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
});
|
||||
const stalledRejection = expect(stalled).rejects.toMatchObject({ stage: "check" });
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
await stalledRejection;
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: successfulReleaseFetch([]),
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).resolves.toEqual({ kind: "no-compatible-release" });
|
||||
});
|
||||
|
||||
it("cleans up an aborted download and releases the module lock", async () => {
|
||||
vi.useFakeTimers();
|
||||
const downloadUrl = `https://git.example.com/attachments/${attachmentUuid(51)}`;
|
||||
const fixture = downloadDependencies({
|
||||
...downloadResponse(downloadUrl, []),
|
||||
body: new ReadableStream<Uint8Array>({ start() {} }),
|
||||
});
|
||||
const stalled = runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: successfulReleaseFetch([release(51)]),
|
||||
downloadApk: (url, versionCode, expectedSize) =>
|
||||
downloadTrustedAndroidApk(url, versionCode, expectedSize, fixture.dependencies),
|
||||
installApk: vi.fn(),
|
||||
});
|
||||
const stalledRejection = expect(stalled).rejects.toMatchObject({ stage: "download" });
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
await stalledRejection;
|
||||
expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile);
|
||||
|
||||
await expect(
|
||||
runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: successfulReleaseFetch([]),
|
||||
downloadApk: vi.fn(),
|
||||
installApk: vi.fn(),
|
||||
}),
|
||||
).resolves.toEqual({ kind: "no-compatible-release" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["check", { fetchReleasePage: vi.fn().mockRejectedValue(new Error("offline")) }],
|
||||
[
|
||||
"download",
|
||||
{
|
||||
fetchReleasePage: successfulReleaseFetch([release(51)]),
|
||||
downloadApk: vi.fn().mockRejectedValue(new Error("disk full")),
|
||||
},
|
||||
],
|
||||
[
|
||||
"install",
|
||||
{
|
||||
fetchReleasePage: successfulReleaseFetch([release(51)]),
|
||||
downloadApk: vi.fn().mockResolvedValue("content://trusted/update.apk"),
|
||||
installApk: vi.fn().mockRejectedValue(new Error("permission denied")),
|
||||
},
|
||||
],
|
||||
] as const)("labels %s failures with a safe user message", async (stage, overrides) => {
|
||||
const promise = runAndroidApkUpdate({
|
||||
apiUrl: API_URL,
|
||||
getInstalledVersionCode: vi.fn().mockResolvedValue(50),
|
||||
fetchReleasePage: overrides.fetchReleasePage,
|
||||
downloadApk: "downloadApk" in overrides ? overrides.downloadApk : vi.fn(),
|
||||
installApk: "installApk" in overrides ? overrides.installApk : vi.fn(),
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toMatchObject({
|
||||
name: "AndroidApkUpdateError",
|
||||
stage,
|
||||
userMessage: expect.any(String),
|
||||
});
|
||||
await promise.catch((error: unknown) => {
|
||||
expect(error).toBeInstanceOf(AndroidApkUpdateError);
|
||||
expect((error as AndroidApkUpdateError).userMessage).not.toMatch(
|
||||
/offline|disk full|permission denied/,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Android APK streaming download", () => {
|
||||
const downloadUrl = `https://git.example.com/attachments/${attachmentUuid(51)}`;
|
||||
|
||||
it("rejects an oversized Content-Length before creating a temporary file", async () => {
|
||||
const fixture = downloadDependencies(
|
||||
downloadResponse(downloadUrl, [], String(500 * 1024 * 1024 + 1)),
|
||||
);
|
||||
await expect(
|
||||
downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies),
|
||||
).rejects.toThrow(/size|large|length/i);
|
||||
expect(fixture.dependencies.createTemporaryFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects redirected and mismatched final download URLs before reading the body", async () => {
|
||||
for (const overrides of [
|
||||
{ redirected: true, url: "https://evil.example/update.apk" },
|
||||
{ redirected: false, url: `https://git.example.com/attachments/${attachmentUuid(52)}` },
|
||||
]) {
|
||||
const fixture = downloadDependencies({
|
||||
...downloadResponse(downloadUrl, [new Uint8Array([1, 2, 3, 4])], "4"),
|
||||
...overrides,
|
||||
});
|
||||
await expect(
|
||||
downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies),
|
||||
).rejects.toThrow(/redirect|URL/i);
|
||||
expect(fixture.dependencies.createTemporaryFile).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("streams without buffering and accepts the exact trusted byte count", async () => {
|
||||
const fixture = downloadDependencies(
|
||||
downloadResponse(downloadUrl, [new Uint8Array([1, 2]), new Uint8Array([3, 4])], "4"),
|
||||
);
|
||||
await expect(downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies)).resolves.toBe(
|
||||
"file:///cache/t3code-apk-51.apk",
|
||||
);
|
||||
expect(fixture.written).toHaveLength(2);
|
||||
expect(fixture.dependencies.fetchApk).toHaveBeenCalledWith(downloadUrl, {
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["overrun", [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5])]],
|
||||
["underrun", [new Uint8Array([1, 2, 3])]],
|
||||
])("rejects a streaming %s and deletes the partial file", async (_kind, chunks) => {
|
||||
const fixture = downloadDependencies(downloadResponse(downloadUrl, chunks));
|
||||
await expect(
|
||||
downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies),
|
||||
).rejects.toThrow(/size|bytes/i);
|
||||
expect(fixture.dependencies.finalizeTemporaryFile).not.toHaveBeenCalled();
|
||||
expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile);
|
||||
});
|
||||
|
||||
it("aborts a stalled body stream and deletes the partial file", async () => {
|
||||
vi.useFakeTimers();
|
||||
const fixture = downloadDependencies({
|
||||
...downloadResponse(downloadUrl, []),
|
||||
body: new ReadableStream<Uint8Array>({ start() {} }),
|
||||
});
|
||||
const download = downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies);
|
||||
const downloadRejection = expect(download).rejects.toThrow(/abort|timed out/i);
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
await downloadRejection;
|
||||
expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,537 @@
|
||||
const MAX_ANDROID_VERSION_CODE = 2_100_000_000;
|
||||
const GITEA_RELEASE_PAGE_SIZE = 50;
|
||||
const MAX_GITEA_RELEASE_COUNT = 10_000;
|
||||
const API_TIMEOUT_MS = 30_000;
|
||||
const DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
|
||||
const GITEA_ATTACHMENT_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export const MAX_ANDROID_APK_BYTES = 500 * 1024 * 1024;
|
||||
|
||||
export interface AndroidApkRelease {
|
||||
readonly versionCode: number;
|
||||
readonly downloadUrl: string;
|
||||
readonly expectedSize: number;
|
||||
}
|
||||
|
||||
export type AndroidApkUpdatePhase = "checking" | "downloading" | "installing";
|
||||
export type AndroidApkUpdateErrorStage = "check" | "download" | "install";
|
||||
|
||||
export type AndroidApkUpdateResult =
|
||||
| { readonly kind: "already-in-progress" }
|
||||
| { readonly kind: "no-compatible-release" }
|
||||
| {
|
||||
readonly kind: "up-to-date";
|
||||
readonly installedVersionCode: number;
|
||||
readonly latestVersionCode: number;
|
||||
}
|
||||
| { readonly kind: "installer-launched"; readonly versionCode: number };
|
||||
|
||||
export class AndroidApkUpdateError extends Error {
|
||||
readonly stage: AndroidApkUpdateErrorStage;
|
||||
readonly userMessage: string;
|
||||
|
||||
constructor(stage: AndroidApkUpdateErrorStage, userMessage: string, cause: unknown) {
|
||||
super(userMessage, { cause });
|
||||
this.name = "AndroidApkUpdateError";
|
||||
this.stage = stage;
|
||||
this.userMessage = userMessage;
|
||||
}
|
||||
}
|
||||
|
||||
interface TrustedFetchInit {
|
||||
readonly credentials: "omit";
|
||||
readonly redirect: "error";
|
||||
readonly signal: AbortSignal;
|
||||
}
|
||||
|
||||
interface HeadersLike {
|
||||
get(name: string): string | null;
|
||||
}
|
||||
|
||||
interface GiteaReleasePageResponse {
|
||||
readonly ok: boolean;
|
||||
readonly status: number;
|
||||
readonly url: string;
|
||||
readonly redirected: boolean;
|
||||
readonly headers: HeadersLike;
|
||||
json(): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface AndroidApkUpdateDependencies {
|
||||
readonly apiUrl: string;
|
||||
readonly getInstalledVersionCode: () => Promise<number>;
|
||||
readonly fetchReleasePage: (
|
||||
apiUrl: string,
|
||||
init: TrustedFetchInit,
|
||||
) => Promise<GiteaReleasePageResponse>;
|
||||
readonly downloadApk: (
|
||||
downloadUrl: string,
|
||||
versionCode: number,
|
||||
expectedSize: number,
|
||||
) => Promise<string>;
|
||||
readonly installApk: (localUri: string, expectedVersionCode: number) => Promise<void>;
|
||||
readonly onPhase?: (phase: AndroidApkUpdatePhase) => void;
|
||||
}
|
||||
|
||||
interface AndroidApkDownloadResponse {
|
||||
readonly ok: boolean;
|
||||
readonly status: number;
|
||||
readonly url: string;
|
||||
readonly redirected: boolean;
|
||||
readonly headers: HeadersLike;
|
||||
readonly body: ReadableStream<Uint8Array> | null;
|
||||
}
|
||||
|
||||
interface AndroidApkDownloadDependencies {
|
||||
readonly fetchApk: (url: string, init: TrustedFetchInit) => Promise<AndroidApkDownloadResponse>;
|
||||
readonly createTemporaryFile: (versionCode: number) => unknown;
|
||||
readonly openTemporaryFileStream: (file: unknown) => WritableStream<Uint8Array>;
|
||||
readonly finalizeTemporaryFile: (file: unknown, versionCode: number) => Promise<string>;
|
||||
readonly deleteTemporaryFile: (file: unknown) => void;
|
||||
readonly pruneObsoleteFiles: (versionCode: number) => void;
|
||||
}
|
||||
|
||||
let androidApkUpdateInProgress = false;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function validVersionCode(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value >= 1 && value <= MAX_ANDROID_VERSION_CODE;
|
||||
}
|
||||
|
||||
function validApkSize(value: unknown): value is number {
|
||||
return isPositiveSafeInteger(value) && value <= MAX_ANDROID_APK_BYTES;
|
||||
}
|
||||
|
||||
function parseVersionCode(tag: unknown): number | null {
|
||||
if (typeof tag !== "string") return null;
|
||||
const match = /^apk-([1-9]\d*)$/.exec(tag);
|
||||
if (!match) return null;
|
||||
const versionCode = Number(match[1]);
|
||||
return validVersionCode(versionCode) ? versionCode : null;
|
||||
}
|
||||
|
||||
function trustedHttpsUrl(rawUrl: string, kind: "API" | "asset"): URL {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(rawUrl);
|
||||
} catch {
|
||||
throw new Error(`The update ${kind} URL is invalid.`);
|
||||
}
|
||||
if (url.protocol !== "https:") {
|
||||
throw new Error(`The update ${kind} URL must use HTTPS.`);
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
throw new Error(`The update ${kind} URL must not contain credentials.`);
|
||||
}
|
||||
if (url.search || url.hash) {
|
||||
throw new Error(`The update ${kind} URL must not contain query parameters or fragments.`);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function giteaServerBase(apiUrl: string): {
|
||||
readonly origin: string;
|
||||
readonly path: string;
|
||||
readonly owner: string;
|
||||
readonly repository: string;
|
||||
} {
|
||||
const url = trustedHttpsUrl(apiUrl, "API");
|
||||
const match = /^(.*)\/api\/v1\/repos\/([^/]+)\/([^/]+)\/releases\/?$/.exec(url.pathname);
|
||||
if (!match) throw new Error("The update API URL is not a Gitea repository releases URL.");
|
||||
return {
|
||||
origin: url.origin,
|
||||
path: match[1] ?? "",
|
||||
owner: match[2] ?? "",
|
||||
repository: match[3] ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function trustedAssetUrl(
|
||||
rawUrl: unknown,
|
||||
apiUrl: string,
|
||||
releaseTag: string,
|
||||
assetName: string,
|
||||
): string | null {
|
||||
if (typeof rawUrl !== "string") return null;
|
||||
try {
|
||||
const url = trustedHttpsUrl(rawUrl, "asset");
|
||||
const server = giteaServerBase(apiUrl);
|
||||
if (url.origin !== server.origin) return null;
|
||||
const attachmentPrefix = `${server.path}/attachments/`;
|
||||
if (url.pathname.startsWith(attachmentPrefix)) {
|
||||
const uuid = url.pathname.slice(attachmentPrefix.length);
|
||||
return GITEA_ATTACHMENT_UUID.test(uuid) ? url.href : null;
|
||||
}
|
||||
const releaseUrl = new URL(
|
||||
`${server.path}/${server.owner}/${server.repository}/releases/download/${releaseTag}/${assetName}`,
|
||||
server.origin,
|
||||
);
|
||||
return url.href === releaseUrl.href ? url.href : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function urlsAreEquivalent(actualUrl: string, requestedUrl: string): boolean {
|
||||
try {
|
||||
return new URL(actualUrl).href === new URL(requestedUrl).href;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validateExactResponseUrl(
|
||||
response: Pick<GiteaReleasePageResponse, "redirected" | "url">,
|
||||
requestedUrl: string,
|
||||
kind: "release API" | "APK download",
|
||||
): void {
|
||||
if (response.redirected) throw new Error(`The ${kind} redirected and was rejected.`);
|
||||
if (!urlsAreEquivalent(response.url, requestedUrl)) {
|
||||
throw new Error(`The ${kind} final URL is not the requested trusted URL.`);
|
||||
}
|
||||
}
|
||||
|
||||
function giteaReleasePageUrl(apiUrl: string, page: number): string {
|
||||
giteaServerBase(apiUrl);
|
||||
const url = new URL(apiUrl);
|
||||
url.searchParams.set("limit", String(GITEA_RELEASE_PAGE_SIZE));
|
||||
url.searchParams.set("page", String(page));
|
||||
return url.href;
|
||||
}
|
||||
|
||||
function parseTotalCount(value: string | null): number {
|
||||
if (value === null || !/^(0|[1-9]\d*)$/.test(value)) {
|
||||
throw new TypeError("The repository did not return a valid X-Total-Count header.");
|
||||
}
|
||||
const total = Number(value);
|
||||
if (!Number.isSafeInteger(total) || total > MAX_GITEA_RELEASE_COUNT) {
|
||||
throw new TypeError("The repository release count exceeds the supported safe limit.");
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function validatePageItems(
|
||||
items: unknown,
|
||||
expectedLength: number,
|
||||
): asserts items is ReadonlyArray<unknown> {
|
||||
if (!Array.isArray(items) || items.length !== expectedLength) {
|
||||
throw new TypeError("The repository did not return a valid releases page.");
|
||||
}
|
||||
}
|
||||
|
||||
function addUniqueReleaseIds(items: ReadonlyArray<unknown>, releaseIds: Set<number>): void {
|
||||
for (const item of items) {
|
||||
if (!isRecord(item) || !isPositiveSafeInteger(item.id)) continue;
|
||||
if (releaseIds.has(item.id)) {
|
||||
throw new TypeError("The repository returned a duplicate release ID during pagination.");
|
||||
}
|
||||
releaseIds.add(item.id);
|
||||
}
|
||||
}
|
||||
|
||||
async function readExactReleasePage(
|
||||
pageUrl: string,
|
||||
expectedLength: number,
|
||||
expectedTotalCount: number,
|
||||
fetchReleasePage: AndroidApkUpdateDependencies["fetchReleasePage"],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyArray<unknown>> {
|
||||
const response = await fetchReleasePage(pageUrl, {
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
signal,
|
||||
});
|
||||
validateExactResponseUrl(response, pageUrl, "release API");
|
||||
if (!response.ok) throw new Error(`Release API returned HTTP ${response.status}.`);
|
||||
const totalCount = parseTotalCount(response.headers.get("X-Total-Count"));
|
||||
if (totalCount !== expectedTotalCount) {
|
||||
throw new TypeError("The repository release total changed during pagination.");
|
||||
}
|
||||
const items = await response.json();
|
||||
validatePageItems(items, expectedLength);
|
||||
return items;
|
||||
}
|
||||
|
||||
async function fetchAllGiteaReleases(
|
||||
apiUrl: string,
|
||||
fetchReleasePage: AndroidApkUpdateDependencies["fetchReleasePage"],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyArray<unknown>> {
|
||||
const firstUrl = giteaReleasePageUrl(apiUrl, 1);
|
||||
const firstResponse = await fetchReleasePage(firstUrl, {
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
signal,
|
||||
});
|
||||
validateExactResponseUrl(firstResponse, firstUrl, "release API");
|
||||
if (!firstResponse.ok) throw new Error(`Release API returned HTTP ${firstResponse.status}.`);
|
||||
const totalCount = parseTotalCount(firstResponse.headers.get("X-Total-Count"));
|
||||
const firstItems = await firstResponse.json();
|
||||
validatePageItems(firstItems, Math.min(GITEA_RELEASE_PAGE_SIZE, totalCount));
|
||||
|
||||
const releaseIds = new Set<number>();
|
||||
addUniqueReleaseIds(firstItems, releaseIds);
|
||||
const releases = [...firstItems];
|
||||
const pageCount = Math.ceil(totalCount / GITEA_RELEASE_PAGE_SIZE);
|
||||
for (let page = 2; page <= pageCount; page += 1) {
|
||||
const offset = (page - 1) * GITEA_RELEASE_PAGE_SIZE;
|
||||
const expectedLength = Math.min(GITEA_RELEASE_PAGE_SIZE, totalCount - offset);
|
||||
const items = await readExactReleasePage(
|
||||
giteaReleasePageUrl(apiUrl, page),
|
||||
expectedLength,
|
||||
totalCount,
|
||||
fetchReleasePage,
|
||||
signal,
|
||||
);
|
||||
addUniqueReleaseIds(items, releaseIds);
|
||||
releases.push(...items);
|
||||
}
|
||||
if (releases.length !== totalCount) {
|
||||
throw new TypeError("The repository release total changed during pagination.");
|
||||
}
|
||||
return releases;
|
||||
}
|
||||
|
||||
async function withAbortDeadline<T>(
|
||||
milliseconds: number,
|
||||
label: string,
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(new Error(`${label} timed out.`)),
|
||||
milliseconds,
|
||||
);
|
||||
try {
|
||||
return await operation(controller.signal);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function parseContentLength(value: string | null, expectedSize: number): void {
|
||||
if (value === null) return;
|
||||
if (!/^(0|[1-9]\d*)$/.test(value)) {
|
||||
throw new Error("The APK download returned an invalid Content-Length.");
|
||||
}
|
||||
const contentLength = Number(value);
|
||||
if (!Number.isSafeInteger(contentLength) || contentLength > MAX_ANDROID_APK_BYTES) {
|
||||
throw new Error("The APK download is larger than the allowed maximum size.");
|
||||
}
|
||||
if (contentLength !== expectedSize) {
|
||||
throw new Error("The APK download Content-Length does not match its trusted asset size.");
|
||||
}
|
||||
}
|
||||
|
||||
async function streamExactApkBytes(
|
||||
body: ReadableStream<Uint8Array>,
|
||||
destination: WritableStream<Uint8Array>,
|
||||
expectedSize: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
let streamedBytes = 0;
|
||||
const byteCounter = new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
if (!(chunk instanceof Uint8Array)) {
|
||||
throw new TypeError("The APK download returned a non-byte stream.");
|
||||
}
|
||||
streamedBytes += chunk.byteLength;
|
||||
if (streamedBytes > expectedSize || streamedBytes > MAX_ANDROID_APK_BYTES) {
|
||||
throw new Error("The APK download exceeded its trusted asset size.");
|
||||
}
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
await body.pipeThrough(byteCounter, { signal }).pipeTo(destination, { signal });
|
||||
if (streamedBytes !== expectedSize) {
|
||||
throw new Error("The APK download byte count does not match its trusted asset size.");
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadTrustedAndroidApk(
|
||||
downloadUrl: string,
|
||||
versionCode: number,
|
||||
expectedSize: number,
|
||||
dependencies: AndroidApkDownloadDependencies,
|
||||
): Promise<string> {
|
||||
if (!validVersionCode(versionCode)) throw new Error("The candidate version code is invalid.");
|
||||
if (!validApkSize(expectedSize)) throw new Error("The trusted APK asset size is invalid.");
|
||||
trustedHttpsUrl(downloadUrl, "asset");
|
||||
|
||||
return withAbortDeadline(DOWNLOAD_TIMEOUT_MS, "APK download", async (signal) => {
|
||||
const response = await dependencies.fetchApk(downloadUrl, {
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
signal,
|
||||
});
|
||||
validateExactResponseUrl(response, downloadUrl, "APK download");
|
||||
if (!response.ok) throw new Error(`The APK download returned HTTP ${response.status}.`);
|
||||
parseContentLength(response.headers.get("Content-Length"), expectedSize);
|
||||
if (response.body === null)
|
||||
throw new Error("The APK download returned an empty response body.");
|
||||
|
||||
const temporaryFile = dependencies.createTemporaryFile(versionCode);
|
||||
try {
|
||||
await streamExactApkBytes(
|
||||
response.body,
|
||||
dependencies.openTemporaryFileStream(temporaryFile),
|
||||
expectedSize,
|
||||
signal,
|
||||
);
|
||||
const localUri = await dependencies.finalizeTemporaryFile(temporaryFile, versionCode);
|
||||
dependencies.pruneObsoleteFiles(versionCode);
|
||||
return localUri;
|
||||
} catch (cause) {
|
||||
try {
|
||||
dependencies.deleteTemporaryFile(temporaryFile);
|
||||
} catch {
|
||||
// The original download failure is more useful than best-effort cache cleanup failure.
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function selectLatestAndroidApkRelease(
|
||||
releases: unknown,
|
||||
apiUrl: string,
|
||||
): AndroidApkRelease | null {
|
||||
giteaServerBase(apiUrl);
|
||||
if (!Array.isArray(releases)) return null;
|
||||
|
||||
let latest: AndroidApkRelease | null = null;
|
||||
for (const release of releases) {
|
||||
if (
|
||||
!isRecord(release) ||
|
||||
!isPositiveSafeInteger(release.id) ||
|
||||
release.draft !== false ||
|
||||
release.prerelease !== false
|
||||
)
|
||||
continue;
|
||||
const versionCode = parseVersionCode(release.tag_name);
|
||||
if (
|
||||
versionCode === null ||
|
||||
release.name !== `Android APK · build ${versionCode}` ||
|
||||
!Array.isArray(release.assets)
|
||||
)
|
||||
continue;
|
||||
const expectedAssetName = `t3code-apk-${versionCode}.apk`;
|
||||
let candidate: AndroidApkRelease | null = null;
|
||||
for (const asset of release.assets) {
|
||||
if (
|
||||
!isRecord(asset) ||
|
||||
!isPositiveSafeInteger(asset.id) ||
|
||||
!validApkSize(asset.size) ||
|
||||
asset.name !== expectedAssetName
|
||||
)
|
||||
continue;
|
||||
const downloadUrl = trustedAssetUrl(
|
||||
asset.browser_download_url,
|
||||
apiUrl,
|
||||
release.tag_name,
|
||||
expectedAssetName,
|
||||
);
|
||||
if (!downloadUrl) continue;
|
||||
candidate = { versionCode, downloadUrl, expectedSize: asset.size };
|
||||
break;
|
||||
}
|
||||
if (!candidate || (latest && latest.versionCode >= versionCode)) continue;
|
||||
latest = candidate;
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export function isNewerAndroidVersion(candidate: number, installed: number): boolean {
|
||||
if (!validVersionCode(installed)) {
|
||||
throw new Error("The installed version code is unavailable or invalid.");
|
||||
}
|
||||
if (!validVersionCode(candidate)) {
|
||||
throw new Error("The candidate version code is invalid.");
|
||||
}
|
||||
return candidate > installed;
|
||||
}
|
||||
|
||||
export async function runAndroidApkUpdate(
|
||||
dependencies: AndroidApkUpdateDependencies,
|
||||
): Promise<AndroidApkUpdateResult> {
|
||||
if (androidApkUpdateInProgress) return { kind: "already-in-progress" };
|
||||
androidApkUpdateInProgress = true;
|
||||
try {
|
||||
return await runCoordinatedAndroidApkUpdate(dependencies);
|
||||
} finally {
|
||||
androidApkUpdateInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function runCoordinatedAndroidApkUpdate({
|
||||
apiUrl,
|
||||
getInstalledVersionCode,
|
||||
fetchReleasePage,
|
||||
downloadApk,
|
||||
installApk,
|
||||
onPhase,
|
||||
}: AndroidApkUpdateDependencies): Promise<
|
||||
Exclude<AndroidApkUpdateResult, { kind: "already-in-progress" }>
|
||||
> {
|
||||
let latest: AndroidApkRelease | null;
|
||||
let installedVersionCode: number;
|
||||
try {
|
||||
onPhase?.("checking");
|
||||
giteaServerBase(apiUrl);
|
||||
installedVersionCode = await getInstalledVersionCode();
|
||||
if (!validVersionCode(installedVersionCode)) {
|
||||
throw new Error("The installed version code is unavailable or invalid.");
|
||||
}
|
||||
const releases = await withAbortDeadline(API_TIMEOUT_MS, "Release check", (signal) =>
|
||||
fetchAllGiteaReleases(apiUrl, fetchReleasePage, signal),
|
||||
);
|
||||
latest = selectLatestAndroidApkRelease(releases, apiUrl);
|
||||
if (latest && !isNewerAndroidVersion(latest.versionCode, installedVersionCode)) {
|
||||
return {
|
||||
kind: "up-to-date",
|
||||
installedVersionCode,
|
||||
latestVersionCode: latest.versionCode,
|
||||
};
|
||||
}
|
||||
} catch (cause) {
|
||||
const userMessage =
|
||||
cause instanceof TypeError && /valid releases (page|list)/.test(cause.message)
|
||||
? "The repository did not return a valid releases list. Try again later."
|
||||
: "Could not check for updates. Check your connection and try again.";
|
||||
throw new AndroidApkUpdateError("check", userMessage, cause);
|
||||
}
|
||||
|
||||
if (!latest) return { kind: "no-compatible-release" };
|
||||
|
||||
let localUri: string;
|
||||
try {
|
||||
onPhase?.("downloading");
|
||||
localUri = await downloadApk(latest.downloadUrl, latest.versionCode, latest.expectedSize);
|
||||
} catch (cause) {
|
||||
throw new AndroidApkUpdateError(
|
||||
"download",
|
||||
"Could not download the update. Check your connection and available storage, then try again.",
|
||||
cause,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
onPhase?.("installing");
|
||||
await installApk(localUri, latest.versionCode);
|
||||
} catch (cause) {
|
||||
throw new AndroidApkUpdateError(
|
||||
"install",
|
||||
"Could not open Android’s package installer. Allow T3 Code to install unknown apps if Android asks, then try again.",
|
||||
cause,
|
||||
);
|
||||
}
|
||||
|
||||
return { kind: "installer-launched", versionCode: latest.versionCode };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export type SettingsSheetTarget =
|
||||
| "SettingsEnvironments"
|
||||
| "SettingsProviders"
|
||||
| "SettingsHermes"
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceConfig,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
addProviderCustomModel,
|
||||
buildMobileProviderInstancePatch,
|
||||
createHermesProviderInstance,
|
||||
deriveMobileProviderSettingsRows,
|
||||
HERMES_DEFAULT_INSTANCE_ID,
|
||||
readProviderCustomModels,
|
||||
readProviderEnvironmentVariable,
|
||||
removeProviderCustomModel,
|
||||
} from "./mobile-provider-settings";
|
||||
|
||||
const hermesProvider = {
|
||||
instanceId: HERMES_DEFAULT_INSTANCE_ID,
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
enabled: false,
|
||||
} as ServerProvider;
|
||||
|
||||
describe("mobile provider settings", () => {
|
||||
it("surfaces the default Hermes provider even before a live probe appears", () => {
|
||||
const rows = deriveMobileProviderSettingsRows(DEFAULT_SERVER_SETTINGS, []);
|
||||
expect(rows[0]?.instanceId).toBe(HERMES_DEFAULT_INSTANCE_ID);
|
||||
expect(rows[0]?.instance.enabled).toBe(false);
|
||||
});
|
||||
|
||||
it("resolves a live Hermes provider through its legacy settings", () => {
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
hermes: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.hermes,
|
||||
enabled: true,
|
||||
binaryPath: "/opt/hermes/bin/hermes",
|
||||
},
|
||||
},
|
||||
};
|
||||
const row = deriveMobileProviderSettingsRows(settings, [hermesProvider])[0];
|
||||
expect(row?.instance).toMatchObject({
|
||||
driver: "hermes",
|
||||
enabled: true,
|
||||
config: { binaryPath: "/opt/hermes/bin/hermes" },
|
||||
});
|
||||
});
|
||||
|
||||
it("promotes default-provider edits into the instance map", () => {
|
||||
const instance = {
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
enabled: true,
|
||||
config: { binaryPath: "/usr/local/bin/hermes" },
|
||||
} satisfies ProviderInstanceConfig;
|
||||
const patch = buildMobileProviderInstancePatch({
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
row: { instanceId: HERMES_DEFAULT_INSTANCE_ID, isDefault: true },
|
||||
instance,
|
||||
});
|
||||
expect(patch.providerInstances?.[HERMES_DEFAULT_INSTANCE_ID]).toEqual(instance);
|
||||
expect(patch.providers?.hermes).toEqual(DEFAULT_SERVER_SETTINGS.providers.hermes);
|
||||
});
|
||||
|
||||
it("adds, deduplicates, and removes custom model IDs", () => {
|
||||
const instance = {
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
enabled: true,
|
||||
} satisfies ProviderInstanceConfig;
|
||||
const added = addProviderCustomModel(instance, " anthropic/claude-new ");
|
||||
expect(added.ok).toBe(true);
|
||||
if (!added.ok) return;
|
||||
expect(readProviderCustomModels(added.instance).map((model) => model.slug)).toEqual([
|
||||
"anthropic/claude-new",
|
||||
]);
|
||||
expect(addProviderCustomModel(added.instance, "anthropic/claude-new")).toEqual({
|
||||
ok: false,
|
||||
message: "That custom model is already saved.",
|
||||
});
|
||||
expect(
|
||||
readProviderCustomModels(removeProviderCustomModel(added.instance, "anthropic/claude-new")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("creates uniquely named Hermes instances with their own profile", () => {
|
||||
const existingId = ProviderInstanceId.make("hermes_work");
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[existingId]: {
|
||||
driver: ProviderDriverKind.make("hermes"),
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
const created = createHermesProviderInstance({
|
||||
settings,
|
||||
label: "Work",
|
||||
binaryPath: "/opt/hermes",
|
||||
hermesHome: "/srv/hermes-work",
|
||||
});
|
||||
expect(created.instanceId).toBe("hermes_work_2");
|
||||
expect(created.instance.config).toEqual({ binaryPath: "/opt/hermes" });
|
||||
expect(readProviderEnvironmentVariable(created.instance, "HERMES_HOME")).toBe(
|
||||
"/srv/hermes-work",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceConfig,
|
||||
type ServerProvider,
|
||||
type ServerSettings,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
normalizeCustomModelSlug,
|
||||
readCustomModelEntries,
|
||||
toCustomModelSetting,
|
||||
type CustomModelDefinition,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
export const HERMES_DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
export const HERMES_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(HERMES_DRIVER_KIND);
|
||||
export const MAX_MOBILE_CUSTOM_MODEL_LENGTH = 256;
|
||||
|
||||
export interface MobileProviderSettingsRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
readonly liveProvider?: ServerProvider | undefined;
|
||||
readonly isDefault: boolean;
|
||||
}
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
function legacyProviderSettings(
|
||||
settings: ServerSettings,
|
||||
driver: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined {
|
||||
return (settings.providers as Record<string, LegacyProviderSettings | undefined>)[driver];
|
||||
}
|
||||
|
||||
function instanceFromLegacySettings(
|
||||
settings: ServerSettings,
|
||||
driver: ProviderDriverKind,
|
||||
fallbackEnabled: boolean,
|
||||
): ProviderInstanceConfig {
|
||||
const legacy = legacyProviderSettings(settings, driver);
|
||||
if (legacy === undefined) {
|
||||
return { driver, enabled: fallbackEnabled };
|
||||
}
|
||||
const { enabled, ...config } = legacy;
|
||||
return {
|
||||
driver,
|
||||
enabled: typeof enabled === "boolean" ? enabled : fallbackEnabled,
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveMobileProviderInstance(
|
||||
settings: ServerSettings,
|
||||
provider: Pick<ServerProvider, "driver" | "enabled" | "instanceId">,
|
||||
): ProviderInstanceConfig {
|
||||
const explicit = settings.providerInstances[provider.instanceId];
|
||||
if (explicit !== undefined) return explicit;
|
||||
if (provider.instanceId === defaultInstanceIdForDriver(provider.driver)) {
|
||||
return instanceFromLegacySettings(settings, provider.driver, provider.enabled);
|
||||
}
|
||||
return { driver: provider.driver, enabled: provider.enabled };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile starts from live provider snapshots, then fills settings-only instances
|
||||
* while provider reconciliation catches up. Hermes is always present on a
|
||||
* Hermes-capable server even while its default-off probe has no live row yet.
|
||||
*/
|
||||
export function deriveMobileProviderSettingsRows(
|
||||
settings: ServerSettings,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<MobileProviderSettingsRow> {
|
||||
const rows = new Map<ProviderInstanceId, MobileProviderSettingsRow>();
|
||||
for (const provider of providers) {
|
||||
rows.set(provider.instanceId, {
|
||||
instanceId: provider.instanceId,
|
||||
instance: resolveMobileProviderInstance(settings, provider),
|
||||
liveProvider: provider,
|
||||
isDefault: provider.instanceId === defaultInstanceIdForDriver(provider.driver),
|
||||
});
|
||||
}
|
||||
for (const [rawInstanceId, instance] of Object.entries(settings.providerInstances)) {
|
||||
const instanceId = ProviderInstanceId.make(rawInstanceId);
|
||||
if (rows.has(instanceId)) continue;
|
||||
rows.set(instanceId, {
|
||||
instanceId,
|
||||
instance,
|
||||
isDefault: instanceId === defaultInstanceIdForDriver(instance.driver),
|
||||
});
|
||||
}
|
||||
if (!rows.has(HERMES_DEFAULT_INSTANCE_ID)) {
|
||||
rows.set(HERMES_DEFAULT_INSTANCE_ID, {
|
||||
instanceId: HERMES_DEFAULT_INSTANCE_ID,
|
||||
instance: instanceFromLegacySettings(settings, HERMES_DRIVER_KIND, false),
|
||||
isDefault: true,
|
||||
});
|
||||
}
|
||||
return [...rows.values()].sort((left, right) => {
|
||||
const leftHermes = left.instance.driver === HERMES_DRIVER_KIND ? 0 : 1;
|
||||
const rightHermes = right.instance.driver === HERMES_DRIVER_KIND ? 0 : 1;
|
||||
if (leftHermes !== rightHermes) return leftHermes - rightHermes;
|
||||
if (left.isDefault !== right.isDefault) return left.isDefault ? -1 : 1;
|
||||
return String(left.instanceId).localeCompare(String(right.instanceId));
|
||||
});
|
||||
}
|
||||
|
||||
export function buildMobileProviderInstancePatch(input: {
|
||||
readonly settings: ServerSettings;
|
||||
readonly row: Pick<MobileProviderSettingsRow, "instanceId" | "isDefault">;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
}): ServerSettingsPatch {
|
||||
const driver = input.instance.driver;
|
||||
const defaultLegacy = legacyProviderSettings(DEFAULT_SERVER_SETTINGS, driver);
|
||||
return {
|
||||
...(input.row.isDefault && defaultLegacy !== undefined
|
||||
? {
|
||||
providers: {
|
||||
...input.settings.providers,
|
||||
[driver]: defaultLegacy,
|
||||
} as ServerSettings["providers"],
|
||||
}
|
||||
: {}),
|
||||
providerInstances: {
|
||||
...input.settings.providerInstances,
|
||||
[input.row.instanceId]: input.instance,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function configRecord(config: unknown): Record<string, unknown> {
|
||||
return config !== null && typeof config === "object" && !Array.isArray(config)
|
||||
? { ...(config as Record<string, unknown>) }
|
||||
: {};
|
||||
}
|
||||
|
||||
export function readProviderCustomModels(
|
||||
instance: Pick<ProviderInstanceConfig, "config">,
|
||||
): ReadonlyArray<CustomModelDefinition> {
|
||||
return readCustomModelEntries(configRecord(instance.config).customModels);
|
||||
}
|
||||
|
||||
function withCustomModels(
|
||||
instance: ProviderInstanceConfig,
|
||||
customModels: ReadonlyArray<CustomModelDefinition>,
|
||||
): ProviderInstanceConfig {
|
||||
return {
|
||||
...instance,
|
||||
config: {
|
||||
...configRecord(instance.config),
|
||||
customModels: customModels.map(toCustomModelSetting),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function addProviderCustomModel(
|
||||
instance: ProviderInstanceConfig,
|
||||
input: string,
|
||||
):
|
||||
| { readonly ok: true; readonly instance: ProviderInstanceConfig }
|
||||
| { readonly ok: false; readonly message: string } {
|
||||
const slug = normalizeCustomModelSlug(input);
|
||||
if (!slug) return { ok: false, message: "Enter a model ID." };
|
||||
if (slug.length > MAX_MOBILE_CUSTOM_MODEL_LENGTH) {
|
||||
return {
|
||||
ok: false,
|
||||
message: `Model IDs must be ${MAX_MOBILE_CUSTOM_MODEL_LENGTH} characters or less.`,
|
||||
};
|
||||
}
|
||||
const customModels = readProviderCustomModels(instance);
|
||||
if (customModels.some((model) => model.slug === slug)) {
|
||||
return { ok: false, message: "That custom model is already saved." };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
instance: withCustomModels(instance, [
|
||||
...customModels,
|
||||
{ slug, name: slug, capabilities: null },
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
export function removeProviderCustomModel(
|
||||
instance: ProviderInstanceConfig,
|
||||
slug: string,
|
||||
): ProviderInstanceConfig {
|
||||
return withCustomModels(
|
||||
instance,
|
||||
readProviderCustomModels(instance).filter((model) => model.slug !== slug),
|
||||
);
|
||||
}
|
||||
|
||||
export function updateProviderConfigString(
|
||||
instance: ProviderInstanceConfig,
|
||||
key: string,
|
||||
value: string,
|
||||
): ProviderInstanceConfig {
|
||||
const config = configRecord(instance.config);
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
delete config[key];
|
||||
} else {
|
||||
config[key] = trimmed;
|
||||
}
|
||||
const { config: _config, ...rest } = instance;
|
||||
return Object.keys(config).length > 0 ? { ...rest, config } : rest;
|
||||
}
|
||||
|
||||
export function readProviderConfigString(
|
||||
instance: Pick<ProviderInstanceConfig, "config">,
|
||||
key: string,
|
||||
): string {
|
||||
const value = configRecord(instance.config)[key];
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
export function readProviderEnvironmentVariable(
|
||||
instance: Pick<ProviderInstanceConfig, "environment">,
|
||||
name: string,
|
||||
): string {
|
||||
return instance.environment?.find((variable) => variable.name === name)?.value ?? "";
|
||||
}
|
||||
|
||||
export function updateProviderEnvironmentVariable(
|
||||
instance: ProviderInstanceConfig,
|
||||
name: string,
|
||||
value: string,
|
||||
): ProviderInstanceConfig {
|
||||
const trimmed = value.trim();
|
||||
const environment = (instance.environment ?? []).filter((variable) => variable.name !== name);
|
||||
if (trimmed.length > 0) {
|
||||
environment.push({ name, value: trimmed, sensitive: false, valueRedacted: false });
|
||||
}
|
||||
const { environment: _environment, ...rest } = instance;
|
||||
return environment.length > 0 ? { ...rest, environment } : rest;
|
||||
}
|
||||
|
||||
function normalizedInstanceSuffix(label: string): string {
|
||||
return (
|
||||
label
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/g, "_")
|
||||
.replace(/^[_-]+|[_-]+$/g, "") || "mobile"
|
||||
);
|
||||
}
|
||||
|
||||
export function createHermesProviderInstance(input: {
|
||||
readonly settings: ServerSettings;
|
||||
readonly label: string;
|
||||
readonly binaryPath: string;
|
||||
readonly hermesHome: string;
|
||||
}): { readonly instanceId: ProviderInstanceId; readonly instance: ProviderInstanceConfig } {
|
||||
const suffix = normalizedInstanceSuffix(input.label);
|
||||
const base = `hermes_${suffix}`.slice(0, 61).replace(/[_-]+$/g, "") || "hermes_mobile";
|
||||
let candidate = base;
|
||||
let counter = 2;
|
||||
while (Object.hasOwn(input.settings.providerInstances, candidate)) {
|
||||
const counterSuffix = `_${counter++}`;
|
||||
candidate = `${base.slice(0, 64 - counterSuffix.length)}${counterSuffix}`;
|
||||
}
|
||||
let instance: ProviderInstanceConfig = {
|
||||
driver: HERMES_DRIVER_KIND,
|
||||
displayName: input.label.trim() || "Hermes Agent",
|
||||
enabled: true,
|
||||
};
|
||||
instance = updateProviderConfigString(instance, "binaryPath", input.binaryPath);
|
||||
instance = updateProviderEnvironmentVariable(instance, "HERMES_HOME", input.hermesHome);
|
||||
return { instanceId: ProviderInstanceId.make(candidate), instance };
|
||||
}
|
||||
@@ -100,6 +100,7 @@ type SidebarListItem =
|
||||
const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
|
||||
|
||||
interface ThreadNavigationSidebarProps {
|
||||
readonly topInset?: number;
|
||||
readonly width: number;
|
||||
readonly visible: boolean;
|
||||
readonly selectedThreadKey: string | null;
|
||||
@@ -152,6 +153,7 @@ function ThreadNavigationSidebarPane(
|
||||
const mutedColor = materialTheme["--color-foreground-muted"];
|
||||
|
||||
const insets = useSafeAreaInsets();
|
||||
const topInset = props.topInset ?? insets.top;
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
|
||||
@@ -748,7 +750,7 @@ function ThreadNavigationSidebarPane(
|
||||
// The sticky header (title row, search field, optional connection status)
|
||||
// is measured so the list inset always matches its real height — no
|
||||
// hardcoded per-variant constants.
|
||||
const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
|
||||
const stickyHeaderHeight = measuredHeaderHeight ?? topInset + SIDEBAR_STICKY_HEADER_HEIGHT;
|
||||
const topListInset = stickyHeaderHeight + 6;
|
||||
const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
@@ -1309,7 +1311,7 @@ function ThreadNavigationSidebarPane(
|
||||
collapsable={false}
|
||||
onLayout={handleStickyHeaderLayout}
|
||||
pointerEvents="auto"
|
||||
style={{ paddingTop: insets.top }}
|
||||
style={{ paddingTop: topInset }}
|
||||
>
|
||||
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
|
||||
{/* Title slot doubles as the connection status surface: while an
|
||||
|
||||
@@ -35,11 +35,13 @@ describe("fileChipMenu", () => {
|
||||
actions: [
|
||||
{ id: "copy-full-path", title: "Copy full path" },
|
||||
{ id: "open-file", title: "Open in file viewer" },
|
||||
{ id: "save", title: "Download file" },
|
||||
],
|
||||
});
|
||||
expect(fileChipMenu({ relativePath: "src/app.ts" }).actions.map(({ id }) => id)).toEqual([
|
||||
"copy-relative-path",
|
||||
"open-file",
|
||||
"save",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -60,12 +62,12 @@ describe("file chip downloads", () => {
|
||||
const target = resolveFileChipTarget(href, "/repo")!;
|
||||
expect(fileChipMenu(target).actions).toContainEqual({
|
||||
id: "save",
|
||||
title: "Save or share",
|
||||
title: "Download file",
|
||||
});
|
||||
expect(fileChipShareSource(target, threadId)).toEqual({
|
||||
name: path.split("/").at(-1),
|
||||
mimeType,
|
||||
resource: { _tag: "media-file", threadId, path },
|
||||
resource: { _tag: "media-file", threadId, path, download: true },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -77,11 +79,14 @@ describe("file chip downloads", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not offer downloads the host asset endpoint cannot serve", () => {
|
||||
for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt"]) {
|
||||
it("offers explicit downloads for source files and unsupported binary formats", () => {
|
||||
for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt", "/tmp/app.apk"]) {
|
||||
const target = resolveFileChipTarget(href, "/repo")!;
|
||||
expect(fileChipShareSource(target, threadId)).toBeNull();
|
||||
expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(false);
|
||||
expect(fileChipShareSource(target, threadId)).toMatchObject({
|
||||
mimeType: "application/octet-stream",
|
||||
resource: { download: true, threadId },
|
||||
});
|
||||
expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -44,8 +44,10 @@ function fileChipMetadata(target: FileChipTarget) {
|
||||
if (!path) return null;
|
||||
const name = fileBasename(path);
|
||||
const dot = name.lastIndexOf(".");
|
||||
const mimeType = dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot));
|
||||
return mimeType ? { path, name, mimeType } : null;
|
||||
const mimeType =
|
||||
(dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot))) ??
|
||||
"application/octet-stream";
|
||||
return { path, name, mimeType };
|
||||
}
|
||||
|
||||
/** Use literal resolved paths so encoded filename characters are not decoded twice. */
|
||||
@@ -55,12 +57,11 @@ export function fileChipShareSource(target: FileChipTarget, threadId: ThreadId)
|
||||
? {
|
||||
name: metadata.name,
|
||||
mimeType: metadata.mimeType,
|
||||
resource: { _tag: "media-file" as const, threadId, path: metadata.path },
|
||||
resource: { _tag: "media-file" as const, threadId, path: metadata.path, download: true },
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Saving is available for the media and documents the host asset endpoint can serve. */
|
||||
export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu {
|
||||
return {
|
||||
title: target.fullPath ?? target.relativePath ?? "",
|
||||
@@ -72,7 +73,7 @@ export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu {
|
||||
? [
|
||||
{
|
||||
id: "save",
|
||||
title: "Save or share",
|
||||
title: "Download file",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import { Alert } from "react-native";
|
||||
@@ -16,6 +16,17 @@ export function useFileChipShare(
|
||||
threadId: ThreadId,
|
||||
sourceIdentifier: string,
|
||||
) {
|
||||
const download = useFileDownload(environmentId, sourceIdentifier);
|
||||
return useCallback(
|
||||
(target: FileChipTarget) => {
|
||||
const source = fileChipShareSource(target, threadId);
|
||||
if (source) download(source);
|
||||
},
|
||||
[download, threadId],
|
||||
);
|
||||
}
|
||||
|
||||
export function useFileDownload(environmentId: EnvironmentId | null, sourceIdentifier: string) {
|
||||
const connection = usePreparedConnection(environmentId);
|
||||
const httpBaseUrl = Option.isSome(connection) ? connection.value.httpBaseUrl : null;
|
||||
const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
|
||||
@@ -30,9 +41,8 @@ export function useFileChipShare(
|
||||
useEffect(() => () => requestRef.current?.abort(), []);
|
||||
|
||||
const share = useCallback(
|
||||
(target: FileChipTarget) => {
|
||||
const source = fileChipShareSource(target, threadId);
|
||||
if (!source || requestRef.current) return;
|
||||
(source: { name: string; mimeType: string; resource: AssetResource }) => {
|
||||
if (environmentId === null || requestRef.current) return;
|
||||
const request = new AbortController();
|
||||
requestRef.current = request;
|
||||
const httpBaseUrl = connectionRef.current;
|
||||
@@ -53,7 +63,7 @@ export function useFileChipShare(
|
||||
.catch((error: unknown) => {
|
||||
if (!request.signal.aborted) {
|
||||
Alert.alert(
|
||||
"Could not share file",
|
||||
"Could not download file",
|
||||
error instanceof Error ? error.message : "Try again.",
|
||||
);
|
||||
}
|
||||
@@ -64,7 +74,7 @@ export function useFileChipShare(
|
||||
}
|
||||
});
|
||||
},
|
||||
[createUrl, environmentId, sourceIdentifier, threadId],
|
||||
[createUrl, environmentId, sourceIdentifier],
|
||||
);
|
||||
return share;
|
||||
}
|
||||
@@ -891,6 +891,125 @@ describe("buildThreadFeed", () => {
|
||||
expect(group.activities[0]?.getFullDetail()).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps Hermes ACP tool inputs and outputs expandable on mobile", () => {
|
||||
const toolData = {
|
||||
toolCallId: "tool-read-file",
|
||||
kind: "other",
|
||||
rawInput: { path: "/workspace/package.json", offset: 1, limit: 80 },
|
||||
rawOutput: { content: '{"name":"example"}' },
|
||||
};
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-hermes-tool-details"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Hermes tool details",
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("hermes-tool-details"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read file",
|
||||
createdAt: "2026-09-01T00:00:00.000Z",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Read file",
|
||||
status: "completed",
|
||||
data: toolData,
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const [group] = buildThreadFeed(thread);
|
||||
expect(group?.type).toBe("activity-group");
|
||||
if (group?.type !== "activity-group") return;
|
||||
const [row] = group.activities;
|
||||
expect(row?.canExpand).toBe(true);
|
||||
expect(row?.workEntry.toolData).toBe(toolData);
|
||||
expect(row?.getFullDetail()).toBe(`Tool call\n${JSON.stringify(toolData, null, 2)}`);
|
||||
});
|
||||
|
||||
it("shows the exact Hermes ACP command payload in expanded mobile rows", () => {
|
||||
const command = "pnpm test --filter mobile";
|
||||
const toolData = {
|
||||
toolCallId: "tool-run-tests",
|
||||
kind: "execute",
|
||||
command,
|
||||
rawInput: { executable: "pnpm", args: ["test", "--filter", "mobile"] },
|
||||
rawOutput: { stdout: "102 tests passed", exitCode: 0 },
|
||||
};
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-hermes-command-details"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Hermes command details",
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("hermes-command-details"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-09-01T00:00:00.000Z",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Ran command",
|
||||
status: "completed",
|
||||
data: toolData,
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const [group] = buildThreadFeed(thread);
|
||||
expect(group?.type).toBe("activity-group");
|
||||
if (group?.type !== "activity-group") return;
|
||||
const [row] = group.activities;
|
||||
expect(row?.workEntry.toolData).toBe(toolData);
|
||||
expect(row?.getFullDetail()).toBe(
|
||||
[`Tool call\n${JSON.stringify(toolData, null, 2)}`, command, "102 tests passed"].join("\n\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["file_change", "web_search"] as const)(
|
||||
"keeps Hermes ACP %s payloads expandable on mobile",
|
||||
(itemType) => {
|
||||
const toolData = {
|
||||
toolCallId: `tool-${itemType}`,
|
||||
kind: itemType === "file_change" ? "edit" : "search",
|
||||
rawInput:
|
||||
itemType === "file_change"
|
||||
? { path: "/workspace/src/app.ts", patch: "@@ -1 +1 @@" }
|
||||
: { query: "React Native expandable rows" },
|
||||
rawOutput: { content: "completed" },
|
||||
};
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make(`thread-hermes-${itemType}-details`),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Hermes tool details",
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make(`hermes-${itemType}-details`),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Tool completed",
|
||||
createdAt: "2026-09-01T00:00:00.000Z",
|
||||
payload: {
|
||||
itemType,
|
||||
title: "Tool completed",
|
||||
status: "completed",
|
||||
data: toolData,
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const [group] = buildThreadFeed(thread);
|
||||
expect(group?.type).toBe("activity-group");
|
||||
if (group?.type !== "activity-group") return;
|
||||
const [row] = group.activities;
|
||||
expect(row?.canExpand).toBe(true);
|
||||
expect(row?.getFullDetail()).toBe(`Tool call\n${JSON.stringify(toolData, null, 2)}`);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps setup failures visible without routine setup notices before or after a turn", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-worktree-setup"),
|
||||
|
||||
@@ -578,12 +578,9 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
if (toolPresentation.toolSource) {
|
||||
entry.toolSource = toolPresentation.toolSource;
|
||||
}
|
||||
if (itemType === "mcp_tool_call") {
|
||||
const data = asRecord(payload?.data);
|
||||
const toolData = typeof data?.toolName === "string" ? (data.item ?? data) : data?.item;
|
||||
if (toolData !== undefined) {
|
||||
entry.toolData = toolData;
|
||||
}
|
||||
const toolData = extractWorkLogToolData(itemType, payload);
|
||||
if (toolData !== undefined) {
|
||||
entry.toolData = toolData;
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
@@ -966,6 +963,21 @@ function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
|
||||
return "zap";
|
||||
}
|
||||
|
||||
function extractWorkLogToolData(
|
||||
itemType: WorkLogEntry["itemType"],
|
||||
payload: Record<string, unknown> | null,
|
||||
): unknown {
|
||||
const data = asRecord(payload?.data);
|
||||
if (!data) return undefined;
|
||||
if (itemType === "mcp_tool_call") {
|
||||
return typeof data.toolName === "string" ? (data.item ?? data) : data.item;
|
||||
}
|
||||
const isAcpToolCall =
|
||||
typeof data.toolCallId === "string" &&
|
||||
("rawInput" in data || "rawOutput" in data || "content" in data || "locations" in data);
|
||||
return isAcpToolCall ? data : undefined;
|
||||
}
|
||||
|
||||
function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
|
||||
if (entry.agentSpawn) return agentSpawnExpandedBody(entry.agentSpawn);
|
||||
const blocks: string[] = [];
|
||||
@@ -979,6 +991,8 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
|
||||
|
||||
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
|
||||
appendBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
|
||||
} else if (entry.toolData !== undefined) {
|
||||
appendBlock(`Tool call\n${JSON.stringify(entry.toolData, null, 2)}`);
|
||||
}
|
||||
appendBlock(entry.rawCommand ?? entry.command);
|
||||
appendBlock(entry.detail);
|
||||
@@ -997,7 +1011,7 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
|
||||
function workEntryCanExpand(entry: WorkLogEntry): boolean {
|
||||
if (entry.questionAnswer) return true;
|
||||
if (entry.agentSpawn) return agentSpawnMembers(entry.agentSpawn).length > 0;
|
||||
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) return true;
|
||||
if (entry.toolData !== undefined) return true;
|
||||
if (entry.changedFiles?.some((path) => path.trim().length > 0)) return true;
|
||||
return Boolean((entry.rawCommand ?? entry.command)?.trim() || entry.detail?.trim());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createHermesState } from "@t3tools/client-runtime/hermes";
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
|
||||
export const hermes = createHermesState(connectionAtomRuntime);
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.40",
|
||||
"version": "0.0.41-hermes.2",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -47,6 +47,45 @@ const testLayer = Layer.mergeAll(
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
describe("AssetAccess", () => {
|
||||
it.effect("downloads arbitrary files with exact signed access and original bytes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-" });
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
for (const name of ["app.apk", "source.ts", "archive.zip", "page.html", "résumé.txt"]) {
|
||||
const filePath = path.join(root, name);
|
||||
const bytes = new Uint8Array([0, 255, 80, 75, 13, 10]);
|
||||
yield* fs.writeFile(filePath, bytes);
|
||||
for (const resource of [
|
||||
{ _tag: "media-file" as const, threadId, path: filePath, download: true },
|
||||
{ _tag: "workspace-file" as const, threadId, path: name, download: true },
|
||||
{ _tag: "draft-workspace-file" as const, cwd: root, path: name, download: true },
|
||||
]) {
|
||||
const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separator = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separator);
|
||||
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
|
||||
expect(asset).toMatchObject({
|
||||
kind: "file",
|
||||
download: true,
|
||||
fileName: name,
|
||||
mimeType: "application/octet-stream",
|
||||
});
|
||||
if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
|
||||
const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
|
||||
expect(response.headers.get("content-disposition")).toContain("attachment;");
|
||||
expect(new Uint8Array(yield* Effect.promise(() => response.arrayBuffer()))).toEqual(
|
||||
bytes,
|
||||
);
|
||||
expect(yield* resolveAsset(token, "sibling.txt")).toBeNull();
|
||||
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
|
||||
}
|
||||
}
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -98,6 +98,7 @@ const AssetClaimsSchema = Schema.Union([
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("media-file-exact"),
|
||||
download: Schema.optionalKey(Schema.Boolean),
|
||||
filePath: Schema.String,
|
||||
device: Schema.String,
|
||||
inode: Schema.String,
|
||||
@@ -274,10 +275,12 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
|
||||
if (!canonicalFile) {
|
||||
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
|
||||
}
|
||||
if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
|
||||
const download = "download" in input.resource && input.resource.download === true;
|
||||
if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
|
||||
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
|
||||
}
|
||||
const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
|
||||
const wantsDimensions =
|
||||
!download && HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
|
||||
const opened = yield* openMediaFile(canonicalFile).pipe(
|
||||
Effect.flatMap((file) =>
|
||||
file === null
|
||||
@@ -304,6 +307,7 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
|
||||
claims: {
|
||||
version: 1 as const,
|
||||
kind: "media-file-exact" as const,
|
||||
...(download ? { download: true } : {}),
|
||||
filePath: canonicalFile,
|
||||
...opened.identity,
|
||||
expiresAt: input.expiresAt,
|
||||
@@ -338,7 +342,8 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
|
||||
const download = "download" in input.resource && input.resource.download === true;
|
||||
if (!download && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({
|
||||
resource: input.resource,
|
||||
});
|
||||
@@ -360,6 +365,13 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
|
||||
resource: input.resource,
|
||||
});
|
||||
}
|
||||
if (download) {
|
||||
return yield* finalizeAbsoluteMediaFileAsset({
|
||||
requestedPath: canonicalFile,
|
||||
resource: input.resource,
|
||||
expiresAt: input.expiresAt,
|
||||
});
|
||||
}
|
||||
const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -778,7 +790,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (canonicalFile !== claims.filePath) return null;
|
||||
const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
|
||||
const mimeType = claims.download
|
||||
? "application/octet-stream"
|
||||
: hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
|
||||
if (!mimeType) return null;
|
||||
const file = yield* openMediaFile(canonicalFile, claims).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
@@ -787,7 +801,13 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
return file
|
||||
? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
|
||||
? ({
|
||||
kind: "file",
|
||||
path: canonicalFile,
|
||||
mimeType,
|
||||
file,
|
||||
...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
if (claims.kind === "workspace-file-exact") {
|
||||
|
||||
@@ -11,6 +11,11 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import { RPC_REQUIRED_SCOPES, requiredScopeForRpcMethod } from "./RpcAuthorization.ts";
|
||||
|
||||
describe("RPC authorization scopes", () => {
|
||||
it("separates Hermes reads from session and management mutations", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.hermesRead)).toBe(AuthOrchestrationReadScope);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.hermesEvents)).toBe(AuthOrchestrationReadScope);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.hermesWrite)).toBe(AuthOrchestrationOperateScope);
|
||||
});
|
||||
it("declares exactly one scope for every RPC in the server group", () => {
|
||||
expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
|
||||
});
|
||||
|
||||
@@ -21,6 +21,9 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
||||
* runtime failure.
|
||||
*/
|
||||
export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.hermesRead]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.hermesWrite]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.hermesEvents]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { ProviderInstanceId, type HermesEvent } from "@t3tools/contracts";
|
||||
import { DashboardClient, hermesReadRoute, hermesWriteRoute } from "./HermesBridge.ts";
|
||||
|
||||
const target = { instanceId: ProviderInstanceId.make("hermes"), profile: "personal" };
|
||||
|
||||
class MockSocket extends EventTarget {
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSED = 3;
|
||||
static instances: MockSocket[] = [];
|
||||
static reply: ((frame: Record<string, unknown>) => Record<string, unknown>) | undefined;
|
||||
readyState = 0;
|
||||
readonly url: URL;
|
||||
readonly frames: Record<string, unknown>[] = [];
|
||||
|
||||
constructor(url: URL) {
|
||||
super();
|
||||
this.url = url;
|
||||
MockSocket.instances.push(this);
|
||||
queueMicrotask(() => {
|
||||
this.readyState = MockSocket.OPEN;
|
||||
this.dispatchEvent(new Event("open"));
|
||||
});
|
||||
}
|
||||
|
||||
send(data: string) {
|
||||
const frame = JSON.parse(data) as Record<string, unknown>;
|
||||
this.frames.push(frame);
|
||||
if (!frame.method) return;
|
||||
const result =
|
||||
frame.method === "session.resume" || frame.method === "session.create"
|
||||
? { session_id: "runtime-1", stored_session_id: "saved-1" }
|
||||
: { ok: true };
|
||||
queueMicrotask(() =>
|
||||
this.receive({ jsonrpc: "2.0", id: frame.id, ...(MockSocket.reply?.(frame) ?? { result }) }),
|
||||
);
|
||||
}
|
||||
|
||||
receive(data: unknown) {
|
||||
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) }));
|
||||
}
|
||||
|
||||
close() {
|
||||
this.readyState = MockSocket.CLOSED;
|
||||
this.dispatchEvent(new Event("close"));
|
||||
}
|
||||
}
|
||||
|
||||
function fixture(
|
||||
options: { remote?: boolean; status?: number; body?: unknown; loginStatus?: number } = {},
|
||||
) {
|
||||
const calls: {
|
||||
url: URL;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
body: string | undefined;
|
||||
}[] = [];
|
||||
const timers = new Set<() => void>();
|
||||
const files: string[] = [];
|
||||
const io: ConstructorParameters<typeof DashboardClient>[3] = {
|
||||
join: (...parts) => parts.join("/"),
|
||||
readText: async (file) => {
|
||||
files.push(file);
|
||||
return file.endsWith(".env")
|
||||
? "HERMES_DASHBOARD_BASIC_AUTH_USERNAME=operator\nHERMES_DASHBOARD_BASIC_AUTH_PASSWORD=test-password"
|
||||
: "";
|
||||
},
|
||||
schedule: (_milliseconds, callback) => {
|
||||
timers.add(callback);
|
||||
return () => {
|
||||
timers.delete(callback);
|
||||
};
|
||||
},
|
||||
request: async (url, method, headers, body) => {
|
||||
calls.push({ url, method, headers, body });
|
||||
if (url.pathname.endsWith("/api/health"))
|
||||
return { status: 200, cookies: [], text: '{"auth_required":true}' };
|
||||
if (url.pathname.endsWith("/auth/password-login"))
|
||||
return {
|
||||
status: options.loginStatus ?? 200,
|
||||
cookies: ["hermes_session=private-token; HttpOnly; Path=/"],
|
||||
text: '{"ok":true}',
|
||||
};
|
||||
if (url.pathname.endsWith("/api/auth/ws-ticket"))
|
||||
return { status: 200, cookies: [], text: '{"ticket":"single-use-ticket"}' };
|
||||
return {
|
||||
status: options.status ?? 200,
|
||||
cookies: [],
|
||||
text: JSON.stringify(options.body ?? { sessions: [{ id: "saved-1" }], total: 1 }),
|
||||
};
|
||||
},
|
||||
};
|
||||
const client = new DashboardClient(
|
||||
new URL(options.remote ? "https://hermes.example/prefix" : "http://127.0.0.1:9119"),
|
||||
"/hermes-test",
|
||||
{},
|
||||
io,
|
||||
);
|
||||
return { client, calls, timers, files };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
MockSocket.instances = [];
|
||||
MockSocket.reply = undefined;
|
||||
});
|
||||
|
||||
describe("Hermes dashboard routes", () => {
|
||||
it("lists recent native sessions across profiles with bounded pages", () => {
|
||||
const route = new URL(
|
||||
hermesReadRoute({ ...target, resource: "sessions", offset: 50 }),
|
||||
"http://localhost",
|
||||
);
|
||||
expect(route.pathname).toBe("/api/profiles/sessions");
|
||||
expect(Object.fromEntries(route.searchParams)).toEqual({
|
||||
profile: "personal",
|
||||
order: "recent",
|
||||
limit: "50",
|
||||
offset: "50",
|
||||
});
|
||||
});
|
||||
|
||||
it("encodes session identifiers instead of allowing API path injection", () => {
|
||||
expect(hermesReadRoute({ ...target, resource: "messages", id: "session/a?b" })).toContain(
|
||||
"/api/sessions/session%2Fa%3Fb/messages?",
|
||||
);
|
||||
expect(() => hermesReadRoute({ ...target, resource: "messages" })).toThrow(
|
||||
"session is required",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the native cron update envelope and supports both pause directions", () => {
|
||||
expect(
|
||||
hermesWriteRoute({
|
||||
...target,
|
||||
action: "updateCron",
|
||||
id: "job",
|
||||
fields: { prompt: "changed" },
|
||||
}),
|
||||
).toEqual({
|
||||
method: "PUT",
|
||||
path: "/api/cron/jobs/job?profile=personal",
|
||||
body: { updates: { prompt: "changed" } },
|
||||
});
|
||||
expect(hermesWriteRoute({ ...target, action: "pauseCron", id: "job" }).path).toContain(
|
||||
"/job/pause?",
|
||||
);
|
||||
expect(hermesWriteRoute({ ...target, action: "resumeCron", id: "job" }).path).toContain(
|
||||
"/job/resume?",
|
||||
);
|
||||
});
|
||||
|
||||
it("routes memory edits through Hermes’s profile-aware mutation API", () => {
|
||||
expect(
|
||||
hermesWriteRoute({ ...target, action: "saveMemory", id: "memory:user:2", text: "updated" }),
|
||||
).toEqual({
|
||||
method: "PUT",
|
||||
path: "/api/learning/node",
|
||||
body: { id: "memory:user:2", content: "updated", profile: "personal" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes dashboard authentication and failures", () => {
|
||||
it("authenticates once and retains cookies only on the server-side client", async () => {
|
||||
const { client, calls } = fixture();
|
||||
const results = await Promise.all([
|
||||
client.read({ ...target, resource: "sessions" }),
|
||||
client.read({ ...target, resource: "logs" }),
|
||||
]);
|
||||
expect(calls.filter((call) => call.url.pathname === "/auth/password-login")).toHaveLength(1);
|
||||
expect(
|
||||
calls.find((call) => call.url.pathname === "/api/profiles/sessions")?.headers.Cookie,
|
||||
).toBe("hermes_session=private-token");
|
||||
expect(JSON.stringify(results)).not.toContain("private-token");
|
||||
expect(JSON.stringify(results)).not.toContain("test-password");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("never sends auto-discovered local credentials to a remote dashboard", async () => {
|
||||
const { client, calls, files } = fixture({ remote: true });
|
||||
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
|
||||
expect(files).toEqual([]);
|
||||
expect(calls).toHaveLength(1);
|
||||
await client.login("operator", "explicit-password");
|
||||
await client.read({ ...target, resource: "sessions" });
|
||||
expect(calls.at(-1)?.url.pathname).toBe("/prefix/api/profiles/sessions");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("preserves structured dashboard error status and detail", async () => {
|
||||
const { client } = fixture({ status: 503, body: { detail: "Session store is busy. Retry." } });
|
||||
await expect(client.read({ ...target, resource: "sessions" })).rejects.toMatchObject({
|
||||
status: 503,
|
||||
message: "Session store is busy. Retry.",
|
||||
operation: "/api/profiles/sessions",
|
||||
});
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("tolerates a newly created session before Hermes persists its first prompt", async () => {
|
||||
const { client } = fixture({ status: 404 });
|
||||
client.remember("new-session", "runtime-new", "personal");
|
||||
await expect(
|
||||
client.read({ ...target, resource: "messages", id: "new-session" }),
|
||||
).resolves.toEqual({ session_id: "new-session", messages: [] });
|
||||
await expect(
|
||||
client.read({ ...target, resource: "messages", id: "missing-session" }),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes gateway lifecycle", () => {
|
||||
it("coalesces concurrent attaches to one native session resume", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
expect(await Promise.all([client.session("saved-1"), client.session("saved-1")])).toEqual([
|
||||
"runtime-1",
|
||||
"runtime-1",
|
||||
]);
|
||||
expect(
|
||||
MockSocket.instances[0]?.frames.filter((frame) => frame.method === "session.resume"),
|
||||
).toHaveLength(1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("replays outstanding requests when the event subscription starts after attach", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await client.session("saved-1");
|
||||
MockSocket.instances[0]!.receive({
|
||||
method: "approval",
|
||||
id: "srq-late",
|
||||
params: { session_id: "runtime-1", choices: ["once", "deny"] },
|
||||
});
|
||||
const events: HermesEvent[] = [];
|
||||
client.listen((event) => events.push(event));
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "request",
|
||||
sessionId: "saved-1",
|
||||
payload: expect.objectContaining({ requestId: "srq-late" }),
|
||||
}),
|
||||
);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("reuses native sessions and translates runtime events to durable IDs", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client, calls, timers } = fixture();
|
||||
const events: HermesEvent[] = [];
|
||||
const remove = client.listen((event) => events.push(event));
|
||||
expect(await client.session("saved-1", "personal")).toBe("runtime-1");
|
||||
expect(await client.session("saved-1", "personal")).toBe("runtime-1");
|
||||
const socket = MockSocket.instances[0]!;
|
||||
expect(socket.frames.filter((frame) => frame.method === "session.resume")).toHaveLength(1);
|
||||
expect(socket.url.searchParams.get("ticket")).toBe("single-use-ticket");
|
||||
expect(calls.find((call) => call.url.pathname === "/api/auth/ws-ticket")?.method).toBe("POST");
|
||||
socket.receive({
|
||||
method: "event",
|
||||
params: {
|
||||
type: "tool.start",
|
||||
session_id: "runtime-1",
|
||||
payload: { command: "echo hello", arguments: { exact: "input" } },
|
||||
},
|
||||
});
|
||||
expect(events.at(-1)).toMatchObject({
|
||||
sessionId: "saved-1",
|
||||
type: "tool.start",
|
||||
payload: { command: "echo hello", arguments: { exact: "input" } },
|
||||
});
|
||||
remove();
|
||||
client.close();
|
||||
expect(timers.size).toBe(0);
|
||||
});
|
||||
|
||||
it("forwards approval requests and rejects stale responses", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
const events: HermesEvent[] = [];
|
||||
client.listen((event) => events.push(event));
|
||||
await client.session("saved-1");
|
||||
const socket = MockSocket.instances[0]!;
|
||||
socket.receive({
|
||||
jsonrpc: "2.0",
|
||||
id: "approval-1",
|
||||
method: "approval",
|
||||
params: { session_id: "runtime-1", choices: ["once", "deny"] },
|
||||
});
|
||||
expect(events.at(-1)).toMatchObject({
|
||||
type: "request",
|
||||
sessionId: "saved-1",
|
||||
payload: { requestId: "approval-1", method: "approval" },
|
||||
});
|
||||
client.respond("approval-1", { choice: "deny" });
|
||||
expect(socket.frames.at(-1)).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: "approval-1",
|
||||
result: { choice: "deny" },
|
||||
});
|
||||
expect(() => client.respond("approval-1", { choice: "once" })).toThrow("expired");
|
||||
expect(events.at(-1)?.type).toBe("request.resolved");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("resumes again after disconnect instead of reusing a stale runtime ID", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await client.session("saved-1");
|
||||
MockSocket.instances[0]!.close();
|
||||
await client.session("saved-1");
|
||||
expect(MockSocket.instances).toHaveLength(2);
|
||||
expect(MockSocket.instances[1]!.frames[0]?.method).toBe("session.resume");
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes native actions", () => {
|
||||
it("creates a project-free session and sends prompts without creating a second runtime", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await expect(client.write({ ...target, action: "create" })).resolves.toMatchObject({
|
||||
stored_session_id: "saved-1",
|
||||
});
|
||||
await client.write({ ...target, action: "send", id: "saved-1", text: "Hello Hermes" });
|
||||
expect(
|
||||
MockSocket.instances[0]!.frames.map(({ method, params }) => ({ method, params })),
|
||||
).toEqual([
|
||||
{ method: "session.create", params: { profile: "personal", close_on_disconnect: false } },
|
||||
{ method: "prompt.submit", params: { session_id: "runtime-1", text: "Hello Hermes" } },
|
||||
]);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("submits the full expanded skill prompt and preserves multiline arguments", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await client.session("saved-1", "personal");
|
||||
MockSocket.reply = (frame) => ({
|
||||
result:
|
||||
frame.method === "command.dispatch"
|
||||
? {
|
||||
type: "skill",
|
||||
message: "Full skill instructions\n".repeat(1000),
|
||||
display: "/research",
|
||||
}
|
||||
: { ok: true },
|
||||
});
|
||||
await client.write({
|
||||
...target,
|
||||
action: "command",
|
||||
id: "saved-1",
|
||||
text: "/research first\n second",
|
||||
});
|
||||
expect(MockSocket.instances[0]!.frames.at(-2)).toMatchObject({
|
||||
method: "command.dispatch",
|
||||
params: { name: "research", arg: "first\n second" },
|
||||
});
|
||||
expect(MockSocket.instances[0]!.frames.at(-1)).toMatchObject({
|
||||
method: "prompt.submit",
|
||||
params: { text: "Full skill instructions\n".repeat(1000) },
|
||||
});
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("resolves aliases but returns undo prefills without submitting them", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await client.session("saved-1", "personal");
|
||||
MockSocket.reply = (frame) => ({
|
||||
result:
|
||||
(frame.params as { name: string }).name === "again"
|
||||
? { type: "alias", target: "undo" }
|
||||
: { type: "prefill", message: "Edit this before sending" },
|
||||
});
|
||||
await expect(
|
||||
client.write({ ...target, action: "command", id: "saved-1", text: "/again" }),
|
||||
).resolves.toMatchObject({ type: "prefill", message: "Edit this before sending" });
|
||||
expect(MockSocket.instances[0]!.frames.map((frame) => frame.method)).not.toContain(
|
||||
"prompt.submit",
|
||||
);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("falls back only for unowned slash commands, not failed executions", async () => {
|
||||
vi.stubGlobal("WebSocket", MockSocket);
|
||||
const { client } = fixture();
|
||||
await client.session("saved-1", "personal");
|
||||
MockSocket.reply = (frame) =>
|
||||
frame.method === "command.dispatch"
|
||||
? { error: { message: "not a quick/plugin/bundle/skill command: status" } }
|
||||
: { result: { output: "Connected" } };
|
||||
await expect(
|
||||
client.write({ ...target, action: "command", id: "saved-1", text: "/status" }),
|
||||
).resolves.toEqual({ output: "Connected" });
|
||||
expect(MockSocket.instances[0]!.frames.at(-1)).toMatchObject({
|
||||
method: "slash.exec",
|
||||
params: { command: "status" },
|
||||
});
|
||||
MockSocket.reply = () => ({ error: { message: "Command failed: invalid credentials" } });
|
||||
await expect(
|
||||
client.write({ ...target, action: "command", id: "saved-1", text: "/status" }),
|
||||
).rejects.toThrow("invalid credentials");
|
||||
expect(
|
||||
MockSocket.instances[0]!.frames.filter((frame) => frame.method === "slash.exec"),
|
||||
).toHaveLength(1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("does not repeatedly submit a bad local password during polling", async () => {
|
||||
const { client, calls } = fixture({ loginStatus: 401 });
|
||||
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
|
||||
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
|
||||
expect(calls.filter((call) => call.url.pathname === "/auth/password-login")).toHaveLength(1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("refuses stale memory edits, then saves the current content through the profile API", async () => {
|
||||
const { client, calls } = fixture({ body: { content: "Already updated" } });
|
||||
await expect(
|
||||
client.write({
|
||||
...target,
|
||||
action: "saveMemory",
|
||||
id: "memory:user:2",
|
||||
text: "New",
|
||||
fields: { expectedContent: "Old" },
|
||||
}),
|
||||
).rejects.toThrow("changed in Hermes");
|
||||
expect(calls.some((call) => call.method === "PUT")).toBe(false);
|
||||
await client.write({
|
||||
...target,
|
||||
action: "saveMemory",
|
||||
id: "memory:user:2",
|
||||
text: "New",
|
||||
fields: { expectedContent: "Already updated" },
|
||||
});
|
||||
expect(JSON.parse(calls.at(-1)!.body!)).toEqual({
|
||||
id: "memory:user:2",
|
||||
content: "New",
|
||||
profile: "personal",
|
||||
});
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,785 @@
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeUtil from "node:util";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import {
|
||||
HermesError,
|
||||
HermesSettings,
|
||||
type HermesEvent,
|
||||
type HermesReadInput,
|
||||
type HermesTarget,
|
||||
type HermesWriteInput,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import { Cookies, HttpClient, HttpClientRequest, type HttpMethod } from "effect/unstable/http";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
const RecordValue = Schema.Record(Schema.String, Schema.Unknown);
|
||||
const decodeRecord = Schema.decodeUnknownSync(RecordValue);
|
||||
const record = (value: unknown): Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? decodeRecord(value) : {};
|
||||
const text = (value: unknown) => (typeof value === "string" ? value : "");
|
||||
const decodeSettings = Schema.decodeUnknownSync(HermesSettings);
|
||||
const isHermesError = Schema.is(HermesError);
|
||||
const errorText = (value: unknown) =>
|
||||
typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
|
||||
|
||||
export function hermesReadRoute(input: HermesReadInput) {
|
||||
const query = new URLSearchParams();
|
||||
if (input.profile) query.set("profile", input.profile);
|
||||
const id = encodeURIComponent(input.id ?? "");
|
||||
let pathname: string;
|
||||
switch (input.resource) {
|
||||
case "sessions":
|
||||
pathname = "/api/profiles/sessions";
|
||||
query.set("order", "recent");
|
||||
query.set("limit", "50");
|
||||
query.set("offset", String(input.offset ?? 0));
|
||||
break;
|
||||
case "messages":
|
||||
if (!input.id) throw new Error("A Hermes session is required.");
|
||||
pathname = `/api/sessions/${id}/messages`;
|
||||
query.set("limit", "100");
|
||||
query.set("offset", String(input.offset ?? 0));
|
||||
query.set("order", "latest");
|
||||
break;
|
||||
case "skills":
|
||||
pathname = "/api/skills";
|
||||
break;
|
||||
case "skill":
|
||||
pathname = "/api/skills/content";
|
||||
query.set("name", input.id ?? "");
|
||||
break;
|
||||
case "memories":
|
||||
pathname = "/api/learning/graph";
|
||||
break;
|
||||
case "memory":
|
||||
pathname = "/api/learning/node";
|
||||
query.set("id", input.id ?? "");
|
||||
break;
|
||||
case "cron":
|
||||
pathname = "/api/cron/jobs";
|
||||
break;
|
||||
case "logs":
|
||||
pathname = "/api/logs";
|
||||
query.set("file", input.logFile ?? "agent");
|
||||
query.set("lines", "300");
|
||||
if (input.text) query.set("search", input.text);
|
||||
break;
|
||||
case "commands":
|
||||
throw new Error("Slash completions use the Hermes gateway.");
|
||||
}
|
||||
return `${pathname}?${query}`;
|
||||
}
|
||||
|
||||
export function hermesWriteRoute(input: HermesWriteInput) {
|
||||
const id = encodeURIComponent(input.id ?? "");
|
||||
const query = new URLSearchParams(input.profile ? { profile: input.profile } : {});
|
||||
const profile = input.profile ? { profile: input.profile } : {};
|
||||
switch (input.action) {
|
||||
case "saveSkill":
|
||||
return {
|
||||
method: "PUT",
|
||||
path: "/api/skills/content",
|
||||
body: { name: input.id, content: input.text, ...profile },
|
||||
};
|
||||
case "saveMemory":
|
||||
return {
|
||||
method: "PUT",
|
||||
path: "/api/learning/node",
|
||||
body: { id: input.id, content: input.text, ...profile },
|
||||
};
|
||||
case "createCron":
|
||||
return { method: "POST", path: `/api/cron/jobs?${query}`, body: input.fields ?? {} };
|
||||
case "updateCron":
|
||||
return {
|
||||
method: "PUT",
|
||||
path: `/api/cron/jobs/${id}?${query}`,
|
||||
body: { updates: input.fields ?? {} },
|
||||
};
|
||||
case "pauseCron":
|
||||
return { method: "POST", path: `/api/cron/jobs/${id}/pause?${query}` };
|
||||
case "resumeCron":
|
||||
return { method: "POST", path: `/api/cron/jobs/${id}/resume?${query}` };
|
||||
case "runCron":
|
||||
return { method: "POST", path: `/api/cron/jobs/${id}/trigger?${query}` };
|
||||
case "deleteCron":
|
||||
return { method: "DELETE", path: `/api/cron/jobs/${id}?${query}` };
|
||||
case "renameSession":
|
||||
return {
|
||||
method: "PATCH",
|
||||
path: `/api/sessions/${id}`,
|
||||
body: { title: input.text, ...profile },
|
||||
};
|
||||
case "deleteSession":
|
||||
return { method: "DELETE", path: `/api/sessions/${id}?${query}` };
|
||||
default:
|
||||
throw new Error("This operation uses the Hermes gateway.");
|
||||
}
|
||||
}
|
||||
|
||||
interface DashboardIO {
|
||||
readonly readText: (file: string) => Promise<string>;
|
||||
readonly join: (...parts: string[]) => string;
|
||||
readonly schedule: (milliseconds: number, callback: () => void) => () => void;
|
||||
readonly request: (
|
||||
url: URL,
|
||||
method: string,
|
||||
headers: Record<string, string>,
|
||||
body?: string,
|
||||
) => Promise<{ status: number; cookies: string[]; text: string }>;
|
||||
}
|
||||
|
||||
export class DashboardClient {
|
||||
private readonly cookies = new Map<string, string>();
|
||||
private socket: WebSocket | undefined;
|
||||
private connecting: Promise<WebSocket> | undefined;
|
||||
private counter = 0;
|
||||
private sequence = 0;
|
||||
private readonly listeners = new Set<(event: HermesEvent) => void>();
|
||||
private readonly pending = new Map<
|
||||
string,
|
||||
{ resolve: (value: unknown) => void; reject: (error: Error) => void; cancelTimer: () => void }
|
||||
>();
|
||||
private readonly sessions = new Map<string, string>();
|
||||
private readonly resuming = new Map<string, Promise<string>>();
|
||||
private readonly storedIds = new Map<string, string>();
|
||||
private readonly newSessions = new Set<string>();
|
||||
private readonly requests = new Map<string, string>();
|
||||
private readonly requestEvents = new Map<string, HermesEvent>();
|
||||
private history: HermesEvent[] = [];
|
||||
private authenticated = false;
|
||||
private autoLoginAttempted = false;
|
||||
private authenticating: Promise<void> | undefined;
|
||||
private disposed = false;
|
||||
|
||||
readonly base: URL;
|
||||
private readonly home: string;
|
||||
private readonly environment: Record<string, string>;
|
||||
private readonly io: DashboardIO;
|
||||
|
||||
constructor(base: URL, home: string, environment: Record<string, string>, io: DashboardIO) {
|
||||
this.base = base;
|
||||
this.home = home;
|
||||
this.environment = environment;
|
||||
this.io = io;
|
||||
}
|
||||
|
||||
private async fetchJson(route: string, method = "GET", body?: unknown): Promise<unknown> {
|
||||
const response = await this.io.request(
|
||||
new URL(`${this.base.pathname.replace(/\/$/, "")}${route}`, this.base),
|
||||
method,
|
||||
{
|
||||
"Content-Type": "application/json",
|
||||
Origin: this.base.origin,
|
||||
Cookie: [...this.cookies].map(([name, value]) => `${name}=${value}`).join("; "),
|
||||
},
|
||||
body === undefined ? undefined : JSON.stringify(body),
|
||||
);
|
||||
for (const cookie of response.cookies) {
|
||||
const pair = cookie.split(";", 1)[0] ?? "";
|
||||
const split = pair.indexOf("=");
|
||||
if (split > 0) this.cookies.set(pair.slice(0, split), pair.slice(split + 1));
|
||||
}
|
||||
const responseText = response.text;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(responseText);
|
||||
} catch {
|
||||
if (response.status >= 200 && response.status < 300 && response.status !== 204)
|
||||
throw new HermesError({
|
||||
operation: route.split("?", 1)[0] ?? route,
|
||||
status: response.status,
|
||||
message:
|
||||
"Hermes returned a non-JSON response. Check the dashboard address and sign-in requirements.",
|
||||
});
|
||||
data = {};
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
if (response.status === 401) this.authenticated = false;
|
||||
const message =
|
||||
response.status === 401 || response.status === 302
|
||||
? "Sign in to the Hermes dashboard to connect this environment."
|
||||
: errorText(record(data).detail) ||
|
||||
errorText(record(data).message) ||
|
||||
`Hermes returned HTTP ${response.status}.`;
|
||||
throw new HermesError({
|
||||
message,
|
||||
operation: route.split("?", 1)[0] ?? route,
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
async login(username: string, password: string) {
|
||||
await this.fetchJson("/auth/password-login", "POST", { provider: "basic", username, password });
|
||||
this.authenticated = true;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
private async authenticate() {
|
||||
if (this.disposed) throw new Error("The T3 connection has closed.");
|
||||
if (this.authenticated) return;
|
||||
if (this.authenticating) return this.authenticating;
|
||||
this.authenticating = (async () => {
|
||||
const health = record(await this.fetchJson("/api/health"));
|
||||
if (!health.auth_required) {
|
||||
this.authenticated = true;
|
||||
return;
|
||||
}
|
||||
if (this.autoLoginAttempted)
|
||||
throw new Error(
|
||||
"Sign in to the Hermes dashboard to reconnect. Automatic sign-in is not retried after a failure or expired login.",
|
||||
);
|
||||
this.autoLoginAttempted = true;
|
||||
if (!["localhost", "127.0.0.1", "[::1]"].includes(this.base.hostname)) {
|
||||
throw new Error("Sign in to the Hermes dashboard. Credentials stay on the T3 server.");
|
||||
}
|
||||
const fileEnv = NodeUtil.parseEnv(await this.io.readText(this.io.join(this.home, ".env")));
|
||||
const config = record(
|
||||
parseYaml(await this.io.readText(this.io.join(this.home, "config.yaml"))),
|
||||
);
|
||||
const basic = record(record(config.dashboard).basic_auth);
|
||||
const username =
|
||||
this.environment.HERMES_DASHBOARD_BASIC_AUTH_USERNAME ||
|
||||
fileEnv.HERMES_DASHBOARD_BASIC_AUTH_USERNAME ||
|
||||
text(basic.username);
|
||||
const password =
|
||||
this.environment.HERMES_DASHBOARD_BASIC_AUTH_PASSWORD ||
|
||||
fileEnv.HERMES_DASHBOARD_BASIC_AUTH_PASSWORD ||
|
||||
text(basic.password);
|
||||
if (!username || !password)
|
||||
throw new Error(
|
||||
"Sign in with your Hermes dashboard username and password. Password-hash-only installations require one sign-in per T3 connection.",
|
||||
);
|
||||
await this.login(username, password);
|
||||
})();
|
||||
try {
|
||||
await this.authenticating;
|
||||
} finally {
|
||||
this.authenticating = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async request(route: string, method = "GET", body?: unknown) {
|
||||
await this.authenticate();
|
||||
return this.fetchJson(route, method, body);
|
||||
}
|
||||
|
||||
private async connect(): Promise<WebSocket> {
|
||||
if (this.disposed) throw new Error("The T3 connection has closed.");
|
||||
if (this.socket?.readyState === WebSocket.OPEN) return this.socket;
|
||||
if (this.connecting) return this.connecting;
|
||||
this.connecting = (async () => {
|
||||
await this.authenticate();
|
||||
const health = record(await this.fetchJson("/api/health"));
|
||||
const url = new URL(`${this.base.pathname.replace(/\/$/, "")}/api/ws`, this.base);
|
||||
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
||||
if (health.auth_required) {
|
||||
const ticket = record(await this.fetchJson("/api/auth/ws-ticket", "POST"));
|
||||
if (!text(ticket.ticket)) throw new Error("Hermes did not issue a WebSocket ticket.");
|
||||
url.searchParams.set("ticket", text(ticket.ticket));
|
||||
} else {
|
||||
const response = await this.io.request(this.base, "GET", {});
|
||||
const html = response.text;
|
||||
const token = html.match(
|
||||
/(?:__HERMES_SESSION_TOKEN__|__HERMES_TOKEN__)\s*=\s*["']([^"']+)/,
|
||||
)?.[1];
|
||||
if (!token)
|
||||
throw new Error(
|
||||
"Hermes dashboard authentication is required for chat. Enable dashboard sign-in and reconnect.",
|
||||
);
|
||||
url.searchParams.set("token", token);
|
||||
}
|
||||
if (this.disposed) throw new Error("The T3 connection has closed.");
|
||||
const socket = new WebSocket(url);
|
||||
this.socket = socket;
|
||||
socket.addEventListener("message", (event) => {
|
||||
if (typeof event.data !== "string") return;
|
||||
for (const line of event.data.split("\n").filter(Boolean)) {
|
||||
try {
|
||||
const frame = record(JSON.parse(line));
|
||||
const pending = this.pending.get(text(frame.id));
|
||||
if (pending) {
|
||||
pending.cancelTimer();
|
||||
this.pending.delete(text(frame.id));
|
||||
if (frame.error) {
|
||||
const error = record(frame.error);
|
||||
pending.reject(
|
||||
new Error(
|
||||
`${text(error.message) || "Hermes gateway rejected the request."}${error.code === undefined ? "" : ` (RPC ${errorText(error.code)})`}${error.data === undefined ? "" : `\n${errorText(error.data)}`}`,
|
||||
),
|
||||
);
|
||||
} else pending.resolve(frame.result);
|
||||
} else if (frame.method === "event") {
|
||||
const params = record(frame.params);
|
||||
if (params.type === "request.cancel") {
|
||||
this.requests.delete(text(record(params.payload).id));
|
||||
this.requestEvents.delete(text(record(params.payload).id));
|
||||
}
|
||||
const runtimeId = text(params.session_id);
|
||||
const storedId = text(record(params.payload).stored_session_id);
|
||||
if (params.type === "session.info" && storedId)
|
||||
this.storedIds.set(runtimeId, storedId);
|
||||
const next = {
|
||||
sequence: ++this.sequence,
|
||||
type: text(params.type),
|
||||
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
|
||||
payload: params.payload,
|
||||
};
|
||||
this.emit(next);
|
||||
} else if (typeof frame.method === "string" && typeof frame.id === "string") {
|
||||
const params = record(frame.params);
|
||||
const runtimeId = text(params.session_id);
|
||||
this.requests.set(frame.id, runtimeId);
|
||||
this.emit({
|
||||
sequence: ++this.sequence,
|
||||
type: "request",
|
||||
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
|
||||
payload: { requestId: frame.id, method: frame.method, params },
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
this.emitError("Hermes sent an unreadable gateway event.");
|
||||
}
|
||||
}
|
||||
});
|
||||
socket.addEventListener("close", () => {
|
||||
if (this.socket !== socket) return;
|
||||
this.sessions.clear();
|
||||
this.storedIds.clear();
|
||||
this.requests.clear();
|
||||
this.requestEvents.clear();
|
||||
this.rejectPending("Hermes gateway disconnected. Reconnect the session to continue.");
|
||||
if (!this.disposed)
|
||||
this.emit({
|
||||
sequence: ++this.sequence,
|
||||
type: "error",
|
||||
sessionId: "",
|
||||
payload: {
|
||||
message: "Hermes gateway disconnected. Reconnect the session to continue.",
|
||||
disconnected: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const cancelTimer = this.io.schedule(15_000, () => {
|
||||
socket.close();
|
||||
reject(new Error("Hermes gateway connection timed out."));
|
||||
});
|
||||
socket.addEventListener(
|
||||
"open",
|
||||
() => {
|
||||
cancelTimer();
|
||||
resolve();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"error",
|
||||
() => {
|
||||
cancelTimer();
|
||||
socket.close();
|
||||
reject(new Error("Could not connect to the Hermes chat gateway."));
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"close",
|
||||
() => {
|
||||
cancelTimer();
|
||||
reject(new Error("Hermes gateway connection closed."));
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
return socket;
|
||||
})();
|
||||
try {
|
||||
return await this.connecting;
|
||||
} finally {
|
||||
this.connecting = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private emitError(message: string) {
|
||||
this.emit({ sequence: ++this.sequence, type: "error", sessionId: "", payload: { message } });
|
||||
}
|
||||
|
||||
private emit(event: HermesEvent) {
|
||||
if (event.type === "request")
|
||||
this.requestEvents.set(text(record(event.payload).requestId), event);
|
||||
const previous = this.history.at(-1);
|
||||
if (
|
||||
event.type === "message.delta" &&
|
||||
previous?.type === event.type &&
|
||||
previous.sessionId === event.sessionId
|
||||
) {
|
||||
this.history[this.history.length - 1] = {
|
||||
...event,
|
||||
payload: {
|
||||
...record(event.payload),
|
||||
text: (text(record(previous.payload).text) + text(record(event.payload).text)).slice(
|
||||
-512_000,
|
||||
),
|
||||
},
|
||||
};
|
||||
} else this.history = [...this.history.slice(-49), event];
|
||||
for (const listener of this.listeners) listener(event);
|
||||
}
|
||||
|
||||
private rejectPending(message: string) {
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.cancelTimer();
|
||||
pending.reject(new Error(message));
|
||||
}
|
||||
this.pending.clear();
|
||||
}
|
||||
|
||||
async rpc(method: string, params: Record<string, unknown>) {
|
||||
const socket = await this.connect();
|
||||
const id = `t3-${++this.counter}`;
|
||||
return new Promise<unknown>((resolve, reject) => {
|
||||
const cancelTimer = this.io.schedule(60_000, () => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Hermes ${method} timed out. Check live logs before retrying.`));
|
||||
});
|
||||
this.pending.set(id, { resolve, reject, cancelTimer });
|
||||
try {
|
||||
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
|
||||
} catch (error) {
|
||||
cancelTimer();
|
||||
this.pending.delete(id);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async session(id: string, profile?: string) {
|
||||
const key = JSON.stringify([profile, id]);
|
||||
const existing = this.sessions.get(key);
|
||||
if (existing && this.socket?.readyState === WebSocket.OPEN) return existing;
|
||||
const pending = this.resuming.get(key);
|
||||
if (pending) return pending;
|
||||
const operation = this.resumeSession(id, profile);
|
||||
this.resuming.set(key, operation);
|
||||
try {
|
||||
return await operation;
|
||||
} finally {
|
||||
this.resuming.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private async resumeSession(id: string, profile?: string) {
|
||||
const resumed = record(await this.rpc("session.resume", { session_id: id, profile }));
|
||||
const runtimeId = text(resumed.session_id);
|
||||
if (!runtimeId) throw new Error("Hermes could not resume this session.");
|
||||
this.sessions.set(JSON.stringify([profile, id]), runtimeId);
|
||||
this.storedIds.set(runtimeId, id);
|
||||
for (const raw of Array.isArray(resumed.open_requests) ? resumed.open_requests : []) {
|
||||
const request = record(raw);
|
||||
const requestId = text(request.id);
|
||||
if (!requestId) continue;
|
||||
this.requests.set(requestId, runtimeId);
|
||||
this.emit({
|
||||
sequence: ++this.sequence,
|
||||
type: "request",
|
||||
sessionId: id,
|
||||
payload: { requestId, method: text(request.method), params: record(request.params) },
|
||||
});
|
||||
}
|
||||
return runtimeId;
|
||||
}
|
||||
|
||||
remember(storedId: string, runtimeId: string, profile?: string) {
|
||||
this.sessions.set(JSON.stringify([profile, storedId]), runtimeId);
|
||||
this.storedIds.set(runtimeId, storedId);
|
||||
this.newSessions.add(storedId);
|
||||
}
|
||||
|
||||
async read(input: HermesReadInput) {
|
||||
try {
|
||||
const result = await this.request(hermesReadRoute(input));
|
||||
if (input.resource === "messages" && input.id) this.newSessions.delete(input.id);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (
|
||||
input.resource === "messages" &&
|
||||
input.id &&
|
||||
this.newSessions.has(input.id) &&
|
||||
isHermesError(error) &&
|
||||
error.status === 404
|
||||
) {
|
||||
return { session_id: input.id, messages: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async create(profile?: string) {
|
||||
const result = record(
|
||||
await this.rpc("session.create", { profile, close_on_disconnect: false }),
|
||||
);
|
||||
const storedId = text(result.stored_session_id);
|
||||
const runtimeId = text(result.session_id);
|
||||
if (!storedId || !runtimeId) throw new Error("Hermes did not return the new session identity.");
|
||||
this.remember(storedId, runtimeId, profile);
|
||||
return result;
|
||||
}
|
||||
|
||||
async command(sessionId: string, command: string, profile?: string, depth = 0): Promise<unknown> {
|
||||
if (depth >= 8) throw new Error("Hermes command alias loop detected.");
|
||||
const match = command
|
||||
.trim()
|
||||
.replace(/^\//, "")
|
||||
.match(/^(\S+)(?:\s+([\s\S]*))?$/);
|
||||
if (!match) throw new Error("Enter a Hermes slash command.");
|
||||
const name = match[1] ?? "";
|
||||
const arg = match[2] ?? "";
|
||||
if (name === "new" || name === "reset") {
|
||||
if (arg)
|
||||
throw new Error("Use New task to start a session, then select its model with /model.");
|
||||
return { ...(await this.create(profile)), type: "session" };
|
||||
}
|
||||
let result: Record<string, unknown>;
|
||||
try {
|
||||
result = record(await this.rpc("command.dispatch", { session_id: sessionId, name, arg }));
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof Error) ||
|
||||
!error.message.startsWith("not a quick/plugin/bundle/skill command:")
|
||||
)
|
||||
throw error;
|
||||
result = record(
|
||||
await this.rpc("slash.exec", {
|
||||
session_id: sessionId,
|
||||
command: command.trim().replace(/^\//, ""),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (result.type === "alias") {
|
||||
const target = text(result.target).replace(/^\//, "");
|
||||
if (!target) throw new Error("Hermes returned an empty command alias.");
|
||||
return this.command(sessionId, `/${target}${arg ? ` ${arg}` : ""}`, profile, depth + 1);
|
||||
}
|
||||
if (result.type === "skill" || result.type === "send") {
|
||||
const message = text(result.message);
|
||||
if (!message.trim()) throw new Error("Hermes returned an empty command prompt.");
|
||||
const submission = await this.rpc("prompt.submit", { session_id: sessionId, text: message });
|
||||
return { ...result, submission };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async write(input: HermesWriteInput): Promise<unknown> {
|
||||
if (input.action === "login") return this.login(text(input.fields?.username), input.text ?? "");
|
||||
if (input.action === "respond")
|
||||
return this.respond(text(input.fields?.requestId), record(input.fields?.response));
|
||||
if (input.action === "create") return this.create(input.profile);
|
||||
if (["attach", "send", "interrupt", "command"].includes(input.action)) {
|
||||
if (!input.id) throw new Error("Select a Hermes session first.");
|
||||
const sessionId = await this.session(input.id, input.profile);
|
||||
if (input.action === "attach") return { session_id: sessionId, stored_session_id: input.id };
|
||||
if (input.action === "interrupt")
|
||||
return this.rpc("session.interrupt", { session_id: sessionId });
|
||||
if (input.action === "send")
|
||||
return this.rpc("prompt.submit", { session_id: sessionId, text: input.text ?? "" });
|
||||
return this.command(sessionId, input.text ?? "", input.profile);
|
||||
}
|
||||
if (input.action !== "createCron" && !input.id) throw new Error("Select an item first.");
|
||||
if (
|
||||
(input.action === "saveSkill" || input.action === "saveMemory") &&
|
||||
typeof input.fields?.expectedContent === "string"
|
||||
) {
|
||||
const current = record(
|
||||
await this.read({ ...input, resource: input.action === "saveSkill" ? "skill" : "memory" }),
|
||||
);
|
||||
if (current.content !== input.fields.expectedContent)
|
||||
throw new Error(
|
||||
"This item changed in Hermes while you were editing. Reload it before saving to avoid overwriting another change.",
|
||||
);
|
||||
}
|
||||
const route = hermesWriteRoute(input);
|
||||
return this.request(route.path, route.method, route.body);
|
||||
}
|
||||
|
||||
listen(listener: (event: HermesEvent) => void) {
|
||||
this.listeners.add(listener);
|
||||
const events = new Map(this.history.map((event) => [event.sequence, event]));
|
||||
for (const event of this.requestEvents.values()) events.set(event.sequence, event);
|
||||
for (const event of [...events.values()].sort((left, right) => left.sequence - right.sequence))
|
||||
listener({ ...event, sessionId: this.storedIds.get(event.sessionId) ?? event.sessionId });
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
close() {
|
||||
this.disposed = true;
|
||||
this.rejectPending("The T3 connection has closed.");
|
||||
this.socket?.close();
|
||||
this.cookies.clear();
|
||||
this.listeners.clear();
|
||||
this.history = [];
|
||||
this.requestEvents.clear();
|
||||
}
|
||||
|
||||
respond(requestId: string, response: Record<string, unknown>) {
|
||||
const runtimeId = this.requests.get(requestId);
|
||||
if (!runtimeId || this.socket?.readyState !== WebSocket.OPEN)
|
||||
throw new Error("This Hermes request has expired. Refresh the session.");
|
||||
this.socket.send(JSON.stringify({ jsonrpc: "2.0", id: requestId, result: response }) + "\n");
|
||||
this.requests.delete(requestId);
|
||||
this.requestEvents.delete(requestId);
|
||||
this.emit({
|
||||
sequence: ++this.sequence,
|
||||
type: "request.resolved",
|
||||
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
|
||||
payload: { id: requestId },
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
export const makeHermesBridge = Effect.fn("makeHermesBridge")(function* (
|
||||
getSettings: Effect.Effect<ServerSettings, { readonly message: string }>,
|
||||
) {
|
||||
const filesystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const http = yield* HttpClient.HttpClient;
|
||||
const io: DashboardIO = {
|
||||
join: path.join,
|
||||
readText: (file) =>
|
||||
Effect.runPromise(
|
||||
filesystem.readFileString(file).pipe(Effect.catch(() => Effect.succeed(""))),
|
||||
),
|
||||
schedule: (milliseconds, callback) => {
|
||||
const fiber = Effect.runFork(
|
||||
Effect.sleep(milliseconds).pipe(Effect.andThen(Effect.sync(callback))),
|
||||
);
|
||||
return () => {
|
||||
Effect.runFork(Fiber.interrupt(fiber));
|
||||
};
|
||||
},
|
||||
request: (url, method, headers, body) =>
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
let request = HttpClientRequest.make(method as HttpMethod.HttpMethod)(url, { headers });
|
||||
if (body !== undefined)
|
||||
request = HttpClientRequest.bodyText(request, body, "application/json");
|
||||
const response = yield* http.execute(request);
|
||||
return {
|
||||
status: response.status,
|
||||
cookies: Cookies.toSetCookieHeaders(response.cookies),
|
||||
text: yield* response.text,
|
||||
};
|
||||
}).pipe(Effect.timeout(20_000)),
|
||||
),
|
||||
};
|
||||
const clients = new Map<string, DashboardClient>();
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
for (const client of clients.values()) client.close();
|
||||
}),
|
||||
);
|
||||
const clientFor = Effect.fn("HermesBridge.client")(function* (target: HermesTarget) {
|
||||
const settings = yield* getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(error) => new HermesError({ message: error.message, operation: "settings" }),
|
||||
),
|
||||
);
|
||||
const instance = settings.providerInstances[target.instanceId];
|
||||
if (!instance || instance.driver !== "hermes" || instance.enabled === false) {
|
||||
return yield* new HermesError({
|
||||
message: "Select an enabled Hermes provider in this environment.",
|
||||
operation: "settings",
|
||||
});
|
||||
}
|
||||
const config = yield* Effect.try({
|
||||
try: () => decodeSettings(instance.config ?? settings.providers.hermes),
|
||||
catch: () =>
|
||||
new HermesError({ message: "Invalid Hermes provider settings.", operation: "settings" }),
|
||||
});
|
||||
const environment = Object.fromEntries(
|
||||
Object.entries(process.env).filter(
|
||||
(entry): entry is [string, string] => entry[1] !== undefined,
|
||||
),
|
||||
);
|
||||
for (const variable of instance.environment ?? []) environment[variable.name] = variable.value;
|
||||
const home = (environment.HERMES_HOME || path.join(NodeOS.homedir(), ".hermes")).replace(
|
||||
/^~(?=\/|$)/,
|
||||
NodeOS.homedir(),
|
||||
);
|
||||
const base = yield* Effect.try({
|
||||
try: () => new URL(config.dashboardUrl),
|
||||
catch: () =>
|
||||
new HermesError({
|
||||
message: "Set a valid Hermes Dashboard URL in provider settings.",
|
||||
operation: "settings",
|
||||
}),
|
||||
});
|
||||
if (
|
||||
!["http:", "https:"].includes(base.protocol) ||
|
||||
base.username ||
|
||||
base.password ||
|
||||
base.search ||
|
||||
base.hash
|
||||
) {
|
||||
return yield* new HermesError({
|
||||
message:
|
||||
"Hermes Dashboard URL must be an HTTP(S) address without credentials, query, or fragment.",
|
||||
operation: "settings",
|
||||
});
|
||||
}
|
||||
const key = `${target.instanceId}\n${base.href}\n${home}`;
|
||||
let client = clients.get(key);
|
||||
if (!client) {
|
||||
client = new DashboardClient(base, home, environment, io);
|
||||
clients.set(key, client);
|
||||
}
|
||||
return client;
|
||||
});
|
||||
const attempt = <Value>(operation: string, run: () => Promise<Value>) =>
|
||||
Effect.tryPromise({
|
||||
try: run,
|
||||
catch: (error) =>
|
||||
isHermesError(error)
|
||||
? error
|
||||
: new HermesError({
|
||||
operation,
|
||||
message: error instanceof Error ? error.message : "Hermes request failed.",
|
||||
}),
|
||||
});
|
||||
return {
|
||||
read: Effect.fn("HermesBridge.read")(function* (input: HermesReadInput) {
|
||||
const client = yield* clientFor(input);
|
||||
const data = yield* attempt(input.resource, async () =>
|
||||
input.resource === "commands"
|
||||
? client.rpc("complete.slash", { text: input.text ?? "/", profile: input.profile })
|
||||
: client.read(input),
|
||||
);
|
||||
return { data };
|
||||
}),
|
||||
write: Effect.fn("HermesBridge.write")(function* (input: HermesWriteInput) {
|
||||
const client = yield* clientFor(input);
|
||||
const data = yield* attempt(input.action, () => client.write(input));
|
||||
return { data };
|
||||
}),
|
||||
events: (input: HermesTarget) =>
|
||||
Stream.callback<HermesEvent, HermesError>((queue) =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* clientFor(input);
|
||||
const remove = client.listen((event) => {
|
||||
Queue.offerUnsafe(queue, event);
|
||||
});
|
||||
yield* Effect.addFinalizer(() => Effect.sync(remove));
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* HermesDriver — `ProviderDriver` for the Hermes Agent (`hermes acp`) runtime.
|
||||
*
|
||||
* Hermes exposes an ACP-based CLI. Model discovery happens during the managed
|
||||
* provider status check via ACP session setup; there is no standalone auth
|
||||
* probe, so a successful discovery doubles as proof of authentication.
|
||||
*
|
||||
* Text generation is supported via the ACP runtime — `makeHermesTextGeneration`
|
||||
* drives `runtime.prompt` with a structured-output schema and collects the
|
||||
* agent's `agent_message_chunk` stream into a single JSON blob.
|
||||
*
|
||||
* @module provider/Drivers/HermesDriver
|
||||
*/
|
||||
import { HermesSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeHermesTextGeneration } from "../../textGeneration/HermesTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
|
||||
import {
|
||||
buildInitialHermesProviderSnapshot,
|
||||
checkHermesProviderStatus,
|
||||
enrichHermesSnapshot,
|
||||
} from "../Layers/HermesProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import {
|
||||
haveProviderSnapshotSettingsChanged,
|
||||
makeProviderSnapshotSettingsSource,
|
||||
type ProviderSnapshotSettings,
|
||||
} from "../providerUpdateSettings.ts";
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
// `ServerConfig` stays in the union even though `create` never yields it
|
||||
// directly: `makeHermesAdapter` reads it for the attachments directory.
|
||||
export type HermesDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "Hermes",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: HermesSettings,
|
||||
defaultConfig: (): HermesSettings => decodeHermesSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
displayName,
|
||||
accentColor,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies HermesSettings;
|
||||
|
||||
const adapter = yield* makeHermesAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
instanceId,
|
||||
});
|
||||
const textGeneration = yield* makeHermesTextGeneration(effectiveConfig, processEnv);
|
||||
|
||||
const checkProvider = checkHermesProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<HermesSettings>>({
|
||||
resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
initialSnapshot: (settings) =>
|
||||
buildInitialHermesProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
|
||||
checkProvider,
|
||||
// Model data comes exclusively from ACP session setup during provider
|
||||
// status checks; enrichment only republishes version advisory metadata.
|
||||
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
|
||||
enrichHermesSnapshot({
|
||||
settings: settings.provider,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities: MAINTENANCE_CAPABILITIES,
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Hermes snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,475 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - the suite writes a real shell wrapper for the mock ACP agent to a temp dir with Node fs/path/url.
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
HermesSettings,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
makeHermesAdapter,
|
||||
resolveRequestedModeId,
|
||||
selectAutoApprovedPermissionOption,
|
||||
selectHermesPermissionOptionId,
|
||||
} from "./HermesAdapter.ts";
|
||||
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const mockAgentCommand = process.execPath;
|
||||
|
||||
async function makeMockHermesWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "hermes-acp-mock-"));
|
||||
const wrapperPath = NodePath.join(dir, "fake-hermes.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await NodeFSP.writeFile(wrapperPath, script, "utf8");
|
||||
await NodeFSP.chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
const hermesAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-hermes-adapter-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeHermesAdapter>[1]) =>
|
||||
makeHermesAdapter(decodeHermesSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("auto-approves with allow_always when the agent offers it", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Always allow", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
assert.equal(optionId, "allow-always");
|
||||
});
|
||||
|
||||
it("auto-approves with allow_once when allow_always is absent", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
assert.equal(optionId, "allow-once");
|
||||
});
|
||||
|
||||
it("auto-approves nothing when the agent offers no allow options", () => {
|
||||
const optionId = selectAutoApprovedPermissionOption({
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [{ optionId: "reject-once", name: "Reject", kind: "reject_once" }],
|
||||
});
|
||||
assert.isUndefined(optionId);
|
||||
});
|
||||
|
||||
it("answers a manual decision with the agent's advertised option id", () => {
|
||||
const request = {
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" as const },
|
||||
{ optionId: "permit-always-7", name: "Always allow", kind: "allow_always" as const },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" as const },
|
||||
],
|
||||
};
|
||||
assert.equal(selectHermesPermissionOptionId(request, "accept"), "permit-42");
|
||||
assert.equal(selectHermesPermissionOptionId(request, "acceptForSession"), "permit-always-7");
|
||||
assert.equal(selectHermesPermissionOptionId(request, "decline"), "deny-9");
|
||||
});
|
||||
|
||||
it("treats acceptAlways as a persistent allow, never a rejection", () => {
|
||||
const options = [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" as const },
|
||||
{ optionId: "permit-always-7", name: "Always allow", kind: "allow_always" as const },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" as const },
|
||||
];
|
||||
assert.equal(
|
||||
selectHermesPermissionOptionId(
|
||||
{ sessionId: "mock-session-1", toolCall: { toolCallId: "tool-1" }, options },
|
||||
"acceptAlways",
|
||||
),
|
||||
"permit-always-7",
|
||||
);
|
||||
// Without allow_always the persistent accept degrades to a one-shot allow,
|
||||
// never to the reject option.
|
||||
assert.equal(
|
||||
selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: options.filter((option) => option.kind !== "allow_always"),
|
||||
},
|
||||
"acceptAlways",
|
||||
),
|
||||
"permit-42",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to allow_once for a session accept when allow_always is absent", () => {
|
||||
const optionId = selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [
|
||||
{ optionId: "permit-42", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "deny-9", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
"acceptForSession",
|
||||
);
|
||||
assert.equal(optionId, "permit-42");
|
||||
});
|
||||
|
||||
it("selects no option when the agent advertised none matching the decision", () => {
|
||||
const optionId = selectHermesPermissionOptionId(
|
||||
{
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: { toolCallId: "tool-1" },
|
||||
options: [{ optionId: "permit-42", name: "Allow once", kind: "allow_once" }],
|
||||
},
|
||||
"decline",
|
||||
);
|
||||
assert.isUndefined(optionId);
|
||||
});
|
||||
|
||||
it("resolves plan interaction mode to the agent's plan mode", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "full-access",
|
||||
modeState: {
|
||||
currentModeId: "implement",
|
||||
availableModes: [
|
||||
{ id: "plan", name: "Plan" },
|
||||
{ id: "implement", name: "Implement" },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "plan");
|
||||
});
|
||||
|
||||
it("resolves approval-required to an approval-shaped mode before implement", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "implement",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask" },
|
||||
{ id: "implement", name: "Implement" },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "ask");
|
||||
});
|
||||
|
||||
// The exact session modes the live `hermes acp` CLI (v0.21) advertises. All
|
||||
// three mention "ask", so approval selection cannot lean on substring order.
|
||||
const liveHermesModes = [
|
||||
{ id: "default", name: "Default", description: "Ask before edits." },
|
||||
{
|
||||
id: "accept_edits",
|
||||
name: "Accept Edits",
|
||||
description: "Auto-allow workspace and /tmp edits; still asks for sensitive paths.",
|
||||
},
|
||||
{
|
||||
id: "dont_ask",
|
||||
name: "Don't Ask",
|
||||
description: "Auto-allow file edits for this session except sensitive paths.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
it("resolves approval-required to the mode that still prompts", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: { currentModeId: "default", availableModes: liveHermesModes },
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("resolves approval-required independently of the order Hermes lists modes in", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [liveHermesModes[2], liveHermesModes[1], liveHermesModes[0]],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("still resolves the implement mode when approvals are not required", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "full-access",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [liveHermesModes[2], liveHermesModes[1], liveHermesModes[0]],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "default");
|
||||
});
|
||||
|
||||
it("resolves approval-required to an asking mode that shares no alias with its id", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "approval-required",
|
||||
modeState: {
|
||||
currentModeId: "dont_ask",
|
||||
availableModes: [
|
||||
{ id: "dont_ask", name: "Don't Ask", description: "Auto-allow." },
|
||||
{ id: "confirm_edits", name: "Confirm Edits", description: "Ask before applying edits." },
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(modeId, "confirm_edits");
|
||||
});
|
||||
|
||||
it("resolves no mode when the agent advertises none", () => {
|
||||
const modeId = resolveRequestedModeId({
|
||||
interactionMode: undefined,
|
||||
runtimeMode: "full-access",
|
||||
modeState: undefined,
|
||||
});
|
||||
assert.isUndefined(modeId);
|
||||
});
|
||||
|
||||
it.layer(hermesAdapterTestLayer)("HermesAdapter (mock ACP agent)", (it) => {
|
||||
it.effect("rejects rollback without discarding the provider conversation", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-unsupported-rollback");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "Remember this turn", attachments: [] });
|
||||
const originalTurns = [...(yield* adapter.readThread(threadId)).turns];
|
||||
|
||||
assert.isFalse(adapter.capabilities.supportsConversationRollback);
|
||||
const error = yield* adapter.rollbackThread(threadId, 1).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.deepStrictEqual((yield* adapter.readThread(threadId)).turns, originalTurns);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-mock-thread");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-mock-alt",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "hermes");
|
||||
assert.equal(session.model, "grok-mock-alt");
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hello hermes",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
const types = runtimeEvents.map((event) => event.type);
|
||||
|
||||
assert.includeMembers(types, [
|
||||
"session.started",
|
||||
"session.state.changed",
|
||||
"thread.started",
|
||||
"turn.started",
|
||||
"content.delta",
|
||||
"turn.completed",
|
||||
] as const);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never announces a turn whose preparation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-failed-preparation");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockHermesWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
if (String(event.threadId) === String(threadId)) {
|
||||
runtimeEvents.push(event);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Rejected prompt: whitespace-only text with no usable attachments.
|
||||
yield* Effect.flip(adapter.sendTurn({ threadId, input: " \n ", attachments: [] }));
|
||||
|
||||
// Rejected configuration: the mock refuses model ids it never advertised.
|
||||
yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "configure with a model the agent rejects",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "model-the-mock-never-advertises",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Neither failure may surface a turn: a started turn that cannot settle
|
||||
// leaves consumers with a permanently running turn.
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter((event) => event.type === "turn.started"),
|
||||
0,
|
||||
);
|
||||
|
||||
// The claim was released, so a good turn afterwards still runs normally.
|
||||
yield* adapter.sendTurn({ threadId, input: "now a real prompt", attachments: [] });
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter((event) => event.type === "turn.started"),
|
||||
1,
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("merges a sendTurn racing session configuration into the in-flight turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("hermes-steer-race");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockHermesWrapper({
|
||||
T3_ACP_EMIT_CONTENT_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "content.delta") {
|
||||
yield* Deferred.succeed(contentDelta, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("hermes"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Steer while the first prompt is still in flight. The steer must
|
||||
// observe the first turn's id — assigned synchronously with the
|
||||
// in-flight increment, before the awaited session configuration — and
|
||||
// merge into it; a second turn.started is the duplicate-turn
|
||||
// regression.
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "start work", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(contentDelta).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
|
||||
const steerSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "steer the running turn", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 12; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
// The steer folded into the running turn: exactly one turn.started,
|
||||
// one distinct turn id. A second of either is the regression.
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
assert.lengthOf(turnStartedEvents, 1);
|
||||
const turnIds = new Set(
|
||||
runtimeEvents
|
||||
.filter((event) => event.type === "turn.started")
|
||||
.map((event) => String(event.turnId)),
|
||||
);
|
||||
assert.equal(turnIds.size, 1);
|
||||
|
||||
// interruptTurn settles both in-flight prompts; stopSession tears the
|
||||
// hung mock child down regardless.
|
||||
yield* adapter.interruptTurn(threadId).pipe(Effect.ignore);
|
||||
yield* Fiber.interrupt(firstSendTurnFiber);
|
||||
yield* Fiber.interrupt(steerSendTurnFiber);
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId).pipe(Effect.ignore);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,346 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HermesSettings } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildHermesProviderSnapshot,
|
||||
checkHermesProviderStatus,
|
||||
getHermesFallbackModels,
|
||||
parseHermesCliVersion,
|
||||
parseHermesVersionOutput,
|
||||
} from "./HermesProvider.ts";
|
||||
|
||||
const decodeHermesSettings = Schema.decodeUnknownSync(HermesSettings);
|
||||
const baseHermesSettings = decodeHermesSettings({ enabled: true });
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
|
||||
});
|
||||
|
||||
const hermesVersionBanner = "Hermes Agent v0.21.0 (2026.8.31) · upstream f98f5e74";
|
||||
|
||||
/**
|
||||
* A minimal newline-delimited JSON-RPC agent whose `session/new` advertises an
|
||||
* empty model catalog — the one shape the shared ACP mock agent cannot
|
||||
* produce.
|
||||
*/
|
||||
const emptyModelsAgentSource = `import * as readline from "node:readline";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin });
|
||||
rl.on("line", (line) => {
|
||||
if (!line.trim()) return;
|
||||
const message = JSON.parse(line);
|
||||
if (message.id === undefined) return;
|
||||
const respond = (result) =>
|
||||
process.stdout.write(\`\${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\\n\`);
|
||||
switch (message.method) {
|
||||
case "initialize":
|
||||
respond({
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
authMethods: [{ id: "custom", name: "Custom", description: null }],
|
||||
});
|
||||
break;
|
||||
case "authenticate":
|
||||
respond({});
|
||||
break;
|
||||
case "session/new":
|
||||
respond({
|
||||
sessionId: "hermes-empty-models",
|
||||
models: { currentModelId: "default", availableModels: [] },
|
||||
});
|
||||
break;
|
||||
default:
|
||||
respond({});
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
/**
|
||||
* Wrap an ACP agent in a shell script that answers `--version` like the real
|
||||
* Hermes CLI. `versionExitCode` breaks the version probe; `acp` selects what
|
||||
* backs the discovery leg.
|
||||
*/
|
||||
const makeMockHermesWrapper = Effect.fn("makeMockHermesWrapper")(function* (options?: {
|
||||
readonly versionExitCode?: number;
|
||||
readonly acp?: "mock-agent" | "empty-models" | "fail";
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fileSystem.makeTempDirectory({
|
||||
directory: NodeOS.tmpdir(),
|
||||
prefix: "hermes-provider-mock-",
|
||||
});
|
||||
|
||||
const acpCommand = yield* Effect.gen(function* () {
|
||||
if (options?.acp === "fail") {
|
||||
return "exit 1";
|
||||
}
|
||||
if (options?.acp === "empty-models") {
|
||||
const agentPath = path.join(dir, "empty-models-agent.mjs");
|
||||
yield* fileSystem.writeFileString(agentPath, emptyModelsAgentSource);
|
||||
return `exec ${["node", agentPath].map((arg) => JSON.stringify(arg)).join(" ")} "$@"`;
|
||||
}
|
||||
const mockAgentPath = yield* resolveMockAgentPath();
|
||||
return `exec ${["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ")} "$@"`;
|
||||
});
|
||||
|
||||
const versionCommand =
|
||||
options?.versionExitCode !== undefined
|
||||
? `exit ${options.versionExitCode}`
|
||||
: `${["printf", "%s\n", hermesVersionBanner]
|
||||
.map((arg) => JSON.stringify(arg))
|
||||
.join(" ")}\n exit 0`;
|
||||
const script = `#!/bin/sh
|
||||
if [ "$1" = "--version" ]; then
|
||||
${versionCommand}
|
||||
fi
|
||||
${acpCommand}
|
||||
`;
|
||||
const wrapperPath = path.join(dir, "fake-hermes.sh");
|
||||
yield* fileSystem.writeFileString(wrapperPath, script);
|
||||
yield* fileSystem.chmod(wrapperPath, 0o755);
|
||||
return { wrapperPath, requestLogPath: path.join(dir, "requests.ndjson") };
|
||||
});
|
||||
|
||||
const missingHermesBinaryPath = "/definitely/not/installed/t3-hermes-agent";
|
||||
const hermesAcpDiscoveryFailedMessage = [
|
||||
"Hermes ACP model discovery failed.",
|
||||
"Hermes may not be configured on this machine yet; run `hermes setup` (or `hermes acp --setup`), then retry.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
|
||||
describe("parseHermesCliVersion", () => {
|
||||
it("extracts the semver from the real `hermes --version` banner, not the build date", () => {
|
||||
expect(parseHermesCliVersion(hermesVersionBanner)).toBe("0.21.0");
|
||||
});
|
||||
|
||||
it("falls back to the generic parser when the version is not v-prefixed", () => {
|
||||
expect(parseHermesCliVersion("hermes 0.21.0")).toBe("0.21.0");
|
||||
});
|
||||
|
||||
it("returns null when no version is present", () => {
|
||||
expect(parseHermesCliVersion("no version here")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseHermesVersionOutput", () => {
|
||||
it("treats a zero exit as a ready probe with unknown auth", () => {
|
||||
expect(
|
||||
parseHermesVersionOutput({
|
||||
stdout: hermesVersionBanner,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a non-zero exit as an error probe", () => {
|
||||
expect(
|
||||
parseHermesVersionOutput({
|
||||
stdout: "",
|
||||
stderr: "boom",
|
||||
code: 1,
|
||||
}),
|
||||
).toMatchObject({
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getHermesFallbackModels", () => {
|
||||
it("publishes the built-in default model plus custom models before ACP discovery", () => {
|
||||
expect(
|
||||
getHermesFallbackModels({
|
||||
customModels: ["anthropic:claude-fable-5"],
|
||||
}).map((model) => model.slug),
|
||||
).toEqual(["default", "anthropic:claude-fable-5"]);
|
||||
});
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("checkHermesProviderStatus", (it) => {
|
||||
it.effect("returns a disabled snapshot without probing the CLI", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
decodeHermesSettings({ enabled: false, binaryPath: missingHermesBinaryPath }),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
enabled: false,
|
||||
installed: false,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a missing Hermes command without attempting ACP discovery", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: missingHermesBinaryPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: [
|
||||
`Hermes Agent command \`${missingHermesBinaryPath}\` was not found.`,
|
||||
`Install the Hermes Agent CLI, make sure \`${missingHermesBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
].join(" "),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips ACP discovery when the version probe exits non-zero", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { wrapperPath, requestLogPath } = yield* makeMockHermesWrapper({ versionExitCode: 1 });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
{ ...baseHermesSettings, binaryPath: wrapperPath },
|
||||
{ ...process.env, T3_ACP_REQUEST_LOG_PATH: requestLogPath },
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
// The ACP mock agent logs every request; an absent log proves the
|
||||
// `parsed.status === "ready"` gate skipped discovery entirely.
|
||||
expect(yield* fileSystem.exists(requestLogPath)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes discovered models and authenticated auth when ACP discovery succeeds", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { wrapperPath, requestLogPath } = yield* makeMockHermesWrapper();
|
||||
|
||||
const provider = yield* checkHermesProviderStatus(
|
||||
{ ...baseHermesSettings, binaryPath: wrapperPath },
|
||||
{ ...process.env, T3_ACP_REQUEST_LOG_PATH: requestLogPath },
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
});
|
||||
expect(provider.message).toBeUndefined();
|
||||
// The shared ACP mock agent advertises a fixed grok-flavored catalog.
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
|
||||
// The mock agent logs every request before responding, so the log is
|
||||
// complete by the time the status check resolves.
|
||||
expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("downgrades to warning with fallback models when ACP discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { wrapperPath } = yield* makeMockHermesWrapper({ acp: "fail" });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: wrapperPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: hermesAcpDiscoveryFailedMessage,
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks auth authenticated but warns when discovery returns no models", () =>
|
||||
Effect.gen(function* () {
|
||||
const { wrapperPath } = yield* makeMockHermesWrapper({ acp: "empty-models" });
|
||||
|
||||
const provider = yield* checkHermesProviderStatus({
|
||||
...baseHermesSettings,
|
||||
binaryPath: wrapperPath,
|
||||
});
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: true,
|
||||
version: "0.21.0",
|
||||
status: "warning",
|
||||
auth: { status: "authenticated" },
|
||||
message: "Hermes ACP model discovery returned no built-in models.",
|
||||
});
|
||||
expect(provider.models.map((model) => model.slug)).toEqual(["default"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("buildHermesProviderSnapshot", () => {
|
||||
it("downgrades ready status to warning when ACP model discovery fails", () => {
|
||||
expect(
|
||||
buildHermesProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
hermesSettings: baseHermesSettings,
|
||||
parsed: {
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
},
|
||||
discoveryWarning: "Hermes ACP model discovery timed out after 15000ms.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "warning",
|
||||
message: "Hermes ACP model discovery timed out after 15000ms.",
|
||||
models: [{ slug: "default", isCustom: false }],
|
||||
});
|
||||
});
|
||||
|
||||
it("publishes discovered models without a warning when discovery succeeds", () => {
|
||||
expect(
|
||||
buildHermesProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
hermesSettings: baseHermesSettings,
|
||||
parsed: {
|
||||
version: "0.21.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
},
|
||||
discoveredModels: [
|
||||
{
|
||||
slug: "moa:default",
|
||||
name: "MoA Default",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({ optionDescriptors: [] }),
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
models: [{ slug: "moa:default", isCustom: false }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
import type {
|
||||
HermesSettings,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { HERMES_DEFAULT_MODEL_SLUG, makeHermesAcpRuntime } from "../acp/HermesAcpSupport.ts";
|
||||
|
||||
const HERMES_PRESENTATION = {
|
||||
displayName: "Hermes",
|
||||
badgeLabel: "Experimental",
|
||||
showInteractionModeToggle: false,
|
||||
} as const;
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
|
||||
const HERMES_VERSION_PROBE_TIMEOUT_MS = 4_000;
|
||||
const HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const HERMES_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Hermes ACP model discovery failed.",
|
||||
"Hermes may not be configured on this machine yet; run `hermes setup` (or `hermes acp --setup`), then retry.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
|
||||
const HERMES_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: HERMES_DEFAULT_MODEL_SLUG,
|
||||
name: "Hermes (configured default)",
|
||||
isCustom: false,
|
||||
isDefault: true,
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
},
|
||||
];
|
||||
|
||||
export function buildInitialHermesProviderSnapshot(
|
||||
hermesSettings: HermesSettings,
|
||||
): Effect.Effect<ServerProviderDraft> {
|
||||
return Effect.gen(function* () {
|
||||
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const models = getHermesFallbackModels(hermesSettings);
|
||||
|
||||
if (!hermesSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Checking Hermes Agent availability...",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function buildHermesDiscoveredModelsFromSessionModelState(
|
||||
modelState: EffectAcpSchema.SessionModelState | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (!modelState || modelState.availableModels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
// Mark the session's current model as the default so the model resolver
|
||||
// binds new sessions to it instead of the catalog's first entry — without
|
||||
// this a session/set_model fires on every start, switching the agent away
|
||||
// from its own configured model.
|
||||
const currentModelId = modelState.currentModelId?.trim();
|
||||
const seen = new Set<string>();
|
||||
return modelState.availableModels.flatMap((model) => {
|
||||
const slug = model.modelId.trim();
|
||||
if (!slug || seen.has(slug)) {
|
||||
return [];
|
||||
}
|
||||
seen.add(slug);
|
||||
return [
|
||||
{
|
||||
slug,
|
||||
name: model.name.trim() || slug,
|
||||
isCustom: false,
|
||||
...(slug === currentModelId ? { isDefault: true } : {}),
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
} satisfies ServerProviderModel,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export const discoverHermesModelsViaAcp = (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const acp = yield* makeHermesAcpRuntime({
|
||||
hermesSettings,
|
||||
...(environment ? { environment } : {}),
|
||||
childProcessSpawner,
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
|
||||
});
|
||||
const started = yield* acp.start();
|
||||
return buildHermesDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
export function getHermesFallbackModels(
|
||||
hermesSettings: Pick<HermesSettings, "customModels">,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return providerModelsFromSettings(
|
||||
HERMES_BUILT_IN_MODELS,
|
||||
hermesSettings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the Hermes Agent version from `hermes --version` output.
|
||||
*
|
||||
* The first line looks like:
|
||||
* `Hermes Agent v0.21.0 (2026.8.31) · upstream f98f5e74`
|
||||
*
|
||||
* The generic parser would grab the parenthesised build date first, so we
|
||||
* prefer the `v`-prefixed semver token and fall back to the generic parser.
|
||||
*/
|
||||
export function parseHermesCliVersion(output: string): string | null {
|
||||
const match = output.match(/\bv(\d+\.\d+\.\d+)\b/);
|
||||
return match?.[1] ?? parseGenericCliVersion(output);
|
||||
}
|
||||
|
||||
export interface HermesVersionResult {
|
||||
readonly version: string | null;
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: ServerProviderAuth;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
|
||||
const parts: Array<string> = [];
|
||||
for (const message of messages) {
|
||||
const trimmed = message?.trim();
|
||||
if (trimmed) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildHermesCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Hermes Agent command \`${binaryPath}\` was not found.`,
|
||||
`Install the Hermes Agent CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildHermesProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly hermesSettings: HermesSettings;
|
||||
readonly parsed: HermesVersionResult;
|
||||
readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
|
||||
readonly discoveryWarning?: string;
|
||||
}): ServerProviderDraft {
|
||||
const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: input.hermesSettings.enabled,
|
||||
checkedAt: input.checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
input.discoveredModels && input.discoveredModels.length > 0
|
||||
? input.discoveredModels
|
||||
: HERMES_BUILT_IN_MODELS,
|
||||
input.hermesSettings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: true,
|
||||
version: input.parsed.version,
|
||||
status:
|
||||
input.discoveryWarning && input.parsed.status === "ready" ? "warning" : input.parsed.status,
|
||||
auth: input.parsed.auth,
|
||||
...(message ? { message } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Interpret `hermes --version` output as a probe result. */
|
||||
export function parseHermesVersionOutput(result: CommandResult): HermesVersionResult {
|
||||
const version = parseHermesCliVersion(`${result.stdout}\n${result.stderr}`);
|
||||
if (result.code !== 0) {
|
||||
return {
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
return { version, status: "ready", auth: { status: "unknown" } };
|
||||
}
|
||||
|
||||
const runHermesVersionCommand = (hermesSettings: HermesSettings, environment?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const command = hermesSettings.binaryPath || "hermes";
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
command,
|
||||
["--version"],
|
||||
environment ? { env: environment } : {},
|
||||
);
|
||||
return yield* spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...(environment ? { env: environment } : { extendEnv: true }),
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const checkHermesProviderStatus = Effect.fn("checkHermesProviderStatus")(function* (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
|
||||
> {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const fallbackModels = getHermesFallbackModels(hermesSettings);
|
||||
|
||||
if (!hermesSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runHermesVersionCommand(hermesSettings, environment).pipe(
|
||||
Effect.timeoutOption(HERMES_VERSION_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
yield* Effect.logWarning("Hermes Agent CLI health check failed.", {
|
||||
errorTag: error._tag,
|
||||
});
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: hermesSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? buildHermesCliCommandMissingMessage(hermesSettings.binaryPath || "hermes")
|
||||
: "Failed to execute Hermes Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
presentation: HERMES_PRESENTATION,
|
||||
enabled: hermesSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Hermes Agent CLI is installed but timed out while running `hermes --version`.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseHermesVersionOutput(versionProbe.success.value);
|
||||
// Hermes has no standalone auth probe: `hermes acp` authenticates through the
|
||||
// "custom" method during startup, so a successful ACP discovery doubles as
|
||||
// proof of authentication.
|
||||
let auth: ServerProviderAuth = parsed.auth;
|
||||
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
|
||||
let discoveryWarning: string | undefined;
|
||||
if (parsed.status === "ready") {
|
||||
const discoveryExit = yield* Effect.exit(
|
||||
discoverHermesModelsViaAcp(hermesSettings, environment).pipe(
|
||||
Effect.timeoutOption(HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
|
||||
),
|
||||
);
|
||||
if (Exit.isFailure(discoveryExit)) {
|
||||
yield* Effect.logWarning("Hermes ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = HERMES_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Hermes ACP model discovery timed out after ${HERMES_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
discoveryWarning = "Hermes ACP model discovery returned no built-in models.";
|
||||
auth = { status: "authenticated" };
|
||||
} else {
|
||||
discoveredModels = discoveryExit.value;
|
||||
auth = { status: "authenticated" };
|
||||
}
|
||||
}
|
||||
return buildHermesProviderSnapshot({
|
||||
checkedAt,
|
||||
hermesSettings,
|
||||
parsed: { ...parsed, auth },
|
||||
discoveredModels: Option.getOrElse(
|
||||
Option.filter(discoveredModels, (models) => models.length > 0),
|
||||
() => [] as const,
|
||||
),
|
||||
...(discoveryWarning ? { discoveryWarning } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Background maintenance enrichment for a Hermes snapshot.
|
||||
*
|
||||
* Used by `HermesDriver` as the `makeManagedServerProvider.enrichSnapshot`
|
||||
* hook: republishes update/version advisory metadata without performing any
|
||||
* model or capability discovery. Hermes model data comes exclusively from ACP
|
||||
* session setup during provider status checks.
|
||||
*/
|
||||
export const enrichHermesSnapshot = (input: {
|
||||
readonly settings: HermesSettings;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly enableProviderUpdateChecks?: boolean;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
if (!settings.enabled || snapshot.auth.status === "unauthenticated") {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: input.enableProviderUpdateChecks,
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Hermes version advisory enrichment failed", {
|
||||
errorTag: causeErrorTag(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -10,7 +10,7 @@
|
||||
*
|
||||
* 2. **Many drivers, one registry** — the "all drivers slice" describe
|
||||
* block below configures one instance of every shipped driver
|
||||
* (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
|
||||
* (`codex`, `claudeAgent`, `cursor`, `grok`, `hermes`, `opencode`) in a single
|
||||
* `ProviderInstanceConfigMap` and asserts the registry boots them all
|
||||
* without cross-contamination. This proves the driver SPI is uniform
|
||||
* across every provider — any driver plugs into the registry through
|
||||
@@ -18,7 +18,7 @@
|
||||
*
|
||||
* Every instance in these tests is configured with `enabled: false` so the
|
||||
* provider-status checks short-circuit to pending/disabled snapshots
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `hermes` / `opencode`
|
||||
* binaries. That keeps the assertions focused on registry routing
|
||||
* behaviour rather than the runtime details of each provider.
|
||||
*/
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type CodexSettings,
|
||||
type CursorSettings,
|
||||
type GrokSettings,
|
||||
type HermesSettings,
|
||||
type OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfigMap,
|
||||
@@ -53,6 +54,7 @@ import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { HermesDriver } from "../Drivers/HermesDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import * as ModelManifest from "../ModelManifest.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
@@ -133,6 +135,14 @@ const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeHermesConfig = (overrides: Partial<HermesSettings>): HermesSettings => ({
|
||||
dashboardUrl: "http://127.0.0.1:9119",
|
||||
enabled: false,
|
||||
binaryPath: "hermes",
|
||||
customModels: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "opencode",
|
||||
@@ -468,12 +478,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const claudeId = ProviderInstanceId.make("claude_default");
|
||||
const cursorId = ProviderInstanceId.make("cursor_default");
|
||||
const grokId = ProviderInstanceId.make("grok_default");
|
||||
const hermesId = ProviderInstanceId.make("hermes_default");
|
||||
const openCodeId = ProviderInstanceId.make("opencode_default");
|
||||
|
||||
const codexDriverKind = ProviderDriverKind.make("codex");
|
||||
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
|
||||
const cursorDriverKind = ProviderDriverKind.make("cursor");
|
||||
const grokDriverKind = ProviderDriverKind.make("grok");
|
||||
const hermesDriverKind = ProviderDriverKind.make("hermes");
|
||||
const openCodeDriverKind = ProviderDriverKind.make("opencode");
|
||||
|
||||
const configMap: ProviderInstanceConfigMap = {
|
||||
@@ -504,6 +516,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
enabled: false,
|
||||
config: makeGrokConfig({}),
|
||||
},
|
||||
[hermesId]: {
|
||||
driver: hermesDriverKind,
|
||||
displayName: "Hermes",
|
||||
enabled: false,
|
||||
config: makeHermesConfig({}),
|
||||
},
|
||||
[openCodeId]: {
|
||||
driver: openCodeDriverKind,
|
||||
displayName: "OpenCode",
|
||||
@@ -513,7 +531,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
};
|
||||
|
||||
const { registry } = yield* makeProviderInstanceRegistry<BuiltInDriversEnv>({
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
|
||||
drivers: [
|
||||
CodexDriver,
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
HermesDriver,
|
||||
OpenCodeDriver,
|
||||
],
|
||||
configMap,
|
||||
});
|
||||
|
||||
@@ -523,9 +548,9 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(unavailable).toEqual([]);
|
||||
|
||||
const instances = yield* registry.listInstances;
|
||||
expect(instances).toHaveLength(5);
|
||||
expect(instances).toHaveLength(6);
|
||||
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
|
||||
[codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
|
||||
[codexId, claudeId, cursorId, grokId, hermesId, openCodeId].toSorted(),
|
||||
);
|
||||
|
||||
// Instance lookup by id resolves each instance to its own bundle —
|
||||
@@ -535,16 +560,19 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const claude = yield* registry.getInstance(claudeId);
|
||||
const cursor = yield* registry.getInstance(cursorId);
|
||||
const grok = yield* registry.getInstance(grokId);
|
||||
const hermes = yield* registry.getInstance(hermesId);
|
||||
const openCode = yield* registry.getInstance(openCodeId);
|
||||
expect(codex?.driverKind).toBe(codexDriverKind);
|
||||
expect(claude?.driverKind).toBe(claudeDriverKind);
|
||||
expect(cursor?.driverKind).toBe(cursorDriverKind);
|
||||
expect(grok?.driverKind).toBe(grokDriverKind);
|
||||
expect(hermes?.driverKind).toBe(hermesDriverKind);
|
||||
expect(openCode?.driverKind).toBe(openCodeDriverKind);
|
||||
expect(codex?.displayName).toBe("Codex");
|
||||
expect(claude?.displayName).toBe("Claude");
|
||||
expect(cursor?.displayName).toBe("Cursor");
|
||||
expect(grok?.displayName).toBe("Grok");
|
||||
expect(hermes?.displayName).toBe("Hermes");
|
||||
expect(openCode?.displayName).toBe("OpenCode");
|
||||
|
||||
// Every instance owns its own set of closures — no sharing across
|
||||
@@ -557,6 +585,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.adapter,
|
||||
cursor!.adapter,
|
||||
grok!.adapter,
|
||||
hermes!.adapter,
|
||||
openCode!.adapter,
|
||||
];
|
||||
expect(new Set(adapters).size).toBe(adapters.length);
|
||||
@@ -565,6 +594,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.textGeneration,
|
||||
cursor!.textGeneration,
|
||||
grok!.textGeneration,
|
||||
hermes!.textGeneration,
|
||||
openCode!.textGeneration,
|
||||
];
|
||||
expect(new Set(textGenerations).size).toBe(textGenerations.length);
|
||||
@@ -573,6 +603,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
claude!.snapshot,
|
||||
cursor!.snapshot,
|
||||
grok!.snapshot,
|
||||
hermes!.snapshot,
|
||||
openCode!.snapshot,
|
||||
];
|
||||
expect(new Set(snapshots).size).toBe(snapshots.length);
|
||||
@@ -613,6 +644,14 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(grokSnapshot.enabled).toBe(false);
|
||||
expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
|
||||
|
||||
const hermesSnapshot = yield* hermes!.snapshot.getSnapshot;
|
||||
expect(hermesSnapshot.instanceId).toBe(hermesId);
|
||||
expect(hermesSnapshot.driver).toBe(hermesDriverKind);
|
||||
expect(hermesSnapshot.enabled).toBe(false);
|
||||
expect(hermesSnapshot.continuation?.groupKey).toBe(
|
||||
`${hermesDriverKind}:instance:${hermesId}`,
|
||||
);
|
||||
|
||||
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
|
||||
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
|
||||
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
|
||||
|
||||
@@ -2244,6 +2244,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
// `providerInstances` keys are branded `ProviderInstanceId`;
|
||||
@@ -2356,6 +2357,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
}),
|
||||
@@ -2472,6 +2474,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
hermes: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
providerInstances: {
|
||||
@@ -2542,6 +2545,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
hermes: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -2616,6 +2622,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
"codex",
|
||||
"cursor",
|
||||
"grok",
|
||||
"hermes",
|
||||
"opencode",
|
||||
]);
|
||||
assert.strictEqual(cursorProvider?.enabled, false);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* HermesAdapter — shape type for the Hermes provider adapter.
|
||||
*
|
||||
* The driver model ({@link ../Drivers/HermesDriver}) bundles one adapter per
|
||||
* instance as a captured closure, so this module only retains the shape
|
||||
* interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module HermesAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* HermesAdapterShape — per-instance Hermes adapter contract.
|
||||
*/
|
||||
export interface HermesAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Optional integration check against a real `hermes acp` install.
|
||||
* Enable with: T3_HERMES_ACP_PROBE=1 vp test run HermesAcpCliProbe
|
||||
* Set T3_HERMES_LIVE_TURN=1 to also send a small prompt to the real model.
|
||||
*
|
||||
* Set T3_HERMES_ACP_PROBE_BINARY to run a hermes binary that is not on
|
||||
* PATH (a wrapper script that proxies stdio to a remote install works,
|
||||
* since ACP is pure stdio).
|
||||
*
|
||||
* The probe assumes the hermes runtime is already configured with model
|
||||
* credentials (`hermes setup`). The prompt turn calls the real model, so
|
||||
* it can take tens of seconds.
|
||||
*/
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { makeHermesAcpRuntime } from "./HermesAcpSupport.ts";
|
||||
|
||||
const probeBinaryPath = process.env.T3_HERMES_ACP_PROBE_BINARY || "hermes";
|
||||
|
||||
// The session cwd must exist wherever the hermes process actually runs:
|
||||
// `hermes acp` rejects `session/new` for a nonexistent cwd, and with a
|
||||
// remote wrapper binary a per-run local temp directory does not exist on
|
||||
// the remote host. `os.tmpdir()` exists everywhere a local install runs
|
||||
// and resolves to /tmp on the hosts a POSIX ssh shim targets;
|
||||
// T3_HERMES_ACP_PROBE_CWD overrides it when that assumption breaks.
|
||||
const probeCwd = process.env.T3_HERMES_ACP_PROBE_CWD || NodeOS.tmpdir();
|
||||
|
||||
const makeProbeRuntime = Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return yield* makeHermesAcpRuntime({
|
||||
hermesSettings: { binaryPath: probeBinaryPath },
|
||||
environment: process.env,
|
||||
childProcessSpawner,
|
||||
cwd: probeCwd,
|
||||
clientInfo: { name: "t3-hermes-probe", version: "0.0.0" },
|
||||
});
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_HERMES_ACP_PROBE === "1")("Hermes ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real hermes acp", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.initializeResult).toBeDefined();
|
||||
expect(typeof started.sessionId).toBe("string");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// Hermes spends a long thinking phase on even trivial prompts, so a real
|
||||
// turn regularly exceeds the suite's default test timeout. The probe is
|
||||
// env-gated and never runs in CI, so a generous explicit budget is safe.
|
||||
it.effect.skipIf(process.env.T3_HERMES_LIVE_TURN !== "1")(
|
||||
"finishes a real Hermes turn and streams its answer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
yield* runtime.start();
|
||||
const chunks: string[] = [];
|
||||
const events = yield* Stream.runForEach(runtime.getEvents(), (event) => {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
return Deferred.succeed(event.acknowledge, undefined);
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
chunks.push(event.text);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
const result = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "Reply exactly HERMES_T3_OK. Do not use any tools." }],
|
||||
});
|
||||
yield* runtime.drainEvents;
|
||||
expect(result.stopReason).toBe("end_turn");
|
||||
// Hermes's thinking-heavy turns don't reliably echo the exact token
|
||||
// (unlike the Grok probe) — assert streamed output arrived, not its
|
||||
// wording.
|
||||
expect(chunks.join("").length).toBeGreaterThan(0);
|
||||
yield* Fiber.interrupt(events);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
300_000,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { applyHermesAcpModelSelection, buildHermesAcpSpawnInput } from "./HermesAcpSupport.ts";
|
||||
|
||||
describe("buildHermesAcpSpawnInput", () => {
|
||||
it("spawns the configured binary with the acp subcommand", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "/opt/hermes" }, "/tmp/project", {
|
||||
PATH: "/usr/bin",
|
||||
});
|
||||
|
||||
expect(spawn).toEqual({
|
||||
command: "/opt/hermes",
|
||||
args: ["acp"],
|
||||
cwd: "/tmp/project",
|
||||
env: {
|
||||
PATH: "/usr/bin",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default binary name", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "" }, "/tmp/project");
|
||||
expect(spawn.command).toBe("hermes");
|
||||
});
|
||||
|
||||
it("falls back when settings are absent", () => {
|
||||
const spawn = buildHermesAcpSpawnInput(null, "/tmp/project");
|
||||
expect(spawn.command).toBe("hermes");
|
||||
});
|
||||
|
||||
it("omits env entirely when no environment is provided", () => {
|
||||
const spawn = buildHermesAcpSpawnInput({ binaryPath: "/opt/hermes" }, "/tmp/project");
|
||||
expect(spawn).toEqual({
|
||||
command: "/opt/hermes",
|
||||
args: ["acp"],
|
||||
cwd: "/tmp/project",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyHermesAcpModelSelection", () => {
|
||||
it.effect("passes the model id to session/set_model verbatim", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-opus-5",
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual(["anthropic:claude-fable-5"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never sends the default product slug as an ACP model id", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-fable-5",
|
||||
model: "default",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips session/set_model when the session is already on the model", () =>
|
||||
Effect.gen(function* () {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.sync(() => {
|
||||
modelCalls.push(modelId);
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "anthropic:claude-fable-5",
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => `failed to set model: ${cause.message}`,
|
||||
});
|
||||
|
||||
expect(modelCalls).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps set_model failures through mapError", () =>
|
||||
Effect.gen(function* () {
|
||||
const acpFailure = new EffectAcpErrors.AcpTransportError({
|
||||
detail: "set_model exploded",
|
||||
cause: new Error("set_model exploded"),
|
||||
});
|
||||
const runtime = {
|
||||
setSessionModel: () => Effect.fail(acpFailure),
|
||||
};
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: undefined,
|
||||
model: "anthropic:claude-fable-5",
|
||||
mapError: ({ cause }) => ({ mapped: true as const, cause }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure).toEqual({ mapped: true, cause: acpFailure });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { HermesSettings } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
/** Auth method advertised by `hermes acp` for pre-configured runtime credentials. */
|
||||
const HERMES_AUTH_METHOD_ID = "custom";
|
||||
|
||||
/**
|
||||
* The product slug T3 publishes for "whatever model Hermes is configured to
|
||||
* use". It is never a real ACP model id, so it must never reach
|
||||
* `session/set_model` — selecting it keeps the session on its current model.
|
||||
*/
|
||||
export const HERMES_DEFAULT_MODEL_SLUG = "default";
|
||||
|
||||
type HermesAcpRuntimeHermesSettings = Pick<HermesSettings, "binaryPath">;
|
||||
|
||||
interface HermesAcpRuntimeInput extends Omit<
|
||||
AcpSessionRuntime.AcpSessionRuntimeOptions,
|
||||
"authMethodId" | "clientCapabilities" | "spawn"
|
||||
> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly hermesSettings: HermesAcpRuntimeHermesSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export function buildHermesAcpSpawnInput(
|
||||
hermesSettings: HermesAcpRuntimeHermesSettings | null | undefined,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): AcpSessionRuntime.AcpSpawnInput {
|
||||
return {
|
||||
command: hermesSettings?.binaryPath || "hermes",
|
||||
args: ["acp"],
|
||||
cwd,
|
||||
...(environment ? { env: environment } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const makeHermesAcpRuntime = (
|
||||
input: HermesAcpRuntimeInput,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildHermesAcpSpawnInput(input.hermesSettings, input.cwd, input.environment),
|
||||
authMethodId: HERMES_AUTH_METHOD_ID,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
});
|
||||
|
||||
export interface HermesAcpModelSelectionErrorContext {
|
||||
readonly cause: EffectAcpErrors.AcpError;
|
||||
}
|
||||
|
||||
type HermesAcpModelSelectionRuntime = Pick<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
"setSessionModel"
|
||||
>;
|
||||
|
||||
export function currentHermesModelIdFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): string | undefined {
|
||||
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a model selection to a live Hermes ACP session. Hermes model ids
|
||||
* (e.g. `anthropic:claude-fable-5`) go to `session/set_model` verbatim —
|
||||
* there is no trait suffix to strip and no reasoning metadata to attach.
|
||||
* Nothing is sent when the selection is empty, is the `default` product slug
|
||||
* (which stands for the session's already-configured model, not a real ACP
|
||||
* id), or already matches the session's current model — a redundant
|
||||
* `session/set_model` risks a rejection for ids the agent reports as current
|
||||
* but does not advertise as switchable.
|
||||
*
|
||||
* `session/set_config_option` is not usable here: the real `hermes acp`
|
||||
* binary treats configId `"model"` as a silent no-op (it always returns
|
||||
* `{ configOptions: [] }`, even for invalid values), so model changes must
|
||||
* go through the unstable `session/set_model` capability instead.
|
||||
*/
|
||||
export function applyHermesAcpModelSelection<E>(input: {
|
||||
readonly runtime: HermesAcpModelSelectionRuntime;
|
||||
readonly currentModelId: string | undefined;
|
||||
readonly model: string;
|
||||
readonly mapError: (context: HermesAcpModelSelectionErrorContext) => E;
|
||||
}): Effect.Effect<void, E> {
|
||||
const requestedModelId = input.model.trim();
|
||||
if (
|
||||
requestedModelId.length === 0 ||
|
||||
requestedModelId === HERMES_DEFAULT_MODEL_SLUG ||
|
||||
requestedModelId === input.currentModelId
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return input.runtime.setSessionModel(requestedModelId).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError((cause) => input.mapError({ cause })),
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
|
||||
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
|
||||
import { HermesDriver, type HermesDriverEnv } from "./Drivers/HermesDriver.ts";
|
||||
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
|
||||
import { AntigravityDriver, type AntigravityDriverEnv } from "./Drivers/AntigravityDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
@@ -38,6 +39,7 @@ export type BuiltInDriversEnv =
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| GrokDriverEnv
|
||||
| HermesDriverEnv
|
||||
| OpenCodeDriverEnv
|
||||
| AntigravityDriverEnv;
|
||||
|
||||
@@ -51,6 +53,7 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
HermesDriver,
|
||||
OpenCodeDriver,
|
||||
AntigravityDriver,
|
||||
];
|
||||
@@ -6866,7 +6866,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () =>
|
||||
it.effect("routes projects.searchEntries with optional ignored files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -6920,6 +6920,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
assert.equal(response.entries.length, 0);
|
||||
assert.equal(response.truncated, false);
|
||||
const allFiles = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.projectsSearchEntries]({
|
||||
cwd: workspaceDir,
|
||||
query: "ignored-search-target",
|
||||
limit: 10,
|
||||
includeIgnored: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(allFiles.entries, [
|
||||
{ path: ".venv/lib/ignored-search-target.ts", kind: "file" },
|
||||
]);
|
||||
assert.equal(allFiles.truncated, false);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
|
||||
);
|
||||
|
||||
|
||||
@@ -617,10 +617,11 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
'{"providerInstances":{"cursor_work":{"driver":"cursor","config":{}},"grok":{"driver":"grok","config":{}},"opencode_work":{"driver":"opencode","config":{"serverUrl":"http://127.0.0.1:4096"}},"opencode_unused":{"driver":"opencode","config":{}}}}',
|
||||
'{"providerInstances":{"cursor_work":{"driver":"cursor","config":{}},"grok":{"driver":"grok","config":{}},"hermes":{"driver":"hermes","config":{}},"opencode_work":{"driver":"opencode","config":{"serverUrl":"http://127.0.0.1:4096"}},"opencode_unused":{"driver":"opencode","config":{}}}}',
|
||||
);
|
||||
yield* recordProviderUsage("cursor", "cursor_work");
|
||||
yield* recordProviderUsage("grok", null);
|
||||
yield* recordProviderUsage("hermes", null);
|
||||
yield* recordProviderUsage("opencode", "opencode_work");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
@@ -628,6 +629,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
assert.isTrue(settings.providers.cursor.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor_work")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("hermes")]?.enabled);
|
||||
assert.isTrue(settings.providerInstances[ProviderInstanceId.make("opencode_work")]?.enabled);
|
||||
const unused = settings.providerInstances[ProviderInstanceId.make("opencode_unused")];
|
||||
assert.isDefined(unused);
|
||||
@@ -642,18 +644,21 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
'{"providers":{"grok":{"enabled":false},"opencode":{"enabled":false},"cursor":{"enabled":false}},"providerInstances":{"grok":{"driver":"grok","enabled":false,"config":{}},"opencode":{"driver":"opencode","config":{"enabled":false}},"cursor":{"driver":"cursor","enabled":false,"config":{}}}}',
|
||||
'{"providers":{"grok":{"enabled":false},"hermes":{"enabled":false},"opencode":{"enabled":false},"cursor":{"enabled":false}},"providerInstances":{"grok":{"driver":"grok","enabled":false,"config":{}},"hermes":{"driver":"hermes","enabled":false,"config":{}},"opencode":{"driver":"opencode","config":{"enabled":false}},"cursor":{"driver":"cursor","enabled":false,"config":{}}}}',
|
||||
);
|
||||
yield* recordProviderUsage("grok");
|
||||
yield* recordProviderUsage("hermes");
|
||||
yield* recordProviderUsage("opencode");
|
||||
yield* recordProviderUsage("cursor");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
|
||||
assert.isFalse(settings.providers.grok.enabled);
|
||||
assert.isFalse(settings.providers.hermes.enabled);
|
||||
assert.isFalse(settings.providers.opencode.enabled);
|
||||
assert.isFalse(settings.providers.cursor.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("hermes")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("opencode")]?.enabled);
|
||||
assert.isFalse(settings.providerInstances[ProviderInstanceId.make("cursor")]?.enabled);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
@@ -705,6 +710,20 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("restores hermes from provider history when no settings file exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
yield* recordProviderUsage("hermes");
|
||||
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
|
||||
assert.isTrue(settings.providers.hermes.enabled);
|
||||
assert.isFalse(settings.providers.grok.enabled);
|
||||
assert.isFalse(settings.providers.opencode.enabled);
|
||||
assert.isFalse(settings.providers.cursor.enabled);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves provider history when the settings file is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
@@ -771,6 +790,27 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("falls back to the Hermes session model when only Hermes is enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
|
||||
const settings = yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: { enabled: false },
|
||||
claudeAgent: { enabled: false },
|
||||
hermes: { enabled: true },
|
||||
},
|
||||
});
|
||||
|
||||
// "default" is Hermes's product slug, not an ACP model id: the adapter
|
||||
// skips session/set_model for it and keeps Hermes's configured model.
|
||||
// Without a DEFAULT_MODEL_BY_PROVIDER entry the fallback would hand
|
||||
// Hermes the Codex text-generation slug, which Hermes rejects.
|
||||
assert.deepEqual(settings.textGenerationModelSelection.instanceId, "hermes");
|
||||
assert.deepEqual(settings.textGenerationModelSelection.model, "default");
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("persists explicit disables after a provider has been used", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
@@ -1043,6 +1083,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
hermes: {
|
||||
enabled: false,
|
||||
},
|
||||
opencode: {
|
||||
enabled: false,
|
||||
serverUrl: "http://127.0.0.1:4096",
|
||||
|
||||
@@ -263,6 +263,7 @@ const PersistedOptionalProviderSettings = Schema.Struct({
|
||||
Schema.Struct({
|
||||
cursor: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
grok: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
hermes: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
opencode: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
|
||||
}),
|
||||
),
|
||||
@@ -291,6 +292,7 @@ function restoreUsedProviders(
|
||||
instance.enabled === undefined &&
|
||||
(instance.driver === "cursor" ||
|
||||
instance.driver === "grok" ||
|
||||
instance.driver === "hermes" ||
|
||||
instance.driver === "opencode") &&
|
||||
usedProviderInstances.has(instanceId)
|
||||
? { ...instance, enabled: true }
|
||||
@@ -310,6 +312,10 @@ function restoreUsedProviders(
|
||||
...settings.providers.grok,
|
||||
enabled: persisted.providers?.grok?.enabled ?? usedProviders.has("grok"),
|
||||
},
|
||||
hermes: {
|
||||
...settings.providers.hermes,
|
||||
enabled: persisted.providers?.hermes?.enabled ?? usedProviders.has("hermes"),
|
||||
},
|
||||
opencode: {
|
||||
...settings.providers.opencode,
|
||||
enabled: persisted.providers?.opencode?.enabled ?? usedProviders.has("opencode"),
|
||||
@@ -367,6 +373,7 @@ const PERSISTED_SERVER_SETTINGS_DEFAULTS = {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
cursor: { ...DEFAULT_SERVER_SETTINGS.providers.cursor, enabled: undefined },
|
||||
grok: { ...DEFAULT_SERVER_SETTINGS.providers.grok, enabled: undefined },
|
||||
hermes: { ...DEFAULT_SERVER_SETTINGS.providers.hermes, enabled: undefined },
|
||||
opencode: { ...DEFAULT_SERVER_SETTINGS.providers.opencode, enabled: undefined },
|
||||
},
|
||||
};
|
||||
@@ -592,13 +599,13 @@ const make = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId"
|
||||
FROM projection_thread_sessions
|
||||
WHERE provider_name IN ('cursor', 'grok', 'opencode')
|
||||
WHERE provider_name IN ('cursor', 'grok', 'hermes', 'opencode')
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId"
|
||||
FROM provider_session_runtime
|
||||
WHERE provider_name IN ('cursor', 'grok', 'opencode')
|
||||
WHERE provider_name IN ('cursor', 'grok', 'hermes', 'opencode')
|
||||
`.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - the suite builds a real on-disk ACP agent wrapper with Node fs/path/url.
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodeURL from "node:url";
|
||||
import * as NodeFS from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import { HermesSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import { makeHermesTextGeneration } from "./HermesTextGeneration.ts";
|
||||
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
const HermesTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-hermes-text-generation-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
|
||||
const binDir = NodePath.join(dir, "bin");
|
||||
const agentPath = NodePath.join(binDir, "agent");
|
||||
NodeFS.mkdirSync(binDir, { recursive: true });
|
||||
NodeFS.writeFileSync(
|
||||
agentPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||
'if [ "$1" != "acp" ]; then',
|
||||
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||
" exit 11",
|
||||
"fi",
|
||||
`exec node ${JSON.stringify(mockAgentPath)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
NodeFS.chmodSync(agentPath, 0o755);
|
||||
return agentPath;
|
||||
}
|
||||
|
||||
function withFakeAcpAgent<A, E, R>(
|
||||
env: Record<string, string>,
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-acp-"));
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||
const config = decodeHermesSettings({ binaryPath: agentPath });
|
||||
const textGeneration = yield* makeHermesTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
|
||||
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = (yield* Clock.currentTimeMillis) + 5_000;
|
||||
for (;;) {
|
||||
const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8")));
|
||||
if (Exit.isSuccess(result)) {
|
||||
return result.value;
|
||||
}
|
||||
{
|
||||
if ((yield* Clock.currentTimeMillis) >= deadline) {
|
||||
return yield* Effect.die(result.cause);
|
||||
}
|
||||
}
|
||||
yield* Effect.sleep(25);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(HermesTextGenerationTestLayer)("HermesTextGeneration", (it) => {
|
||||
it.effect("forwards the requested model id to the ACP session verbatim", () => {
|
||||
const requestLogDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-log-"),
|
||||
);
|
||||
const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Add generated commit message",
|
||||
body: "- verify hermes acp model selection path",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-text-generation",
|
||||
stagedSummary: "M apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/HermesTextGeneration.ts b/apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
// The shared acp-mock-agent only allowlists grok-* ids for
|
||||
// session/set_model, so Hermes tests reuse them.
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("hermes"),
|
||||
"grok-mock-alt",
|
||||
),
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add generated commit message");
|
||||
expect(generated.body).toBe("- verify hermes acp model selection path");
|
||||
|
||||
const requests = NodeFS.readFileSync(requestLogPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map(
|
||||
(line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> },
|
||||
);
|
||||
|
||||
expect(
|
||||
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||
).toMatchObject({
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_model" &&
|
||||
request.params?.modelId === "grok-mock-alt",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Staged patch:"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
NodeFS.rmSync(requestLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts json objects with extra assistant text around them", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-noisy-json",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
|
||||
expect(generated.body).toBe("");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through Hermes ACP text generation", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
title: '"Trim reconnect spinner status after resume."',
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix the reconnect spinner after a resumed session.",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process after text generation completes", () => {
|
||||
const exitLogDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-hermes-text-exit-log-"),
|
||||
);
|
||||
const exitLogPath = NodePath.join(exitLogDir, "exit.log");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Close runtime after generation",
|
||||
body: "",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/hermes-runtime-close",
|
||||
stagedSummary: "M apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/HermesTextGeneration.ts b/apps/server/src/textGeneration/HermesTextGeneration.ts",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("hermes"),
|
||||
model: "grok-4.6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Close runtime after generation");
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("exit:0");
|
||||
|
||||
NodeFS.rmSync(exitLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { type HermesSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { extractJsonObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
applyHermesAcpModelSelection,
|
||||
currentHermesModelIdFromSessionSetup,
|
||||
makeHermesAcpRuntime,
|
||||
} from "../provider/acp/HermesAcpSupport.ts";
|
||||
|
||||
const HERMES_TIMEOUT_MS = 180_000;
|
||||
|
||||
const isTextGenerationError = Schema.is(TextGenerationError);
|
||||
|
||||
/**
|
||||
* Build a Hermes text-generation closure bound to a specific `HermesSettings`
|
||||
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
|
||||
*/
|
||||
export const makeHermesTextGeneration = Effect.fn("makeHermesTextGeneration")(function* (
|
||||
hermesSettings: HermesSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
|
||||
const runHermesJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const outputRef = yield* Ref.make("");
|
||||
const runtime = yield* makeHermesAcpRuntime({
|
||||
hermesSettings,
|
||||
environment: resolvedEnvironment,
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "agent_message_chunk") {
|
||||
return Effect.void;
|
||||
}
|
||||
const content = update.content;
|
||||
if (content.type !== "text") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.update(outputRef, (current) => current + content.text);
|
||||
});
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
const started = yield* runtime.start();
|
||||
yield* Effect.ignore(runtime.setMode("ask"));
|
||||
yield* applyHermesAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: currentHermesModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
model: modelSelection.model,
|
||||
mapError: ({ cause }) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to set Hermes ACP model for text generation.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: prompt }],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeoutOption(HERMES_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes Agent request timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes ACP request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const rawResult = (yield* Ref.get(outputRef)).trim();
|
||||
if (!rawResult) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
promptResult.stopReason === "cancelled"
|
||||
? "Hermes ACP request was cancelled."
|
||||
: "Hermes Agent returned empty output.",
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Hermes ACP text generation failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
|
||||
Effect.fn("HermesTextGeneration.generateCommitMessage")(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
|
||||
Effect.fn("HermesTextGeneration.generatePrContent")(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
|
||||
Effect.fn("HermesTextGeneration.generateBranchName")(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
|
||||
Effect.fn("HermesTextGeneration.generateThreadTitle")(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
previousTitle: input.previousTitle,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runHermesJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies TextGeneration.ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGeneration.TextGeneration["Service"];
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { vi } from "vite-plus/test";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
|
||||
import * as WorkspacePaths from "./WorkspacePaths.ts";
|
||||
@@ -77,6 +78,8 @@ const searchWorkspaceEntries = (input: {
|
||||
query: string;
|
||||
limit: number;
|
||||
kind?: "file" | "directory";
|
||||
includeIgnored?: boolean;
|
||||
imageOnly?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
@@ -95,6 +98,105 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("current filesystem search", () => {
|
||||
it.effect(
|
||||
"finds ignored APKs, hidden files, and nested build outputs without exposing git internals",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ git: true });
|
||||
yield* writeTextFile(cwd, ".gitignore", "build/\n*.apk\n.cache/\n");
|
||||
yield* writeTextFile(cwd, "build/outputs/app-release.apk", "binary artifact");
|
||||
yield* writeTextFile(cwd, ".cache/APP.APK");
|
||||
yield* writeTextFile(cwd, "download.apk");
|
||||
yield* writeTextFile(cwd, "mapKeys.ts");
|
||||
yield* writeTextFile(cwd, ".git/private.apk");
|
||||
yield* writeTextFile(cwd, "nested/.git/private.apk");
|
||||
const indexed = yield* searchWorkspaceEntries({ cwd, query: ".apk", limit: 200 });
|
||||
expect(indexed.entries.some((entry) => entry.path.toLowerCase().endsWith(".apk"))).toBe(
|
||||
false,
|
||||
);
|
||||
const result = yield* searchWorkspaceEntries({
|
||||
cwd,
|
||||
query: ".ApK",
|
||||
limit: 200,
|
||||
includeIgnored: true,
|
||||
});
|
||||
expect(result.entries.map((entry) => entry.path).sort()).toEqual([
|
||||
".cache/APP.APK",
|
||||
"build/outputs/app-release.apk",
|
||||
"download.apk",
|
||||
]);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reflects created and deleted files without refreshing an index", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const input = { cwd, query: "apk", limit: 200, includeIgnored: true };
|
||||
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]);
|
||||
yield* writeTextFile(cwd, "build/new.apk");
|
||||
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([
|
||||
{ path: "build/new.apk", kind: "file" },
|
||||
]);
|
||||
yield* fs.remove(path.join(cwd, "build/new.apk"));
|
||||
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds results and preserves kind, image, and multi-part query filters", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
yield* writeTextFile(cwd, "build/one.apk");
|
||||
yield* writeTextFile(cwd, "build/two.apk");
|
||||
yield* writeTextFile(cwd, "build/icon.png");
|
||||
const input = { cwd, query: "build", limit: 200, includeIgnored: true };
|
||||
expect(
|
||||
yield* searchWorkspaceEntries({ ...input, query: "build apk", limit: 1 }),
|
||||
).toMatchObject({
|
||||
entries: [expect.objectContaining({ kind: "file" })],
|
||||
truncated: true,
|
||||
});
|
||||
expect(
|
||||
yield* searchWorkspaceEntries({ ...input, query: "build/apk", limit: 2 }),
|
||||
).toMatchObject({
|
||||
entries: expect.arrayContaining([
|
||||
{ path: "build/one.apk", kind: "file" },
|
||||
{ path: "build/two.apk", kind: "file" },
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
expect((yield* searchWorkspaceEntries({ ...input, kind: "directory" })).entries).toEqual([
|
||||
{ path: "build", kind: "directory" },
|
||||
]);
|
||||
expect(
|
||||
(yield* searchWorkspaceEntries({ ...input, kind: "directory", imageOnly: true })).entries,
|
||||
).toEqual([{ path: "build/icon.png", kind: "file" }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.skipIf(!symlinksSupported)(
|
||||
"does not follow symlinks outside the workspace or into cycles",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
const outside = yield* makeTempDir();
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* writeTextFile(cwd, "inside.apk");
|
||||
yield* writeTextFile(outside, "outside.apk");
|
||||
yield* fs.symlink(outside, path.join(cwd, "outside"));
|
||||
yield* fs.symlink(cwd, path.join(cwd, "loop"));
|
||||
expect(
|
||||
(yield* searchWorkspaceEntries({ cwd, query: "apk", limit: 200, includeIgnored: true }))
|
||||
.entries,
|
||||
).toEqual([{ path: "inside.apk", kind: "file" }]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("list", () => {
|
||||
it.effect("lists immediate children including ignored and empty directories", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
|
||||
import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
|
||||
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
|
||||
|
||||
import { expandHomePathWith } from "../pathExpansion.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
@@ -236,8 +237,61 @@ export const make = Effect.gen(function* () {
|
||||
function* (input) {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
const normalizedQuery = normalizeSearchQuery(input.query, {
|
||||
trimLeadingPattern: /^[@./]+/,
|
||||
trimLeadingPattern: input.includeIgnored ? /^(?:@|\.[/\\])+/ : /^[@./]+/,
|
||||
});
|
||||
if (input.includeIgnored) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async (signal) => {
|
||||
const entries: ProjectEntry[] = [];
|
||||
const directories = [""];
|
||||
const tokens = normalizedQuery.split(/[\s/\\]+/).filter(Boolean);
|
||||
let truncated = false;
|
||||
while (directories.length > 0) {
|
||||
signal.throwIfAborted();
|
||||
const relativeDirectory = directories.pop()!;
|
||||
let directory;
|
||||
try {
|
||||
directory = await NodeFSP.opendir(path.join(normalizedCwd, relativeDirectory));
|
||||
} catch (cause) {
|
||||
const code = (cause as NodeJS.ErrnoException).code;
|
||||
if (code === "ENOENT" || code === "ENOTDIR") continue;
|
||||
if (code === "EACCES" || code === "EPERM") {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
for await (const child of directory) {
|
||||
signal.throwIfAborted();
|
||||
if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) continue;
|
||||
const relativePath = relativeDirectory
|
||||
? `${relativeDirectory}/${child.name}`
|
||||
: child.name;
|
||||
const kind = child.isDirectory() ? "directory" : "file";
|
||||
if (kind === "directory") directories.push(relativePath);
|
||||
if (
|
||||
input.imageOnly
|
||||
? kind !== "file" || !isWorkspaceImagePreviewPath(relativePath)
|
||||
: input.kind && input.kind !== kind
|
||||
)
|
||||
continue;
|
||||
if (!tokens.every((token) => relativePath.toLowerCase().includes(token))) continue;
|
||||
if (entries.length === input.limit) return { entries, truncated: true };
|
||||
entries.push({ path: relativePath, kind });
|
||||
}
|
||||
}
|
||||
return { entries, truncated };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed({
|
||||
cwd: normalizedCwd,
|
||||
queryLength: normalizedQuery.length,
|
||||
pageSize: input.limit,
|
||||
reason: "Failed to search current workspace files.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return yield* Effect.gen(function* () {
|
||||
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
|
||||
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeHermesBridge } from "./hermes/HermesBridge.ts";
|
||||
import {
|
||||
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
|
||||
AuthAccessStreamError,
|
||||
@@ -557,6 +558,7 @@ const makeWsRpcLayer = (
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const hermes = yield* makeHermesBridge(serverSettings.getSettings);
|
||||
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
@@ -1339,6 +1341,12 @@ const makeWsRpcLayer = (
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[WS_METHODS.hermesRead]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.hermesRead, hermes.read(input)),
|
||||
[WS_METHODS.hermesWrite]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.hermesWrite, hermes.write(input)),
|
||||
[WS_METHODS.hermesEvents]: (input) =>
|
||||
observeRpcStream(WS_METHODS.hermesEvents, hermes.events(input)),
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
|
||||
import { ConversationTabs, HermesSidebar, HermesWorkspace } from "./hermes/HermesWorkspace";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
useEffect,
|
||||
@@ -27,7 +29,7 @@ import {
|
||||
import LegacyThreadSidebar from "./LegacySidebar";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import {
|
||||
resolveSidebarStageFocusRingOffsetClass,
|
||||
useSidebarStageBackdropVariant,
|
||||
@@ -146,6 +148,7 @@ function ProjectProjectionRetention() {
|
||||
}
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const conversationSource = useAtomValue(conversationSourceAtom);
|
||||
const navigate = useNavigate();
|
||||
const legacySidebarEnabled = useLegacySidebarEnabled();
|
||||
const compactSidebarEnabled = useCompactSidebarEnabled();
|
||||
@@ -252,6 +255,13 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<SettingsSidebarNav pathname={pathname} />
|
||||
</>
|
||||
) : conversationSource === "hermes" ? (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<ConversationTabs />
|
||||
<HermesSidebar />
|
||||
<SidebarChromeFooter />
|
||||
</>
|
||||
) : legacySidebarEnabled ? (
|
||||
<LegacyThreadSidebar />
|
||||
) : (
|
||||
@@ -259,7 +269,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
)}
|
||||
<SidebarRail onDoubleClick={resetSidebarWidth} />
|
||||
</Sidebar>
|
||||
{children}
|
||||
{!isOnSettings && conversationSource === "hermes" ? <HermesWorkspace /> : children}
|
||||
<SidebarControl />
|
||||
</SidebarProvider>
|
||||
</PanelAnimationSuppressionProvider>
|
||||
|
||||
@@ -66,7 +66,8 @@ import {
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
|
||||
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
@@ -649,6 +650,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
const availableSettingsSearchItems = useAvailableSettingsSearchItems();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const conversationSource = useAtomValue(conversationSourceAtom);
|
||||
const setConversationSource = useAtomSet(conversationSourceAtom);
|
||||
const startHermesSession = useAtomSet(hermesNewSessionAtom);
|
||||
const projects = useProjects();
|
||||
const referenceThreadRef =
|
||||
pathname === "/pull-requests"
|
||||
@@ -1095,6 +1099,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
setConversationSource("t3");
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(
|
||||
@@ -1111,6 +1116,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
handleNewThread,
|
||||
navigate,
|
||||
projectGroupByTargetKey,
|
||||
setConversationSource,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
@@ -1275,6 +1281,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
: undefined;
|
||||
},
|
||||
runThread: async (thread) => {
|
||||
setConversationSource("t3");
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
@@ -1289,6 +1296,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
projectEnvironmentLocationById,
|
||||
projectTitleById,
|
||||
providerEntryByEnvironmentAndInstanceId,
|
||||
setConversationSource,
|
||||
threadContentMatchByKey,
|
||||
threadSearchQuery,
|
||||
threads,
|
||||
@@ -1643,7 +1651,22 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
if (conversationSource === "hermes") {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:new-hermes-session",
|
||||
searchTerms: ["new", "task", "hermes", "chat", "session"],
|
||||
title: "New Hermes session",
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "chat.new",
|
||||
run: async () => {
|
||||
startHermesSession((value) => value + 1);
|
||||
await navigate({ to: "/" });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (projects.length > 0 && conversationSource === "t3") {
|
||||
const activeProjectTitle =
|
||||
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
|
||||
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
|
||||
@@ -1855,6 +1878,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
description: contextualProjectGroup.displayName,
|
||||
icon: <FolderIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
setConversationSource("t3");
|
||||
await navigate({
|
||||
to: "/projects/$projectKey",
|
||||
params: { projectKey: contextualProjectGroup.projectKey },
|
||||
|
||||
@@ -709,6 +709,25 @@ export const AntigravityIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const HermesIcon: Icon = (props) => (
|
||||
<svg
|
||||
{...props}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 3v18" />
|
||||
<path d="M8.5 5.5C6 3.5 3.5 4 2 6c2.8-.2 4.8.7 6 2.5" />
|
||||
<path d="M15.5 5.5C18 3.5 20.5 4 22 6c-2.8-.2-4.8.7-6 2.5" />
|
||||
<path d="M8 9.5c0 2 1.7 2.5 4 3.5 2.3 1 4 1.5 4 3.5S14.3 19 12 20" />
|
||||
<path d="M16 9.5c0 2-1.7 2.5-4 3.5-2.3 1-4 1.5-4 3.5S9.7 19 12 20" />
|
||||
<path d="M10 3h4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const OpenCodeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clipPath="url(#opencode__clip0_1311_94969)">
|
||||
|
||||
@@ -196,6 +196,7 @@ import {
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { ConversationTabs } from "./hermes/HermesWorkspace";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
@@ -3804,6 +3805,7 @@ export default function LegacySidebar() {
|
||||
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
|
||||
))}
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<ConversationTabs />
|
||||
|
||||
<SidebarProjectsContent
|
||||
showArm64IntelBuildWarning={showArm64IntelBuildWarning}
|
||||
|
||||
@@ -235,6 +235,7 @@ import {
|
||||
} from "./ui/combobox";
|
||||
import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { ConversationTabs } from "./hermes/HermesWorkspace";
|
||||
import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -4688,6 +4689,7 @@ export default function Sidebar() {
|
||||
return (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<ConversationTabs />
|
||||
<SidebarContent
|
||||
className={cn(
|
||||
"gap-0",
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ClaudeAI,
|
||||
CursorIcon,
|
||||
GrokIcon,
|
||||
HermesIcon,
|
||||
Icon,
|
||||
OpenAI,
|
||||
OpenCodeIcon,
|
||||
@@ -15,6 +16,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
|
||||
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
|
||||
[ProviderDriverKind.make("cursor")]: CursorIcon,
|
||||
[ProviderDriverKind.make("grok")]: GrokIcon,
|
||||
[ProviderDriverKind.make("hermes")]: HermesIcon,
|
||||
[ProviderDriverKind.make("antigravity")]: AntigravityIcon,
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import { createFileTreeDragMentionController } from "./fileTreeDragMention";
|
||||
import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
|
||||
import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
|
||||
import { useDirectoryEntries } from "./useDirectoryEntries";
|
||||
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
|
||||
import { useProjectPathSearch } from "~/state/queries";
|
||||
|
||||
interface FileBrowserPanelProps {
|
||||
@@ -104,6 +105,7 @@ export default function FileBrowserPanel({
|
||||
workspaceMutationId,
|
||||
}: FileBrowserPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
|
||||
const composerRef = useComposerHandleContext();
|
||||
const {
|
||||
entries: directoryEntries,
|
||||
@@ -115,7 +117,10 @@ export default function FileBrowserPanel({
|
||||
} = useDirectoryEntries(environmentId, cwd);
|
||||
const [query, setQuery] = useState("");
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
const pathSearch = useProjectPathSearch({ environmentId, cwd, query: query.slice(0, 256) }, 200);
|
||||
const pathSearch = useProjectPathSearch(
|
||||
{ environmentId, cwd, query: query.slice(0, 256), includeIgnored: true },
|
||||
200,
|
||||
);
|
||||
const entries = useMemo(() => {
|
||||
const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
|
||||
if (query.trim() && !pathSearch.isPending) {
|
||||
@@ -179,9 +184,16 @@ export default function FileBrowserPanel({
|
||||
[
|
||||
{ id: "copy-mention", label: "Copy mention" },
|
||||
{ id: "add-to-chat", label: "Add to chat" },
|
||||
...(entryKindsRef.current.get(relativePath) === "file"
|
||||
? [{ id: "download", label: "Download file" }]
|
||||
: []),
|
||||
],
|
||||
position,
|
||||
);
|
||||
if (clicked === "download") {
|
||||
void downloadFile(relativePath);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-mention") {
|
||||
try {
|
||||
await writeTextToClipboard(mention);
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
|
||||
import {
|
||||
isWorkspaceAudioPreviewPath,
|
||||
isDownloadOnlyFile,
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspaceVideoPreviewPath,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
@@ -21,13 +22,14 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
|
||||
import { Code2, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react";
|
||||
import { Code2, Download, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
|
||||
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
|
||||
import { OpenInPicker } from "~/components/chat/OpenInPicker";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
|
||||
import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
|
||||
import { useRemoteOpenState } from "~/remoteOpen";
|
||||
@@ -55,6 +57,7 @@ import { AudioPreview } from "./AudioPreview";
|
||||
import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
|
||||
import { DelimitedTablePreview } from "./DelimitedTablePreview";
|
||||
import FileBrowserPanel from "./FileBrowserPanel";
|
||||
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
|
||||
import { FileBreadcrumbs } from "./FileBreadcrumbs";
|
||||
import { FileMarkdownPreview } from "./FileMarkdownPreview";
|
||||
import {
|
||||
@@ -921,6 +924,8 @@ export default function FilePreviewPanel({
|
||||
workspaceMutationId,
|
||||
}: FilePreviewPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
|
||||
const downloadOnly = relativePath !== null && isDownloadOnlyFile(relativePath);
|
||||
const wordWrap = useClientSettings((settings) => settings.wordWrap);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const remoteOpenState = useRemoteOpenState(environmentId);
|
||||
@@ -945,7 +950,7 @@ export default function FilePreviewPanel({
|
||||
environmentId,
|
||||
cwd,
|
||||
relativePath,
|
||||
attachment === undefined && !isMedia && !isPdf,
|
||||
attachment === undefined && !isMedia && !isPdf && !downloadOnly,
|
||||
);
|
||||
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
|
||||
const showExplorer = shouldShowFileExplorer({
|
||||
@@ -1108,6 +1113,14 @@ export default function FilePreviewPanel({
|
||||
enableShortcut={false}
|
||||
/>
|
||||
) : null}
|
||||
{relativePath && attachment === undefined ? (
|
||||
<FileSurfaceAction
|
||||
label="Download file"
|
||||
onPress={() => void downloadFile(relativePath)}
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
</FileSurfaceAction>
|
||||
) : null}
|
||||
{canToggleRendered && renderedMode ? (
|
||||
<FileSurfaceAction
|
||||
label={renderedToggleLabel(renderedMode, rendered)}
|
||||
@@ -1219,9 +1232,20 @@ export default function FilePreviewPanel({
|
||||
title={relativePath}
|
||||
workspaceMutationId={workspaceMutationId}
|
||||
/>
|
||||
) : relativePath && file.error && file.data === null ? (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
|
||||
{file.error}
|
||||
) : relativePath && (downloadOnly || (file.error && file.data === null)) ? (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 items-center justify-center px-6 text-center text-xs leading-relaxed text-muted-foreground">
|
||||
<p>
|
||||
{downloadOnly
|
||||
? "This file cannot be previewed. Would you like to download it?"
|
||||
: file.error}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void downloadFile(relativePath)}
|
||||
>
|
||||
Download file
|
||||
</Button>
|
||||
</div>
|
||||
) : relativePath && file.data === null ? (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { resolveAssetUrl } from "~/assets/assetUrls";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { assetEnvironment } from "~/state/assets";
|
||||
import { usePreparedConnection } from "~/state/session";
|
||||
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
|
||||
|
||||
export function useWorkspaceFileDownload(environmentId: EnvironmentId, cwd: string) {
|
||||
const connection = usePreparedConnection(environmentId);
|
||||
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
|
||||
const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
|
||||
refresh: true,
|
||||
reportFailure: false,
|
||||
});
|
||||
return useCallback(
|
||||
async (path: string) => {
|
||||
try {
|
||||
if (httpBaseUrl === null) throw new Error("Reconnect to the environment and try again.");
|
||||
const result = await createUrl({
|
||||
environmentId,
|
||||
input: {
|
||||
resource: { _tag: "draft-workspace-file", cwd, path, download: true },
|
||||
},
|
||||
});
|
||||
const url =
|
||||
result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null;
|
||||
if (url === null)
|
||||
throw new Error("The file could not be downloaded. Reconnect and try again.");
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = path.split(/[\\/]/).at(-1) ?? "download";
|
||||
document.body.append(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not download file",
|
||||
description: error instanceof Error ? error.message : "Try again.",
|
||||
});
|
||||
}
|
||||
},
|
||||
[createUrl, cwd, environmentId, httpBaseUrl],
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -70,6 +70,13 @@ describe("ProviderSettingsForm helpers", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers Hermes with its ACP binary setting", () => {
|
||||
const hermes = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("hermes")];
|
||||
expect(hermes).toBeDefined();
|
||||
expect(hermes?.badgeLabel).toBe("Experimental");
|
||||
expect(deriveProviderSettingsFields(hermes!).map((field) => field.key)).toEqual(["binaryPath"]);
|
||||
});
|
||||
|
||||
it("preserves unknown config keys while omitting empty configurable fields", () => {
|
||||
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
|
||||
expect(opencode).toBeDefined();
|
||||
|
||||
@@ -82,6 +82,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
|
||||
"/settings/keybindings": KeyboardIcon,
|
||||
"/settings/snap-shot": SnapShotIcon,
|
||||
"/settings/providers": BotIcon,
|
||||
"/settings/hermes": BotIcon,
|
||||
"/settings/integrations": BlocksIcon,
|
||||
"/settings/source-control": GitBranchIcon,
|
||||
"/settings/connections": Link2Icon,
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CodexSettings,
|
||||
CursorSettings,
|
||||
GrokSettings,
|
||||
HermesSettings,
|
||||
OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
ClaudeAI,
|
||||
CursorIcon,
|
||||
GrokIcon,
|
||||
HermesIcon,
|
||||
type Icon,
|
||||
OpenAI,
|
||||
OpenCodeIcon,
|
||||
@@ -70,6 +72,13 @@ const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] = [
|
||||
badgeLabel: "Early Access",
|
||||
settingsSchema: GrokSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("hermes"),
|
||||
label: "Hermes",
|
||||
icon: HermesIcon,
|
||||
badgeLabel: "Experimental",
|
||||
settingsSchema: HermesSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("opencode"),
|
||||
label: "OpenCode",
|
||||
|
||||
@@ -15,6 +15,7 @@ export type SettingsPath =
|
||||
| "/settings/keybindings"
|
||||
| "/settings/snap-shot"
|
||||
| "/settings/providers"
|
||||
| "/settings/hermes"
|
||||
| "/settings/integrations"
|
||||
| "/settings/source-control"
|
||||
| "/settings/connections"
|
||||
@@ -76,6 +77,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
|
||||
"/settings/keybindings": "Keybindings",
|
||||
"/settings/snap-shot": "SnapShots",
|
||||
"/settings/providers": "Providers",
|
||||
"/settings/hermes": "Hermes",
|
||||
"/settings/integrations": "Integrations",
|
||||
"/settings/source-control": "Source Control",
|
||||
"/settings/connections": "Connections",
|
||||
@@ -729,6 +731,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScop
|
||||
// environment at any selection. Neither needs a particular scope to render.
|
||||
"/settings/keybindings": null,
|
||||
"/settings/providers": null,
|
||||
"/settings/hermes": null,
|
||||
"/settings/integrations": null,
|
||||
"/settings/source-control": "environment-defaults",
|
||||
"/settings/connections": "connections",
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
} from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback } from "react";
|
||||
import { useAtomSet } from "@effect/atom-react";
|
||||
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
|
||||
import { Link, useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
|
||||
@@ -158,24 +160,27 @@ export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
}, [isMobile, setOpenMobile]);
|
||||
const setConversationSource = useAtomSet(conversationSourceAtom);
|
||||
const handlePullRequestsClick = useCallback(() => {
|
||||
setConversationSource("t3");
|
||||
closeMobileSidebar();
|
||||
void navigate({
|
||||
to: "/pull-requests",
|
||||
search: readPullRequestListPreferences(),
|
||||
});
|
||||
}, [closeMobileSidebar, navigate]);
|
||||
}, [closeMobileSidebar, navigate, setConversationSource]);
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
closeMobileSidebar();
|
||||
void navigate({ to: "/settings" });
|
||||
}, [closeMobileSidebar, navigate]);
|
||||
|
||||
const handleUsageClick = useCallback(() => {
|
||||
setConversationSource("t3");
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void navigate({ to: "/usage" });
|
||||
}, [isMobile, navigate, setOpenMobile]);
|
||||
}, [isMobile, navigate, setOpenMobile, setConversationSource]);
|
||||
|
||||
const handleBackClick = useCallback(() => {
|
||||
closeMobileSidebar();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopeProjectRef,
|
||||
@@ -56,6 +57,7 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
|
||||
}
|
||||
|
||||
export function useNewThreadHandler() {
|
||||
const setConversationSource = useAtomSet(conversationSourceAtom);
|
||||
const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const router = useRouter();
|
||||
@@ -78,6 +80,7 @@ export function useNewThreadHandler() {
|
||||
// prepared checkout, a task to write — addresses that one rather than looking the project
|
||||
// up again and finding whichever draft it happens to hold.
|
||||
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
|
||||
setConversationSource("t3");
|
||||
const projects = readProjects();
|
||||
const targetServerSettings =
|
||||
environmentServerConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
|
||||
@@ -435,7 +438,13 @@ export function useNewThreadHandler() {
|
||||
return { draftId, threadId };
|
||||
})();
|
||||
},
|
||||
[environmentServerConfigs, getCurrentRouteTarget, projectGroupingSettings, router],
|
||||
[
|
||||
environmentServerConfigs,
|
||||
getCurrentRouteTarget,
|
||||
projectGroupingSettings,
|
||||
router,
|
||||
setConversationSource,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import { Route as SettingsProjectsRouteImport } from './routes/settings.projects
|
||||
import { Route as SettingsOpenSourceLicensesRouteImport } from './routes/settings.open-source-licenses'
|
||||
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
|
||||
import { Route as SettingsIntegrationsRouteImport } from './routes/settings.integrations'
|
||||
import { Route as SettingsHermesRouteImport } from './routes/settings.hermes'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
@@ -104,6 +105,11 @@ const SettingsIntegrationsRoute = SettingsIntegrationsRouteImport.update({
|
||||
path: '/integrations',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsHermesRoute = SettingsHermesRouteImport.update({
|
||||
id: '/hermes',
|
||||
path: '/hermes',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
|
||||
id: '/general',
|
||||
path: '/general',
|
||||
@@ -171,6 +177,7 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/hermes': typeof SettingsHermesRoute
|
||||
'/settings/integrations': typeof SettingsIntegrationsRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
|
||||
@@ -195,6 +202,7 @@ export interface FileRoutesByTo {
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/hermes': typeof SettingsHermesRoute
|
||||
'/settings/integrations': typeof SettingsIntegrationsRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
|
||||
@@ -222,6 +230,7 @@ export interface FileRoutesById {
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/hermes': typeof SettingsHermesRoute
|
||||
'/settings/integrations': typeof SettingsIntegrationsRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
|
||||
@@ -250,6 +259,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/hermes'
|
||||
| '/settings/integrations'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/open-source-licenses'
|
||||
@@ -274,6 +284,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/hermes'
|
||||
| '/settings/integrations'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/open-source-licenses'
|
||||
@@ -300,6 +311,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/hermes'
|
||||
| '/settings/integrations'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/open-source-licenses'
|
||||
@@ -423,6 +435,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsIntegrationsRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/hermes': {
|
||||
id: '/settings/hermes'
|
||||
path: '/hermes'
|
||||
fullPath: '/settings/hermes'
|
||||
preLoaderRoute: typeof SettingsHermesRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/general': {
|
||||
id: '/settings/general'
|
||||
path: '/general'
|
||||
@@ -518,6 +537,7 @@ interface SettingsRouteChildren {
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
SettingsHermesRoute: typeof SettingsHermesRoute
|
||||
SettingsIntegrationsRoute: typeof SettingsIntegrationsRoute
|
||||
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
|
||||
SettingsOpenSourceLicensesRoute: typeof SettingsOpenSourceLicensesRoute
|
||||
@@ -533,6 +553,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
SettingsHermesRoute: SettingsHermesRoute,
|
||||
SettingsIntegrationsRoute: SettingsIntegrationsRoute,
|
||||
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
|
||||
SettingsOpenSourceLicensesRoute: SettingsOpenSourceLicensesRoute,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { HermesSettingsWorkspace } from "../components/hermes/HermesWorkspace";
|
||||
|
||||
export const Route = createFileRoute("/settings/hermes")({
|
||||
component: HermesSettingsWorkspace,
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createHermesState } from "@t3tools/client-runtime/hermes";
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
|
||||
export const hermes = createHermesState(connectionAtomRuntime);
|
||||
@@ -22,5 +22,8 @@ describe("areProjectPathSearchTargetsEqual", () => {
|
||||
expect(areProjectPathSearchTargetsEqual(target, { ...target, query: "readme" })).toBe(false);
|
||||
expect(areProjectPathSearchTargetsEqual(target, { ...target, kind: "file" })).toBe(false);
|
||||
expect(areProjectPathSearchTargetsEqual(target, { ...target, imageOnly: true })).toBe(false);
|
||||
expect(areProjectPathSearchTargetsEqual(target, { ...target, includeIgnored: true })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -205,6 +205,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
|
||||
}
|
||||
|
||||
type ProjectPathSearchTarget = ComposerPathSearchTarget & {
|
||||
readonly includeIgnored?: boolean | undefined;
|
||||
readonly kind?: ProjectEntryKind | undefined;
|
||||
readonly imageOnly?: boolean | undefined;
|
||||
};
|
||||
@@ -218,7 +219,8 @@ export function areProjectPathSearchTargetsEqual(
|
||||
left.cwd === right.cwd &&
|
||||
left.query === right.query &&
|
||||
left.kind === right.kind &&
|
||||
left.imageOnly === right.imageOnly
|
||||
left.imageOnly === right.imageOnly &&
|
||||
left.includeIgnored === right.includeIgnored
|
||||
);
|
||||
}
|
||||
|
||||
@@ -235,8 +237,16 @@ export function useProjectPathSearch(
|
||||
query: target.query == null ? null : target.query.trim(),
|
||||
kind: target.kind,
|
||||
imageOnly: target.imageOnly,
|
||||
includeIgnored: target.includeIgnored,
|
||||
}),
|
||||
[target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
|
||||
[
|
||||
target.cwd,
|
||||
target.environmentId,
|
||||
target.imageOnly,
|
||||
target.includeIgnored,
|
||||
target.kind,
|
||||
target.query,
|
||||
],
|
||||
);
|
||||
const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
|
||||
const result = useEnvironmentQuery(
|
||||
@@ -252,6 +262,7 @@ export function useProjectPathSearch(
|
||||
limit,
|
||||
...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
|
||||
...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
|
||||
...(debouncedTarget.includeIgnored ? { includeIgnored: true } : {}),
|
||||
},
|
||||
})
|
||||
: null,
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@
|
||||
- [Remote access](./user/remote-access.md)
|
||||
- [Running in the background](./user/background-service.md)
|
||||
- [Updating T3 Code](./user/updating.md)
|
||||
- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md)
|
||||
- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [Hermes](./user/providers-hermes.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# Fork Android APK releases
|
||||
|
||||
The fork publishes signed APKs to the repository running the workflow using
|
||||
`.gitea/workflows/android-apk.yml`. This is separate from upstream's EAS/store
|
||||
release workflows. Fork APK builds disable Expo OTA updates so upstream JavaScript
|
||||
cannot replace the fork's bundled code.
|
||||
|
||||
## One-time setup
|
||||
|
||||
Enable repository Actions and register a dedicated Linux runner with the
|
||||
`android-apk` label. Use an isolated CI checkout, not a running T3 environment:
|
||||
the build regenerates `apps/mobile/android`. Install Node 24.13.1 or later in
|
||||
the supported Node 24 line, the repository's pinned pnpm version, Java 17,
|
||||
Git, curl, tar, xz, and the Android SDK with accepted licenses. Set `ANDROID_HOME`
|
||||
and `ANDROID_NDK_HOME` in the runner environment. Install the SDK/NDK versions
|
||||
required by the current Expo/React Native dependencies and CMake 3.22.1.
|
||||
Signing uses SDK build-tools 36.0.0 by default; override
|
||||
`ANDROID_BUILD_TOOLS_VERSION` if needed. The terminal build script downloads
|
||||
its pinned Zig compiler and Ghostty sources.
|
||||
|
||||
Configure these repository Actions secrets:
|
||||
|
||||
| Secret | Value |
|
||||
| ----------------------- | ------------------------------------------------------ |
|
||||
| `APK_KEYSTORE_BASE64` | Base64-encoded Android release keystore |
|
||||
| `APK_KEYSTORE_PASSWORD` | Keystore password |
|
||||
| `APK_KEY_ALIAS` | Signing key alias |
|
||||
| `APK_KEY_PASSWORD` | Signing key password |
|
||||
| `APK_RELEASE_TOKEN` | Token with repository release write access to the fork |
|
||||
|
||||
Reuse the signing key of the currently installed APK if you want an in-place
|
||||
upgrade. Back up that key securely and keep it unchanged across releases. A new
|
||||
key cannot upgrade an existing installation signed by another key; uninstalling
|
||||
first deletes local app data. The workflow never publishes the generated
|
||||
debug-signed intermediate APK: it re-signs and verifies the final artifact with
|
||||
the configured release key before uploading.
|
||||
|
||||
## Repository moves
|
||||
|
||||
Android builds default to the baked-in repository URL
|
||||
`https://git.molberg.cloud/alex/t3code`, so local builds work without release-source
|
||||
configuration. CI overrides that default with the repository running the workflow. Set
|
||||
`T3CODE_APK_REPOSITORY_URL` only when building for another full HTTPS repository URL. Public downloads
|
||||
need no authentication; the CI token is still required to publish releases and
|
||||
is never embedded in the APK.
|
||||
|
||||
Already-installed APKs retain their original repository API URL. After a move,
|
||||
keep the old repository API and release assets reachable long enough to publish
|
||||
and distribute an APK built for the new repository URL. Keep the same signing key
|
||||
across the move and ensure the release token has write access to the new owner’s
|
||||
repository.
|
||||
|
||||
## Local release
|
||||
|
||||
For a local build from a checkout, copy the example configuration and run the
|
||||
release script exactly like the MG Utility release flow:
|
||||
|
||||
```sh
|
||||
cp .env.release.example .env.release
|
||||
$EDITOR .env.release
|
||||
./scripts/release-apk.sh --dry-run # prints the next apk-<versionCode>
|
||||
./scripts/release-apk.sh # builds, signs, uploads, publishes
|
||||
```
|
||||
|
||||
`GITEA_TOKEN` (or `APK_RELEASE_TOKEN`) must be present in `.env.release`. The
|
||||
keystore, Android SDK, NDK, and Expo toolchain still need to match the build
|
||||
script. The release body defaults to a `production` JSON envelope
|
||||
(`schema: 1, channel, versionCode, versionName, branch, commit, sha256`);
|
||||
`APK_RELEASE_BODY` overrides the entire body when set. `APK_VERSION_CODE` pins
|
||||
the next release only when it exceeds the highest existing `apk-*` tag on the
|
||||
target Gitea repository.
|
||||
|
||||
## Publish an update
|
||||
|
||||
Push a tag of the form `apk-<versionCode>` on the commit to release. For example,
|
||||
`git tag apk-1001` followed by `git push origin apk-1001`. Choose a number greater
|
||||
than every previously installed build's Android version code, at most 2100000000. Do not reuse tags. The app's display version still comes from
|
||||
`apps/mobile/app.config.ts`.
|
||||
|
||||
The workflow builds a universal release APK, attaches it and a SHA-256 checksum
|
||||
to a draft release, then publishes only after both uploads succeed. If an upload
|
||||
fails, delete the incomplete draft release before rerunning the job; do not
|
||||
delete its Git tag. Release creation intentionally fails rather than overwriting
|
||||
an existing release. Signing/build failures publish nothing.
|
||||
|
||||
On Android, open **Settings → Software Update → Check for updates**. The app asks
|
||||
the public repository API for releases, selects the highest published
|
||||
`apk-<versionCode>` release with its matching APK, and downloads it into app-owned
|
||||
cache. It then opens Android’s package installer with the downloaded APK; the user
|
||||
must confirm installation, and Android may first require permission to install
|
||||
unknown apps from T3 Code. This is not a silent installer. Downloads require no
|
||||
repository credentials, and the flow does not depend on the connected T3
|
||||
environment. iOS, web, and desktop keep their existing update paths.
|
||||
@@ -196,6 +196,18 @@ File links refer to the environment's machine, including when you connect remote
|
||||
Previews use the original file, even outside the workspace. Moving or deleting it
|
||||
can break the preview, so save a copy if you need to keep it.
|
||||
|
||||
## Downloading files
|
||||
|
||||
To download a workspace file, right-click it in the file explorer on web or desktop,
|
||||
or touch and hold it in Files on mobile, then choose **Download file**. Files such
|
||||
as APKs and archives offer a download instead of a preview when you follow an
|
||||
agent's file link. Nothing downloads until you choose to proceed. Mobile uses the
|
||||
device's save/share sheet so you can choose where to keep or send the file.
|
||||
|
||||
File explorer search includes hidden and Git-ignored files, including generated
|
||||
build outputs. Refresh the file explorer to pick up newly created or deleted files.
|
||||
Broad searches show up to 200 matches; narrow the query if results are truncated.
|
||||
|
||||
## Files outside the workspace
|
||||
|
||||
Follow an agent's file link to read a report or other file outside the workspace.
|
||||
|
||||
+18
-12
@@ -68,24 +68,30 @@ before sharing.
|
||||
|
||||
## Providers
|
||||
|
||||
Open **Settings → Providers** in the web or desktop app, select the environment,
|
||||
and enable the provider you want. Installation, login, and configuration belong
|
||||
to that environment's machine, even when you connect from a phone or another
|
||||
computer.
|
||||
Open **Settings → Providers**, select the environment, and enable the provider
|
||||
you want. Installation, login, and configuration belong to that environment's
|
||||
machine, even when you configure it from the mobile app or another computer.
|
||||
|
||||
| Provider | Install and authenticate |
|
||||
| ----------- | -------------------------------------------------------------------------------------------- |
|
||||
| Codex | Install [Codex CLI](https://developers.openai.com/codex/cli), then run `codex login`. |
|
||||
| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. |
|
||||
| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. |
|
||||
| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. |
|
||||
| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. |
|
||||
| Antigravity | Install and sign in with Google from T3 Code's provider settings. |
|
||||
| Provider | Install and authenticate |
|
||||
| ----------- | ---------------------------------------------------------------------------------------------- |
|
||||
| Codex | Install [Codex CLI](https://developers.openai.com/codex/cli), then run `codex login`. |
|
||||
| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. |
|
||||
| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. |
|
||||
| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. |
|
||||
| Hermes | Install [Hermes Agent](https://github.com/NousResearch/hermes-agent), then run `hermes setup`. |
|
||||
| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. |
|
||||
| Antigravity | Install and sign in with Google from T3 Code's provider settings. |
|
||||
|
||||
Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its
|
||||
**Binary path** in provider settings, especially when using a version manager.
|
||||
Cursor's executable is `cursor-agent`, although its login command is
|
||||
`agent login`. Antigravity can use its managed runtime without a `PATH` entry.
|
||||
Hermes is experimental — its provider card shows an **Experimental** badge; see
|
||||
[Hermes](./providers-hermes.md) for details.
|
||||
|
||||
If a provider accepts a model that it does not advertise, add the exact model ID
|
||||
under that provider's **Custom models** setting. The model then appears in the
|
||||
thread model picker on every client connected to that environment.
|
||||
|
||||
When a provider CLI is behind its latest release, its provider card shows the
|
||||
available version. **Update now** appears only when T3 Code can tell which
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Hermes
|
||||
|
||||
[Hermes Agent](https://github.com/NousResearch/hermes-agent) works in two ways: as a coding provider
|
||||
inside a T3 project, or through the **Hermes** tab for native Hermes conversations without a project.
|
||||
|
||||
Hermes support is experimental. The provider card in **Settings** shows an **Experimental** badge.
|
||||
|
||||
## Requirements
|
||||
|
||||
Hermes Agent must be installed and configured on the machine running the T3 Code server, not on
|
||||
the device you browse from:
|
||||
|
||||
```bash
|
||||
hermes setup
|
||||
```
|
||||
|
||||
T3 Code spawns `hermes acp` and expects Hermes to already know which model providers to use. It
|
||||
does not configure Hermes on your behalf.
|
||||
|
||||
## Enable Hermes
|
||||
|
||||
Hermes is off by default. In the web, desktop, or mobile app, open **Settings** →
|
||||
**Providers**, select the environment, then turn on **Hermes**.
|
||||
|
||||
**Binary path** defaults to `hermes`. Set it when a version manager or
|
||||
a non-standard install location keeps the CLI off the `PATH` of the shell that started T3 Code.
|
||||
|
||||
**Dashboard URL** connects the Hermes tab to your running Hermes dashboard. It defaults to
|
||||
`http://127.0.0.1:9119`. This address is reached from the T3 server, not your Android phone or
|
||||
desktop client. Use the dashboard's HTTP address, not a messaging gateway or Android bridge port.
|
||||
|
||||
To use more than one Hermes installation or profile on the same environment, choose **Add provider
|
||||
instance** on web or desktop, or **Add another Hermes instance** on mobile. Give the instance a
|
||||
name and set `HERMES_HOME` when the instances should use separate Hermes profiles.
|
||||
|
||||
## Chat without a project
|
||||
|
||||
Choose **Hermes** above the conversation list, then **New task**. On **T3**, the same action
|
||||
continues to create a project thread. This works on Android, desktop, and web.
|
||||
|
||||
The Hermes list reads recent sessions directly from the dashboard, including their source and
|
||||
profile, and refreshes while open. Opening a session resumes its native history; it does not
|
||||
import it into a T3 project. Choose **Load older sessions** for earlier conversations.
|
||||
|
||||
The dashboard must expose its sessions API and chat WebSocket. For a local installation, T3 can
|
||||
use dashboard basic-auth credentials from the Hermes configuration. Otherwise, use **Dashboard
|
||||
sign-in** in the Hermes list. Remote dashboards require explicit sign-in. Credentials remain on
|
||||
the T3 server for that connection; use HTTPS for a dashboard on another machine.
|
||||
|
||||
Enter `/` and use **Commands & skills** to discover the commands advertised by your installation.
|
||||
Skills run with their full expanded instructions. Commands such as `/undo` can put text back in
|
||||
the composer for review instead of sending it automatically. Terminal-only interfaces are not
|
||||
embedded; Hermes reports their availability. Use **Reconnect** after a gateway disconnect.
|
||||
|
||||
## Inspect and manage Hermes
|
||||
|
||||
Choose the gear button on the Hermes tab to open its management page. There you can:
|
||||
|
||||
- Expand complete tool inputs, commands, outputs, and live activity instead of only summaries.
|
||||
- View agent, gateway, and error logs, refreshed while open, and inspect detailed failures.
|
||||
- View and edit skills and memory entries in the selected session's profile.
|
||||
- Create or edit cron jobs as JSON, pause or resume them, run them immediately, or delete them.
|
||||
|
||||
These are your actual Hermes resources: edits affect other Hermes clients using the same profile.
|
||||
Skill and memory saves check for changes since loading; reload a conflicting edit before saving.
|
||||
Without a selected session, management uses the dashboard's default profile. Native Hermes chats
|
||||
do not use T3's Git checkpoints or project worktrees.
|
||||
|
||||
The Android app and the connected T3 server must both include native Hermes support. If the app
|
||||
reports that the host is too old, update and restart T3 Code on the machine running the server;
|
||||
updating only the phone cannot add server-side Hermes commands.
|
||||
|
||||
## Models
|
||||
|
||||
For project threads, T3 Code asks Hermes for the catalog it advertises
|
||||
when a session starts — whatever providers you configured through `hermes setup` or `hermes
|
||||
model`. Pick a model from that list in the model picker for each thread, the same as with any
|
||||
other provider. If Hermes accepts a model that it does not advertise, add its exact ID under
|
||||
**Custom models** on the Hermes provider card.
|
||||
In a native Hermes chat, use `/model` and the other commands provided by your Hermes installation.
|
||||
|
||||
## What works
|
||||
|
||||
- Chat, including tool calls and file edits
|
||||
- Tool approvals through T3 Code's normal permission prompts
|
||||
- Resuming an existing thread
|
||||
- Generated thread titles, commit messages, PR titles and descriptions, and branch names
|
||||
|
||||
## Limits
|
||||
|
||||
- Experimental: expect rougher edges than the other providers.
|
||||
- Project threads require a local binary: T3 Code spawns `hermes acp` as a subprocess. The Hermes
|
||||
tab instead requires a compatible running dashboard and can use a remote dashboard address.
|
||||
- A client connecting from a phone or another desktop does not need Hermes installed locally.
|
||||
@@ -1,5 +1,17 @@
|
||||
# Updating T3 Code
|
||||
|
||||
## Update the app
|
||||
|
||||
On desktop, open **Settings → General** and choose **Check for Updates**. When a release is
|
||||
available, the same button downloads it and then installs it after confirmation. Packaged desktop
|
||||
apps check automatically in the background; Linux automatic updates require the AppImage build.
|
||||
You can choose the stable or nightly update track in the same section.
|
||||
|
||||
On Android, open **Settings → Software Update** and choose **Check for updates**. Store builds use
|
||||
the app's signed update channel and restart only after pending drafts and messages are saved. Fork
|
||||
APK builds use the repository updater described below. Android also checks its signed app update
|
||||
channel automatically while the app is in use.
|
||||
|
||||
The app you use and the server running your agents can be on different machines.
|
||||
When a server is behind your web or desktop app, an update notice appears in the
|
||||
conversation and **Settings → Connections**. Update the machine named in that
|
||||
@@ -58,6 +70,17 @@ update can roll back to the previous version. If the update still fails:
|
||||
|
||||
## Mobile updates
|
||||
|
||||
For fork Android APK installations, open **Settings → Software Update →
|
||||
Check for updates**. T3 Code checks its public repository, downloads the newest
|
||||
compatible APK into app-owned cache, and opens Android's package installer. Confirm
|
||||
the installation there. Android may first ask you to allow T3 Code to install
|
||||
unknown apps. Before Android opens, T3 Code verifies that the APK has this app's
|
||||
package name, the exact version selected from the repository, a newer version code,
|
||||
and the same signing certificate set as the installed app. Downloads larger than
|
||||
500 MiB are rejected. A stalled check or download times out so you can retry. The
|
||||
unchanged signing key preserves your local data. These fork releases do not receive
|
||||
upstream background updates. Updating the APK does not update your server.
|
||||
|
||||
Install App Store or Google Play releases as usual. The mobile app can also
|
||||
download updates in the background and apply them when you next leave the app.
|
||||
It saves drafts and queued messages before restarting. If you keep the app open
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./hermes": {
|
||||
"types": "./src/hermes.ts",
|
||||
"default": "./src/hermes.ts"
|
||||
},
|
||||
"./load-balancing": {
|
||||
"types": "./src/load-balancing.ts",
|
||||
"default": "./src/load-balancing.ts"
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
appendHermesEvent,
|
||||
hermesCronEditor,
|
||||
hermesCronJobs,
|
||||
hermesMessages,
|
||||
hermesSessions,
|
||||
pendingHermesRequests,
|
||||
applyHermesCompletion,
|
||||
hermesCronPaused,
|
||||
mergeHermesSessions,
|
||||
mergeHermesMessages,
|
||||
hermesErrorMessage,
|
||||
} from "./hermes.ts";
|
||||
import type { HermesEvent } from "@t3tools/contracts";
|
||||
|
||||
describe("native Hermes presentation", () => {
|
||||
it("explains when the connected host lacks Hermes RPC support", () => {
|
||||
expect(hermesErrorMessage("Error: Unknown request tag: hermes.write")).toContain(
|
||||
"Update and restart the T3 desktop app or server",
|
||||
);
|
||||
});
|
||||
it("merges overlapping transcript pages with stable message identities", () => {
|
||||
const older = hermesMessages({
|
||||
messages: [
|
||||
{ id: 1, role: "user", content: "Hello" },
|
||||
{ id: 2, role: "assistant", content: "Partial" },
|
||||
],
|
||||
});
|
||||
const latest = hermesMessages({
|
||||
messages: [
|
||||
{ id: 2, role: "assistant", content: "Complete" },
|
||||
{ id: 3, role: "tool", content: "output" },
|
||||
],
|
||||
});
|
||||
expect(mergeHermesMessages(older, latest).map((row) => [row.id, row.content])).toEqual([
|
||||
["1", "Hello"],
|
||||
["2", "Complete"],
|
||||
["3", "output"],
|
||||
]);
|
||||
});
|
||||
it("applies command and argument completions at the gateway replacement position", () => {
|
||||
expect(applyHermesCompletion("/sta", "status", 1)).toBe("/status");
|
||||
expect(applyHermesCompletion("/cron ad", "add", 6)).toBe("/cron add");
|
||||
expect(applyHermesCompletion("/res", "/research ", 1)).toBe("/research ");
|
||||
});
|
||||
|
||||
it("deduplicates changing session pages without merging different profiles", () => {
|
||||
const recent = hermesSessions({ sessions: [{ id: "one", profile: "work", title: "Latest" }] });
|
||||
const older = hermesSessions({
|
||||
sessions: [
|
||||
{ id: "one", profile: "work", title: "Old" },
|
||||
{ id: "one", profile: "home" },
|
||||
],
|
||||
});
|
||||
expect(
|
||||
mergeHermesSessions(recent, older, older).map((row) => [row.profile, row.title]),
|
||||
).toEqual([
|
||||
["work", "Latest"],
|
||||
["home", "Hermes chat"],
|
||||
]);
|
||||
expect(hermesCronPaused({ state: "paused" })).toBe(true);
|
||||
expect(hermesCronPaused({ state: "scheduled", enabled: true })).toBe(false);
|
||||
});
|
||||
it("preserves session identity, source, and owning profile without creating T3 projects", () => {
|
||||
const [session] = hermesSessions({
|
||||
sessions: [
|
||||
{
|
||||
id: "native-1",
|
||||
title: "Hello Hermes",
|
||||
profile: "work",
|
||||
source: "telegram",
|
||||
is_active: true,
|
||||
last_active: 123,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(session).toMatchObject({
|
||||
id: "native-1",
|
||||
title: "Hello Hermes",
|
||||
profile: "work",
|
||||
source: "telegram",
|
||||
active: true,
|
||||
updated: 123,
|
||||
});
|
||||
});
|
||||
|
||||
it("retains exact tool inputs and long outputs for full expansion", () => {
|
||||
const longOutput = "output\n".repeat(2_000);
|
||||
const [call, output] = hermesMessages({
|
||||
messages: [
|
||||
{
|
||||
id: 1,
|
||||
role: "assistant",
|
||||
content: "",
|
||||
tool_calls: [{ function: { name: "terminal", arguments: '{"command":"printf hello"}' } }],
|
||||
},
|
||||
{ id: 2, role: "tool", tool_call_id: "call-1", content: longOutput },
|
||||
],
|
||||
});
|
||||
expect(call?.details).toContain("printf hello");
|
||||
expect(output?.content).toBe(longOutput);
|
||||
expect(output?.details).toContain(JSON.stringify(longOutput));
|
||||
});
|
||||
|
||||
it("handles native array cron responses and excludes scheduler-owned fields from editing", () => {
|
||||
const jobs = [
|
||||
{
|
||||
id: "job-1",
|
||||
name: "Daily",
|
||||
schedule: { kind: "cron", expr: "0 9 * * *" },
|
||||
prompt: "News",
|
||||
state: "scheduled",
|
||||
last_run_at: "yesterday",
|
||||
},
|
||||
];
|
||||
expect(hermesCronJobs(jobs)).toBe(jobs);
|
||||
expect(hermesCronEditor(jobs[0])).toEqual({
|
||||
name: "Daily",
|
||||
schedule: { kind: "cron", expr: "0 9 * * *" },
|
||||
prompt: "News",
|
||||
});
|
||||
});
|
||||
|
||||
it("coalesces streaming text only within the same session", () => {
|
||||
const first: HermesEvent = {
|
||||
sequence: 1,
|
||||
type: "message.delta",
|
||||
sessionId: "one",
|
||||
payload: { text: "Hello " },
|
||||
};
|
||||
const merged = appendHermesEvent([first], {
|
||||
...first,
|
||||
sequence: 2,
|
||||
payload: { text: "Hermes" },
|
||||
});
|
||||
expect(merged).toHaveLength(1);
|
||||
expect(merged[0]?.payload).toEqual({ text: "Hello Hermes" });
|
||||
expect(appendHermesEvent(merged, { ...first, sessionId: "two" })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("bounds the live activity buffer without truncating tool payloads", () => {
|
||||
const payload = { rawOutput: "x".repeat(20_000) };
|
||||
const events = Array.from({ length: 200 }, (_, index) => ({
|
||||
sequence: index,
|
||||
type: "tool.done",
|
||||
sessionId: "one",
|
||||
payload,
|
||||
}));
|
||||
const next = appendHermesEvent(events, {
|
||||
sequence: 201,
|
||||
type: "tool.done",
|
||||
sessionId: "one",
|
||||
payload,
|
||||
});
|
||||
expect(next).toHaveLength(200);
|
||||
expect(next.at(-1)?.payload).toBe(payload);
|
||||
});
|
||||
|
||||
it("withdraws answered and cancelled requests and isolates sessions", () => {
|
||||
const request: HermesEvent = {
|
||||
sequence: 1,
|
||||
type: "request",
|
||||
sessionId: "one",
|
||||
payload: {
|
||||
requestId: "approval-1",
|
||||
method: "approval",
|
||||
params: { choices: ["once", "deny"] },
|
||||
},
|
||||
};
|
||||
expect(pendingHermesRequests([request], "one")).toHaveLength(1);
|
||||
expect(pendingHermesRequests([request], "two")).toEqual([]);
|
||||
expect(
|
||||
pendingHermesRequests(
|
||||
[
|
||||
request,
|
||||
{ sequence: 2, type: "request.cancel", sessionId: "one", payload: { id: "approval-1" } },
|
||||
],
|
||||
"one",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
pendingHermesRequests(
|
||||
[
|
||||
request,
|
||||
{
|
||||
sequence: 2,
|
||||
type: "request.resolved",
|
||||
sessionId: "one",
|
||||
payload: { id: "approval-1" },
|
||||
},
|
||||
],
|
||||
"one",
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
WS_METHODS,
|
||||
type HermesEvent,
|
||||
type HermesTarget,
|
||||
type ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { type EnvironmentRegistry } from "./connection/registry.ts";
|
||||
import {
|
||||
createEnvironmentRpcCommand,
|
||||
createEnvironmentRpcQueryAtomFamily,
|
||||
createEnvironmentRpcSubscriptionAtomFamily,
|
||||
} from "./state/runtime.ts";
|
||||
|
||||
export const conversationSourceAtom = Atom.make<"t3" | "hermes">("t3").pipe(Atom.keepAlive);
|
||||
export interface HermesConnection {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly target: HermesTarget;
|
||||
readonly label: string;
|
||||
}
|
||||
export interface HermesSelection {
|
||||
readonly connection: HermesConnection;
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
}
|
||||
export const hermesSelectionAtom = Atom.make<HermesSelection | null>(null).pipe(Atom.keepAlive);
|
||||
export const hermesConnectionAtom = Atom.make<HermesConnection | null>(null).pipe(Atom.keepAlive);
|
||||
export const hermesNewSessionAtom = Atom.make(0).pipe(Atom.keepAlive);
|
||||
export const hermesHandledNewSessionAtom = Atom.make(0).pipe(Atom.keepAlive);
|
||||
|
||||
export function hermesRecord(value: unknown): Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
export function hermesText(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
export function hermesArray(value: unknown): ReadonlyArray<unknown> {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
export function hermesPretty(value: unknown): string {
|
||||
return typeof value === "string" ? value : (JSON.stringify(value, null, 2) ?? "");
|
||||
}
|
||||
|
||||
export function hermesErrorMessage(message: string): string {
|
||||
if (/Unknown request tag: hermes\.(?:read|write|events)/i.test(message)) {
|
||||
return "This T3 host is too old for native Hermes controls. Update and restart the T3 desktop app or server on the connected machine, then try again.";
|
||||
}
|
||||
return message;
|
||||
}
|
||||
export function hermesCronJobs(value: unknown): ReadonlyArray<unknown> {
|
||||
return Array.isArray(value) ? value : hermesArray(hermesRecord(value).jobs);
|
||||
}
|
||||
|
||||
export function hermesCronPaused(value: unknown) {
|
||||
const job = hermesRecord(value);
|
||||
return job.state === "paused" || job.enabled === false || job.paused === true;
|
||||
}
|
||||
|
||||
export function applyHermesCompletion(input: string, value: unknown, replaceFrom: unknown) {
|
||||
const start =
|
||||
typeof replaceFrom === "number" && Number.isInteger(replaceFrom)
|
||||
? Math.max(0, Math.min(input.length, replaceFrom))
|
||||
: input.startsWith("/")
|
||||
? 1
|
||||
: 0;
|
||||
const completion = hermesText(value);
|
||||
return (
|
||||
input.slice(0, start) + (input[start - 1] === "/" ? completion.replace(/^\//, "") : completion)
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeHermesSessions(...pages: ReturnType<typeof hermesSessions>[]) {
|
||||
const rows = new Map<string, ReturnType<typeof hermesSessions>[number]>();
|
||||
for (const page of pages)
|
||||
for (const row of page) {
|
||||
const key = JSON.stringify([row.profile, row.id]);
|
||||
if (!rows.has(key)) rows.set(key, row);
|
||||
}
|
||||
return [...rows.values()];
|
||||
}
|
||||
|
||||
export function hermesCronEditor(value: unknown) {
|
||||
const row = hermesRecord(value);
|
||||
const fields = [
|
||||
"name",
|
||||
"schedule",
|
||||
"prompt",
|
||||
"deliver",
|
||||
"skills",
|
||||
"model",
|
||||
"provider",
|
||||
"base_url",
|
||||
"script",
|
||||
"context_from",
|
||||
"enabled_toolsets",
|
||||
"workdir",
|
||||
"no_agent",
|
||||
"failure_deliver",
|
||||
];
|
||||
return Object.fromEntries(
|
||||
fields.filter((field) => row[field] !== undefined).map((field) => [field, row[field]]),
|
||||
);
|
||||
}
|
||||
export function hermesConnections(
|
||||
configs: ReadonlyMap<EnvironmentId, ServerConfig>,
|
||||
labels: ReadonlyMap<EnvironmentId, string>,
|
||||
): HermesConnection[] {
|
||||
return [...configs].flatMap(([environmentId, config]) =>
|
||||
config.providers
|
||||
.filter((provider) => provider.driver === "hermes" && provider.enabled !== false)
|
||||
.map((provider) => ({
|
||||
environmentId,
|
||||
target: { instanceId: provider.instanceId },
|
||||
label: `${labels.get(environmentId) ?? "Environment"} · ${provider.displayName ?? "Hermes"}`,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export function hermesSessions(data: unknown) {
|
||||
return hermesArray(hermesRecord(data).sessions)
|
||||
.map((value) => {
|
||||
const row = hermesRecord(value);
|
||||
return {
|
||||
id: hermesText(row.id) || hermesText(row.session_id),
|
||||
title: hermesText(row.title) || hermesText(row.first_user_message) || "Hermes chat",
|
||||
profile: hermesText(row.profile),
|
||||
source: hermesText(row.source),
|
||||
active: row.is_active === true,
|
||||
updated: row.last_active ?? row.last_active_at ?? row.started_at,
|
||||
raw: row,
|
||||
};
|
||||
})
|
||||
.filter((row) => row.id.length > 0);
|
||||
}
|
||||
|
||||
export function hermesMessages(data: unknown) {
|
||||
return hermesArray(hermesRecord(data).messages).map((value, index) => {
|
||||
const row = hermesRecord(value);
|
||||
const content =
|
||||
typeof row.content === "string"
|
||||
? row.content
|
||||
: hermesArray(row.content)
|
||||
.map((block) => hermesText(hermesRecord(block).text))
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
const details = row.role === "tool" || row.tool_calls || row.tool_call_id;
|
||||
return {
|
||||
id: String(row.id ?? row.message_id ?? index),
|
||||
role: hermesText(row.role),
|
||||
content,
|
||||
details: details ? hermesPretty(row) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function mergeHermesMessages(...pages: ReturnType<typeof hermesMessages>[]) {
|
||||
const messages = new Map<string, ReturnType<typeof hermesMessages>[number]>();
|
||||
for (const page of pages) for (const message of page) messages.set(message.id, message);
|
||||
return [...messages.values()];
|
||||
}
|
||||
|
||||
export function appendHermesEvent(
|
||||
events: ReadonlyArray<HermesEvent>,
|
||||
event: HermesEvent,
|
||||
): ReadonlyArray<HermesEvent> {
|
||||
const previous = events.at(-1);
|
||||
if (
|
||||
previous?.type === event.type &&
|
||||
previous.sessionId === event.sessionId &&
|
||||
event.type === "message.delta"
|
||||
) {
|
||||
const payload = hermesRecord(event.payload);
|
||||
return [
|
||||
...events.slice(0, -1),
|
||||
{
|
||||
...event,
|
||||
payload: {
|
||||
...payload,
|
||||
text: (hermesText(hermesRecord(previous.payload).text) + hermesText(payload.text)).slice(
|
||||
-512_000,
|
||||
),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [...events.slice(-199), event];
|
||||
}
|
||||
|
||||
export function pendingHermesRequests(events: ReadonlyArray<HermesEvent>, sessionId: string) {
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ id: string; method: string; params: Record<string, unknown> }
|
||||
>();
|
||||
for (const event of events) {
|
||||
if (event.type === "error" && hermesRecord(event.payload).disconnected === true)
|
||||
pending.clear();
|
||||
if (event.sessionId !== sessionId) continue;
|
||||
const payload = hermesRecord(event.payload);
|
||||
if (event.type === "request") {
|
||||
const id = hermesText(payload.requestId);
|
||||
pending.set(id, {
|
||||
id,
|
||||
method: hermesText(payload.method),
|
||||
params: hermesRecord(payload.params),
|
||||
});
|
||||
} else if (event.type === "request.cancel" || event.type === "request.resolved")
|
||||
pending.delete(hermesText(payload.id));
|
||||
}
|
||||
return [...pending.values()];
|
||||
}
|
||||
|
||||
export function createHermesState<R, Error>(
|
||||
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, Error>,
|
||||
) {
|
||||
return {
|
||||
read: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "hermes:read",
|
||||
tag: WS_METHODS.hermesRead,
|
||||
staleTimeMs: 1_000,
|
||||
idleTtlMs: 0,
|
||||
}),
|
||||
live: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "hermes:live",
|
||||
tag: WS_METHODS.hermesRead,
|
||||
staleTimeMs: 1_000,
|
||||
refreshIntervalMs: 5_000,
|
||||
idleTtlMs: 0,
|
||||
}),
|
||||
request: createEnvironmentRpcCommand(runtime, {
|
||||
label: "hermes:request",
|
||||
tag: WS_METHODS.hermesRead,
|
||||
}),
|
||||
write: createEnvironmentRpcCommand(runtime, {
|
||||
label: "hermes:write",
|
||||
tag: WS_METHODS.hermesWrite,
|
||||
}),
|
||||
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "hermes:events",
|
||||
tag: WS_METHODS.hermesEvents,
|
||||
idleTtlMs: 0,
|
||||
transform: (stream) =>
|
||||
stream.pipe(Stream.scan([] as ReadonlyArray<HermesEvent>, appendHermesEvent)),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -40,6 +40,7 @@ export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string;
|
||||
type RpcMethod<TTag extends EnvironmentRpcTag> = WsRpcProtocolClient[TTag];
|
||||
|
||||
export type EnvironmentSubscriptionRpcTag =
|
||||
| typeof WS_METHODS.hermesEvents
|
||||
| typeof WS_METHODS.providerAuthSubscribe
|
||||
| typeof WS_METHODS.providerInstallSubscribe
|
||||
| typeof ORCHESTRATION_WS_METHODS.subscribeShell
|
||||
|
||||
@@ -14,19 +14,23 @@ const ASSET_PATH_MAX_LENGTH = 1024;
|
||||
export const AssetResource = Schema.Union([
|
||||
Schema.TaggedStruct("workspace-file", {
|
||||
threadId: ThreadId,
|
||||
download: Schema.optionalKey(Schema.Boolean),
|
||||
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
}),
|
||||
// One file served in place from anywhere the environment host can read:
|
||||
// images, videos, HTML, and PDF. An absolute path may lie outside the
|
||||
// workspace; a relative one resolves against the thread's workspace.
|
||||
// previews of images, videos, HTML, and PDF, or explicit downloads of any type.
|
||||
// An absolute path may lie outside the workspace; a relative one resolves
|
||||
// against the thread's workspace.
|
||||
Schema.TaggedStruct("media-file", {
|
||||
threadId: ThreadId,
|
||||
download: Schema.optionalKey(Schema.Boolean),
|
||||
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
}),
|
||||
// A workspace file named by a draft that has no thread yet. The draft names
|
||||
// its workspace root explicitly instead of resolving one from a thread.
|
||||
Schema.TaggedStruct("draft-workspace-file", {
|
||||
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
download: Schema.optionalKey(Schema.Boolean),
|
||||
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
}),
|
||||
Schema.TaggedStruct("attachment", {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HermesReadInput, HermesWriteInput } from "./hermes.ts";
|
||||
const read = Schema.decodeUnknownSync(HermesReadInput);
|
||||
const write = Schema.decodeUnknownSync(HermesWriteInput);
|
||||
|
||||
describe("Hermes wire contracts", () => {
|
||||
it("rejects arbitrary paths, methods, and invalid pagination", () => {
|
||||
expect(() => read({ instanceId: "hermes", resource: "/etc/passwd" })).toThrow();
|
||||
expect(() => read({ instanceId: "hermes", resource: "sessions", offset: -1 })).toThrow();
|
||||
expect(() => write({ instanceId: "hermes", action: "shell.exec" })).toThrow();
|
||||
});
|
||||
|
||||
it("keeps native Hermes sessions independent of project identifiers", () => {
|
||||
expect(
|
||||
write({
|
||||
instanceId: "hermes",
|
||||
action: "create",
|
||||
profile: "personal",
|
||||
}),
|
||||
).toEqual({ instanceId: "hermes", action: "create", profile: "personal" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
const Text = Schema.String.check(Schema.isMaxLength(512_000));
|
||||
const Identifier = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
|
||||
|
||||
export const HermesTarget = Schema.Struct({
|
||||
instanceId: ProviderInstanceId,
|
||||
profile: Schema.optional(Identifier),
|
||||
});
|
||||
export type HermesTarget = typeof HermesTarget.Type;
|
||||
|
||||
export const HermesReadInput = Schema.Struct({
|
||||
...HermesTarget.fields,
|
||||
resource: Schema.Literals([
|
||||
"sessions",
|
||||
"messages",
|
||||
"skills",
|
||||
"skill",
|
||||
"memories",
|
||||
"memory",
|
||||
"cron",
|
||||
"logs",
|
||||
"commands",
|
||||
]),
|
||||
id: Schema.optional(Identifier),
|
||||
text: Schema.optional(Text),
|
||||
offset: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
||||
logFile: Schema.optional(Schema.Literals(["agent", "gateway", "errors"])),
|
||||
});
|
||||
export type HermesReadInput = typeof HermesReadInput.Type;
|
||||
|
||||
export const HermesWriteInput = Schema.Struct({
|
||||
...HermesTarget.fields,
|
||||
action: Schema.Literals([
|
||||
"create",
|
||||
"attach",
|
||||
"send",
|
||||
"interrupt",
|
||||
"command",
|
||||
"respond",
|
||||
"saveSkill",
|
||||
"saveMemory",
|
||||
"createCron",
|
||||
"updateCron",
|
||||
"pauseCron",
|
||||
"resumeCron",
|
||||
"runCron",
|
||||
"deleteCron",
|
||||
"renameSession",
|
||||
"deleteSession",
|
||||
"login",
|
||||
]),
|
||||
id: Schema.optional(Identifier),
|
||||
text: Schema.optional(Text),
|
||||
fields: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
});
|
||||
export type HermesWriteInput = typeof HermesWriteInput.Type;
|
||||
|
||||
export const HermesResult = Schema.Struct({ data: Schema.Unknown });
|
||||
export type HermesResult = typeof HermesResult.Type;
|
||||
|
||||
export const HermesEvent = Schema.Struct({
|
||||
sequence: Schema.Number,
|
||||
type: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
payload: Schema.Unknown,
|
||||
});
|
||||
export type HermesEvent = typeof HermesEvent.Type;
|
||||
|
||||
export class HermesError extends Schema.TaggedError<HermesError>()("HermesError", {
|
||||
message: Schema.String,
|
||||
operation: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
}) {}
|
||||
@@ -42,3 +42,4 @@ export * from "./previewAutomation.ts";
|
||||
export * from "./resourceTelemetry.ts";
|
||||
export * from "./usage.ts";
|
||||
export * from "./rpc.ts";
|
||||
export * from "./hermes.ts";
|
||||
@@ -147,6 +147,7 @@ const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const HERMES_DRIVER_KIND = ProviderDriverKind.make("hermes");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-6-astra";
|
||||
@@ -172,6 +173,9 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
[CURSOR_DRIVER_KIND]: "auto",
|
||||
// Product slug, not an ACP model id. The Grok adapter treats it as "the session's current model".
|
||||
[GROK_DRIVER_KIND]: "grok-build",
|
||||
// Product slug, not an ACP model id. The Hermes adapter treats it as "keep the
|
||||
// model Hermes is configured with" and skips session/set_model for it.
|
||||
[HERMES_DRIVER_KIND]: "default",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
[ProviderDriverKind.make("antigravity")]: ANTIGRAVITY_DEFAULT_MODEL,
|
||||
};
|
||||
@@ -184,6 +188,7 @@ export const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
[ProviderDriverKind.make("antigravity")]: ANTIGRAVITY_DEFAULT_MODEL,
|
||||
[CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",
|
||||
[CURSOR_DRIVER_KIND]: "composer-2",
|
||||
[HERMES_DRIVER_KIND]: "default",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
};
|
||||
|
||||
@@ -221,5 +226,6 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
|
||||
[CLAUDE_DRIVER_KIND]: "Claude",
|
||||
[CURSOR_DRIVER_KIND]: "Cursor",
|
||||
[GROK_DRIVER_KIND]: "Grok",
|
||||
[HERMES_DRIVER_KIND]: "Hermes",
|
||||
[OPENCODE_DRIVER_KIND]: "OpenCode",
|
||||
};
|
||||
@@ -14,6 +14,11 @@ const decodeSearchEntriesInput = Schema.decodeUnknownSync(ProjectSearchEntriesIn
|
||||
const decodeSearchContentsInput = Schema.decodeUnknownSync(ProjectSearchContentsInput);
|
||||
|
||||
describe("project search inputs", () => {
|
||||
it("allows file browsers to include ignored files without changing legacy requests", () => {
|
||||
const input = { cwd: "/workspace", query: ".apk", limit: 200 };
|
||||
expect(decodeSearchEntriesInput(input).includeIgnored).toBeUndefined();
|
||||
expect(decodeSearchEntriesInput({ ...input, includeIgnored: true }).includeIgnored).toBe(true);
|
||||
});
|
||||
it("allows an empty entries query for bounded frecency browsing", () => {
|
||||
const decoded = decodeSearchEntriesInput({
|
||||
cwd: "/workspace",
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user