Compare commits

...
Author SHA1 Message Date
bonzi 8d45b184d7 fix: build arm64 APK release artifacts
Fork Android APK / release (push) Has been cancelled
2026-09-14 15:24:34 +00:00
bonzi cb9719f1dc fix: verify APK checksum from release directory 2026-09-14 15:16:37 +00:00
bonzi 0a1bec5a98 feat: improve file downloads and APK release flow 2026-09-14 15:04:08 +00:00
bonzi c607b73d94 chore(mobile): add one-command APK release script 2026-09-14 13:32:59 +00:00
bonzi a8b175132a [verified] feat(mobile): install repository APK updates
Fork Android APK / release (push) Has been cancelled
2026-09-14 05:33:05 +00:00
bonzi 7bbf4b0e53 build(server): version Hermes fork runtime
CI / Check (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Test Server 1 (push) Has been cancelled
CI / Test Server 2 (push) Has been cancelled
CI / Test Server 3 (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Mobile Native Changes (push) Has been cancelled
CI / Release Smoke (push) Has been cancelled
Forward to Cursor hygiene / POST to Cursor (push) Has been cancelled
Deploy T3 Connect relay / Deploy production relay (push) Has been cancelled
CI / Mobile Native Static Analysis (push) Has been cancelled
2026-09-14 02:24:17 +00:00
bonzi f325d1aa64 feat(mobile): manage providers and custom models
Deploy T3 Connect relay / Deploy production relay (push) Has been cancelled
CI / Check (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Test Server 1 (push) Has been cancelled
CI / Test Server 2 (push) Has been cancelled
CI / Test Server 3 (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Mobile Native Changes (push) Has been cancelled
CI / Release Smoke (push) Has been cancelled
Forward to Cursor hygiene / POST to Cursor (push) Has been cancelled
Mobile EAS Production / EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }} (push) Has been cancelled
CI / Mobile Native Static Analysis (push) Has been cancelled
2026-09-14 01:56:59 +00:00
bonzi 79b59d5e94 feat(server): add Hermes Agent support
Deploy T3 Connect relay / Deploy production relay (push) Has been cancelled
Mobile EAS Production / EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }} (push) Has been cancelled
CI / Check (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Test Server 1 (push) Has been cancelled
CI / Test Server 2 (push) Has been cancelled
CI / Test Server 3 (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Mobile Native Changes (push) Has been cancelled
CI / Release Smoke (push) Has been cancelled
Forward to Cursor hygiene / POST to Cursor (push) Has been cancelled
CI / Mobile Native Static Analysis (push) Has been cancelled
2026-09-14 01:04:27 +00:00
raman325 f9b4ceb463 Merge remote-tracking branch 'origin/main' into pr-server-only
* origin/main: (675 commits)
  fix(web): tolerate servers that predate git identity in project import (#10547)
  chore(mobile): bump app version to 1.1.0
  fix(mobile): wait for native thread scroll before reveal (#10486)
  fix(mobile): match Working status color to desktop
  fix(web): remove inserted citations on cancel (#10518)
  feat(web): group onboarding project import by repository (#10493)
  fix(mobile): preserve chat rows when toggling commands (#10492)
  fix(mobile): restore assistant message bottom padding (#10491)
  fix(mobile): animate thread lifecycle transitions consistently (#10487)
  fix(mobile): release initial scroll target after dragging (#10483)
  fix(mobile): smooth composer status pill resizing (#10484)
  fix(mobile): prevent chat from disappearing when scrolling (#10479)
  fix(web): resize the floating preview from any edge (#10467)
  fix(web): keep composer toolbar controls anchored during transitions (#10478)
  fix(mobile): improve font-size slider performance and prevent maximum update depth errors (#7138)
  feat(mobile): start a new thread on an existing branch (#10359)
  fix(ios): scroll short source files from blank space (#10178)
  fix(mobile): hide changed-files navigator and restore refresh in raw diff fallback (#9828)
  fix(projects): prevent invalid script IDs from crashing threads (#10019)
  fix(devcontainer): make repository setup work (#7875)
  ...

# Conflicts:
#	apps/server/src/provider/builtInDrivers.ts
#	docs/README.md
#	docs/user/install.md
#	packages/contracts/src/settings.test.ts
#	packages/contracts/src/settings.ts
2026-09-07 15:47:47 -04:00
raman325andClaude Opus 5 8c12290a17 fix(contracts): give Hermes a default model for text generation
Hermes had no DEFAULT_MODEL_BY_PROVIDER entry, so a Hermes-only install
fell through to the Codex text-generation slug (gpt-5.6-luna). The
adapter forwards any non-sentinel id to session/set_model, which the
real CLI rejects, breaking generated titles, commit messages, PR text,
and branch names.

Mirrors Grok: the entry is the product slug the adapter already treats
as "keep the session's configured model" and skips set_model for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:18:04 -04:00
raman325andClaude Opus 5 a54fe4e34d fix(server): select Hermes approval mode by intent, not substring
The live `hermes acp` CLI advertises three session modes -- `default`
("Ask before edits."), `accept_edits` ("Auto-allow workspace and /tmp
edits; still asks for sensitive paths.") and `dont_ask` ("Don't Ask") --
and every one of them contains the "ask" approval alias somewhere in its
id, name, or description. The substring fallback in findModeByAliases
therefore returned whichever of the three Hermes listed first, so
approval-required resolved to `default` only by accident of ordering. A
reorder or a new mode would have silently pointed "approve every edit"
at an auto-allow mode.

The approval lookup now asks findModeByAliases for a mode that still
prompts, rejecting substring candidates whose own text says otherwise
("dont ask", "auto", "accept", "bypass", ...). The filter is opt-in and
scoped to approval intent only: an "Accept Edits" mode remains a valid
implement-mode candidate, and exact id/name matches are untouched.

Model: Claude Opus 5 (1M context). Harness: Claude Code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:47:39 -04:00
raman325andClaude Opus 5 f2d2f960a6 test(server): follow the shared ACP mock's renamed model id
The mock agent's catalog moved from `grok-build` to `grok-4.6` in #9154;
the Hermes discovery test still asserted the old slug and failed against
current main.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Fable 5 79a4f3409d fix(server): honor acceptAlways and never announce an unstartable turn
`selectHermesPermissionOptionId` handled only `acceptForSession` and
`accept`, so the valid `acceptAlways` decision fell through to the
agent's reject option — a permanent approval denied the tool call.
Both persistent decisions now map to `allow_always`, with the same
`allow_once` fallback.

`turn.started` was also published before prompt validation, so a
whitespace-only prompt or an attachment set with no images announced a
turn that then failed with no terminal event, leaving consumers with a
permanently running turn. Announcement now happens after both fallible
preparation steps (validation and session configuration) and is keyed on
a session-level announced flag, so a steer that overtakes a not-yet
announced turn still announces it exactly once. Preparation failures
release the turn claim so the next sendTurn opens a fresh turn.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QingonqJgq96d3byM5qRh9
2026-09-02 14:43:57 -04:00
raman325andClaude Fable 5 50013a2591 fix(server): announce a Hermes turn before fallible configuration
Publishing the active turn id before the awaited session configuration
let a concurrent sendTurn merge into a turn whose preparation could still
fail. Because a steer skips its own turn.started, the merged turn could
settle without one ever being emitted.

Emit turn.started in the same window that publishes the id, before the
configuration await, and compare the skip-if-match guard against the
model captured before the session record adopts this turn's selection.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QingonqJgq96d3byM5qRh9
2026-09-02 14:43:57 -04:00
raman325andClaude Fable 5 462742eb49 fix(server): answer Hermes approvals with advertised option ids
Manual approval replies sent the canonical `allow-always`/`allow-once`/
`reject-once` literals rather than the option ids Hermes advertised, so
an agent minting opaque ids (`permit-42`) rejected the reply and the
permission-gated turn stayed blocked. Match the resolved decision by
option `kind` and answer with the advertised id, mirroring Grok, and
cancel rather than synthesize an id when the agent advertised no
matching option.

Also explains both new nodeBuiltinImport suppressions.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QingonqJgq96d3byM5qRh9
2026-09-02 14:43:57 -04:00
raman325andClaude Fable 5 128a6134cd fix(server): address Hermes provider review findings
- never send the `default` product slug to session/set_model: it stands
  for Hermes's own configured model, not an ACP model id, so start and
  first turn failed whenever the picker still held it
- track the session's real current model at start (ACP setup's current
  model when no switch happened) so the skip-if-match guard compares
  against the session rather than the picker selection
- mark the session's current model as the discovered catalog default so
  the resolver stops binding to the first entry
- assign the active turn id synchronously with the in-flight increment,
  so a sendTurn racing session configuration merges into the running
  turn instead of opening a duplicate
- use the shared withInstanceIdentity helper instead of a local copy
- add HermesAdapter tests: auto-approval option selection, mode-alias
  resolution, mock ACP session flow, and the steer-merge path

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QingonqJgq96d3byM5qRh9
2026-09-02 14:43:57 -04:00
raman325andClaude Fable 5 948eb8a1ca fix(server): skip redundant Hermes session/set_model
Hermes model selection sent session/set_model unconditionally, including
when the session was already on the requested model. Grok's ACP fix
(#9154) made the mock agent reject set_model for ids it does not
advertise as switchable, which surfaced the redundancy: selecting the
session's current model failed instead of no-opping.

applyHermesAcpModelSelection now takes the session's current model id
(read from session setup at start, tracked on the session for turns) and
sends set_model only when the selection actually changes the model.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QingonqJgq96d3byM5qRh9
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 1af86c90ad docs(user): list Hermes in the install providers table
Adds a Hermes row to the install guide's Providers table and notes it's
off by default and experimental, consistent with the other opt-in
providers already documented there.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 106c208553 test(server): extend Hermes settings and probe coverage
Mirrors Hermes into the settings restore/disable fixtures alongside
Grok and OpenCode, drops the tautological HERMES_AUTH_METHOD_ID unit
test and un-exports the now test-only constant, and gates the Hermes
ACP probe's live-turn test behind T3_HERMES_LIVE_TURN, matching the
Grok probe's T3_GROK_LIVE_TURN gate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 1c84a54a80 docs(user): add Hermes provider setup guide
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 5f178fc567 test(server): add env-gated Hermes ACP live probe
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 a9068978e9 feat(server): register Hermes as a built-in provider driver
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 6f9cd78787 fix(server): send Hermes model selection via session/set_model
The real hermes acp binary treats session/set_config_option (configId
"model") as a silent no-op — it returns {"configOptions": []} for both
valid and invalid values — so routing model selection through it never
actually changed the active model. Switch applyHermesAcpModelSelection
to the unstable session/set_model capability (runtime.setSessionModel),
matching how GrokAcpSupport already selects its models.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 3dc38031f1 feat(server): add Hermes text generation
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 564f916cdb feat(server): add Hermes ACP adapter
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 a1237d983a feat(server): add Hermes provider snapshot and probe
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 fc43823227 feat(server): add Hermes ACP spawn support
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:57 -04:00
raman325andClaude Opus 5 ce23e3bbe4 feat(server): restore Hermes enablement from provider history
Hermes needs to opt back in when session history shows it was used
before, matching the existing behavior for Cursor, Grok, and OpenCode.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:56 -04:00
raman325andClaude Opus 5 fa3ea832c6 feat(contracts): add Hermes provider settings schema
Mirrors GrokSettings exactly: enabled off by default, binaryPath
falling back to "hermes", and a hidden customModels list. Wires
HermesSettings/HermesSettingsPatch into ServerSettings and
ServerSettingsPatch alongside the other legacy per-driver settings.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:43:56 -04:00
76 changed files with 7417 additions and 66 deletions

No files matched your search

+14
View File
@@ -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"}
+34
View File
@@ -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
+1
View File
@@ -40,6 +40,7 @@ node_modules/
*.log
.env*
!.env.example
!.env.release.example
# pnpm content-addressable store; never belongs in the repo.
.pnpm-store/
+17 -1
View File
@@ -1,6 +1,10 @@
import type { ExpoConfig } from "expo/config";
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
import {
parseAndroidApkReleaseTag,
resolveAndroidApkRepository,
} from "../../scripts/lib/android-apk-release.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
@@ -9,6 +13,12 @@ const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
const DEFAULT_APK_REPOSITORY_URL = "https://git.molberg.cloud/alex/t3code";
const apkReleaseTag = repoEnv.T3CODE_APK_RELEASE_TAG;
const apkVersionCode = apkReleaseTag ? parseAndroidApkReleaseTag(apkReleaseTag) : undefined;
const apkRepository = resolveAndroidApkRepository(
repoEnv.T3CODE_APK_REPOSITORY_URL || DEFAULT_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'
}
@@ -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()
}
}
@@ -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))
}
}
+8
View File
@@ -62,6 +62,7 @@ import {
SettingsOpenSourceLicensesRouteScreen,
} from "./features/settings/SettingsOpenSourceLicensesRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { SettingsProvidersRouteScreen } from "./features/settings/SettingsProvidersRouteScreen";
import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled";
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
@@ -164,6 +165,13 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Environments",
},
}),
SettingsProviders: createNativeStackScreen({
screen: SettingsProvidersRouteScreen,
linking: "providers",
options: {
title: "Providers",
},
}),
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],
);
}
@@ -0,0 +1,560 @@
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={`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>
);
}
@@ -55,6 +55,7 @@ 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 +133,7 @@ function LocalSettingsRouteScreen() {
value={`${environmentCount}`}
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
</SettingsSection>
<GeneralSettingsSection />
@@ -144,6 +146,7 @@ function LocalSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
<SoftwareUpdateSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -514,6 +517,7 @@ function ConfiguredSettingsRouteScreen() {
value={`${environmentCount}`}
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
<SettingsSwitchRow
icon="bell.badge"
label="Device Notifications"
@@ -564,6 +568,7 @@ function ConfiguredSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
<SoftwareUpdateSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -0,0 +1,193 @@
import Constants from "expo-constants";
import { 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 { 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",
};
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 apiUrl = Constants.expoConfig?.extra?.apkReleaseApiUrl;
const manifestVersionCode =
Constants.platform?.android?.versionCode ?? Constants.expoConfig?.android?.versionCode;
if (Platform.OS !== "android" || typeof apiUrl !== "string" || !apiUrl) 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 busy = status === "checking" || status === "downloading" || status === "installing";
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>
<SettingsRow
icon="arrow.down.circle"
label="Check for updates"
value={STATUS_LABEL[status]}
disabled={busy}
onPress={() => void update()}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
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.
</Text>
</View>
);
}
@@ -0,0 +1,636 @@
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("rejects same-origin assets outside the exact Gitea attachment path", () => {
for (const browser_download_url of [
`https://git.example.com/alex/t3code/releases/download/apk-5/t3code-apk-5.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("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,511 @@
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 } {
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] ?? "" };
}
function trustedAttachmentUrl(rawUrl: unknown, apiUrl: 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 prefix = `${server.path}/attachments/`;
if (!url.pathname.startsWith(prefix)) return null;
const uuid = url.pathname.slice(prefix.length);
return GITEA_ATTACHMENT_UUID.test(uuid) ? 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 = trustedAttachmentUrl(asset.browser_download_url, apiUrl);
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,6 @@
export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsProviders"
| "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 };
}
@@ -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;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.40",
"version": "0.0.41-hermes.1",
"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;
+25 -5
View File
@@ -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") {
@@ -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,13 @@ const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
...overrides,
});
const makeHermesConfig = (overrides: Partial<HermesSettings>): HermesSettings => ({
enabled: false,
binaryPath: "hermes",
customModels: [],
...overrides,
});
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
enabled: false,
binaryPath: "opencode",
@@ -468,12 +477,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 +515,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 +530,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 +547,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 +559,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 +584,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 +593,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 +602,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 +643,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,
];
+15 -1
View File
@@ -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),
);
+45 -2
View File
@@ -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",
+9 -2
View File
@@ -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* () {
+55 -1
View File
@@ -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);
+19
View File
@@ -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)">
@@ -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],
);
}
@@ -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();
@@ -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",
+3
View File
@@ -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,
);
});
});
+13 -2
View File
@@ -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
View File
@@ -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)
---
+93
View File
@@ -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
CI derives both the publication destination and the app's release API from
the current Git server and repository, so transferring to another owner or
renaming the repository needs no source changes. For local builds, set
`T3CODE_APK_REPOSITORY_URL` to the 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.
+12
View File
@@ -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
View File
@@ -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
+54
View File
@@ -0,0 +1,54 @@
# Hermes
[Hermes Agent](https://github.com/NousResearch/hermes-agent) is a coding agent CLI. T3 Code can
drive it like any other provider, giving it the same chat, tool-approval, and checkpoint
experience as Codex, Claude, Cursor, Grok Build, and OpenCode.
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**.
The only setting is **Binary path**, which 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.
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.
## Models
Hermes has no model list of its own in T3 Code. 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.
## 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.
- Local binary only. T3 Code spawns `hermes acp` as a subprocess; it does not support a remote
Hermes endpoint.
- Hermes Agent must be installed and configured on the machine running the T3 Code server. A
client connecting from a phone or another desktop does not need it installed locally.
+11
View File
@@ -58,6 +58,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
+6 -2
View File
@@ -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", {
+6
View File
@@ -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",
};
+5
View File
@@ -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",
+1
View File
@@ -22,6 +22,7 @@ export const ProjectSearchEntriesInput = Schema.Struct({
limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),
kind: Schema.optional(ProjectEntryKind),
imageOnly: Schema.optional(Schema.Boolean),
includeIgnored: Schema.optional(Schema.Boolean),
});
export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;
+17
View File
@@ -7,6 +7,7 @@ import {
ClientSettingsPatch,
ClaudeSettings,
DEFAULT_SERVER_SETTINGS,
HermesSettings,
resolveProviderInstanceEnabled,
ServerSettings,
ServerSettingsPatch,
@@ -19,6 +20,7 @@ const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
const decodeHermesSettings = Schema.decodeUnknownSync(HermesSettings);
describe("ServerSettings default permissions", () => {
it("keeps full access for settings saved before a default was configured", () => {
@@ -665,6 +667,7 @@ describe("provider enabled defaults", () => {
expect(decoded.providers.claudeAgent.enabled).toBe(true);
expect(decoded.providers.cursor.enabled).toBe(false);
expect(decoded.providers.grok.enabled).toBe(false);
expect(decoded.providers.hermes.enabled).toBe(false);
expect(decoded.providers.opencode.enabled).toBe(false);
});
@@ -840,6 +843,20 @@ describe("ServerSettingsPatch string normalization", () => {
});
});
describe("HermesSettings", () => {
it("decodes defaults", () => {
const decoded = decodeHermesSettings({});
expect(decoded.enabled).toBe(false);
expect(decoded.binaryPath).toBe("hermes");
expect(decoded.customModels).toEqual([]);
});
it("is reachable via ServerSettings defaults", () => {
const settings = decodeServerSettings({});
expect(settings.providers.hermes.binaryPath).toBe("hermes");
});
});
describe("ServerSettings environment icon", () => {
it("defaults to null", () => {
expect(decodeServerSettings({}).environmentIcon).toBeNull();
+34
View File
@@ -813,6 +813,32 @@ export const AntigravitySettings = makeProviderSettingsSchema(
);
export type AntigravitySettings = typeof AntigravitySettings.Type;
export const HermesSettings = makeProviderSettingsSchema(
{
// Off by default (like Cursor, Grok, and OpenCode): the binding is not
// yet stable enough to probe on every install. Users opt in from Settings.
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("hermes").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Hermes Agent binary.",
providerSettingsForm: { placeholder: "hermes", clearWhenEmpty: "omit" },
}),
),
customModels: Schema.Array(CustomModelSetting).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath"],
},
);
export type HermesSettings = typeof HermesSettings.Type;
export const OpenCodeSettings = makeProviderSettingsSchema(
{
// Off by default (like Cursor and Grok): the binding is not yet stable
@@ -1160,6 +1186,7 @@ export const ServerSettings = Schema.Struct({
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
hermes: HermesSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
antigravity: AntigravitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
@@ -1327,6 +1354,12 @@ const AntigravitySettingsPatch = Schema.Struct({
customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
});
const HermesSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
});
const OpenCodeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
@@ -1407,6 +1440,7 @@ export const ServerSettingsPatch = Schema.Struct({
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
cursor: Schema.optionalKey(CursorSettingsPatch),
grok: Schema.optionalKey(GrokSettingsPatch),
hermes: Schema.optionalKey(HermesSettingsPatch),
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
antigravity: Schema.optionalKey(AntigravitySettingsPatch),
}),
+14
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
filePreviewKind,
isDownloadOnlyFile,
decodeFilePreviewText,
FILE_TEXT_PREVIEW_MAX_BYTES,
hostPreviewMimeTypeFromExtension,
@@ -14,6 +15,19 @@ import {
} from "./filePreview.ts";
describe("workspace file previews", () => {
it.each(["app.apk", "APP.APK", "build/app.aab", "archive.tar.gz", "installer.exe"])(
"offers a download instead of previewing %s",
(path) => {
expect(isDownloadOnlyFile(path)).toBe(true);
},
);
it.each(["app.apk.ts", "README", "source.custom", "image.png", "report.pdf"])(
"retains preview behavior for %s",
(path) => {
expect(isDownloadOnlyFile(path)).toBe(false);
},
);
it.each(["report.html", "report.HTM", "document.pdf?download=1"])(
"recognizes browser preview path %s",
(path) => {
+6
View File
@@ -10,6 +10,12 @@ export type FilePreviewKind =
| "text"
| "unsupported";
export function isDownloadOnlyFile(path: string): boolean {
return /\.(apk|aab|ipa|exe|msi|dmg|iso|zip|tar|gz|bz2|xz|7z|rar|jar|war|dll|so|dylib|wasm|bin)$/i.test(
path,
);
}
/** Content classification is identical for captured attachments and workspace references. */
export function filePreviewKind(file: {
readonly name: string;
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
: "${T3CODE_APK_RELEASE_TAG:?Set an apk-<versionCode> release tag}"
: "${T3CODE_APK_REPOSITORY_URL:?Set the fork repository URL}"
: "${ANDROID_HOME:?Set ANDROID_HOME to the Android SDK}"
: "${ANDROID_NDK_HOME:?Set ANDROID_NDK_HOME to the Android NDK}"
: "${APK_KEYSTORE_BASE64:?Set the release keystore secret}"
: "${APK_KEYSTORE_PASSWORD:?Set the keystore password secret}"
: "${APK_KEY_ALIAS:?Set the signing key alias}"
: "${APK_KEY_PASSWORD:?Set the signing key password secret}"
node --input-type=module -e 'import { parseAndroidApkReleaseTag } from "./scripts/lib/android-apk-release.ts"; parseAndroidApkReleaseTag(process.env.T3CODE_APK_RELEASE_TAG)'
export APP_VARIANT=production
export T3CODE_MOBILE_UPDATES_ENABLED=0
export MOBILE_VERSION_POLICY=appVersion
export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=8192}"
signing_dir="$(mktemp -d)"
trap 'rm -rf "$signing_dir"' EXIT
printf '%s' "$APK_KEYSTORE_BASE64" | base64 --decode > "$signing_dir/release.keystore"
chmod 600 "$signing_dir/release.keystore"
unset APK_KEYSTORE_BASE64
bash apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
(
cd apps/mobile
EXPO_NO_GIT_STATUS=1 node_modules/.bin/expo prebuild --clean --platform android --no-install
cd android
./gradlew --no-daemon -PreactNativeArchitectures="${ANDROID_ARCHITECTURES:-arm64-v8a}" :app:assembleRelease
)
build_tools="${ANDROID_HOME}/build-tools/${ANDROID_BUILD_TOOLS_VERSION:-36.0.0}"
mkdir -p release
apk="release/t3code-${T3CODE_APK_RELEASE_TAG}.apk"
"$build_tools/apksigner" sign \
--ks "$signing_dir/release.keystore" \
--ks-key-alias "$APK_KEY_ALIAS" \
--ks-pass env:APK_KEYSTORE_PASSWORD \
--key-pass env:APK_KEY_PASSWORD \
--out "$apk" \
apps/mobile/android/app/build/outputs/apk/release/app-release.apk
"$build_tools/apksigner" verify --verbose --print-certs "$apk"
(
cd release
sha256sum "$(basename "$apk")" > "$(basename "$apk").sha256"
)
+32
View File
@@ -0,0 +1,32 @@
export function parseAndroidApkReleaseTag(tag: string): number {
const match = /^apk-([1-9]\d*)$/.exec(tag);
const versionCode = match ? Number(match[1]) : NaN;
if (!Number.isSafeInteger(versionCode) || versionCode > 2_100_000_000) {
throw new Error("APK release tags must be apk-<versionCode>, from 1 to 2100000000.");
}
return versionCode;
}
export function resolveAndroidApkRepository(repositoryUrl: string) {
const url = new URL(repositoryUrl);
const path = url.pathname.replace(/\/+$/, "").replace(/\.git$/, "");
const parts = path.split("/").filter(Boolean);
if (
url.protocol !== "https:" ||
url.username ||
url.password ||
url.search ||
url.hash ||
parts.length < 2
)
throw new Error(
"APK repository must be an HTTPS repository URL without credentials or query parameters.",
);
const repository = parts.slice(-2).join("/");
const basePath = parts.slice(0, -2).join("/");
const serverUrl = `${url.origin}${basePath ? `/${basePath}` : ""}`;
return {
releasesUrl: `${serverUrl}/${repository}/releases`,
apiUrl: `${serverUrl}/api/v1/repos/${repository}/releases`,
};
}
+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
parseAndroidApkReleaseTag,
resolveAndroidApkRepository,
} from "./lib/android-apk-release.ts";
import { publishForkApk } from "./publish-fork-apk.ts";
describe("APK release version codes", () => {
it("accepts Android version codes, including the platform maximum", () => {
expect(parseAndroidApkReleaseTag("apk-42")).toBe(42);
expect(parseAndroidApkReleaseTag("apk-2100000000")).toBe(2100000000);
});
it.each([
"v1.2.3",
"apk-0",
"apk-01",
"apk--1",
"apk-1.5",
"apk-2100000001",
"apk-1/../../secret",
])("rejects invalid release tag %s", (tag) =>
expect(() => parseAndroidApkReleaseTag(tag)).toThrow("APK release tags"),
);
});
describe("fork APK publishing", () => {
const options = {
tag: "apk-42",
commit: "abc123",
token: "test-token",
repositoryUrl: "https://git.example.com/new-owner/renamed-repo",
apk: new Blob(["apk"]),
checksum: new Blob(["checksum"]),
};
it("keeps the release in draft until both authenticated uploads finish", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response("{}"));
request.mockResolvedValueOnce(Response.json({ id: 123 }));
await publishForkApk({ ...options, request });
expect(request).toHaveBeenCalledTimes(4);
const [create, apk, checksum, publish] = request.mock.calls;
expect(create?.[0]).toBe(
"https://git.example.com/api/v1/repos/new-owner/renamed-repo/releases",
);
expect(JSON.parse(String(create?.[1]?.body))).toMatchObject({
draft: true,
tag_name: "apk-42",
target_commitish: "abc123",
});
expect(apk?.[0]).toContain("/123/assets?name=t3code-apk-42.apk");
const attachment = apk?.[1]?.body;
expect(attachment).toBeInstanceOf(FormData);
if (!(attachment instanceof FormData)) throw new Error("Missing upload form");
expect(attachment.get("attachment")).toBeInstanceOf(Blob);
expect(checksum?.[0]).toContain("t3code-apk-42.apk.sha256");
expect(publish?.[1]?.method).toBe("PATCH");
expect(JSON.parse(String(publish?.[1]?.body))).toEqual({ draft: false });
for (const [, init] of request.mock.calls) {
expect(init?.headers).toMatchObject({ Authorization: "token test-token" });
expect(init?.redirect).toBe("error");
}
});
it("passes a configured release body to the repository release", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response("{}"));
request.mockResolvedValueOnce(Response.json({ id: 123 }));
await publishForkApk({ ...options, body: "Local release notes", request });
expect(JSON.parse(String(request.mock.calls[0]?.[1]?.body))).toMatchObject({
body: "Local release notes",
});
});
it("does not publish an incomplete release after an upload failure", async () => {
const request = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ id: 123 }))
.mockResolvedValueOnce(new Response("", { status: 500 }));
await expect(publishForkApk({ ...options, request })).rejects.toThrow("HTTP 500");
expect(request).toHaveBeenCalledTimes(2);
});
it("reports authentication failures without exposing credentials", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response("", { status: 401 }));
await expect(publishForkApk({ ...options, request })).rejects.toThrow("HTTP 401");
expect(request).toHaveBeenCalledTimes(1);
});
it("does not upload without a valid release ID", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ id: "../other" }));
await expect(publishForkApk({ ...options, request })).rejects.toThrow("valid release ID");
expect(request).toHaveBeenCalledTimes(1);
});
});
describe("APK repository location", () => {
it.each(["original-owner", "new-owner"])("derives release locations for %s", (owner) => {
expect(resolveAndroidApkRepository(`https://git.example.com/${owner}/app.git/`)).toEqual({
releasesUrl: `https://git.example.com/${owner}/app/releases`,
apiUrl: `https://git.example.com/api/v1/repos/${owner}/app/releases`,
});
});
it("supports a Git server hosted under a subpath", () => {
expect(resolveAndroidApkRepository("https://example.com/git/owner/app").apiUrl).toBe(
"https://example.com/git/api/v1/repos/owner/app/releases",
);
});
it.each([
"http://example.com/owner/app",
"https://[email protected]/owner/app",
"https://example.com/owner",
"https://example.com/owner/app?token=secret",
])("rejects invalid repository URL %s", (url) => {
expect(() => resolveAndroidApkRepository(url)).toThrow();
});
});
+97
View File
@@ -0,0 +1,97 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeURL from "node:url";
import {
parseAndroidApkReleaseTag,
resolveAndroidApkRepository,
} from "./lib/android-apk-release.ts";
export async function publishForkApk(options: {
tag: string;
commit: string;
token: string;
repositoryUrl: string;
apk: Blob;
checksum: Blob;
request?: typeof fetch;
body?: string;
}) {
const versionCode = parseAndroidApkReleaseTag(options.tag);
const request = options.request ?? fetch;
const endpoint = resolveAndroidApkRepository(options.repositoryUrl).apiUrl;
const authorization = `token ${options.token}`;
const send = async (url: string, init: RequestInit) => {
const response = await request(url, {
...init,
redirect: "error",
headers: { ...init.headers, Authorization: authorization },
});
if (!response.ok) throw new Error(`Release request failed: HTTP ${response.status}`);
return response;
};
const created = await send(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
tag_name: options.tag,
target_commitish: options.commit,
name: `Android APK · build ${versionCode}`,
body:
options.body ??
"Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.",
draft: true,
prerelease: false,
}),
});
const release: unknown = await created.json();
if (
typeof release !== "object" ||
release === null ||
!("id" in release) ||
typeof release.id !== "number" ||
!Number.isSafeInteger(release.id) ||
release.id <= 0
)
throw new Error("Release API did not return a valid release ID.");
const filename = `t3code-${options.tag}.apk`;
for (const [name, file] of [
[filename, options.apk],
[`${filename}.sha256`, options.checksum],
] as const) {
const form = new FormData();
form.append("attachment", file, name);
await send(`${endpoint}/${release.id}/assets?name=${encodeURIComponent(name)}`, {
method: "POST",
body: form,
});
}
await send(`${endpoint}/${release.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ draft: false }),
});
}
if (process.argv[1] && import.meta.url === NodeURL.pathToFileURL(process.argv[1]).href) {
const tag = process.env.T3CODE_APK_RELEASE_TAG;
const token = process.env.APK_RELEASE_TOKEN;
const commit = process.env.APK_RELEASE_COMMIT;
const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL;
if (!tag || !token || !commit || !repositoryUrl)
throw new Error("Missing APK release tag, token, commit, or repository URL.");
parseAndroidApkReleaseTag(tag);
await publishForkApk({
tag,
token,
commit,
repositoryUrl,
apk: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk`)], {
type: "application/vnd.android.package-archive",
}),
checksum: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk.sha256`)], {
type: "text/plain",
}),
});
}
+149
View File
@@ -0,0 +1,149 @@
#!/bin/sh
# Build and publish the next t3code Android APK release.
#
# Without flags: build and publish the next APK version.
# With --dry-run: calculate and print the next version without building or publishing.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
DRY_RUN=0
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=1 ;;
--help|-h)
printf '%s\n' 'Usage: ./scripts/release-apk.sh [--dry-run]'
printf '%s\n' ' (default) build and publish the next APK release'
printf '%s\n' ' --dry-run calculate and print the next version without building or publishing'
exit 0
;;
*) echo "Unknown option: $arg" >&2; exit 2 ;;
esac
done
CONFIG_FILE=${CONFIG_FILE:-$ROOT/.env.release}
case "$CONFIG_FILE" in
/*) ;;
*) CONFIG_FILE="$ROOT/$CONFIG_FILE" ;;
esac
if [ -f "$CONFIG_FILE" ]; then
set -a
# shellcheck disable=SC1090
. "$CONFIG_FILE"
set +a
fi
API=${GITEA_API_URL:-https://git.molberg.cloud/api/v1/repos/alex/t3code}
REPOSITORY_URL=${T3CODE_APK_REPOSITORY_URL:-https://git.molberg.cloud/alex/t3code}
TOKEN=${APK_RELEASE_TOKEN:-${GITEA_TOKEN:-}}
if [ "$DRY_RUN" -eq 0 ] && [ -z "$TOKEN" ]; then
echo "Set GITEA_TOKEN or APK_RELEASE_TOKEN in $CONFIG_FILE or the environment" >&2
exit 2
fi
RELEASES_JSON=$(mktemp)
trap 'rm -f "$RELEASES_JSON"' EXIT HUP INT TERM
if [ -n "$TOKEN" ]; then
curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \
-H "Authorization: token $TOKEN" "$API/releases?limit=50" > "$RELEASES_JSON"
else
curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \
"$API/releases?limit=50" > "$RELEASES_JSON"
fi
VERSION_CODE=$(python3 - "$RELEASES_JSON" "${APK_VERSION_CODE:-}" <<'PY'
import json
import re
import sys
path, override = sys.argv[1:]
if override:
print(override)
raise SystemExit
highest = 0
with open(path, encoding="utf-8") as handle:
for release in json.load(handle):
tag = str(release.get("tag_name", ""))
match = re.fullmatch(r"apk-([1-9][0-9]*)", tag)
if match:
highest = max(highest, int(match.group(1)))
print(highest + 1)
PY
)
case "$VERSION_CODE" in
*[!0-9]*|'') echo "APK_VERSION_CODE must be a positive integer" >&2; exit 2 ;;
esac
[ "$VERSION_CODE" -gt 0 ] || { echo "APK_VERSION_CODE must be positive" >&2; exit 2; }
[ "$VERSION_CODE" -le 2100000000 ] || { echo "APK_VERSION_CODE must be at most 2100000000" >&2; exit 2; }
TAG="apk-$VERSION_CODE"
VERSION_NAME=$(sed -n 's/.*version: "\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)".*/\1/p' "$ROOT/apps/mobile/app.config.ts" | head -n 1)
VERSION_NAME=${VERSION_NAME:-unknown}
printf 'Next APK release: %s (versionName %s)\n' "$TAG" "$VERSION_NAME"
[ "$DRY_RUN" -eq 0 ] || exit 0
export T3CODE_APK_RELEASE_TAG="$TAG"
export T3CODE_APK_RELEASE_COMMIT=$(git -C "$ROOT" rev-parse HEAD)
export T3CODE_APK_REPOSITORY_URL="$REPOSITORY_URL"
export APK_RELEASE_TOKEN="$TOKEN"
export APP_VARIANT=production
export T3CODE_MOBILE_UPDATES_ENABLED=0
cd "$ROOT"
bash scripts/build-fork-apk.sh
APK="release/t3code-$TAG.apk"
CHECKSUM="$APK.sha256"
[ -s "$APK" ] || { echo "Build did not produce $APK" >&2; exit 1; }
[ -s "$CHECKSUM" ] || { echo "Build did not produce $CHECKSUM" >&2; exit 1; }
# build-fork-apk.sh runs `sha256sum` from inside release/, so the file references
# only the bare filename. Verify from that directory.
(
cd release
sha256sum -c "$(basename "$CHECKSUM")"
)
if [ -z "${APK_RELEASE_BODY:-}" ]; then
APK_RELEASE_BODY=$(python3 - "$TAG" "$VERSION_CODE" "$VERSION_NAME" "$T3CODE_APK_RELEASE_COMMIT" "$(sha256sum "$APK" | cut -d' ' -f1)" <<'PY'
import json
import sys
print(json.dumps({
"schema": 1,
"channel": "production",
"versionCode": int(sys.argv[2]),
"versionName": sys.argv[3],
"branch": "main",
"commit": sys.argv[4],
"sha256": sys.argv[5],
}, separators=(",", ":")))
PY
)
fi
APK_RELEASE_BODY="$APK_RELEASE_BODY" node --input-type=module <<'NODE'
import * as NodeFS from "node:fs/promises";
import { publishForkApk } from "./scripts/publish-fork-apk.ts";
const tag = process.env.T3CODE_APK_RELEASE_TAG;
const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL;
const token = process.env.APK_RELEASE_TOKEN;
const commit = process.env.T3CODE_APK_RELEASE_COMMIT;
if (!tag || !repositoryUrl || !token || !commit) throw new Error("Release environment is incomplete.");
await publishForkApk({
tag,
repositoryUrl,
token,
commit,
body: process.env.APK_RELEASE_BODY,
apk: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk`)], { type: "application/vnd.android.package-archive" }),
checksum: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk.sha256`)], { type: "text/plain" }),
});
NODE
printf 'Published %s\n' "$TAG"