Compare commits

...
4 Commits
Author SHA1 Message Date
bonzi 99fb86471e fix(mobile): use shared Hermes chat action
Fork Android APK / release (push) Has been cancelled
2026-09-20 12:31:49 +00:00
bonzi 92724f1509 fix(mobile): trust Gitea release download assets
Fork Android APK / release (push) Has been cancelled
2026-09-19 03:07:38 +00:00
bonzi 0d0f592a54 fix(hermes): align sessions and settings
Fork Android APK / release (push) Has been cancelled
2026-09-19 02:54:11 +00:00
bonzi c44c38f096 feat(hermes): add native Hermes workspace
Fork Android APK / release (push) Has been cancelled
2026-09-19 01:39:31 +00:00
51 changed files with 4553 additions and 162 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.40",
"version": "0.0.41-hermes.2",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+2 -2
View File
@@ -2,6 +2,7 @@ import type { ExpoConfig } from "expo/config";
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
import {
DEFAULT_ANDROID_APK_REPOSITORY_URL,
parseAndroidApkReleaseTag,
resolveAndroidApkRepository,
} from "../../scripts/lib/android-apk-release.ts";
@@ -13,11 +14,10 @@ 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,
repoEnv.T3CODE_APK_REPOSITORY_URL || DEFAULT_ANDROID_APK_REPOSITORY_URL,
);
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const runtimeVersionPolicy =
+8
View File
@@ -63,6 +63,7 @@ import {
} from "./features/settings/SettingsOpenSourceLicensesRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { SettingsProvidersRouteScreen } from "./features/settings/SettingsProvidersRouteScreen";
import { SettingsHermesRouteScreen } from "./features/settings/SettingsHermesRouteScreen";
import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled";
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
@@ -172,6 +173,13 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Providers",
},
}),
SettingsHermes: createNativeStackScreen({
screen: SettingsHermesRouteScreen,
linking: "hermes",
options: {
title: "Hermes",
},
}),
SettingsEnvironmentNew: createNativeStackScreen({
screen: ConnectionsNewRouteScreen,
linking: "environment-new",
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,12 @@
import * as Arr from "effect/Array";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { ConversationTabs, HermesMobileWorkspace } from "../hermes/HermesWorkspace";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { Platform, useWindowDimensions } from "react-native";
import { Platform, View, useWindowDimensions } from "react-native";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
@@ -26,6 +30,8 @@ import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle
/* ─── Route screen ───────────────────────────────────────────────────── */
export function HomeRouteScreen() {
const conversationSource = useAtomValue(conversationSourceAtom);
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
const { width: windowWidth } = useWindowDimensions();
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
@@ -106,6 +112,41 @@ export function HomeRouteScreen() {
// In split layouts the persistent sidebar IS the thread list — Home becomes
// an empty detail pane so selecting a thread never transitions layouts.
if (conversationSource === "hermes" && !layout.usesSplitView) {
const content = (
<View className="flex-1 bg-screen">
<NativeStackScreenOptions
options={{ title: "Hermes", headerShown: Platform.OS !== "android" }}
/>
{Platform.OS === "android" && (
<AndroidScreenHeader
title="Hermes"
actions={[
{
accessibilityLabel: "Settings",
icon: "gearshape",
onPress: () =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsHermes" },
}),
},
]}
/>
)}
<ConversationTabs />
<HermesMobileWorkspace />
</View>
);
return Platform.OS === "android" ? (
<AndroidHomeFabLayout onStartNewTask={() => requestHermesSession((value) => value + 1)}>
{content}
</AndroidHomeFabLayout>
) : (
content
);
}
if (layout.usesSplitView) {
return (
<>
@@ -181,6 +222,7 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<ConversationTabs />
<HomeScreen
catalogState={catalogState}
@@ -1,4 +1,6 @@
import { StackActions, useNavigation } from "@react-navigation/native";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
import {
useCallback,
@@ -36,6 +38,8 @@ export function HardwareKeyboardCommandProvider({
pathname,
}: PropsWithChildren<{ readonly pathname: string }>) {
const navigation = useNavigation();
const conversationSource = useAtomValue(conversationSourceAtom);
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
const activeThread = useThreadShell(activeThreadRef);
const copyTarget = useMemo(
@@ -125,6 +129,11 @@ export function HardwareKeyboardCommandProvider({
}
if (command === "newTask") {
if (conversationSource === "hermes") {
requestHermesSession((value) => value + 1);
navigation.navigate("Home");
return;
}
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
return;
}
@@ -149,7 +158,7 @@ export function HardwareKeyboardCommandProvider({
navigation.navigate("ThreadReview", thread);
}
},
[copyTarget, navigation, pathname, showCopyFeedback],
[conversationSource, copyTarget, navigation, pathname, requestHermesSession, showCopyFeedback],
);
return (
@@ -3,7 +3,9 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { ConversationTabs, HermesMobileWorkspace } from "../hermes/HermesWorkspace";
import { useFocusEffect } from "@react-navigation/native";
import {
NavigationContext,
@@ -226,6 +228,8 @@ function AdaptiveWorkspaceLayoutContent(
},
) {
const projectGroupingMode = props.projectGroupingMode;
const conversationSource = useAtomValue(conversationSourceAtom);
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
const { materialYouStyleLayoutActive } = useAppearancePreferences();
const { width, height } = useWindowDimensions();
const pathname = props.pathname;
@@ -445,8 +449,12 @@ function AdaptiveWorkspaceLayoutContent(
}, [navigation]);
const handleStartNewTask = useCallback(() => {
if (conversationSource === "hermes") {
requestHermesSession((value) => value + 1);
return;
}
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
}, [navigation]);
}, [conversationSource, navigation, requestHermesSession]);
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
@@ -561,21 +569,31 @@ function AdaptiveWorkspaceLayoutContent(
style={sidebarAnimatedStyle}
>
<View className="flex-1" style={{ width: layout.listPaneWidth }}>
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
<ThreadNavigationSidebar
width={layout.listPaneWidth}
visible={panes.primarySidebarVisible}
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onNewThreadOnBranch={handleNewThreadOnBranch}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
/>
</AndroidHomeFabLayout>
<ConversationTabs topInset />
{conversationSource === "hermes" ? (
<AndroidHomeFabLayout
onStartNewTask={() => requestHermesSession((value) => value + 1)}
>
<HermesMobileWorkspace mode="list" />
</AndroidHomeFabLayout>
) : (
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
<ThreadNavigationSidebar
topInset={0}
width={layout.listPaneWidth}
visible={panes.primarySidebarVisible}
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onNewThreadOnBranch={handleNewThreadOnBranch}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
/>
</AndroidHomeFabLayout>
)}
</View>
</Animated.View>
) : null}
@@ -596,7 +614,11 @@ function AdaptiveWorkspaceLayoutContent(
<WorkspaceContentWidthContext
value={layout.usesSplitView ? renderedContentWidth : null}
>
{props.children}
{layout.usesSplitView && conversationSource === "hermes" ? (
<HermesMobileWorkspace mode="detail" />
) : (
props.children
)}
</WorkspaceContentWidthContext>
</View>
</View>
@@ -0,0 +1,21 @@
import { useNavigation } from "@react-navigation/native";
import { Platform, View } from "react-native";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { HermesSettingsMobileWorkspace } from "../hermes/HermesWorkspace";
export function SettingsHermesRouteScreen() {
const navigation = useNavigation();
return (
<View className="flex-1 bg-screen">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Hermes" onBack={() => navigation.goBack()} />
</>
) : null}
<HermesSettingsMobileWorkspace />
</View>
);
}
@@ -168,6 +168,16 @@ function ProviderCard(props: {
{isHermes ? (
<View className="gap-3">
<CommittedTextInput
key={`dashboard:${readProviderConfigString(row.instance, "dashboardUrl")}`}
label="Dashboard URL (on the T3 server)"
value={readProviderConfigString(row.instance, "dashboardUrl")}
placeholder="http://127.0.0.1:9119"
disabled={props.saving}
onCommit={(value) =>
props.onCommit(updateProviderConfigString(row.instance, "dashboardUrl", value))
}
/>
<CommittedTextInput
key={`binary:${readProviderConfigString(row.instance, "binaryPath")}`}
label="Binary path"
@@ -7,7 +7,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "../../components/AppSymbol";
import * as Effect from "effect/Effect";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -44,12 +44,6 @@ import {
} from "@t3tools/contracts";
import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -134,6 +128,7 @@ function LocalSettingsRouteScreen() {
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
<SettingsRow icon="gearshape.2" label="Hermes" target="SettingsHermes" />
</SettingsSection>
<GeneralSettingsSection />
@@ -518,6 +513,7 @@ function ConfiguredSettingsRouteScreen() {
target="SettingsEnvironments"
/>
<SettingsRow icon="terminal" label="Providers" target="SettingsProviders" />
<SettingsRow icon="gearshape.2" label="Hermes" target="SettingsHermes" />
<SettingsSwitchRow
icon="bell.badge"
label="Device Notifications"
@@ -740,70 +736,12 @@ function LegacySettingsSection() {
}
function AppSettingsSection() {
const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
const updateInFlight = useRef(false);
const hiddenUpdateTapCount = useRef(0);
const version = Constants.expoConfig?.version ?? "0.0.0";
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
// missing variant never mislabels a production build as development.
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
const updateCheckAvailable = isAppUpdateCheckAvailable();
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
// "Up to date" is a transient acknowledgement, not a state worth persisting —
// return the version row to its normal, deliberately quiet state.
useEffect(() => {
if (updateState !== "current") return;
const timer = setTimeout(() => setUpdateState("idle"), 3000);
return () => clearTimeout(timer);
}, [updateState]);
const checkForUpdate = useCallback(async () => {
// `disabled={busy}` only takes effect on the next render, so two taps in the
// same frame would both get through. The ref closes that window.
if (updateInFlight.current) return;
updateInFlight.current = true;
try {
// The user asked for this restart by tapping the version row, so it may
// apply immediately instead of prompting.
await runAppUpdateCheck({
applyMode: "immediate",
onFailure: (message) => Alert.alert("Update failed", message),
onStateChange: setUpdateState,
});
} finally {
updateInFlight.current = false;
}
}, []);
const handleVersionPress = useCallback(() => {
if (!updateCheckAvailable || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate, updateCheckAvailable]);
const statusLabel =
updateState === "checking"
? "Checking…"
: updateState === "downloading"
? "Downloading…"
: // "ready" appears only when this check joined an in-flight background-mode
// check; that download installs at the next backgrounding.
updateState === "ready"
? "Update ready"
: updateState === "restarting"
? "Restarting…"
: updateState === "current"
? "Up to date"
: null;
const versionRow = (
<View className="flex-row items-center gap-4 p-4">
<SymbolView
@@ -814,12 +752,7 @@ function AppSettingsSection() {
weight="regular"
/>
<Text className="flex-1 text-lg text-foreground">Version</Text>
<View className="items-end">
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
{statusLabel ? (
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
) : null}
</View>
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
</View>
);
@@ -833,18 +766,7 @@ function AppSettingsSection() {
target="SettingsOpenSourceLicenses"
/>
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{updateCheckAvailable ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
disabled={busy}
onPress={handleVersionPress}
>
{versionRow}
</Pressable>
) : (
versionRow
)}
{versionRow}
</SettingsSection>
);
}
@@ -1,5 +1,5 @@
import Constants from "expo-constants";
import { useState } from "react";
import { useCallback, useState } from "react";
import { Alert, Platform, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -9,6 +9,11 @@ import {
downloadTrustedAndroidApk,
runAndroidApkUpdate,
} from "./androidApkUpdater";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
runAppUpdateCheck,
} from "../updates/app-updates";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -33,6 +38,15 @@ const STATUS_LABEL: Record<UpdateStatus, string | undefined> = {
failed: "Try again",
};
const APP_UPDATE_STATUS_LABEL: Record<AppUpdateCheckState, string | undefined> = {
idle: undefined,
checking: "Checking…",
downloading: "Downloading…",
ready: "Update ready",
restarting: "Restarting…",
current: "Up to date",
};
async function fetchReleasePage(
apiUrl: string,
init: { credentials: "omit"; redirect: "error"; signal: AbortSignal },
@@ -111,11 +125,24 @@ async function launchPackageInstaller(
export function SoftwareUpdateSection() {
const [status, setStatus] = useState<UpdateStatus>("idle");
const [appUpdateState, setAppUpdateState] = useState<AppUpdateCheckState>("idle");
const apiUrl = Constants.expoConfig?.extra?.apkReleaseApiUrl;
const manifestVersionCode =
Constants.platform?.android?.versionCode ?? Constants.expoConfig?.android?.versionCode;
if (Platform.OS !== "android" || typeof apiUrl !== "string" || !apiUrl) return null;
const hasApkUpdates =
Platform.OS === "android" && typeof apiUrl === "string" && apiUrl.length > 0;
const hasAppUpdates = isAppUpdateCheckAvailable();
const checkAppUpdate = useCallback(async () => {
await runAppUpdateCheck({
applyMode: "immediate",
onFailure: (message) => Alert.alert("Could not update T3 Code", message),
onStateChange: setAppUpdateState,
});
}, []);
if (!hasApkUpdates && !hasAppUpdates) return null;
const update = async () => {
try {
@@ -163,7 +190,11 @@ export function SoftwareUpdateSection() {
}
};
const busy = status === "checking" || status === "downloading" || status === "installing";
const apkBusy = status === "checking" || status === "downloading" || status === "installing";
const appUpdateBusy =
appUpdateState === "checking" ||
appUpdateState === "downloading" ||
appUpdateState === "restarting";
return (
<View className="gap-2">
@@ -175,18 +206,28 @@ export function SoftwareUpdateSection() {
{manifestVersionCode ? ` (${manifestVersionCode})` : ""}
</Text>
</View>
<SettingsRow
icon="arrow.down.circle"
label="Check for updates"
value={STATUS_LABEL[status]}
disabled={busy}
onPress={() => void update()}
/>
{hasApkUpdates ? (
<SettingsRow
icon="arrow.down.circle"
label="Check for updates"
value={STATUS_LABEL[status]}
disabled={apkBusy}
onPress={() => void update()}
/>
) : (
<SettingsRow
icon="arrow.down.circle"
label="Check for updates"
value={APP_UPDATE_STATUS_LABEL[appUpdateState]}
disabled={appUpdateBusy}
onPress={() => void checkAppUpdate()}
/>
)}
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
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.
{hasApkUpdates
? "Checks the repository, downloads a newer APK inside T3 Code, then opens Android’s installer for your confirmation. Android may require permission to install unknown apps from T3 Code. Updates must use the same signing key as your installed app."
: "Checks for an app update, downloads it securely, and restarts T3 Code after saving pending drafts and messages. Background update checks also run automatically."}
</Text>
</View>
);
@@ -159,9 +159,26 @@ describe("Android APK release selection", () => {
).toBeNull();
});
it("rejects same-origin assets outside the exact Gitea attachment path", () => {
it("accepts the exact Gitea repository release download path", () => {
const browser_download_url =
"https://git.example.com/alex/t3code/releases/download/apk-5/t3code-apk-5.apk";
expect(
selectLatestAndroidApkRelease(
[
release(5, {
assets: [{ id: 5, name: "t3code-apk-5.apk", size: 4, browser_download_url }],
}),
],
API_URL,
),
).toEqual({ versionCode: 5, downloadUrl: browser_download_url, expectedSize: 4 });
});
it("rejects same-origin assets outside trusted Gitea asset paths", () => {
for (const browser_download_url of [
`https://git.example.com/alex/t3code/releases/download/apk-5/t3code-apk-5.apk`,
`https://git.example.com/other/t3code/releases/download/apk-5/t3code-apk-5.apk`,
`https://git.example.com/alex/t3code/releases/download/apk-6/t3code-apk-5.apk`,
`https://git.example.com/alex/t3code/releases/download/apk-5/other.apk`,
`https://git.example.com/api/v1/repos/alex/t3code/releases/assets/5`,
`https://git.example.com/other/attachments/${attachmentUuid(5)}`,
`https://git.example.com/attachments/not-a-uuid`,
@@ -201,6 +218,22 @@ describe("Android APK release selection", () => {
expect(selectLatestAndroidApkRelease([valid], API_URL)).toBeNull();
});
it("uses the exact configured Gitea subpath for release downloads", () => {
const valid = release(5, {
assets: [
{
id: 5,
name: "t3code-apk-5.apk",
size: 4,
browser_download_url:
"https://git.example.com/git/alex/t3code/releases/download/apk-5/t3code-apk-5.apk",
},
],
});
expect(selectLatestAndroidApkRelease([valid], SUBPATH_API_URL)?.versionCode).toBe(5);
expect(selectLatestAndroidApkRelease([valid], API_URL)).toBeNull();
});
it("rejects assets with invalid or excessive declared sizes", () => {
for (const size of [0, -1, 1.5, 500 * 1024 * 1024 + 1]) {
expect(
@@ -136,23 +136,44 @@ function trustedHttpsUrl(rawUrl: string, kind: "API" | "asset"): URL {
return url;
}
function giteaServerBase(apiUrl: string): { readonly origin: string; readonly path: string } {
function giteaServerBase(apiUrl: string): {
readonly origin: string;
readonly path: string;
readonly owner: string;
readonly repository: string;
} {
const url = trustedHttpsUrl(apiUrl, "API");
const match = /^(.*)\/api\/v1\/repos\/[^/]+\/[^/]+\/releases\/?$/.exec(url.pathname);
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] ?? "" };
return {
origin: url.origin,
path: match[1] ?? "",
owner: match[2] ?? "",
repository: match[3] ?? "",
};
}
function trustedAttachmentUrl(rawUrl: unknown, apiUrl: string): string | null {
function trustedAssetUrl(
rawUrl: unknown,
apiUrl: string,
releaseTag: string,
assetName: string,
): string | null {
if (typeof rawUrl !== "string") return null;
try {
const url = trustedHttpsUrl(rawUrl, "asset");
const server = giteaServerBase(apiUrl);
if (url.origin !== server.origin) return null;
const 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;
const attachmentPrefix = `${server.path}/attachments/`;
if (url.pathname.startsWith(attachmentPrefix)) {
const uuid = url.pathname.slice(attachmentPrefix.length);
return GITEA_ATTACHMENT_UUID.test(uuid) ? url.href : null;
}
const releaseUrl = new URL(
`${server.path}/${server.owner}/${server.repository}/releases/download/${releaseTag}/${assetName}`,
server.origin,
);
return url.href === releaseUrl.href ? url.href : null;
} catch {
return null;
}
@@ -411,7 +432,12 @@ export function selectLatestAndroidApkRelease(
asset.name !== expectedAssetName
)
continue;
const downloadUrl = trustedAttachmentUrl(asset.browser_download_url, apiUrl);
const downloadUrl = trustedAssetUrl(
asset.browser_download_url,
apiUrl,
release.tag_name,
expectedAssetName,
);
if (!downloadUrl) continue;
candidate = { versionCode, downloadUrl, expectedSize: asset.size };
break;
@@ -1,6 +1,7 @@
export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsProviders"
| "SettingsHermes"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
@@ -100,6 +100,7 @@ type SidebarListItem =
const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
interface ThreadNavigationSidebarProps {
readonly topInset?: number;
readonly width: number;
readonly visible: boolean;
readonly selectedThreadKey: string | null;
@@ -152,6 +153,7 @@ function ThreadNavigationSidebarPane(
const mutedColor = materialTheme["--color-foreground-muted"];
const insets = useSafeAreaInsets();
const topInset = props.topInset ?? insets.top;
const projects = useProjects();
const threads = useThreadShells();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
@@ -748,7 +750,7 @@ function ThreadNavigationSidebarPane(
// The sticky header (title row, search field, optional connection status)
// is measured so the list inset always matches its real height — no
// hardcoded per-variant constants.
const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
const stickyHeaderHeight = measuredHeaderHeight ?? topInset + SIDEBAR_STICKY_HEADER_HEIGHT;
const topListInset = stickyHeaderHeight + 6;
const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -1309,7 +1311,7 @@ function ThreadNavigationSidebarPane(
collapsable={false}
onLayout={handleStickyHeaderLayout}
pointerEvents="auto"
style={{ paddingTop: insets.top }}
style={{ paddingTop: topInset }}
>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
{/* Title slot doubles as the connection status surface: while an
+119
View File
@@ -891,6 +891,125 @@ describe("buildThreadFeed", () => {
expect(group.activities[0]?.getFullDetail()).toBeNull();
});
it("keeps Hermes ACP tool inputs and outputs expandable on mobile", () => {
const toolData = {
toolCallId: "tool-read-file",
kind: "other",
rawInput: { path: "/workspace/package.json", offset: 1, limit: 80 },
rawOutput: { content: '{"name":"example"}' },
};
const thread = makeThread({
id: ThreadId.make("thread-hermes-tool-details"),
projectId: ProjectId.make("project-1"),
title: "Hermes tool details",
activities: [
makeActivity({
id: EventId.make("hermes-tool-details"),
kind: "tool.completed",
tone: "tool",
summary: "Read file",
createdAt: "2026-09-01T00:00:00.000Z",
payload: {
itemType: "dynamic_tool_call",
title: "Read file",
status: "completed",
data: toolData,
},
}),
],
});
const [group] = buildThreadFeed(thread);
expect(group?.type).toBe("activity-group");
if (group?.type !== "activity-group") return;
const [row] = group.activities;
expect(row?.canExpand).toBe(true);
expect(row?.workEntry.toolData).toBe(toolData);
expect(row?.getFullDetail()).toBe(`Tool call\n${JSON.stringify(toolData, null, 2)}`);
});
it("shows the exact Hermes ACP command payload in expanded mobile rows", () => {
const command = "pnpm test --filter mobile";
const toolData = {
toolCallId: "tool-run-tests",
kind: "execute",
command,
rawInput: { executable: "pnpm", args: ["test", "--filter", "mobile"] },
rawOutput: { stdout: "102 tests passed", exitCode: 0 },
};
const thread = makeThread({
id: ThreadId.make("thread-hermes-command-details"),
projectId: ProjectId.make("project-1"),
title: "Hermes command details",
activities: [
makeActivity({
id: EventId.make("hermes-command-details"),
kind: "tool.completed",
tone: "tool",
summary: "Ran command",
createdAt: "2026-09-01T00:00:00.000Z",
payload: {
itemType: "command_execution",
title: "Ran command",
status: "completed",
data: toolData,
},
}),
],
});
const [group] = buildThreadFeed(thread);
expect(group?.type).toBe("activity-group");
if (group?.type !== "activity-group") return;
const [row] = group.activities;
expect(row?.workEntry.toolData).toBe(toolData);
expect(row?.getFullDetail()).toBe(
[`Tool call\n${JSON.stringify(toolData, null, 2)}`, command, "102 tests passed"].join("\n\n"),
);
});
it.each(["file_change", "web_search"] as const)(
"keeps Hermes ACP %s payloads expandable on mobile",
(itemType) => {
const toolData = {
toolCallId: `tool-${itemType}`,
kind: itemType === "file_change" ? "edit" : "search",
rawInput:
itemType === "file_change"
? { path: "/workspace/src/app.ts", patch: "@@ -1 +1 @@" }
: { query: "React Native expandable rows" },
rawOutput: { content: "completed" },
};
const thread = makeThread({
id: ThreadId.make(`thread-hermes-${itemType}-details`),
projectId: ProjectId.make("project-1"),
title: "Hermes tool details",
activities: [
makeActivity({
id: EventId.make(`hermes-${itemType}-details`),
kind: "tool.completed",
tone: "tool",
summary: "Tool completed",
createdAt: "2026-09-01T00:00:00.000Z",
payload: {
itemType,
title: "Tool completed",
status: "completed",
data: toolData,
},
}),
],
});
const [group] = buildThreadFeed(thread);
expect(group?.type).toBe("activity-group");
if (group?.type !== "activity-group") return;
const [row] = group.activities;
expect(row?.canExpand).toBe(true);
expect(row?.getFullDetail()).toBe(`Tool call\n${JSON.stringify(toolData, null, 2)}`);
},
);
it("keeps setup failures visible without routine setup notices before or after a turn", () => {
const thread = makeThread({
id: ThreadId.make("thread-worktree-setup"),
+21 -7
View File
@@ -578,12 +578,9 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (toolPresentation.toolSource) {
entry.toolSource = toolPresentation.toolSource;
}
if (itemType === "mcp_tool_call") {
const data = asRecord(payload?.data);
const toolData = typeof data?.toolName === "string" ? (data.item ?? data) : data?.item;
if (toolData !== undefined) {
entry.toolData = toolData;
}
const toolData = extractWorkLogToolData(itemType, payload);
if (toolData !== undefined) {
entry.toolData = toolData;
}
if (itemType) {
entry.itemType = itemType;
@@ -966,6 +963,21 @@ function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
return "zap";
}
function extractWorkLogToolData(
itemType: WorkLogEntry["itemType"],
payload: Record<string, unknown> | null,
): unknown {
const data = asRecord(payload?.data);
if (!data) return undefined;
if (itemType === "mcp_tool_call") {
return typeof data.toolName === "string" ? (data.item ?? data) : data.item;
}
const isAcpToolCall =
typeof data.toolCallId === "string" &&
("rawInput" in data || "rawOutput" in data || "content" in data || "locations" in data);
return isAcpToolCall ? data : undefined;
}
function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
if (entry.agentSpawn) return agentSpawnExpandedBody(entry.agentSpawn);
const blocks: string[] = [];
@@ -979,6 +991,8 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
appendBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
} else if (entry.toolData !== undefined) {
appendBlock(`Tool call\n${JSON.stringify(entry.toolData, null, 2)}`);
}
appendBlock(entry.rawCommand ?? entry.command);
appendBlock(entry.detail);
@@ -997,7 +1011,7 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
function workEntryCanExpand(entry: WorkLogEntry): boolean {
if (entry.questionAnswer) return true;
if (entry.agentSpawn) return agentSpawnMembers(entry.agentSpawn).length > 0;
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) return true;
if (entry.toolData !== undefined) return true;
if (entry.changedFiles?.some((path) => path.trim().length > 0)) return true;
return Boolean((entry.rawCommand ?? entry.command)?.trim() || entry.detail?.trim());
}
+4
View File
@@ -0,0 +1,4 @@
import { createHermesState } from "@t3tools/client-runtime/hermes";
import { connectionAtomRuntime } from "../connection/runtime";
export const hermes = createHermesState(connectionAtomRuntime);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.41-hermes.1",
"version": "0.0.41-hermes.2",
"license": "MIT",
"repository": {
"type": "git",
@@ -11,6 +11,11 @@ import { describe, expect, it } from "@effect/vitest";
import { RPC_REQUIRED_SCOPES, requiredScopeForRpcMethod } from "./RpcAuthorization.ts";
describe("RPC authorization scopes", () => {
it("separates Hermes reads from session and management mutations", () => {
expect(requiredScopeForRpcMethod(WS_METHODS.hermesRead)).toBe(AuthOrchestrationReadScope);
expect(requiredScopeForRpcMethod(WS_METHODS.hermesEvents)).toBe(AuthOrchestrationReadScope);
expect(requiredScopeForRpcMethod(WS_METHODS.hermesWrite)).toBe(AuthOrchestrationOperateScope);
});
it("declares exactly one scope for every RPC in the server group", () => {
expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
});
+3
View File
@@ -21,6 +21,9 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
* runtime failure.
*/
export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.hermesRead]: AuthOrchestrationReadScope,
[WS_METHODS.hermesWrite]: AuthOrchestrationOperateScope,
[WS_METHODS.hermesEvents]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
+445
View File
@@ -0,0 +1,445 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { ProviderInstanceId, type HermesEvent } from "@t3tools/contracts";
import { DashboardClient, hermesReadRoute, hermesWriteRoute } from "./HermesBridge.ts";
const target = { instanceId: ProviderInstanceId.make("hermes"), profile: "personal" };
class MockSocket extends EventTarget {
static readonly OPEN = 1;
static readonly CLOSED = 3;
static instances: MockSocket[] = [];
static reply: ((frame: Record<string, unknown>) => Record<string, unknown>) | undefined;
readyState = 0;
readonly url: URL;
readonly frames: Record<string, unknown>[] = [];
constructor(url: URL) {
super();
this.url = url;
MockSocket.instances.push(this);
queueMicrotask(() => {
this.readyState = MockSocket.OPEN;
this.dispatchEvent(new Event("open"));
});
}
send(data: string) {
const frame = JSON.parse(data) as Record<string, unknown>;
this.frames.push(frame);
if (!frame.method) return;
const result =
frame.method === "session.resume" || frame.method === "session.create"
? { session_id: "runtime-1", stored_session_id: "saved-1" }
: { ok: true };
queueMicrotask(() =>
this.receive({ jsonrpc: "2.0", id: frame.id, ...(MockSocket.reply?.(frame) ?? { result }) }),
);
}
receive(data: unknown) {
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) }));
}
close() {
this.readyState = MockSocket.CLOSED;
this.dispatchEvent(new Event("close"));
}
}
function fixture(
options: { remote?: boolean; status?: number; body?: unknown; loginStatus?: number } = {},
) {
const calls: {
url: URL;
method: string;
headers: Record<string, string>;
body: string | undefined;
}[] = [];
const timers = new Set<() => void>();
const files: string[] = [];
const io: ConstructorParameters<typeof DashboardClient>[3] = {
join: (...parts) => parts.join("/"),
readText: async (file) => {
files.push(file);
return file.endsWith(".env")
? "HERMES_DASHBOARD_BASIC_AUTH_USERNAME=operator\nHERMES_DASHBOARD_BASIC_AUTH_PASSWORD=test-password"
: "";
},
schedule: (_milliseconds, callback) => {
timers.add(callback);
return () => {
timers.delete(callback);
};
},
request: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
if (url.pathname.endsWith("/api/health"))
return { status: 200, cookies: [], text: '{"auth_required":true}' };
if (url.pathname.endsWith("/auth/password-login"))
return {
status: options.loginStatus ?? 200,
cookies: ["hermes_session=private-token; HttpOnly; Path=/"],
text: '{"ok":true}',
};
if (url.pathname.endsWith("/api/auth/ws-ticket"))
return { status: 200, cookies: [], text: '{"ticket":"single-use-ticket"}' };
return {
status: options.status ?? 200,
cookies: [],
text: JSON.stringify(options.body ?? { sessions: [{ id: "saved-1" }], total: 1 }),
};
},
};
const client = new DashboardClient(
new URL(options.remote ? "https://hermes.example/prefix" : "http://127.0.0.1:9119"),
"/hermes-test",
{},
io,
);
return { client, calls, timers, files };
}
afterEach(() => {
vi.unstubAllGlobals();
MockSocket.instances = [];
MockSocket.reply = undefined;
});
describe("Hermes dashboard routes", () => {
it("lists recent native sessions across profiles with bounded pages", () => {
const route = new URL(
hermesReadRoute({ ...target, resource: "sessions", offset: 50 }),
"http://localhost",
);
expect(route.pathname).toBe("/api/profiles/sessions");
expect(Object.fromEntries(route.searchParams)).toEqual({
profile: "personal",
order: "recent",
limit: "50",
offset: "50",
});
});
it("encodes session identifiers instead of allowing API path injection", () => {
expect(hermesReadRoute({ ...target, resource: "messages", id: "session/a?b" })).toContain(
"/api/sessions/session%2Fa%3Fb/messages?",
);
expect(() => hermesReadRoute({ ...target, resource: "messages" })).toThrow(
"session is required",
);
});
it("uses the native cron update envelope and supports both pause directions", () => {
expect(
hermesWriteRoute({
...target,
action: "updateCron",
id: "job",
fields: { prompt: "changed" },
}),
).toEqual({
method: "PUT",
path: "/api/cron/jobs/job?profile=personal",
body: { updates: { prompt: "changed" } },
});
expect(hermesWriteRoute({ ...target, action: "pauseCron", id: "job" }).path).toContain(
"/job/pause?",
);
expect(hermesWriteRoute({ ...target, action: "resumeCron", id: "job" }).path).toContain(
"/job/resume?",
);
});
it("routes memory edits through Hermes’s profile-aware mutation API", () => {
expect(
hermesWriteRoute({ ...target, action: "saveMemory", id: "memory:user:2", text: "updated" }),
).toEqual({
method: "PUT",
path: "/api/learning/node",
body: { id: "memory:user:2", content: "updated", profile: "personal" },
});
});
});
describe("Hermes dashboard authentication and failures", () => {
it("authenticates once and retains cookies only on the server-side client", async () => {
const { client, calls } = fixture();
const results = await Promise.all([
client.read({ ...target, resource: "sessions" }),
client.read({ ...target, resource: "logs" }),
]);
expect(calls.filter((call) => call.url.pathname === "/auth/password-login")).toHaveLength(1);
expect(
calls.find((call) => call.url.pathname === "/api/profiles/sessions")?.headers.Cookie,
).toBe("hermes_session=private-token");
expect(JSON.stringify(results)).not.toContain("private-token");
expect(JSON.stringify(results)).not.toContain("test-password");
client.close();
});
it("never sends auto-discovered local credentials to a remote dashboard", async () => {
const { client, calls, files } = fixture({ remote: true });
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
expect(files).toEqual([]);
expect(calls).toHaveLength(1);
await client.login("operator", "explicit-password");
await client.read({ ...target, resource: "sessions" });
expect(calls.at(-1)?.url.pathname).toBe("/prefix/api/profiles/sessions");
client.close();
});
it("preserves structured dashboard error status and detail", async () => {
const { client } = fixture({ status: 503, body: { detail: "Session store is busy. Retry." } });
await expect(client.read({ ...target, resource: "sessions" })).rejects.toMatchObject({
status: 503,
message: "Session store is busy. Retry.",
operation: "/api/profiles/sessions",
});
client.close();
});
it("tolerates a newly created session before Hermes persists its first prompt", async () => {
const { client } = fixture({ status: 404 });
client.remember("new-session", "runtime-new", "personal");
await expect(
client.read({ ...target, resource: "messages", id: "new-session" }),
).resolves.toEqual({ session_id: "new-session", messages: [] });
await expect(
client.read({ ...target, resource: "messages", id: "missing-session" }),
).rejects.toMatchObject({ status: 404 });
client.close();
});
});
describe("Hermes gateway lifecycle", () => {
it("coalesces concurrent attaches to one native session resume", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
expect(await Promise.all([client.session("saved-1"), client.session("saved-1")])).toEqual([
"runtime-1",
"runtime-1",
]);
expect(
MockSocket.instances[0]?.frames.filter((frame) => frame.method === "session.resume"),
).toHaveLength(1);
client.close();
});
it("replays outstanding requests when the event subscription starts after attach", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await client.session("saved-1");
MockSocket.instances[0]!.receive({
method: "approval",
id: "srq-late",
params: { session_id: "runtime-1", choices: ["once", "deny"] },
});
const events: HermesEvent[] = [];
client.listen((event) => events.push(event));
expect(events).toContainEqual(
expect.objectContaining({
type: "request",
sessionId: "saved-1",
payload: expect.objectContaining({ requestId: "srq-late" }),
}),
);
client.close();
});
it("reuses native sessions and translates runtime events to durable IDs", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client, calls, timers } = fixture();
const events: HermesEvent[] = [];
const remove = client.listen((event) => events.push(event));
expect(await client.session("saved-1", "personal")).toBe("runtime-1");
expect(await client.session("saved-1", "personal")).toBe("runtime-1");
const socket = MockSocket.instances[0]!;
expect(socket.frames.filter((frame) => frame.method === "session.resume")).toHaveLength(1);
expect(socket.url.searchParams.get("ticket")).toBe("single-use-ticket");
expect(calls.find((call) => call.url.pathname === "/api/auth/ws-ticket")?.method).toBe("POST");
socket.receive({
method: "event",
params: {
type: "tool.start",
session_id: "runtime-1",
payload: { command: "echo hello", arguments: { exact: "input" } },
},
});
expect(events.at(-1)).toMatchObject({
sessionId: "saved-1",
type: "tool.start",
payload: { command: "echo hello", arguments: { exact: "input" } },
});
remove();
client.close();
expect(timers.size).toBe(0);
});
it("forwards approval requests and rejects stale responses", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
const events: HermesEvent[] = [];
client.listen((event) => events.push(event));
await client.session("saved-1");
const socket = MockSocket.instances[0]!;
socket.receive({
jsonrpc: "2.0",
id: "approval-1",
method: "approval",
params: { session_id: "runtime-1", choices: ["once", "deny"] },
});
expect(events.at(-1)).toMatchObject({
type: "request",
sessionId: "saved-1",
payload: { requestId: "approval-1", method: "approval" },
});
client.respond("approval-1", { choice: "deny" });
expect(socket.frames.at(-1)).toEqual({
jsonrpc: "2.0",
id: "approval-1",
result: { choice: "deny" },
});
expect(() => client.respond("approval-1", { choice: "once" })).toThrow("expired");
expect(events.at(-1)?.type).toBe("request.resolved");
client.close();
});
it("resumes again after disconnect instead of reusing a stale runtime ID", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await client.session("saved-1");
MockSocket.instances[0]!.close();
await client.session("saved-1");
expect(MockSocket.instances).toHaveLength(2);
expect(MockSocket.instances[1]!.frames[0]?.method).toBe("session.resume");
client.close();
});
});
describe("Hermes native actions", () => {
it("creates a project-free session and sends prompts without creating a second runtime", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await expect(client.write({ ...target, action: "create" })).resolves.toMatchObject({
stored_session_id: "saved-1",
});
await client.write({ ...target, action: "send", id: "saved-1", text: "Hello Hermes" });
expect(
MockSocket.instances[0]!.frames.map(({ method, params }) => ({ method, params })),
).toEqual([
{ method: "session.create", params: { profile: "personal", close_on_disconnect: false } },
{ method: "prompt.submit", params: { session_id: "runtime-1", text: "Hello Hermes" } },
]);
client.close();
});
it("submits the full expanded skill prompt and preserves multiline arguments", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await client.session("saved-1", "personal");
MockSocket.reply = (frame) => ({
result:
frame.method === "command.dispatch"
? {
type: "skill",
message: "Full skill instructions\n".repeat(1000),
display: "/research",
}
: { ok: true },
});
await client.write({
...target,
action: "command",
id: "saved-1",
text: "/research first\n second",
});
expect(MockSocket.instances[0]!.frames.at(-2)).toMatchObject({
method: "command.dispatch",
params: { name: "research", arg: "first\n second" },
});
expect(MockSocket.instances[0]!.frames.at(-1)).toMatchObject({
method: "prompt.submit",
params: { text: "Full skill instructions\n".repeat(1000) },
});
client.close();
});
it("resolves aliases but returns undo prefills without submitting them", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await client.session("saved-1", "personal");
MockSocket.reply = (frame) => ({
result:
(frame.params as { name: string }).name === "again"
? { type: "alias", target: "undo" }
: { type: "prefill", message: "Edit this before sending" },
});
await expect(
client.write({ ...target, action: "command", id: "saved-1", text: "/again" }),
).resolves.toMatchObject({ type: "prefill", message: "Edit this before sending" });
expect(MockSocket.instances[0]!.frames.map((frame) => frame.method)).not.toContain(
"prompt.submit",
);
client.close();
});
it("falls back only for unowned slash commands, not failed executions", async () => {
vi.stubGlobal("WebSocket", MockSocket);
const { client } = fixture();
await client.session("saved-1", "personal");
MockSocket.reply = (frame) =>
frame.method === "command.dispatch"
? { error: { message: "not a quick/plugin/bundle/skill command: status" } }
: { result: { output: "Connected" } };
await expect(
client.write({ ...target, action: "command", id: "saved-1", text: "/status" }),
).resolves.toEqual({ output: "Connected" });
expect(MockSocket.instances[0]!.frames.at(-1)).toMatchObject({
method: "slash.exec",
params: { command: "status" },
});
MockSocket.reply = () => ({ error: { message: "Command failed: invalid credentials" } });
await expect(
client.write({ ...target, action: "command", id: "saved-1", text: "/status" }),
).rejects.toThrow("invalid credentials");
expect(
MockSocket.instances[0]!.frames.filter((frame) => frame.method === "slash.exec"),
).toHaveLength(1);
client.close();
});
it("does not repeatedly submit a bad local password during polling", async () => {
const { client, calls } = fixture({ loginStatus: 401 });
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
await expect(client.read({ ...target, resource: "sessions" })).rejects.toThrow("Sign in");
expect(calls.filter((call) => call.url.pathname === "/auth/password-login")).toHaveLength(1);
client.close();
});
it("refuses stale memory edits, then saves the current content through the profile API", async () => {
const { client, calls } = fixture({ body: { content: "Already updated" } });
await expect(
client.write({
...target,
action: "saveMemory",
id: "memory:user:2",
text: "New",
fields: { expectedContent: "Old" },
}),
).rejects.toThrow("changed in Hermes");
expect(calls.some((call) => call.method === "PUT")).toBe(false);
await client.write({
...target,
action: "saveMemory",
id: "memory:user:2",
text: "New",
fields: { expectedContent: "Already updated" },
});
expect(JSON.parse(calls.at(-1)!.body!)).toEqual({
id: "memory:user:2",
content: "New",
profile: "personal",
});
client.close();
});
});
+785
View File
@@ -0,0 +1,785 @@
import * as NodeOS from "node:os";
import * as NodeUtil from "node:util";
import { parse as parseYaml } from "yaml";
import {
HermesError,
HermesSettings,
type HermesEvent,
type HermesReadInput,
type HermesTarget,
type HermesWriteInput,
type ServerSettings,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { Cookies, HttpClient, HttpClientRequest, type HttpMethod } from "effect/unstable/http";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
const RecordValue = Schema.Record(Schema.String, Schema.Unknown);
const decodeRecord = Schema.decodeUnknownSync(RecordValue);
const record = (value: unknown): Record<string, unknown> =>
value !== null && typeof value === "object" && !Array.isArray(value) ? decodeRecord(value) : {};
const text = (value: unknown) => (typeof value === "string" ? value : "");
const decodeSettings = Schema.decodeUnknownSync(HermesSettings);
const isHermesError = Schema.is(HermesError);
const errorText = (value: unknown) =>
typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
export function hermesReadRoute(input: HermesReadInput) {
const query = new URLSearchParams();
if (input.profile) query.set("profile", input.profile);
const id = encodeURIComponent(input.id ?? "");
let pathname: string;
switch (input.resource) {
case "sessions":
pathname = "/api/profiles/sessions";
query.set("order", "recent");
query.set("limit", "50");
query.set("offset", String(input.offset ?? 0));
break;
case "messages":
if (!input.id) throw new Error("A Hermes session is required.");
pathname = `/api/sessions/${id}/messages`;
query.set("limit", "100");
query.set("offset", String(input.offset ?? 0));
query.set("order", "latest");
break;
case "skills":
pathname = "/api/skills";
break;
case "skill":
pathname = "/api/skills/content";
query.set("name", input.id ?? "");
break;
case "memories":
pathname = "/api/learning/graph";
break;
case "memory":
pathname = "/api/learning/node";
query.set("id", input.id ?? "");
break;
case "cron":
pathname = "/api/cron/jobs";
break;
case "logs":
pathname = "/api/logs";
query.set("file", input.logFile ?? "agent");
query.set("lines", "300");
if (input.text) query.set("search", input.text);
break;
case "commands":
throw new Error("Slash completions use the Hermes gateway.");
}
return `${pathname}?${query}`;
}
export function hermesWriteRoute(input: HermesWriteInput) {
const id = encodeURIComponent(input.id ?? "");
const query = new URLSearchParams(input.profile ? { profile: input.profile } : {});
const profile = input.profile ? { profile: input.profile } : {};
switch (input.action) {
case "saveSkill":
return {
method: "PUT",
path: "/api/skills/content",
body: { name: input.id, content: input.text, ...profile },
};
case "saveMemory":
return {
method: "PUT",
path: "/api/learning/node",
body: { id: input.id, content: input.text, ...profile },
};
case "createCron":
return { method: "POST", path: `/api/cron/jobs?${query}`, body: input.fields ?? {} };
case "updateCron":
return {
method: "PUT",
path: `/api/cron/jobs/${id}?${query}`,
body: { updates: input.fields ?? {} },
};
case "pauseCron":
return { method: "POST", path: `/api/cron/jobs/${id}/pause?${query}` };
case "resumeCron":
return { method: "POST", path: `/api/cron/jobs/${id}/resume?${query}` };
case "runCron":
return { method: "POST", path: `/api/cron/jobs/${id}/trigger?${query}` };
case "deleteCron":
return { method: "DELETE", path: `/api/cron/jobs/${id}?${query}` };
case "renameSession":
return {
method: "PATCH",
path: `/api/sessions/${id}`,
body: { title: input.text, ...profile },
};
case "deleteSession":
return { method: "DELETE", path: `/api/sessions/${id}?${query}` };
default:
throw new Error("This operation uses the Hermes gateway.");
}
}
interface DashboardIO {
readonly readText: (file: string) => Promise<string>;
readonly join: (...parts: string[]) => string;
readonly schedule: (milliseconds: number, callback: () => void) => () => void;
readonly request: (
url: URL,
method: string,
headers: Record<string, string>,
body?: string,
) => Promise<{ status: number; cookies: string[]; text: string }>;
}
export class DashboardClient {
private readonly cookies = new Map<string, string>();
private socket: WebSocket | undefined;
private connecting: Promise<WebSocket> | undefined;
private counter = 0;
private sequence = 0;
private readonly listeners = new Set<(event: HermesEvent) => void>();
private readonly pending = new Map<
string,
{ resolve: (value: unknown) => void; reject: (error: Error) => void; cancelTimer: () => void }
>();
private readonly sessions = new Map<string, string>();
private readonly resuming = new Map<string, Promise<string>>();
private readonly storedIds = new Map<string, string>();
private readonly newSessions = new Set<string>();
private readonly requests = new Map<string, string>();
private readonly requestEvents = new Map<string, HermesEvent>();
private history: HermesEvent[] = [];
private authenticated = false;
private autoLoginAttempted = false;
private authenticating: Promise<void> | undefined;
private disposed = false;
readonly base: URL;
private readonly home: string;
private readonly environment: Record<string, string>;
private readonly io: DashboardIO;
constructor(base: URL, home: string, environment: Record<string, string>, io: DashboardIO) {
this.base = base;
this.home = home;
this.environment = environment;
this.io = io;
}
private async fetchJson(route: string, method = "GET", body?: unknown): Promise<unknown> {
const response = await this.io.request(
new URL(`${this.base.pathname.replace(/\/$/, "")}${route}`, this.base),
method,
{
"Content-Type": "application/json",
Origin: this.base.origin,
Cookie: [...this.cookies].map(([name, value]) => `${name}=${value}`).join("; "),
},
body === undefined ? undefined : JSON.stringify(body),
);
for (const cookie of response.cookies) {
const pair = cookie.split(";", 1)[0] ?? "";
const split = pair.indexOf("=");
if (split > 0) this.cookies.set(pair.slice(0, split), pair.slice(split + 1));
}
const responseText = response.text;
let data: unknown;
try {
data = JSON.parse(responseText);
} catch {
if (response.status >= 200 && response.status < 300 && response.status !== 204)
throw new HermesError({
operation: route.split("?", 1)[0] ?? route,
status: response.status,
message:
"Hermes returned a non-JSON response. Check the dashboard address and sign-in requirements.",
});
data = {};
}
if (response.status < 200 || response.status >= 300) {
if (response.status === 401) this.authenticated = false;
const message =
response.status === 401 || response.status === 302
? "Sign in to the Hermes dashboard to connect this environment."
: errorText(record(data).detail) ||
errorText(record(data).message) ||
`Hermes returned HTTP ${response.status}.`;
throw new HermesError({
message,
operation: route.split("?", 1)[0] ?? route,
status: response.status,
});
}
return data;
}
async login(username: string, password: string) {
await this.fetchJson("/auth/password-login", "POST", { provider: "basic", username, password });
this.authenticated = true;
return { ok: true };
}
private async authenticate() {
if (this.disposed) throw new Error("The T3 connection has closed.");
if (this.authenticated) return;
if (this.authenticating) return this.authenticating;
this.authenticating = (async () => {
const health = record(await this.fetchJson("/api/health"));
if (!health.auth_required) {
this.authenticated = true;
return;
}
if (this.autoLoginAttempted)
throw new Error(
"Sign in to the Hermes dashboard to reconnect. Automatic sign-in is not retried after a failure or expired login.",
);
this.autoLoginAttempted = true;
if (!["localhost", "127.0.0.1", "[::1]"].includes(this.base.hostname)) {
throw new Error("Sign in to the Hermes dashboard. Credentials stay on the T3 server.");
}
const fileEnv = NodeUtil.parseEnv(await this.io.readText(this.io.join(this.home, ".env")));
const config = record(
parseYaml(await this.io.readText(this.io.join(this.home, "config.yaml"))),
);
const basic = record(record(config.dashboard).basic_auth);
const username =
this.environment.HERMES_DASHBOARD_BASIC_AUTH_USERNAME ||
fileEnv.HERMES_DASHBOARD_BASIC_AUTH_USERNAME ||
text(basic.username);
const password =
this.environment.HERMES_DASHBOARD_BASIC_AUTH_PASSWORD ||
fileEnv.HERMES_DASHBOARD_BASIC_AUTH_PASSWORD ||
text(basic.password);
if (!username || !password)
throw new Error(
"Sign in with your Hermes dashboard username and password. Password-hash-only installations require one sign-in per T3 connection.",
);
await this.login(username, password);
})();
try {
await this.authenticating;
} finally {
this.authenticating = undefined;
}
}
async request(route: string, method = "GET", body?: unknown) {
await this.authenticate();
return this.fetchJson(route, method, body);
}
private async connect(): Promise<WebSocket> {
if (this.disposed) throw new Error("The T3 connection has closed.");
if (this.socket?.readyState === WebSocket.OPEN) return this.socket;
if (this.connecting) return this.connecting;
this.connecting = (async () => {
await this.authenticate();
const health = record(await this.fetchJson("/api/health"));
const url = new URL(`${this.base.pathname.replace(/\/$/, "")}/api/ws`, this.base);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
if (health.auth_required) {
const ticket = record(await this.fetchJson("/api/auth/ws-ticket", "POST"));
if (!text(ticket.ticket)) throw new Error("Hermes did not issue a WebSocket ticket.");
url.searchParams.set("ticket", text(ticket.ticket));
} else {
const response = await this.io.request(this.base, "GET", {});
const html = response.text;
const token = html.match(
/(?:__HERMES_SESSION_TOKEN__|__HERMES_TOKEN__)\s*=\s*["']([^"']+)/,
)?.[1];
if (!token)
throw new Error(
"Hermes dashboard authentication is required for chat. Enable dashboard sign-in and reconnect.",
);
url.searchParams.set("token", token);
}
if (this.disposed) throw new Error("The T3 connection has closed.");
const socket = new WebSocket(url);
this.socket = socket;
socket.addEventListener("message", (event) => {
if (typeof event.data !== "string") return;
for (const line of event.data.split("\n").filter(Boolean)) {
try {
const frame = record(JSON.parse(line));
const pending = this.pending.get(text(frame.id));
if (pending) {
pending.cancelTimer();
this.pending.delete(text(frame.id));
if (frame.error) {
const error = record(frame.error);
pending.reject(
new Error(
`${text(error.message) || "Hermes gateway rejected the request."}${error.code === undefined ? "" : ` (RPC ${errorText(error.code)})`}${error.data === undefined ? "" : `\n${errorText(error.data)}`}`,
),
);
} else pending.resolve(frame.result);
} else if (frame.method === "event") {
const params = record(frame.params);
if (params.type === "request.cancel") {
this.requests.delete(text(record(params.payload).id));
this.requestEvents.delete(text(record(params.payload).id));
}
const runtimeId = text(params.session_id);
const storedId = text(record(params.payload).stored_session_id);
if (params.type === "session.info" && storedId)
this.storedIds.set(runtimeId, storedId);
const next = {
sequence: ++this.sequence,
type: text(params.type),
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
payload: params.payload,
};
this.emit(next);
} else if (typeof frame.method === "string" && typeof frame.id === "string") {
const params = record(frame.params);
const runtimeId = text(params.session_id);
this.requests.set(frame.id, runtimeId);
this.emit({
sequence: ++this.sequence,
type: "request",
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
payload: { requestId: frame.id, method: frame.method, params },
});
}
} catch {
this.emitError("Hermes sent an unreadable gateway event.");
}
}
});
socket.addEventListener("close", () => {
if (this.socket !== socket) return;
this.sessions.clear();
this.storedIds.clear();
this.requests.clear();
this.requestEvents.clear();
this.rejectPending("Hermes gateway disconnected. Reconnect the session to continue.");
if (!this.disposed)
this.emit({
sequence: ++this.sequence,
type: "error",
sessionId: "",
payload: {
message: "Hermes gateway disconnected. Reconnect the session to continue.",
disconnected: true,
},
});
});
await new Promise<void>((resolve, reject) => {
const cancelTimer = this.io.schedule(15_000, () => {
socket.close();
reject(new Error("Hermes gateway connection timed out."));
});
socket.addEventListener(
"open",
() => {
cancelTimer();
resolve();
},
{ once: true },
);
socket.addEventListener(
"error",
() => {
cancelTimer();
socket.close();
reject(new Error("Could not connect to the Hermes chat gateway."));
},
{ once: true },
);
socket.addEventListener(
"close",
() => {
cancelTimer();
reject(new Error("Hermes gateway connection closed."));
},
{ once: true },
);
});
return socket;
})();
try {
return await this.connecting;
} finally {
this.connecting = undefined;
}
}
private emitError(message: string) {
this.emit({ sequence: ++this.sequence, type: "error", sessionId: "", payload: { message } });
}
private emit(event: HermesEvent) {
if (event.type === "request")
this.requestEvents.set(text(record(event.payload).requestId), event);
const previous = this.history.at(-1);
if (
event.type === "message.delta" &&
previous?.type === event.type &&
previous.sessionId === event.sessionId
) {
this.history[this.history.length - 1] = {
...event,
payload: {
...record(event.payload),
text: (text(record(previous.payload).text) + text(record(event.payload).text)).slice(
-512_000,
),
},
};
} else this.history = [...this.history.slice(-49), event];
for (const listener of this.listeners) listener(event);
}
private rejectPending(message: string) {
for (const pending of this.pending.values()) {
pending.cancelTimer();
pending.reject(new Error(message));
}
this.pending.clear();
}
async rpc(method: string, params: Record<string, unknown>) {
const socket = await this.connect();
const id = `t3-${++this.counter}`;
return new Promise<unknown>((resolve, reject) => {
const cancelTimer = this.io.schedule(60_000, () => {
this.pending.delete(id);
reject(new Error(`Hermes ${method} timed out. Check live logs before retrying.`));
});
this.pending.set(id, { resolve, reject, cancelTimer });
try {
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
} catch (error) {
cancelTimer();
this.pending.delete(id);
reject(error);
}
});
}
async session(id: string, profile?: string) {
const key = JSON.stringify([profile, id]);
const existing = this.sessions.get(key);
if (existing && this.socket?.readyState === WebSocket.OPEN) return existing;
const pending = this.resuming.get(key);
if (pending) return pending;
const operation = this.resumeSession(id, profile);
this.resuming.set(key, operation);
try {
return await operation;
} finally {
this.resuming.delete(key);
}
}
private async resumeSession(id: string, profile?: string) {
const resumed = record(await this.rpc("session.resume", { session_id: id, profile }));
const runtimeId = text(resumed.session_id);
if (!runtimeId) throw new Error("Hermes could not resume this session.");
this.sessions.set(JSON.stringify([profile, id]), runtimeId);
this.storedIds.set(runtimeId, id);
for (const raw of Array.isArray(resumed.open_requests) ? resumed.open_requests : []) {
const request = record(raw);
const requestId = text(request.id);
if (!requestId) continue;
this.requests.set(requestId, runtimeId);
this.emit({
sequence: ++this.sequence,
type: "request",
sessionId: id,
payload: { requestId, method: text(request.method), params: record(request.params) },
});
}
return runtimeId;
}
remember(storedId: string, runtimeId: string, profile?: string) {
this.sessions.set(JSON.stringify([profile, storedId]), runtimeId);
this.storedIds.set(runtimeId, storedId);
this.newSessions.add(storedId);
}
async read(input: HermesReadInput) {
try {
const result = await this.request(hermesReadRoute(input));
if (input.resource === "messages" && input.id) this.newSessions.delete(input.id);
return result;
} catch (error) {
if (
input.resource === "messages" &&
input.id &&
this.newSessions.has(input.id) &&
isHermesError(error) &&
error.status === 404
) {
return { session_id: input.id, messages: [] };
}
throw error;
}
}
async create(profile?: string) {
const result = record(
await this.rpc("session.create", { profile, close_on_disconnect: false }),
);
const storedId = text(result.stored_session_id);
const runtimeId = text(result.session_id);
if (!storedId || !runtimeId) throw new Error("Hermes did not return the new session identity.");
this.remember(storedId, runtimeId, profile);
return result;
}
async command(sessionId: string, command: string, profile?: string, depth = 0): Promise<unknown> {
if (depth >= 8) throw new Error("Hermes command alias loop detected.");
const match = command
.trim()
.replace(/^\//, "")
.match(/^(\S+)(?:\s+([\s\S]*))?$/);
if (!match) throw new Error("Enter a Hermes slash command.");
const name = match[1] ?? "";
const arg = match[2] ?? "";
if (name === "new" || name === "reset") {
if (arg)
throw new Error("Use New task to start a session, then select its model with /model.");
return { ...(await this.create(profile)), type: "session" };
}
let result: Record<string, unknown>;
try {
result = record(await this.rpc("command.dispatch", { session_id: sessionId, name, arg }));
} catch (error) {
if (
!(error instanceof Error) ||
!error.message.startsWith("not a quick/plugin/bundle/skill command:")
)
throw error;
result = record(
await this.rpc("slash.exec", {
session_id: sessionId,
command: command.trim().replace(/^\//, ""),
}),
);
}
if (result.type === "alias") {
const target = text(result.target).replace(/^\//, "");
if (!target) throw new Error("Hermes returned an empty command alias.");
return this.command(sessionId, `/${target}${arg ? ` ${arg}` : ""}`, profile, depth + 1);
}
if (result.type === "skill" || result.type === "send") {
const message = text(result.message);
if (!message.trim()) throw new Error("Hermes returned an empty command prompt.");
const submission = await this.rpc("prompt.submit", { session_id: sessionId, text: message });
return { ...result, submission };
}
return result;
}
async write(input: HermesWriteInput): Promise<unknown> {
if (input.action === "login") return this.login(text(input.fields?.username), input.text ?? "");
if (input.action === "respond")
return this.respond(text(input.fields?.requestId), record(input.fields?.response));
if (input.action === "create") return this.create(input.profile);
if (["attach", "send", "interrupt", "command"].includes(input.action)) {
if (!input.id) throw new Error("Select a Hermes session first.");
const sessionId = await this.session(input.id, input.profile);
if (input.action === "attach") return { session_id: sessionId, stored_session_id: input.id };
if (input.action === "interrupt")
return this.rpc("session.interrupt", { session_id: sessionId });
if (input.action === "send")
return this.rpc("prompt.submit", { session_id: sessionId, text: input.text ?? "" });
return this.command(sessionId, input.text ?? "", input.profile);
}
if (input.action !== "createCron" && !input.id) throw new Error("Select an item first.");
if (
(input.action === "saveSkill" || input.action === "saveMemory") &&
typeof input.fields?.expectedContent === "string"
) {
const current = record(
await this.read({ ...input, resource: input.action === "saveSkill" ? "skill" : "memory" }),
);
if (current.content !== input.fields.expectedContent)
throw new Error(
"This item changed in Hermes while you were editing. Reload it before saving to avoid overwriting another change.",
);
}
const route = hermesWriteRoute(input);
return this.request(route.path, route.method, route.body);
}
listen(listener: (event: HermesEvent) => void) {
this.listeners.add(listener);
const events = new Map(this.history.map((event) => [event.sequence, event]));
for (const event of this.requestEvents.values()) events.set(event.sequence, event);
for (const event of [...events.values()].sort((left, right) => left.sequence - right.sequence))
listener({ ...event, sessionId: this.storedIds.get(event.sessionId) ?? event.sessionId });
return () => {
this.listeners.delete(listener);
};
}
close() {
this.disposed = true;
this.rejectPending("The T3 connection has closed.");
this.socket?.close();
this.cookies.clear();
this.listeners.clear();
this.history = [];
this.requestEvents.clear();
}
respond(requestId: string, response: Record<string, unknown>) {
const runtimeId = this.requests.get(requestId);
if (!runtimeId || this.socket?.readyState !== WebSocket.OPEN)
throw new Error("This Hermes request has expired. Refresh the session.");
this.socket.send(JSON.stringify({ jsonrpc: "2.0", id: requestId, result: response }) + "\n");
this.requests.delete(requestId);
this.requestEvents.delete(requestId);
this.emit({
sequence: ++this.sequence,
type: "request.resolved",
sessionId: this.storedIds.get(runtimeId) ?? runtimeId,
payload: { id: requestId },
});
return { ok: true };
}
}
export const makeHermesBridge = Effect.fn("makeHermesBridge")(function* (
getSettings: Effect.Effect<ServerSettings, { readonly message: string }>,
) {
const filesystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const http = yield* HttpClient.HttpClient;
const io: DashboardIO = {
join: path.join,
readText: (file) =>
Effect.runPromise(
filesystem.readFileString(file).pipe(Effect.catch(() => Effect.succeed(""))),
),
schedule: (milliseconds, callback) => {
const fiber = Effect.runFork(
Effect.sleep(milliseconds).pipe(Effect.andThen(Effect.sync(callback))),
);
return () => {
Effect.runFork(Fiber.interrupt(fiber));
};
},
request: (url, method, headers, body) =>
Effect.runPromise(
Effect.gen(function* () {
let request = HttpClientRequest.make(method as HttpMethod.HttpMethod)(url, { headers });
if (body !== undefined)
request = HttpClientRequest.bodyText(request, body, "application/json");
const response = yield* http.execute(request);
return {
status: response.status,
cookies: Cookies.toSetCookieHeaders(response.cookies),
text: yield* response.text,
};
}).pipe(Effect.timeout(20_000)),
),
};
const clients = new Map<string, DashboardClient>();
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
for (const client of clients.values()) client.close();
}),
);
const clientFor = Effect.fn("HermesBridge.client")(function* (target: HermesTarget) {
const settings = yield* getSettings.pipe(
Effect.mapError(
(error) => new HermesError({ message: error.message, operation: "settings" }),
),
);
const instance = settings.providerInstances[target.instanceId];
if (!instance || instance.driver !== "hermes" || instance.enabled === false) {
return yield* new HermesError({
message: "Select an enabled Hermes provider in this environment.",
operation: "settings",
});
}
const config = yield* Effect.try({
try: () => decodeSettings(instance.config ?? settings.providers.hermes),
catch: () =>
new HermesError({ message: "Invalid Hermes provider settings.", operation: "settings" }),
});
const environment = Object.fromEntries(
Object.entries(process.env).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
for (const variable of instance.environment ?? []) environment[variable.name] = variable.value;
const home = (environment.HERMES_HOME || path.join(NodeOS.homedir(), ".hermes")).replace(
/^~(?=\/|$)/,
NodeOS.homedir(),
);
const base = yield* Effect.try({
try: () => new URL(config.dashboardUrl),
catch: () =>
new HermesError({
message: "Set a valid Hermes Dashboard URL in provider settings.",
operation: "settings",
}),
});
if (
!["http:", "https:"].includes(base.protocol) ||
base.username ||
base.password ||
base.search ||
base.hash
) {
return yield* new HermesError({
message:
"Hermes Dashboard URL must be an HTTP(S) address without credentials, query, or fragment.",
operation: "settings",
});
}
const key = `${target.instanceId}\n${base.href}\n${home}`;
let client = clients.get(key);
if (!client) {
client = new DashboardClient(base, home, environment, io);
clients.set(key, client);
}
return client;
});
const attempt = <Value>(operation: string, run: () => Promise<Value>) =>
Effect.tryPromise({
try: run,
catch: (error) =>
isHermesError(error)
? error
: new HermesError({
operation,
message: error instanceof Error ? error.message : "Hermes request failed.",
}),
});
return {
read: Effect.fn("HermesBridge.read")(function* (input: HermesReadInput) {
const client = yield* clientFor(input);
const data = yield* attempt(input.resource, async () =>
input.resource === "commands"
? client.rpc("complete.slash", { text: input.text ?? "/", profile: input.profile })
: client.read(input),
);
return { data };
}),
write: Effect.fn("HermesBridge.write")(function* (input: HermesWriteInput) {
const client = yield* clientFor(input);
const data = yield* attempt(input.action, () => client.write(input));
return { data };
}),
events: (input: HermesTarget) =>
Stream.callback<HermesEvent, HermesError>((queue) =>
Effect.gen(function* () {
const client = yield* clientFor(input);
const remove = client.listen((event) => {
Queue.offerUnsafe(queue, event);
});
yield* Effect.addFinalizer(() => Effect.sync(remove));
}),
),
};
});
@@ -136,6 +136,7 @@ const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
});
const makeHermesConfig = (overrides: Partial<HermesSettings>): HermesSettings => ({
dashboardUrl: "http://127.0.0.1:9119",
enabled: false,
binaryPath: "hermes",
customModels: [],
+8
View File
@@ -14,6 +14,7 @@ import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { makeHermesBridge } from "./hermes/HermesBridge.ts";
import {
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
AuthAccessStreamError,
@@ -557,6 +558,7 @@ const makeWsRpcLayer = (
const config = yield* ServerConfig.ServerConfig;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const hermes = yield* makeHermesBridge(serverSettings.getSettings);
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -1339,6 +1341,12 @@ const makeWsRpcLayer = (
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
return WsRpcGroup.of({
[WS_METHODS.hermesRead]: (input) =>
observeRpcEffect(WS_METHODS.hermesRead, hermes.read(input)),
[WS_METHODS.hermesWrite]: (input) =>
observeRpcEffect(WS_METHODS.hermesWrite, hermes.write(input)),
[WS_METHODS.hermesEvents]: (input) =>
observeRpcStream(WS_METHODS.hermesEvents, hermes.events(input)),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.dispatchCommand,
+12 -2
View File
@@ -1,4 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
import { ConversationTabs, HermesSidebar, HermesWorkspace } from "./hermes/HermesWorkspace";
import * as Schema from "effect/Schema";
import {
useEffect,
@@ -27,7 +29,7 @@ import {
import LegacyThreadSidebar from "./LegacySidebar";
import ThreadSidebar from "./Sidebar";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import {
resolveSidebarStageFocusRingOffsetClass,
useSidebarStageBackdropVariant,
@@ -146,6 +148,7 @@ function ProjectProjectionRetention() {
}
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const conversationSource = useAtomValue(conversationSourceAtom);
const navigate = useNavigate();
const legacySidebarEnabled = useLegacySidebarEnabled();
const compactSidebarEnabled = useCompactSidebarEnabled();
@@ -252,6 +255,13 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<SidebarChromeHeader isElectron={isElectron} />
<SettingsSidebarNav pathname={pathname} />
</>
) : conversationSource === "hermes" ? (
<>
<SidebarChromeHeader isElectron={isElectron} />
<ConversationTabs />
<HermesSidebar />
<SidebarChromeFooter />
</>
) : legacySidebarEnabled ? (
<LegacyThreadSidebar />
) : (
@@ -259,7 +269,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
)}
<SidebarRail onDoubleClick={resetSidebarWidth} />
</Sidebar>
{children}
{!isOnSettings && conversationSource === "hermes" ? <HermesWorkspace /> : children}
<SidebarControl />
</SidebarProvider>
</PanelAnimationSuppressionProvider>
+26 -2
View File
@@ -66,7 +66,8 @@ import {
type KeyboardEvent,
type ReactNode,
} from "react";
import { useAtomValue } from "@effect/atom-react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
@@ -649,6 +650,9 @@ function OpenCommandPaletteDialog(props: {
const availableSettingsSearchItems = useAvailableSettingsSearchItems();
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
useHandleNewThread();
const conversationSource = useAtomValue(conversationSourceAtom);
const setConversationSource = useAtomSet(conversationSourceAtom);
const startHermesSession = useAtomSet(hermesNewSessionAtom);
const projects = useProjects();
const referenceThreadRef =
pathname === "/pull-requests"
@@ -1095,6 +1099,7 @@ function OpenCommandPaletteDialog(props: {
clientSettings.sidebarThreadSortOrder,
);
if (latestThread) {
setConversationSource("t3");
await navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
@@ -1111,6 +1116,7 @@ function OpenCommandPaletteDialog(props: {
handleNewThread,
navigate,
projectGroupByTargetKey,
setConversationSource,
threads,
],
);
@@ -1275,6 +1281,7 @@ function OpenCommandPaletteDialog(props: {
: undefined;
},
runThread: async (thread) => {
setConversationSource("t3");
await navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
@@ -1289,6 +1296,7 @@ function OpenCommandPaletteDialog(props: {
projectEnvironmentLocationById,
projectTitleById,
providerEntryByEnvironmentAndInstanceId,
setConversationSource,
threadContentMatchByKey,
threadSearchQuery,
threads,
@@ -1643,7 +1651,22 @@ function OpenCommandPaletteDialog(props: {
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (projects.length > 0) {
if (conversationSource === "hermes") {
actionItems.push({
kind: "action",
value: "action:new-hermes-session",
searchTerms: ["new", "task", "hermes", "chat", "session"],
title: "New Hermes session",
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "chat.new",
run: async () => {
startHermesSession((value) => value + 1);
await navigate({ to: "/" });
},
});
}
if (projects.length > 0 && conversationSource === "t3") {
const activeProjectTitle =
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
@@ -1855,6 +1878,7 @@ function OpenCommandPaletteDialog(props: {
description: contextualProjectGroup.displayName,
icon: <FolderIcon className={ITEM_ICON_CLASS} />,
run: async () => {
setConversationSource("t3");
await navigate({
to: "/projects/$projectKey",
params: { projectKey: contextualProjectGroup.projectKey },
@@ -196,6 +196,7 @@ import {
} from "./Sidebar.logic";
import { sortThreads } from "../lib/threadSort";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { ConversationTabs } from "./hermes/HermesWorkspace";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
@@ -3804,6 +3805,7 @@ export default function LegacySidebar() {
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
))}
<SidebarChromeHeader isElectron={isElectron} />
<ConversationTabs />
<SidebarProjectsContent
showArm64IntelBuildWarning={showArm64IntelBuildWarning}
+2
View File
@@ -235,6 +235,7 @@ import {
} from "./ui/combobox";
import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { ConversationTabs } from "./hermes/HermesWorkspace";
import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
@@ -4688,6 +4689,7 @@ export default function Sidebar() {
return (
<>
<SidebarChromeHeader isElectron={isElectron} />
<ConversationTabs />
<SidebarContent
className={cn(
"gap-0",
File diff suppressed because it is too large. Load diff
@@ -82,6 +82,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/keybindings": KeyboardIcon,
"/settings/snap-shot": SnapShotIcon,
"/settings/providers": BotIcon,
"/settings/hermes": BotIcon,
"/settings/integrations": BlocksIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
@@ -15,6 +15,7 @@ export type SettingsPath =
| "/settings/keybindings"
| "/settings/snap-shot"
| "/settings/providers"
| "/settings/hermes"
| "/settings/integrations"
| "/settings/source-control"
| "/settings/connections"
@@ -76,6 +77,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/keybindings": "Keybindings",
"/settings/snap-shot": "SnapShots",
"/settings/providers": "Providers",
"/settings/hermes": "Hermes",
"/settings/integrations": "Integrations",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
@@ -729,6 +731,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScop
// environment at any selection. Neither needs a particular scope to render.
"/settings/keybindings": null,
"/settings/providers": null,
"/settings/hermes": null,
"/settings/integrations": null,
"/settings/source-control": "environment-defaults",
"/settings/connections": "connections",
@@ -6,6 +6,8 @@ import {
} from "lucide-react";
import type { ReactNode } from "react";
import { memo, useCallback } from "react";
import { useAtomSet } from "@effect/atom-react";
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
import { Link, useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
@@ -158,24 +160,27 @@ export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() {
setOpenMobile(false);
}
}, [isMobile, setOpenMobile]);
const setConversationSource = useAtomSet(conversationSourceAtom);
const handlePullRequestsClick = useCallback(() => {
setConversationSource("t3");
closeMobileSidebar();
void navigate({
to: "/pull-requests",
search: readPullRequestListPreferences(),
});
}, [closeMobileSidebar, navigate]);
}, [closeMobileSidebar, navigate, setConversationSource]);
const handleSettingsClick = useCallback(() => {
closeMobileSidebar();
void navigate({ to: "/settings" });
}, [closeMobileSidebar, navigate]);
const handleUsageClick = useCallback(() => {
setConversationSource("t3");
if (isMobile) {
setOpenMobile(false);
}
void navigate({ to: "/usage" });
}, [isMobile, navigate, setOpenMobile]);
}, [isMobile, navigate, setOpenMobile, setConversationSource]);
const handleBackClick = useCallback(() => {
closeMobileSidebar();
+11 -2
View File
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom } from "@t3tools/client-runtime/hermes";
import {
scopedProjectKey,
scopeProjectRef,
@@ -56,6 +57,7 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
}
export function useNewThreadHandler() {
const setConversationSource = useAtomSet(conversationSourceAtom);
const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const router = useRouter();
@@ -78,6 +80,7 @@ export function useNewThreadHandler() {
// prepared checkout, a task to write — addresses that one rather than looking the project
// up again and finding whichever draft it happens to hold.
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
setConversationSource("t3");
const projects = readProjects();
const targetServerSettings =
environmentServerConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
@@ -435,7 +438,13 @@ export function useNewThreadHandler() {
return { draftId, threadId };
})();
},
[environmentServerConfigs, getCurrentRouteTarget, projectGroupingSettings, router],
[
environmentServerConfigs,
getCurrentRouteTarget,
projectGroupingSettings,
router,
setConversationSource,
],
);
}
+21
View File
@@ -23,6 +23,7 @@ import { Route as SettingsProjectsRouteImport } from './routes/settings.projects
import { Route as SettingsOpenSourceLicensesRouteImport } from './routes/settings.open-source-licenses'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
import { Route as SettingsIntegrationsRouteImport } from './routes/settings.integrations'
import { Route as SettingsHermesRouteImport } from './routes/settings.hermes'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
@@ -104,6 +105,11 @@ const SettingsIntegrationsRoute = SettingsIntegrationsRouteImport.update({
path: '/integrations',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsHermesRoute = SettingsHermesRouteImport.update({
id: '/hermes',
path: '/hermes',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
id: '/general',
path: '/general',
@@ -171,6 +177,7 @@ export interface FileRoutesByFullPath {
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/hermes': typeof SettingsHermesRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
@@ -195,6 +202,7 @@ export interface FileRoutesByTo {
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/hermes': typeof SettingsHermesRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
@@ -222,6 +230,7 @@ export interface FileRoutesById {
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/hermes': typeof SettingsHermesRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/open-source-licenses': typeof SettingsOpenSourceLicensesRoute
@@ -250,6 +259,7 @@ export interface FileRouteTypes {
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
| '/settings/hermes'
| '/settings/integrations'
| '/settings/keybindings'
| '/settings/open-source-licenses'
@@ -274,6 +284,7 @@ export interface FileRouteTypes {
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
| '/settings/hermes'
| '/settings/integrations'
| '/settings/keybindings'
| '/settings/open-source-licenses'
@@ -300,6 +311,7 @@ export interface FileRouteTypes {
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
| '/settings/hermes'
| '/settings/integrations'
| '/settings/keybindings'
| '/settings/open-source-licenses'
@@ -423,6 +435,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsIntegrationsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/hermes': {
id: '/settings/hermes'
path: '/hermes'
fullPath: '/settings/hermes'
preLoaderRoute: typeof SettingsHermesRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/general': {
id: '/settings/general'
path: '/general'
@@ -518,6 +537,7 @@ interface SettingsRouteChildren {
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
SettingsHermesRoute: typeof SettingsHermesRoute
SettingsIntegrationsRoute: typeof SettingsIntegrationsRoute
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
SettingsOpenSourceLicensesRoute: typeof SettingsOpenSourceLicensesRoute
@@ -533,6 +553,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
SettingsHermesRoute: SettingsHermesRoute,
SettingsIntegrationsRoute: SettingsIntegrationsRoute,
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
SettingsOpenSourceLicensesRoute: SettingsOpenSourceLicensesRoute,
+7
View File
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { HermesSettingsWorkspace } from "../components/hermes/HermesWorkspace";
export const Route = createFileRoute("/settings/hermes")({
component: HermesSettingsWorkspace,
});
+4
View File
@@ -0,0 +1,4 @@
import { createHermesState } from "@t3tools/client-runtime/hermes";
import { connectionAtomRuntime } from "../connection/runtime";
export const hermes = createHermesState(connectionAtomRuntime);
+4 -4
View File
@@ -37,10 +37,10 @@ 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
Android builds default to the baked-in repository URL
`https://git.molberg.cloud/alex/t3code`, so local builds work without release-source
configuration. CI overrides that default with the repository running the workflow. Set
`T3CODE_APK_REPOSITORY_URL` only when building for another full HTTPS repository URL. Public downloads
need no authentication; the CI token is still required to publish releases and
is never embedded in the APK.
+49 -9
View File
@@ -1,8 +1,7 @@
# 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 Agent](https://github.com/NousResearch/hermes-agent) works in two ways: as a coding provider
inside a T3 project, or through the **Hermes** tab for native Hermes conversations without a project.
Hermes support is experimental. The provider card in **Settings** shows an **Experimental** badge.
@@ -23,20 +22,62 @@ does not configure Hermes on your behalf.
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
**Binary path** defaults to `hermes`. Set it when a version manager or
a non-standard install location keeps the CLI off the `PATH` of the shell that started T3 Code.
**Dashboard URL** connects the Hermes tab to your running Hermes dashboard. It defaults to
`http://127.0.0.1:9119`. This address is reached from the T3 server, not your Android phone or
desktop client. Use the dashboard's HTTP address, not a messaging gateway or Android bridge port.
To use more than one Hermes installation or profile on the same environment, choose **Add provider
instance** on web or desktop, or **Add another Hermes instance** on mobile. Give the instance a
name and set `HERMES_HOME` when the instances should use separate Hermes profiles.
## Chat without a project
Choose **Hermes** above the conversation list, then **New task**. On **T3**, the same action
continues to create a project thread. This works on Android, desktop, and web.
The Hermes list reads recent sessions directly from the dashboard, including their source and
profile, and refreshes while open. Opening a session resumes its native history; it does not
import it into a T3 project. Choose **Load older sessions** for earlier conversations.
The dashboard must expose its sessions API and chat WebSocket. For a local installation, T3 can
use dashboard basic-auth credentials from the Hermes configuration. Otherwise, use **Dashboard
sign-in** in the Hermes list. Remote dashboards require explicit sign-in. Credentials remain on
the T3 server for that connection; use HTTPS for a dashboard on another machine.
Enter `/` and use **Commands & skills** to discover the commands advertised by your installation.
Skills run with their full expanded instructions. Commands such as `/undo` can put text back in
the composer for review instead of sending it automatically. Terminal-only interfaces are not
embedded; Hermes reports their availability. Use **Reconnect** after a gateway disconnect.
## Inspect and manage Hermes
Choose the gear button on the Hermes tab to open its management page. There you can:
- Expand complete tool inputs, commands, outputs, and live activity instead of only summaries.
- View agent, gateway, and error logs, refreshed while open, and inspect detailed failures.
- View and edit skills and memory entries in the selected session's profile.
- Create or edit cron jobs as JSON, pause or resume them, run them immediately, or delete them.
These are your actual Hermes resources: edits affect other Hermes clients using the same profile.
Skill and memory saves check for changes since loading; reload a conflicting edit before saving.
Without a selected session, management uses the dashboard's default profile. Native Hermes chats
do not use T3's Git checkpoints or project worktrees.
The Android app and the connected T3 server must both include native Hermes support. If the app
reports that the host is too old, update and restart T3 Code on the machine running the server;
updating only the phone cannot add server-side Hermes commands.
## Models
Hermes has no model list of its own in T3 Code. T3 Code asks Hermes for the catalog it advertises
For project threads, T3 Code asks Hermes for the catalog it advertises
when a session starts — whatever providers you configured through `hermes setup` or `hermes
model`. Pick a model from that list in the model picker for each thread, the same as with any
other provider. If Hermes accepts a model that it does not advertise, add its exact ID under
**Custom models** on the Hermes provider card.
In a native Hermes chat, use `/model` and the other commands provided by your Hermes installation.
## What works
@@ -48,7 +89,6 @@ other provider. If Hermes accepts a model that it does not advertise, add its ex
## 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.
- Project threads require a local binary: T3 Code spawns `hermes acp` as a subprocess. The Hermes
tab instead requires a compatible running dashboard and can use a remote dashboard address.
- A client connecting from a phone or another desktop does not need Hermes installed locally.
+12
View File
@@ -1,5 +1,17 @@
# Updating T3 Code
## Update the app
On desktop, open **Settings → General** and choose **Check for Updates**. When a release is
available, the same button downloads it and then installs it after confirmation. Packaged desktop
apps check automatically in the background; Linux automatic updates require the AppImage build.
You can choose the stable or nightly update track in the same section.
On Android, open **Settings → Software Update** and choose **Check for updates**. Store builds use
the app's signed update channel and restart only after pending drafts and messages are saved. Fork
APK builds use the repository updater described below. Android also checks its signed app update
channel automatically while the app is in use.
The app you use and the server running your agents can be on different machines.
When a server is behind your web or desktop app, an update notice appears in the
conversation and **Settings → Connections**. Update the machine named in that
+4
View File
@@ -3,6 +3,10 @@
"private": true,
"type": "module",
"exports": {
"./hermes": {
"types": "./src/hermes.ts",
"default": "./src/hermes.ts"
},
"./load-balancing": {
"types": "./src/load-balancing.ts",
"default": "./src/load-balancing.ts"
+200
View File
@@ -0,0 +1,200 @@
import { describe, expect, it } from "vite-plus/test";
import {
appendHermesEvent,
hermesCronEditor,
hermesCronJobs,
hermesMessages,
hermesSessions,
pendingHermesRequests,
applyHermesCompletion,
hermesCronPaused,
mergeHermesSessions,
mergeHermesMessages,
hermesErrorMessage,
} from "./hermes.ts";
import type { HermesEvent } from "@t3tools/contracts";
describe("native Hermes presentation", () => {
it("explains when the connected host lacks Hermes RPC support", () => {
expect(hermesErrorMessage("Error: Unknown request tag: hermes.write")).toContain(
"Update and restart the T3 desktop app or server",
);
expect(hermesErrorMessage("Unknown request tag: hermes.read")).toContain(
"Update and restart the T3 desktop app or server",
);
});
it("merges overlapping transcript pages with stable message identities", () => {
const older = hermesMessages({
messages: [
{ id: 1, role: "user", content: "Hello" },
{ id: 2, role: "assistant", content: "Partial" },
],
});
const latest = hermesMessages({
messages: [
{ id: 2, role: "assistant", content: "Complete" },
{ id: 3, role: "tool", content: "output" },
],
});
expect(mergeHermesMessages(older, latest).map((row) => [row.id, row.content])).toEqual([
["1", "Hello"],
["2", "Complete"],
["3", "output"],
]);
});
it("applies command and argument completions at the gateway replacement position", () => {
expect(applyHermesCompletion("/sta", "status", 1)).toBe("/status");
expect(applyHermesCompletion("/cron ad", "add", 6)).toBe("/cron add");
expect(applyHermesCompletion("/res", "/research ", 1)).toBe("/research ");
});
it("deduplicates changing session pages without merging different profiles", () => {
const recent = hermesSessions({ sessions: [{ id: "one", profile: "work", title: "Latest" }] });
const older = hermesSessions({
sessions: [
{ id: "one", profile: "work", title: "Old" },
{ id: "one", profile: "home" },
],
});
expect(
mergeHermesSessions(recent, older, older).map((row) => [row.profile, row.title]),
).toEqual([
["work", "Latest"],
["home", "Hermes chat"],
]);
expect(hermesCronPaused({ state: "paused" })).toBe(true);
expect(hermesCronPaused({ state: "scheduled", enabled: true })).toBe(false);
});
it("preserves session identity, source, and owning profile without creating T3 projects", () => {
const [session] = hermesSessions({
sessions: [
{
id: "native-1",
title: "Hello Hermes",
profile: "work",
source: "telegram",
is_active: true,
last_active: 123,
},
],
});
expect(session).toMatchObject({
id: "native-1",
title: "Hello Hermes",
profile: "work",
source: "telegram",
active: true,
updated: 123,
});
});
it("retains exact tool inputs and long outputs for full expansion", () => {
const longOutput = "output\n".repeat(2_000);
const [call, output] = hermesMessages({
messages: [
{
id: 1,
role: "assistant",
content: "",
tool_calls: [{ function: { name: "terminal", arguments: '{"command":"printf hello"}' } }],
},
{ id: 2, role: "tool", tool_call_id: "call-1", content: longOutput },
],
});
expect(call?.details).toContain("printf hello");
expect(output?.content).toBe(longOutput);
expect(output?.details).toContain(JSON.stringify(longOutput));
});
it("handles native array cron responses and excludes scheduler-owned fields from editing", () => {
const jobs = [
{
id: "job-1",
name: "Daily",
schedule: { kind: "cron", expr: "0 9 * * *" },
prompt: "News",
state: "scheduled",
last_run_at: "yesterday",
},
];
expect(hermesCronJobs(jobs)).toBe(jobs);
expect(hermesCronEditor(jobs[0])).toEqual({
name: "Daily",
schedule: { kind: "cron", expr: "0 9 * * *" },
prompt: "News",
});
});
it("coalesces streaming text only within the same session", () => {
const first: HermesEvent = {
sequence: 1,
type: "message.delta",
sessionId: "one",
payload: { text: "Hello " },
};
const merged = appendHermesEvent([first], {
...first,
sequence: 2,
payload: { text: "Hermes" },
});
expect(merged).toHaveLength(1);
expect(merged[0]?.payload).toEqual({ text: "Hello Hermes" });
expect(appendHermesEvent(merged, { ...first, sessionId: "two" })).toHaveLength(2);
});
it("bounds the live activity buffer without truncating tool payloads", () => {
const payload = { rawOutput: "x".repeat(20_000) };
const events = Array.from({ length: 200 }, (_, index) => ({
sequence: index,
type: "tool.done",
sessionId: "one",
payload,
}));
const next = appendHermesEvent(events, {
sequence: 201,
type: "tool.done",
sessionId: "one",
payload,
});
expect(next).toHaveLength(200);
expect(next.at(-1)?.payload).toBe(payload);
});
it("withdraws answered and cancelled requests and isolates sessions", () => {
const request: HermesEvent = {
sequence: 1,
type: "request",
sessionId: "one",
payload: {
requestId: "approval-1",
method: "approval",
params: { choices: ["once", "deny"] },
},
};
expect(pendingHermesRequests([request], "one")).toHaveLength(1);
expect(pendingHermesRequests([request], "two")).toEqual([]);
expect(
pendingHermesRequests(
[
request,
{ sequence: 2, type: "request.cancel", sessionId: "one", payload: { id: "approval-1" } },
],
"one",
),
).toEqual([]);
expect(
pendingHermesRequests(
[
request,
{
sequence: 2,
type: "request.resolved",
sessionId: "one",
payload: { id: "approval-1" },
},
],
"one",
),
).toEqual([]);
});
});
+249
View File
@@ -0,0 +1,249 @@
import {
type EnvironmentId,
WS_METHODS,
type HermesEvent,
type HermesTarget,
type ServerConfig,
} from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import * as Stream from "effect/Stream";
import { type EnvironmentRegistry } from "./connection/registry.ts";
import {
createEnvironmentRpcCommand,
createEnvironmentRpcQueryAtomFamily,
createEnvironmentRpcSubscriptionAtomFamily,
} from "./state/runtime.ts";
export const conversationSourceAtom = Atom.make<"t3" | "hermes">("t3").pipe(Atom.keepAlive);
export interface HermesConnection {
readonly environmentId: EnvironmentId;
readonly target: HermesTarget;
readonly label: string;
}
export interface HermesSelection {
readonly connection: HermesConnection;
readonly id: string;
readonly title: string;
}
export const hermesSelectionAtom = Atom.make<HermesSelection | null>(null).pipe(Atom.keepAlive);
export const hermesConnectionAtom = Atom.make<HermesConnection | null>(null).pipe(Atom.keepAlive);
export const hermesNewSessionAtom = Atom.make(0).pipe(Atom.keepAlive);
export const hermesHandledNewSessionAtom = Atom.make(0).pipe(Atom.keepAlive);
export function hermesRecord(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export function hermesText(value: unknown): string {
return typeof value === "string" ? value : "";
}
export function hermesArray(value: unknown): ReadonlyArray<unknown> {
return Array.isArray(value) ? value : [];
}
export function hermesPretty(value: unknown): string {
return typeof value === "string" ? value : (JSON.stringify(value, null, 2) ?? "");
}
export function hermesErrorMessage(message: string): string {
if (/unknown request tag:\s*hermes\.(?:read|write|events)/i.test(message)) {
return "This T3 host is too old for native Hermes controls. Update and restart the T3 desktop app or server on the connected machine, then try again.";
}
return message;
}
export function hermesCronJobs(value: unknown): ReadonlyArray<unknown> {
return Array.isArray(value) ? value : hermesArray(hermesRecord(value).jobs);
}
export function hermesCronPaused(value: unknown) {
const job = hermesRecord(value);
return job.state === "paused" || job.enabled === false || job.paused === true;
}
export function applyHermesCompletion(input: string, value: unknown, replaceFrom: unknown) {
const start =
typeof replaceFrom === "number" && Number.isInteger(replaceFrom)
? Math.max(0, Math.min(input.length, replaceFrom))
: input.startsWith("/")
? 1
: 0;
const completion = hermesText(value);
return (
input.slice(0, start) + (input[start - 1] === "/" ? completion.replace(/^\//, "") : completion)
);
}
export function mergeHermesSessions(...pages: ReturnType<typeof hermesSessions>[]) {
const rows = new Map<string, ReturnType<typeof hermesSessions>[number]>();
for (const page of pages)
for (const row of page) {
const key = JSON.stringify([row.profile, row.id]);
if (!rows.has(key)) rows.set(key, row);
}
return [...rows.values()];
}
export function hermesCronEditor(value: unknown) {
const row = hermesRecord(value);
const fields = [
"name",
"schedule",
"prompt",
"deliver",
"skills",
"model",
"provider",
"base_url",
"script",
"context_from",
"enabled_toolsets",
"workdir",
"no_agent",
"failure_deliver",
];
return Object.fromEntries(
fields.filter((field) => row[field] !== undefined).map((field) => [field, row[field]]),
);
}
export function hermesConnections(
configs: ReadonlyMap<EnvironmentId, ServerConfig>,
labels: ReadonlyMap<EnvironmentId, string>,
): HermesConnection[] {
return [...configs].flatMap(([environmentId, config]) =>
config.providers
.filter((provider) => provider.driver === "hermes" && provider.enabled !== false)
.map((provider) => ({
environmentId,
target: { instanceId: provider.instanceId },
label: `${labels.get(environmentId) ?? "Environment"} · ${provider.displayName ?? "Hermes"}`,
})),
);
}
export function hermesSessions(data: unknown) {
return hermesArray(hermesRecord(data).sessions)
.map((value) => {
const row = hermesRecord(value);
return {
id: hermesText(row.id) || hermesText(row.session_id),
title: hermesText(row.title) || hermesText(row.first_user_message) || "Hermes chat",
profile: hermesText(row.profile),
source: hermesText(row.source),
active: row.is_active === true,
updated: row.last_active ?? row.last_active_at ?? row.started_at,
raw: row,
};
})
.filter((row) => row.id.length > 0);
}
export function hermesMessages(data: unknown) {
return hermesArray(hermesRecord(data).messages).map((value, index) => {
const row = hermesRecord(value);
const content =
typeof row.content === "string"
? row.content
: hermesArray(row.content)
.map((block) => hermesText(hermesRecord(block).text))
.filter(Boolean)
.join("\n");
const details = row.role === "tool" || row.tool_calls || row.tool_call_id;
return {
id: String(row.id ?? row.message_id ?? index),
role: hermesText(row.role),
content,
details: details ? hermesPretty(row) : null,
};
});
}
export function mergeHermesMessages(...pages: ReturnType<typeof hermesMessages>[]) {
const messages = new Map<string, ReturnType<typeof hermesMessages>[number]>();
for (const page of pages) for (const message of page) messages.set(message.id, message);
return [...messages.values()];
}
export function appendHermesEvent(
events: ReadonlyArray<HermesEvent>,
event: HermesEvent,
): ReadonlyArray<HermesEvent> {
const previous = events.at(-1);
if (
previous?.type === event.type &&
previous.sessionId === event.sessionId &&
event.type === "message.delta"
) {
const payload = hermesRecord(event.payload);
return [
...events.slice(0, -1),
{
...event,
payload: {
...payload,
text: (hermesText(hermesRecord(previous.payload).text) + hermesText(payload.text)).slice(
-512_000,
),
},
},
];
}
return [...events.slice(-199), event];
}
export function pendingHermesRequests(events: ReadonlyArray<HermesEvent>, sessionId: string) {
const pending = new Map<
string,
{ id: string; method: string; params: Record<string, unknown> }
>();
for (const event of events) {
if (event.type === "error" && hermesRecord(event.payload).disconnected === true)
pending.clear();
if (event.sessionId !== sessionId) continue;
const payload = hermesRecord(event.payload);
if (event.type === "request") {
const id = hermesText(payload.requestId);
pending.set(id, {
id,
method: hermesText(payload.method),
params: hermesRecord(payload.params),
});
} else if (event.type === "request.cancel" || event.type === "request.resolved")
pending.delete(hermesText(payload.id));
}
return [...pending.values()];
}
export function createHermesState<R, Error>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, Error>,
) {
return {
read: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "hermes:read",
tag: WS_METHODS.hermesRead,
staleTimeMs: 1_000,
idleTtlMs: 0,
}),
live: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "hermes:live",
tag: WS_METHODS.hermesRead,
staleTimeMs: 1_000,
refreshIntervalMs: 5_000,
idleTtlMs: 0,
}),
request: createEnvironmentRpcCommand(runtime, {
label: "hermes:request",
tag: WS_METHODS.hermesRead,
}),
write: createEnvironmentRpcCommand(runtime, {
label: "hermes:write",
tag: WS_METHODS.hermesWrite,
}),
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
label: "hermes:events",
tag: WS_METHODS.hermesEvents,
idleTtlMs: 0,
transform: (stream) =>
stream.pipe(Stream.scan([] as ReadonlyArray<HermesEvent>, appendHermesEvent)),
}),
};
}
@@ -40,6 +40,7 @@ export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string;
type RpcMethod<TTag extends EnvironmentRpcTag> = WsRpcProtocolClient[TTag];
export type EnvironmentSubscriptionRpcTag =
| typeof WS_METHODS.hermesEvents
| typeof WS_METHODS.providerAuthSubscribe
| typeof WS_METHODS.providerInstallSubscribe
| typeof ORCHESTRATION_WS_METHODS.subscribeShell
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { HermesReadInput, HermesWriteInput } from "./hermes.ts";
const read = Schema.decodeUnknownSync(HermesReadInput);
const write = Schema.decodeUnknownSync(HermesWriteInput);
describe("Hermes wire contracts", () => {
it("rejects arbitrary paths, methods, and invalid pagination", () => {
expect(() => read({ instanceId: "hermes", resource: "/etc/passwd" })).toThrow();
expect(() => read({ instanceId: "hermes", resource: "sessions", offset: -1 })).toThrow();
expect(() => write({ instanceId: "hermes", action: "shell.exec" })).toThrow();
});
it("keeps native Hermes sessions independent of project identifiers", () => {
expect(
write({
instanceId: "hermes",
action: "create",
profile: "personal",
}),
).toEqual({ instanceId: "hermes", action: "create", profile: "personal" });
});
});
+75
View File
@@ -0,0 +1,75 @@
import * as Schema from "effect/Schema";
import { ProviderInstanceId } from "./providerInstance.ts";
const Text = Schema.String.check(Schema.isMaxLength(512_000));
const Identifier = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
export const HermesTarget = Schema.Struct({
instanceId: ProviderInstanceId,
profile: Schema.optional(Identifier),
});
export type HermesTarget = typeof HermesTarget.Type;
export const HermesReadInput = Schema.Struct({
...HermesTarget.fields,
resource: Schema.Literals([
"sessions",
"messages",
"skills",
"skill",
"memories",
"memory",
"cron",
"logs",
"commands",
]),
id: Schema.optional(Identifier),
text: Schema.optional(Text),
offset: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
logFile: Schema.optional(Schema.Literals(["agent", "gateway", "errors"])),
});
export type HermesReadInput = typeof HermesReadInput.Type;
export const HermesWriteInput = Schema.Struct({
...HermesTarget.fields,
action: Schema.Literals([
"create",
"attach",
"send",
"interrupt",
"command",
"respond",
"saveSkill",
"saveMemory",
"createCron",
"updateCron",
"pauseCron",
"resumeCron",
"runCron",
"deleteCron",
"renameSession",
"deleteSession",
"login",
]),
id: Schema.optional(Identifier),
text: Schema.optional(Text),
fields: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
});
export type HermesWriteInput = typeof HermesWriteInput.Type;
export const HermesResult = Schema.Struct({ data: Schema.Unknown });
export type HermesResult = typeof HermesResult.Type;
export const HermesEvent = Schema.Struct({
sequence: Schema.Number,
type: Schema.String,
sessionId: Schema.String,
payload: Schema.Unknown,
});
export type HermesEvent = typeof HermesEvent.Type;
export class HermesError extends Schema.TaggedError<HermesError>()("HermesError", {
message: Schema.String,
operation: Schema.String,
status: Schema.optional(Schema.Number),
}) {}
+1
View File
@@ -42,3 +42,4 @@ export * from "./previewAutomation.ts";
export * from "./resourceTelemetry.ts";
export * from "./usage.ts";
export * from "./rpc.ts";
export * from "./hermes.ts";
+27
View File
@@ -1,6 +1,14 @@
import * as Schema from "effect/Schema";
import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import {
HermesTarget,
HermesReadInput,
HermesWriteInput,
HermesResult,
HermesEvent,
HermesError,
} from "./hermes.ts";
import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
import {
ProviderAuthCancelInput,
@@ -256,6 +264,9 @@ import {
import { VcsError } from "./vcs.ts";
export const WS_METHODS = {
hermesRead: "hermes.read",
hermesWrite: "hermes.write",
hermesEvents: "hermes.events",
// Project registry methods
projectsList: "projects.list",
projectsAdd: "projects.add",
@@ -1294,6 +1305,22 @@ const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeResourceTel
});
export const WsRpcGroup = RpcGroup.make(
Rpc.make(WS_METHODS.hermesRead, {
payload: HermesReadInput,
success: HermesResult,
error: Schema.Union([HermesError, EnvironmentAuthorizationError]),
}),
Rpc.make(WS_METHODS.hermesWrite, {
payload: HermesWriteInput,
success: HermesResult,
error: Schema.Union([HermesError, EnvironmentAuthorizationError]),
}),
Rpc.make(WS_METHODS.hermesEvents, {
payload: HermesTarget,
success: HermesEvent,
error: Schema.Union([HermesError, EnvironmentAuthorizationError]),
stream: true,
}),
WsServerProbeRpc,
WsServerGetConfigRpc,
WsServerRefreshProvidersRpc,
+9 -1
View File
@@ -815,6 +815,13 @@ export type AntigravitySettings = typeof AntigravitySettings.Type;
export const HermesSettings = makeProviderSettingsSchema(
{
dashboardUrl: Schema.String.pipe(
Schema.withDecodingDefault(Effect.succeed("http://127.0.0.1:9119")),
Schema.annotateKey({
title: "Dashboard URL",
description: "Hermes dashboard address, reachable from the T3 server.",
}),
),
// 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(
@@ -834,7 +841,7 @@ export const HermesSettings = makeProviderSettingsSchema(
),
},
{
order: ["binaryPath"],
order: ["binaryPath", "dashboardUrl"],
},
);
export type HermesSettings = typeof HermesSettings.Type;
@@ -1355,6 +1362,7 @@ const AntigravitySettingsPatch = Schema.Struct({
});
const HermesSettingsPatch = Schema.Struct({
dashboardUrl: Schema.optionalKey(TrimmedString),
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_ANDROID_APK_REPOSITORY_URL,
resolveAndroidApkRepository,
} from "./android-apk-release.ts";
describe("Android APK release source", () => {
it("bakes this fork's public release API into Android builds", () => {
expect(DEFAULT_ANDROID_APK_REPOSITORY_URL).toBe("https://git.molberg.cloud/alex/t3code");
expect(resolveAndroidApkRepository(DEFAULT_ANDROID_APK_REPOSITORY_URL)).toEqual({
releasesUrl: "https://git.molberg.cloud/alex/t3code/releases",
apiUrl: "https://git.molberg.cloud/api/v1/repos/alex/t3code/releases",
});
});
});
+2
View File
@@ -1,3 +1,5 @@
export const DEFAULT_ANDROID_APK_REPOSITORY_URL = "https://git.molberg.cloud/alex/t3code";
export function parseAndroidApkReleaseTag(tag: string): number {
const match = /^apk-([1-9]\d*)$/.exec(tag);
const versionCode = match ? Number(match[1]) : NaN;