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

This commit is contained in:
bonzi committed 2026-09-14 01:56:59 +00:00
1 parent 79b59d5e94
commit f325d1aa64
9 files changed
+990 -9

No files matched your search

+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">
@@ -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>
);
}
@@ -132,6 +132,7 @@ function LocalSettingsRouteScreen() {
value={`${environmentCount}`}
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
</SettingsSection>
<GeneralSettingsSection />
@@ -514,6 +515,7 @@ function ConfiguredSettingsRouteScreen() {
value={`${environmentCount}`}
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
<SettingsSwitchRow
icon="bell.badge"
label="Device Notifications"
@@ -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 };
}
+7 -4
View File
@@ -68,10 +68,9 @@ 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 |
| ----------- | ---------------------------------------------------------------------------------------------- |
@@ -90,6 +89,10 @@ Cursor's executable is `cursor-agent`, although its login command is
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
installer owns the CLI (its own update command, Homebrew, or a global npm, pnpm,
+6 -5
View File
@@ -20,22 +20,23 @@ does not configure Hermes on your behalf.
## Enable Hermes
Hermes is off by default. Turn it on in **Settings** → **Providers** → **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**, select **Hermes**, and give the instance a name. Each instance can use its own binary
path and environment variables; set `HERMES_HOME` there when the instances should use separate
Hermes profiles.
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.
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