Compare commits

..
5 Commits
Author SHA1 Message Date
bonzi c44c38f096 feat(hermes): add native Hermes workspace
Fork Android APK / release (push) Has been cancelled
2026-09-19 01:39:31 +00:00
bonzi 8d45b184d7 fix: build arm64 APK release artifacts
Fork Android APK / release (push) Has been cancelled
2026-09-14 15:24:34 +00:00
bonzi cb9719f1dc fix: verify APK checksum from release directory 2026-09-14 15:16:37 +00:00
bonzi 0a1bec5a98 feat: improve file downloads and APK release flow 2026-09-14 15:04:08 +00:00
bonzi c607b73d94 chore(mobile): add one-command APK release script 2026-09-14 13:32:59 +00:00
71 changed files with 4986 additions and 191 deletions

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Copy this file to .env.release for local releases. Never commit .env.release.
GITEA_TOKEN=<gitea-release-token>
GITEA_API_URL=https://git.molberg.cloud/api/v1/repos/alex/t3code
T3CODE_APK_REPOSITORY_URL=https://git.molberg.cloud/alex/t3code
ANDROID_HOME=/opt/android-sdk
ANDROID_NDK_HOME=/opt/android-sdk/ndk/27.1.12297006
ANDROID_BUILD_TOOLS_VERSION=36.0.0
APK_KEYSTORE_BASE64=<base64-encoded-release-keystore>
APK_KEYSTORE_PASSWORD=<keystore-password>
APK_KEY_ALIAS=<key-alias>
APK_KEY_PASSWORD=<key-password>
# Optional overrides:
# APK_VERSION_CODE=45
# APK_RELEASE_BODY={"schema":1,"channel":"production"}
+1
View File
@@ -40,6 +40,7 @@ node_modules/
*.log
.env*
!.env.example
!.env.release.example
# pnpm content-addressable store; never belongs in the repo.
.pnpm-store/
+5 -4
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";
@@ -15,9 +16,9 @@ Object.assign(process.env, repoEnv);
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
const apkReleaseTag = repoEnv.T3CODE_APK_RELEASE_TAG;
const apkVersionCode = apkReleaseTag ? parseAndroidApkReleaseTag(apkReleaseTag) : undefined;
const apkRepository = repoEnv.T3CODE_APK_REPOSITORY_URL
? resolveAndroidApkRepository(repoEnv.T3CODE_APK_REPOSITORY_URL)
: undefined;
const apkRepository = resolveAndroidApkRepository(
repoEnv.T3CODE_APK_REPOSITORY_URL || DEFAULT_ANDROID_APK_REPOSITORY_URL,
);
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const runtimeVersionPolicy =
process.env.MOBILE_VERSION_POLICY ??
@@ -443,7 +444,7 @@ const config: ExpoConfig = {
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
apkReleaseApiUrl: apkRepository?.apiUrl || null,
apkReleaseApiUrl: apkRepository.apiUrl,
appVariant: APP_VARIANT,
iosPersonalTeamBuild: isIosPersonalTeamBuild,
relay: {
@@ -5,6 +5,7 @@ import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "re
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import { cn } from "../../lib/cn";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
@@ -48,10 +49,11 @@ const FileTreeRow = memo(function FileTreeRow(props: {
readonly onPressDirectory: (path: string) => void;
readonly onPreviewFile?: (path: string) => void;
readonly onPressFile: (path: string) => void;
readonly onDownloadFile: (path: string) => void;
}) {
const { node, depth } = props.item;
return (
const row = (
<Pressable
accessibilityRole="button"
accessibilityLabel={node.path}
@@ -104,6 +106,20 @@ const FileTreeRow = memo(function FileTreeRow(props: {
) : null}
</Pressable>
);
return node.kind === "file" ? (
<ControlPillMenu
title={node.name}
shouldOpenOnLongPress
actions={[{ id: "download", title: "Download file", image: "arrow.down.to.line" }]}
onPressAction={({ nativeEvent }) => {
if (nativeEvent.event === "download") props.onDownloadFile(node.path);
}}
>
{row}
</ControlPillMenu>
) : (
row
);
});
export function FileTreeBrowser(props: {
@@ -118,6 +134,7 @@ export function FileTreeBrowser(props: {
readonly onPreviewFile?: (path: string) => void;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
readonly onDownloadFile: (path: string) => void;
}) {
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
const [pendingSelection, setPendingSelection] = useState<{
@@ -132,6 +149,7 @@ export function FileTreeBrowser(props: {
onLoadDirectory,
onPreviewFile,
onSelectFile,
onDownloadFile,
loadedDirectories,
selectedPath: controlledSelectedPath,
} = props;
@@ -222,12 +240,14 @@ export function FileTreeBrowser(props: {
onPressDirectory={toggleDirectory}
onPreviewFile={onPreviewFile}
onPressFile={handleSelectFile}
onDownloadFile={onDownloadFile}
/>
),
[
expandedPaths,
handleSelectFile,
onPreviewFile,
onDownloadFile,
loadedDirectories,
selectedPath,
toggleDirectory,
@@ -9,6 +9,7 @@ import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/co
import { videoMimeType } from "@t3tools/shared/video";
import {
isWorkspaceBrowserPreviewPath,
isDownloadOnlyFile,
isWorkspaceImagePreviewPath,
mediaMimeTypeFromExtension,
} from "@t3tools/shared/filePreview";
@@ -48,6 +49,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
import { useFileTreeEntries } from "./useFileTreeEntries";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { SourceFileSurface } from "./SourceFileSurface";
@@ -114,6 +116,7 @@ function FileContent(props: {
readonly resolveVideoUri: () => Promise<string | null>;
readonly fileContents: string | null;
readonly fileError: string | null;
readonly onDownload: () => void;
readonly relativePath: string;
readonly threadId: ThreadId | null;
readonly initialLine: number | null;
@@ -183,10 +186,19 @@ function FileContent(props: {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
}
if (props.fileError && props.fileContents === null) {
if (isDownloadOnlyFile(props.relativePath) || (props.fileError && props.fileContents === null)) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<EmptyState title="File unavailable" detail={props.fileError} />
<EmptyState
title="Preview unavailable"
detail={
isDownloadOnlyFile(props.relativePath)
? "This file cannot be previewed. Would you like to download it?"
: `${props.fileError}\nYou can download this file instead.`
}
actionLabel="Download file"
onAction={props.onDownload}
/>
</View>
);
}
@@ -337,6 +349,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
props.route.params,
);
const revealedInspectorRef = useRef(false);
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
const entriesQuery = useFileTreeEntries({
environmentId,
cwd: fileInspector.supported ? null : cwd,
@@ -561,6 +574,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={handleSelectFile}
onDownloadFile={downloadFile}
/>
<FilesToolbarBottomFade />
</>
@@ -592,6 +606,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
readonly path: string;
readonly mode: FileViewMode;
} | null>(null);
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
const [previewRevision, setPreviewRevision] = useState(0);
const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
@@ -674,6 +689,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
};
const needsFileContents =
relativePath !== null &&
!isDownloadOnlyFile(relativePath) &&
!isVideoFile &&
!isAudioFile &&
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
@@ -742,6 +758,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
if (relativePath === null) return [];
const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
return [
{
id: "download",
title: "Download file",
icon: "arrow.down.to.line" as const,
inline: false,
onPress: () => downloadFile(relativePath),
},
canToggleMode
? ({
id: "preview",
@@ -840,6 +863,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
].filter((action) => action !== null);
}, [
appearance.codeWordBreak,
downloadFile,
setCodeWordBreak,
assetPreviewUri,
assetPreview.refresh,
@@ -1020,6 +1044,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
resolveVideoUri={assetPreview.refresh}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
onDownload={() => downloadFile(relativePath)}
initialLine={targetLine}
relativePath={relativePath}
threadId={threadId}
@@ -1,6 +1,7 @@
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
isDownloadOnlyFile,
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
} from "@t3tools/shared/filePreview";
@@ -30,6 +31,7 @@ export function preloadWorkspaceFileContents(input: {
readonly theme: ReviewDiffTheme;
}): void {
if (
isDownloadOnlyFile(input.relativePath) ||
isWorkspaceBrowserPreviewPath(input.relativePath) ||
isWorkspaceImagePreviewPath(input.relativePath) ||
isVideoPreviewFile(input.relativePath)
@@ -15,6 +15,7 @@ import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
import { useFileTreeEntries } from "./useFileTreeEntries";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
@@ -28,6 +29,7 @@ export function ThreadFileNavigatorPane(props: {
readonly onSelectFile: (path: string) => void;
}) {
const [searchQuery, setSearchQuery] = useState("");
const downloadFile = useWorkspaceFileDownload(props.environmentId, props.cwd);
const { toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const { themeAppearance: highlightTheme } = useAppearancePreferences();
const theme = useUniwindTheme();
@@ -91,6 +93,7 @@ export function ThreadFileNavigatorPane(props: {
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={props.onSelectFile}
onDownloadFile={downloadFile}
/>
);
@@ -26,7 +26,7 @@ export function useFileTreeEntries(input: {
searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
? projectEnvironment.searchEntries({
environmentId,
input: { cwd, query: debouncedQuery, limit: 200 },
input: { cwd, query: debouncedQuery, limit: 200, includeIgnored: true },
})
: null,
);
@@ -0,0 +1,20 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback } from "react";
import { useFileDownload } from "../threads/useFileChipShare";
import { basename } from "./filePath";
export function useWorkspaceFileDownload(environmentId: EnvironmentId | null, cwd: string | null) {
const download = useFileDownload(environmentId, "workspace-file-download");
return useCallback(
(path: string) => {
if (cwd === null) return;
download({
name: basename(path),
mimeType: "application/octet-stream",
resource: { _tag: "draft-workspace-file", cwd, path, download: true },
});
},
[cwd, download],
);
}
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,12 @@
import * as Arr from "effect/Array";
import { useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom } 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,7 @@ import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle
/* ─── Route screen ───────────────────────────────────────────────────── */
export function HomeRouteScreen() {
const conversationSource = useAtomValue(conversationSourceAtom);
const { width: windowWidth } = useWindowDimensions();
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
@@ -106,6 +111,34 @@ 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) {
return (
<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: "Settings" },
}),
},
]}
/>
)}
<ConversationTabs />
<HermesMobileWorkspace />
</View>
);
}
if (layout.usesSplitView) {
return (
<>
@@ -181,6 +214,7 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<ConversationTabs />
<HomeScreen
catalogState={catalogState}
@@ -1,4 +1,6 @@
import { StackActions, useNavigation } from "@react-navigation/native";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
import {
useCallback,
@@ -36,6 +38,8 @@ export function HardwareKeyboardCommandProvider({
pathname,
}: PropsWithChildren<{ readonly pathname: string }>) {
const navigation = useNavigation();
const conversationSource = useAtomValue(conversationSourceAtom);
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
const activeThread = useThreadShell(activeThreadRef);
const copyTarget = useMemo(
@@ -125,6 +129,11 @@ export function HardwareKeyboardCommandProvider({
}
if (command === "newTask") {
if (conversationSource === "hermes") {
requestHermesSession((value) => value + 1);
navigation.navigate("Home");
return;
}
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
return;
}
@@ -149,7 +158,7 @@ export function HardwareKeyboardCommandProvider({
navigation.navigate("ThreadReview", thread);
}
},
[copyTarget, navigation, pathname, showCopyFeedback],
[conversationSource, copyTarget, navigation, pathname, requestHermesSession, showCopyFeedback],
);
return (
@@ -3,7 +3,9 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { conversationSourceAtom, hermesNewSessionAtom } from "@t3tools/client-runtime/hermes";
import { ConversationTabs, HermesMobileWorkspace } from "../hermes/HermesWorkspace";
import { useFocusEffect } from "@react-navigation/native";
import {
NavigationContext,
@@ -226,6 +228,8 @@ function AdaptiveWorkspaceLayoutContent(
},
) {
const projectGroupingMode = props.projectGroupingMode;
const conversationSource = useAtomValue(conversationSourceAtom);
const requestHermesSession = useAtomSet(hermesNewSessionAtom);
const { materialYouStyleLayoutActive } = useAppearancePreferences();
const { width, height } = useWindowDimensions();
const pathname = props.pathname;
@@ -445,8 +449,12 @@ function AdaptiveWorkspaceLayoutContent(
}, [navigation]);
const handleStartNewTask = useCallback(() => {
if (conversationSource === "hermes") {
requestHermesSession((value) => value + 1);
return;
}
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
}, [navigation]);
}, [conversationSource, navigation, requestHermesSession]);
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
@@ -561,21 +569,27 @@ function AdaptiveWorkspaceLayoutContent(
style={sidebarAnimatedStyle}
>
<View className="flex-1" style={{ width: layout.listPaneWidth }}>
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
<ThreadNavigationSidebar
width={layout.listPaneWidth}
visible={panes.primarySidebarVisible}
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onNewThreadOnBranch={handleNewThreadOnBranch}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
/>
</AndroidHomeFabLayout>
<ConversationTabs topInset />
{conversationSource === "hermes" ? (
<HermesMobileWorkspace mode="list" />
) : (
<AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
<ThreadNavigationSidebar
topInset={0}
width={layout.listPaneWidth}
visible={panes.primarySidebarVisible}
onRequestVisibility={revealPrimarySidebar}
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onNewThreadOnBranch={handleNewThreadOnBranch}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
/>
</AndroidHomeFabLayout>
)}
</View>
</Animated.View>
) : null}
@@ -596,7 +610,11 @@ function AdaptiveWorkspaceLayoutContent(
<WorkspaceContentWidthContext
value={layout.usesSplitView ? renderedContentWidth : null}
>
{props.children}
{layout.usesSplitView && conversationSource === "hermes" ? (
<HermesMobileWorkspace mode="detail" />
) : (
props.children
)}
</WorkspaceContentWidthContext>
</View>
</View>
@@ -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";
@@ -740,70 +734,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 +750,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 +764,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>
);
@@ -100,6 +100,7 @@ type SidebarListItem =
const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
interface ThreadNavigationSidebarProps {
readonly topInset?: number;
readonly width: number;
readonly visible: boolean;
readonly selectedThreadKey: string | null;
@@ -152,6 +153,7 @@ function ThreadNavigationSidebarPane(
const mutedColor = materialTheme["--color-foreground-muted"];
const insets = useSafeAreaInsets();
const topInset = props.topInset ?? insets.top;
const projects = useProjects();
const threads = useThreadShells();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
@@ -748,7 +750,7 @@ function ThreadNavigationSidebarPane(
// The sticky header (title row, search field, optional connection status)
// is measured so the list inset always matches its real height — no
// hardcoded per-variant constants.
const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
const stickyHeaderHeight = measuredHeaderHeight ?? topInset + SIDEBAR_STICKY_HEADER_HEIGHT;
const topListInset = stickyHeaderHeight + 6;
const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -1309,7 +1311,7 @@ function ThreadNavigationSidebarPane(
collapsable={false}
onLayout={handleStickyHeaderLayout}
pointerEvents="auto"
style={{ paddingTop: insets.top }}
style={{ paddingTop: topInset }}
>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
{/* Title slot doubles as the connection status surface: while an
@@ -35,11 +35,13 @@ describe("fileChipMenu", () => {
actions: [
{ id: "copy-full-path", title: "Copy full path" },
{ id: "open-file", title: "Open in file viewer" },
{ id: "save", title: "Download file" },
],
});
expect(fileChipMenu({ relativePath: "src/app.ts" }).actions.map(({ id }) => id)).toEqual([
"copy-relative-path",
"open-file",
"save",
]);
});
});
@@ -60,12 +62,12 @@ describe("file chip downloads", () => {
const target = resolveFileChipTarget(href, "/repo")!;
expect(fileChipMenu(target).actions).toContainEqual({
id: "save",
title: "Save or share",
title: "Download file",
});
expect(fileChipShareSource(target, threadId)).toEqual({
name: path.split("/").at(-1),
mimeType,
resource: { _tag: "media-file", threadId, path },
resource: { _tag: "media-file", threadId, path, download: true },
});
});
@@ -77,11 +79,14 @@ describe("file chip downloads", () => {
});
});
it("does not offer downloads the host asset endpoint cannot serve", () => {
for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt"]) {
it("offers explicit downloads for source files and unsupported binary formats", () => {
for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt", "/tmp/app.apk"]) {
const target = resolveFileChipTarget(href, "/repo")!;
expect(fileChipShareSource(target, threadId)).toBeNull();
expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(false);
expect(fileChipShareSource(target, threadId)).toMatchObject({
mimeType: "application/octet-stream",
resource: { download: true, threadId },
});
expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(true);
}
});
});
@@ -44,8 +44,10 @@ function fileChipMetadata(target: FileChipTarget) {
if (!path) return null;
const name = fileBasename(path);
const dot = name.lastIndexOf(".");
const mimeType = dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot));
return mimeType ? { path, name, mimeType } : null;
const mimeType =
(dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot))) ??
"application/octet-stream";
return { path, name, mimeType };
}
/** Use literal resolved paths so encoded filename characters are not decoded twice. */
@@ -55,12 +57,11 @@ export function fileChipShareSource(target: FileChipTarget, threadId: ThreadId)
? {
name: metadata.name,
mimeType: metadata.mimeType,
resource: { _tag: "media-file" as const, threadId, path: metadata.path },
resource: { _tag: "media-file" as const, threadId, path: metadata.path, download: true },
}
: null;
}
/** Saving is available for the media and documents the host asset endpoint can serve. */
export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu {
return {
title: target.fullPath ?? target.relativePath ?? "",
@@ -72,7 +73,7 @@ export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu {
? [
{
id: "save",
title: "Save or share",
title: "Download file",
},
]
: []),
@@ -1,5 +1,5 @@
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { Alert } from "react-native";
@@ -16,6 +16,17 @@ export function useFileChipShare(
threadId: ThreadId,
sourceIdentifier: string,
) {
const download = useFileDownload(environmentId, sourceIdentifier);
return useCallback(
(target: FileChipTarget) => {
const source = fileChipShareSource(target, threadId);
if (source) download(source);
},
[download, threadId],
);
}
export function useFileDownload(environmentId: EnvironmentId | null, sourceIdentifier: string) {
const connection = usePreparedConnection(environmentId);
const httpBaseUrl = Option.isSome(connection) ? connection.value.httpBaseUrl : null;
const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
@@ -30,9 +41,8 @@ export function useFileChipShare(
useEffect(() => () => requestRef.current?.abort(), []);
const share = useCallback(
(target: FileChipTarget) => {
const source = fileChipShareSource(target, threadId);
if (!source || requestRef.current) return;
(source: { name: string; mimeType: string; resource: AssetResource }) => {
if (environmentId === null || requestRef.current) return;
const request = new AbortController();
requestRef.current = request;
const httpBaseUrl = connectionRef.current;
@@ -53,7 +63,7 @@ export function useFileChipShare(
.catch((error: unknown) => {
if (!request.signal.aborted) {
Alert.alert(
"Could not share file",
"Could not download file",
error instanceof Error ? error.message : "Try again.",
);
}
@@ -64,7 +74,7 @@ export function useFileChipShare(
}
});
},
[createUrl, environmentId, sourceIdentifier, threadId],
[createUrl, environmentId, sourceIdentifier],
);
return share;
}
+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);
@@ -47,6 +47,45 @@ const testLayer = Layer.mergeAll(
).pipe(Layer.provideMerge(NodeServices.layer));
describe("AssetAccess", () => {
it.effect("downloads arbitrary files with exact signed access and original bytes", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-" });
const threadId = ThreadId.make("thread-1");
for (const name of ["app.apk", "source.ts", "archive.zip", "page.html", "résumé.txt"]) {
const filePath = path.join(root, name);
const bytes = new Uint8Array([0, 255, 80, 75, 13, 10]);
yield* fs.writeFile(filePath, bytes);
for (const resource of [
{ _tag: "media-file" as const, threadId, path: filePath, download: true },
{ _tag: "workspace-file" as const, threadId, path: name, download: true },
{ _tag: "draft-workspace-file" as const, cwd: root, path: name, download: true },
]) {
const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separator = suffix.indexOf("/");
const token = suffix.slice(0, separator);
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
expect(asset).toMatchObject({
kind: "file",
download: true,
fileName: name,
mimeType: "application/octet-stream",
});
if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
expect(response.headers.get("content-disposition")).toContain("attachment;");
expect(new Uint8Array(yield* Effect.promise(() => response.arrayBuffer()))).toEqual(
bytes,
);
expect(yield* resolveAsset(token, "sibling.txt")).toBeNull();
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
}
}
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+25 -5
View File
@@ -98,6 +98,7 @@ const AssetClaimsSchema = Schema.Union([
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("media-file-exact"),
download: Schema.optionalKey(Schema.Boolean),
filePath: Schema.String,
device: Schema.String,
inode: Schema.String,
@@ -274,10 +275,12 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
if (!canonicalFile) {
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
}
if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
const download = "download" in input.resource && input.resource.download === true;
if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
const wantsDimensions =
!download && HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
const opened = yield* openMediaFile(canonicalFile).pipe(
Effect.flatMap((file) =>
file === null
@@ -304,6 +307,7 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
claims: {
version: 1 as const,
kind: "media-file-exact" as const,
...(download ? { download: true } : {}),
filePath: canonicalFile,
...opened.identity,
expiresAt: input.expiresAt,
@@ -338,7 +342,8 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
}),
),
);
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
const download = "download" in input.resource && input.resource.download === true;
if (!download && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* new AssetPreviewTypeValidationError({
resource: input.resource,
});
@@ -360,6 +365,13 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
resource: input.resource,
});
}
if (download) {
return yield* finalizeAbsoluteMediaFileAsset({
requestedPath: canonicalFile,
resource: input.resource,
expiresAt: input.expiresAt,
});
}
const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
Effect.mapError(
(cause) =>
@@ -778,7 +790,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
Effect.orElseSucceed(() => null),
);
if (canonicalFile !== claims.filePath) return null;
const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
const mimeType = claims.download
? "application/octet-stream"
: hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
if (!mimeType) return null;
const file = yield* openMediaFile(canonicalFile, claims).pipe(
Effect.tapError((cause) =>
@@ -787,7 +801,13 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
Effect.orElseSucceed(() => null),
);
return file
? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
? ({
kind: "file",
path: canonicalFile,
mimeType,
file,
...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
} satisfies ResolvedAsset)
: null;
}
if (claims.kind === "workspace-file-exact") {
@@ -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: [],
+15 -1
View File
@@ -6866,7 +6866,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () =>
it.effect("routes projects.searchEntries with optional ignored files", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -6920,6 +6920,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(response.entries.length, 0);
assert.equal(response.truncated, false);
const allFiles = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.projectsSearchEntries]({
cwd: workspaceDir,
query: "ignored-search-target",
limit: 10,
includeIgnored: true,
}),
),
);
assert.deepEqual(allFiles.entries, [
{ path: ".venv/lib/ignored-search-target.ts", kind: "file" },
]);
assert.equal(allFiles.truncated, false);
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
@@ -12,6 +12,7 @@ import { vi } from "vite-plus/test";
import * as ServerConfig from "../config.ts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
@@ -77,6 +78,8 @@ const searchWorkspaceEntries = (input: {
query: string;
limit: number;
kind?: "file" | "directory";
includeIgnored?: boolean;
imageOnly?: boolean;
}) =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
@@ -95,6 +98,105 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
vi.restoreAllMocks();
});
describe("current filesystem search", () => {
it.effect(
"finds ignored APKs, hidden files, and nested build outputs without exposing git internals",
() =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ git: true });
yield* writeTextFile(cwd, ".gitignore", "build/\n*.apk\n.cache/\n");
yield* writeTextFile(cwd, "build/outputs/app-release.apk", "binary artifact");
yield* writeTextFile(cwd, ".cache/APP.APK");
yield* writeTextFile(cwd, "download.apk");
yield* writeTextFile(cwd, "mapKeys.ts");
yield* writeTextFile(cwd, ".git/private.apk");
yield* writeTextFile(cwd, "nested/.git/private.apk");
const indexed = yield* searchWorkspaceEntries({ cwd, query: ".apk", limit: 200 });
expect(indexed.entries.some((entry) => entry.path.toLowerCase().endsWith(".apk"))).toBe(
false,
);
const result = yield* searchWorkspaceEntries({
cwd,
query: ".ApK",
limit: 200,
includeIgnored: true,
});
expect(result.entries.map((entry) => entry.path).sort()).toEqual([
".cache/APP.APK",
"build/outputs/app-release.apk",
"download.apk",
]);
expect(result.truncated).toBe(false);
}),
);
it.effect("reflects created and deleted files without refreshing an index", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir();
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const input = { cwd, query: "apk", limit: 200, includeIgnored: true };
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]);
yield* writeTextFile(cwd, "build/new.apk");
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([
{ path: "build/new.apk", kind: "file" },
]);
yield* fs.remove(path.join(cwd, "build/new.apk"));
expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]);
}),
);
it.effect("bounds results and preserves kind, image, and multi-part query filters", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir();
yield* writeTextFile(cwd, "build/one.apk");
yield* writeTextFile(cwd, "build/two.apk");
yield* writeTextFile(cwd, "build/icon.png");
const input = { cwd, query: "build", limit: 200, includeIgnored: true };
expect(
yield* searchWorkspaceEntries({ ...input, query: "build apk", limit: 1 }),
).toMatchObject({
entries: [expect.objectContaining({ kind: "file" })],
truncated: true,
});
expect(
yield* searchWorkspaceEntries({ ...input, query: "build/apk", limit: 2 }),
).toMatchObject({
entries: expect.arrayContaining([
{ path: "build/one.apk", kind: "file" },
{ path: "build/two.apk", kind: "file" },
]),
truncated: false,
});
expect((yield* searchWorkspaceEntries({ ...input, kind: "directory" })).entries).toEqual([
{ path: "build", kind: "directory" },
]);
expect(
(yield* searchWorkspaceEntries({ ...input, kind: "directory", imageOnly: true })).entries,
).toEqual([{ path: "build/icon.png", kind: "file" }]);
}),
);
it.effect.skipIf(!symlinksSupported)(
"does not follow symlinks outside the workspace or into cycles",
() =>
Effect.gen(function* () {
const cwd = yield* makeTempDir();
const outside = yield* makeTempDir();
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* writeTextFile(cwd, "inside.apk");
yield* writeTextFile(outside, "outside.apk");
yield* fs.symlink(outside, path.join(cwd, "outside"));
yield* fs.symlink(cwd, path.join(cwd, "loop"));
expect(
(yield* searchWorkspaceEntries({ cwd, query: "apk", limit: 200, includeIgnored: true }))
.entries,
).toEqual([{ path: "inside.apk", kind: "file" }]);
}),
);
});
describe("list", () => {
it.effect("lists immediate children including ignored and empty directories", () =>
Effect.gen(function* () {
+55 -1
View File
@@ -22,6 +22,7 @@ import type {
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
import { expandHomePathWith } from "../pathExpansion.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
@@ -236,8 +237,61 @@ export const make = Effect.gen(function* () {
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
const normalizedQuery = normalizeSearchQuery(input.query, {
trimLeadingPattern: /^[@./]+/,
trimLeadingPattern: input.includeIgnored ? /^(?:@|\.[/\\])+/ : /^[@./]+/,
});
if (input.includeIgnored) {
return yield* Effect.tryPromise({
try: async (signal) => {
const entries: ProjectEntry[] = [];
const directories = [""];
const tokens = normalizedQuery.split(/[\s/\\]+/).filter(Boolean);
let truncated = false;
while (directories.length > 0) {
signal.throwIfAborted();
const relativeDirectory = directories.pop()!;
let directory;
try {
directory = await NodeFSP.opendir(path.join(normalizedCwd, relativeDirectory));
} catch (cause) {
const code = (cause as NodeJS.ErrnoException).code;
if (code === "ENOENT" || code === "ENOTDIR") continue;
if (code === "EACCES" || code === "EPERM") {
truncated = true;
continue;
}
throw cause;
}
for await (const child of directory) {
signal.throwIfAborted();
if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) continue;
const relativePath = relativeDirectory
? `${relativeDirectory}/${child.name}`
: child.name;
const kind = child.isDirectory() ? "directory" : "file";
if (kind === "directory") directories.push(relativePath);
if (
input.imageOnly
? kind !== "file" || !isWorkspaceImagePreviewPath(relativePath)
: input.kind && input.kind !== kind
)
continue;
if (!tokens.every((token) => relativePath.toLowerCase().includes(token))) continue;
if (entries.length === input.limit) return { entries, truncated: true };
entries.push({ path: relativePath, kind });
}
}
return { entries, truncated };
},
catch: (cause) =>
new WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed({
cwd: normalizedCwd,
queryLength: normalizedQuery.length,
pageSize: input.limit,
reason: "Failed to search current workspace files.",
cause,
}),
});
}
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
+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",
@@ -25,6 +25,7 @@ import { createFileTreeDragMentionController } from "./fileTreeDragMention";
import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
import { useDirectoryEntries } from "./useDirectoryEntries";
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
import { useProjectPathSearch } from "~/state/queries";
interface FileBrowserPanelProps {
@@ -104,6 +105,7 @@ export default function FileBrowserPanel({
workspaceMutationId,
}: FileBrowserPanelProps) {
const { resolvedTheme } = useTheme();
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
const composerRef = useComposerHandleContext();
const {
entries: directoryEntries,
@@ -115,7 +117,10 @@ export default function FileBrowserPanel({
} = useDirectoryEntries(environmentId, cwd);
const [query, setQuery] = useState("");
const [expandAll, setExpandAll] = useState(false);
const pathSearch = useProjectPathSearch({ environmentId, cwd, query: query.slice(0, 256) }, 200);
const pathSearch = useProjectPathSearch(
{ environmentId, cwd, query: query.slice(0, 256), includeIgnored: true },
200,
);
const entries = useMemo(() => {
const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
if (query.trim() && !pathSearch.isPending) {
@@ -179,9 +184,16 @@ export default function FileBrowserPanel({
[
{ id: "copy-mention", label: "Copy mention" },
{ id: "add-to-chat", label: "Add to chat" },
...(entryKindsRef.current.get(relativePath) === "file"
? [{ id: "download", label: "Download file" }]
: []),
],
position,
);
if (clicked === "download") {
void downloadFile(relativePath);
return;
}
if (clicked === "copy-mention") {
try {
await writeTextToClipboard(mention);
@@ -9,6 +9,7 @@ import type {
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
import {
isWorkspaceAudioPreviewPath,
isDownloadOnlyFile,
isWorkspaceImagePreviewPath,
isWorkspaceVideoPreviewPath,
} from "@t3tools/shared/filePreview";
@@ -21,13 +22,14 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { Code2, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react";
import { Code2, Download, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { Button } from "~/components/ui/button";
import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
import { useRemoteOpenState } from "~/remoteOpen";
@@ -55,6 +57,7 @@ import { AudioPreview } from "./AudioPreview";
import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
import { DelimitedTablePreview } from "./DelimitedTablePreview";
import FileBrowserPanel from "./FileBrowserPanel";
import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload";
import { FileBreadcrumbs } from "./FileBreadcrumbs";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import {
@@ -921,6 +924,8 @@ export default function FilePreviewPanel({
workspaceMutationId,
}: FilePreviewPanelProps) {
const { resolvedTheme } = useTheme();
const downloadFile = useWorkspaceFileDownload(environmentId, cwd);
const downloadOnly = relativePath !== null && isDownloadOnlyFile(relativePath);
const wordWrap = useClientSettings((settings) => settings.wordWrap);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const remoteOpenState = useRemoteOpenState(environmentId);
@@ -945,7 +950,7 @@ export default function FilePreviewPanel({
environmentId,
cwd,
relativePath,
attachment === undefined && !isMedia && !isPdf,
attachment === undefined && !isMedia && !isPdf && !downloadOnly,
);
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const showExplorer = shouldShowFileExplorer({
@@ -1108,6 +1113,14 @@ export default function FilePreviewPanel({
enableShortcut={false}
/>
) : null}
{relativePath && attachment === undefined ? (
<FileSurfaceAction
label="Download file"
onPress={() => void downloadFile(relativePath)}
>
<Download className="size-3.5" />
</FileSurfaceAction>
) : null}
{canToggleRendered && renderedMode ? (
<FileSurfaceAction
label={renderedToggleLabel(renderedMode, rendered)}
@@ -1219,9 +1232,20 @@ export default function FilePreviewPanel({
title={relativePath}
workspaceMutationId={workspaceMutationId}
/>
) : relativePath && file.error && file.data === null ? (
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
{file.error}
) : relativePath && (downloadOnly || (file.error && file.data === null)) ? (
<div className="flex min-h-0 flex-1 flex-col gap-3 items-center justify-center px-6 text-center text-xs leading-relaxed text-muted-foreground">
<p>
{downloadOnly
? "This file cannot be previewed. Would you like to download it?"
: file.error}
</p>
<Button
type="button"
variant="outline"
onClick={() => void downloadFile(relativePath)}
>
Download file
</Button>
</div>
) : relativePath && file.data === null ? (
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
@@ -0,0 +1,47 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback } from "react";
import { resolveAssetUrl } from "~/assets/assetUrls";
import { toastManager } from "~/components/ui/toast";
import { assetEnvironment } from "~/state/assets";
import { usePreparedConnection } from "~/state/session";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
export function useWorkspaceFileDownload(environmentId: EnvironmentId, cwd: string) {
const connection = usePreparedConnection(environmentId);
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
refresh: true,
reportFailure: false,
});
return useCallback(
async (path: string) => {
try {
if (httpBaseUrl === null) throw new Error("Reconnect to the environment and try again.");
const result = await createUrl({
environmentId,
input: {
resource: { _tag: "draft-workspace-file", cwd, path, download: true },
},
});
const url =
result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null;
if (url === null)
throw new Error("The file could not be downloaded. Reconnect and try again.");
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = path.split(/[\\/]/).at(-1) ?? "download";
document.body.append(anchor);
anchor.click();
anchor.remove();
} catch (error) {
toastManager.add({
type: "error",
title: "Could not download file",
description: error instanceof Error ? error.message : "Try again.",
});
}
},
[createUrl, cwd, environmentId, httpBaseUrl],
);
}
@@ -0,0 +1,970 @@
import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";
import {
conversationSourceAtom,
hermesSelectionAtom,
hermesConnectionAtom,
hermesNewSessionAtom,
hermesHandledNewSessionAtom,
hermesConnections,
hermesSessions,
hermesMessages,
hermesRecord,
hermesText,
hermesArray,
hermesPretty,
hermesCronJobs,
hermesCronEditor,
hermesCronPaused,
applyHermesCompletion,
mergeHermesSessions,
mergeHermesMessages,
type HermesConnection,
} from "@t3tools/client-runtime/hermes";
import type { HermesReadInput, HermesWriteInput } from "@t3tools/contracts";
import { pendingHermesRequests } from "@t3tools/client-runtime/hermes";
import { AsyncResult } from "effect/unstable/reactivity";
import * as Cause from "effect/Cause";
import { useContext, useEffect, useEffectEvent, useState } from "react";
import { hermes } from "../../state/hermes";
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../../state/server";
import { useEnvironments } from "../../state/environments";
import { useAtomCommand } from "../../state/use-atom-command";
import { resolveShortcutCommand } from "../../keybindings";
import { isCommandPaletteOpen } from "../../commandPaletteBus";
const buttonClass =
"rounded-md border border-border px-3 py-2 text-sm hover:bg-accent disabled:opacity-50";
const inputClass = "w-full rounded-md border border-border bg-background px-3 py-2 text-sm";
type Section = "chat" | "skills" | "memories" | "cron" | "logs";
export function ConversationTabs() {
const source = useAtomValue(conversationSourceAtom);
const setSource = useAtomSet(conversationSourceAtom);
return (
<div className="flex gap-1 p-2" role="tablist" aria-label="Conversations">
{(["t3", "hermes"] as const).map((tab) => (
<button
key={tab}
type="button"
role="tab"
aria-selected={source === tab}
className={`min-w-0 flex-1 rounded-md px-2 py-2 text-sm ${source === tab ? "bg-accent font-semibold" : "text-muted-foreground hover:bg-accent/50"}`}
onClick={() => setSource(tab)}
>
{tab === "t3" ? "T3" : "Hermes"}
</button>
))}
</div>
);
}
function useHermesConnection() {
const configs = useAtomValue(environmentServerConfigsAtom);
const { environments } = useEnvironments();
const saved = useAtomValue(hermesConnectionAtom);
const setConnection = useAtomSet(hermesConnectionAtom);
const choices = hermesConnections(
configs,
new Map(environments.map((environment) => [environment.environmentId, environment.label])),
);
const connection =
choices.find(
(choice) =>
choice.environmentId === saved?.environmentId &&
choice.target.instanceId === saved.target.instanceId,
) ??
choices[0] ??
null;
useEffect(() => {
if (
connection &&
(saved?.environmentId !== connection.environmentId ||
saved.target.instanceId !== connection.target.instanceId)
)
setConnection(connection);
}, [connection, saved, setConnection]);
return { choices, connection, setConnection };
}
export function HermesSidebar() {
const { choices, connection, setConnection } = useHermesConnection();
const selection = useAtomValue(hermesSelectionAtom);
const setSelection = useAtomSet(hermesSelectionAtom);
const requestNew = useAtomValue(hermesNewSessionAtom);
const newSession = useAtomSet(hermesNewSessionAtom);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
useEffect(() => {
const listener = (event: KeyboardEvent) => {
if (isCommandPaletteOpen()) return;
const command = resolveShortcutCommand(event, keybindings);
if (!event.defaultPrevented && (command === "chat.new" || command === "chat.newLocal")) {
event.preventDefault();
newSession((value) => value + 1);
}
};
window.addEventListener("keydown", listener);
return () => window.removeEventListener("keydown", listener);
}, [keybindings, newSession]);
return (
<div className="flex min-h-0 flex-1 flex-col gap-2 p-2">
<select
aria-label="Hermes environment"
className={inputClass}
value={connection ? `${connection.environmentId}:${connection.target.instanceId}` : ""}
onChange={(event) => {
const chosen = choices.find(
(choice) =>
`${choice.environmentId}:${choice.target.instanceId}` === event.target.value,
);
if (chosen) {
setConnection(chosen);
setSelection(null);
}
}}
>
{choices.length === 0 && <option value="">No enabled Hermes provider</option>}
{choices.map((choice) => (
<option
key={`${choice.environmentId}:${choice.target.instanceId}`}
value={`${choice.environmentId}:${choice.target.instanceId}`}
>
{choice.label}
</option>
))}
</select>
{connection ? (
<HermesSessionList
key={`${connection.environmentId}:${connection.target.instanceId}`}
connection={connection}
requestNew={requestNew}
selectedId={selection?.id ?? null}
/>
) : (
<p className="p-2 text-sm text-muted-foreground">
Enable Hermes in Settings → Providers on a connected environment. No project is required.
</p>
)}
</div>
);
}
function HermesSessionList({
connection,
requestNew,
selectedId,
}: {
connection: HermesConnection;
requestNew: number;
selectedId: string | null;
}) {
const registry = useContext(RegistryContext);
const target = {
environmentId: connection.environmentId,
input: { ...connection.target, resource: "sessions" as const },
};
const atom = hermes.live(target);
const result = useAtomValue(atom);
const setSelection = useAtomSet(hermesSelectionAtom);
const write = useAtomCommand(hermes.write, { reportFailure: false });
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [search, setSearch] = useState("");
const [older, setOlder] = useState<ReturnType<typeof hermesSessions>>([]);
const read = useAtomCommand(hermes.request, { reportFailure: false });
const handledNew = useAtomValue(hermesHandledNewSessionAtom);
const setHandledNew = useAtomSet(hermesHandledNewSessionAtom);
const create = async () => {
if (busy) return;
setBusy(true);
setError("");
const next = await write({
environmentId: connection.environmentId,
input: { ...connection.target, action: "create" },
});
setBusy(false);
if (AsyncResult.isSuccess(next)) {
const data = hermesRecord(next.value.data);
setSelection({
connection,
id: hermesText(data.stored_session_id),
title: "New Hermes chat",
});
registry.refresh(atom);
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
};
const createRequested = useEffectEvent(create);
useEffect(() => {
if (handledNew >= requestNew || busy) return;
setHandledNew(requestNew);
void createRequested();
}, [busy, handledNew, requestNew, setHandledNew]);
const rows = AsyncResult.isSuccess(result) ? hermesSessions(result.value.data) : [];
const combined = mergeHermesSessions(rows, older);
return (
<>
<button className={buttonClass} disabled={busy} onClick={() => void create()}>
{busy ? "Starting Hermes…" : "New task"}
</button>
<input
className={inputClass}
aria-label="Search Hermes sessions"
placeholder="Search sessions"
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
<button
className="text-left text-xs text-muted-foreground"
onClick={() => registry.refresh(atom)}
>
Refresh · updates every 5 seconds
</button>
{error && <ErrorDetail message={error} />}
{AsyncResult.isFailure(result) ? (
<>
<ErrorDetail message={Cause.pretty(result.cause)} />
<HermesLogin connection={connection} onSuccess={() => registry.refresh(atom)} />
</>
) : null}
<div className="min-h-0 flex-1 overflow-auto" aria-label="Hermes sessions">
{combined
.filter((row) => row.title.toLowerCase().includes(search.toLowerCase()))
.map((row) => (
<button
className={`mb-1 w-full rounded-md p-2 text-left hover:bg-accent ${selectedId === row.id ? "bg-accent" : ""}`}
key={`${row.profile}:${row.id}`}
onClick={() =>
setSelection({
connection: {
...connection,
target: {
...connection.target,
...(row.profile ? { profile: row.profile } : {}),
},
},
id: row.id,
title: row.title,
})
}
>
<span className="block truncate text-sm">{row.title}</span>
<span className="text-xs text-muted-foreground">
{row.active ? "Active · " : ""}
{row.source || "Hermes"}
{row.profile ? ` · ${row.profile}` : ""}
</span>
</button>
))}
{AsyncResult.isInitial(result) && <p className="p-2 text-sm">Loading Hermes sessions…</p>}
{AsyncResult.isSuccess(result) && combined.length === 0 && (
<p className="p-2 text-sm text-muted-foreground">
No sessions yet. Start a new task to chat with Hermes.
</p>
)}
{AsyncResult.isSuccess(result) &&
combined.length < Number(hermesRecord(result.value.data).total ?? 0) && (
<button
className={buttonClass}
onClick={async () => {
const next = await read({
...target,
input: { ...target.input, offset: combined.length },
});
if (AsyncResult.isSuccess(next))
setOlder((value) => [...value, ...hermesSessions(next.value.data)]);
else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
}}
>
Load older sessions
</button>
)}
</div>
</>
);
}
function ErrorDetail({ message }: { message: string }) {
return (
<details open className="rounded-md border border-destructive/40 p-2 text-sm text-destructive">
<summary>Hermes error</summary>
<pre className="mt-2 max-h-60 overflow-auto whitespace-pre-wrap break-words text-xs">
{message}
</pre>
</details>
);
}
function HermesLogin({
connection,
onSuccess,
}: {
connection: HermesConnection;
onSuccess: () => void;
}) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const write = useAtomCommand(hermes.write, { reportFailure: false });
return (
<details className="text-sm">
<summary>Dashboard sign-in</summary>
<form
className="mt-2 grid gap-2"
onSubmit={async (event) => {
event.preventDefault();
setBusy(true);
setError("");
const result = await write({
environmentId: connection.environmentId,
input: { ...connection.target, action: "login", text: password, fields: { username } },
});
setPassword("");
setBusy(false);
if (AsyncResult.isSuccess(result)) onSuccess();
else if (AsyncResult.isFailure(result)) setError(Cause.pretty(result.cause));
}}
>
<input
className={inputClass}
aria-label="Dashboard username"
autoComplete="username"
value={username}
onChange={(event) => setUsername(event.target.value)}
/>
<input
className={inputClass}
aria-label="Dashboard password"
type="password"
autoComplete="current-password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
<button className={buttonClass} disabled={busy || !username || !password}>
Sign in
</button>
{error && <ErrorDetail message={error} />}
</form>
</details>
);
}
export function HermesWorkspace() {
const selection = useAtomValue(hermesSelectionAtom);
const { connection } = useHermesConnection();
const [sectionState, setSectionState] = useState<{ session: typeof selection; section: Section }>(
{ session: selection, section: "chat" },
);
const section = sectionState.session === selection ? sectionState.section : "chat";
const setSection = (section: Section) => setSectionState({ session: selection, section });
const target = selection?.connection ?? connection;
return (
<main className="flex h-dvh min-w-0 flex-1 flex-col bg-background text-foreground">
<header className="border-b border-border px-5 pb-3 pt-14">
<h1 className="truncate text-lg font-semibold">{selection?.title ?? "Hermes"}</h1>
<nav className="mt-3 flex flex-wrap gap-2" aria-label="Hermes tools">
{(["chat", "skills", "memories", "cron", "logs"] as const).map((item) => (
<button
key={item}
className={`${buttonClass} ${section === item ? "bg-accent" : ""}`}
aria-pressed={section === item}
onClick={() => setSection(item)}
>
{item === "cron" ? "Cron jobs" : item[0]?.toUpperCase() + item.slice(1)}
</button>
))}
</nav>
</header>
{target ? (
section === "chat" ? (
selection ? (
<HermesChat
key={`${selection.connection.environmentId}:${selection.connection.target.instanceId}:${selection.connection.target.profile}:${selection.id}`}
connection={selection.connection}
id={selection.id}
/>
) : (
<p className="p-6 text-muted-foreground">
Choose a Hermes session or use New task. No project or repository is required.
</p>
)
) : (
<HermesManager
key={`${target.environmentId}:${target.target.instanceId}:${section}`}
connection={target}
section={section}
/>
)
) : (
<p className="p-6">Enable Hermes in Settings → Providers to connect.</p>
)}
</main>
);
}
function HermesChat({ connection, id }: { connection: HermesConnection; id: string }) {
const registry = useContext(RegistryContext);
const query = hermes.live({
environmentId: connection.environmentId,
input: { ...connection.target, resource: "messages", id },
});
const result = useAtomValue(query);
const events = useAtomValue(
hermes.events({ environmentId: connection.environmentId, input: connection.target }),
);
const write = useAtomCommand(hermes.write, { reportFailure: false });
const read = useAtomCommand(hermes.request, { reportFailure: false });
const [prompt, setPrompt] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [output, setOutput] = useState("");
const [commands, setCommands] = useState<ReadonlyArray<unknown>>([]);
const [completion, setCompletion] = useState<{ input: string; replaceFrom: unknown }>({
input: "/",
replaceFrom: 1,
});
const setSelection = useAtomSet(hermesSelectionAtom);
const [older, setOlder] = useState<ReturnType<typeof hermesMessages>>([]);
const [hasEarlier, setHasEarlier] = useState(true);
useEffect(() => {
let active = true;
void write({
environmentId: connection.environmentId,
input: { ...connection.target, action: "attach", id },
}).then((next) => {
if (!active) return;
if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
});
return () => {
active = false;
};
}, [connection, id, write]);
const act = async (action: "send" | "command" | "interrupt" | "attach", text?: string) => {
setBusy(true);
setError("");
const next = await write({
environmentId: connection.environmentId,
input: { ...connection.target, action, id, ...(text === undefined ? {} : { text }) },
});
setBusy(false);
if (AsyncResult.isSuccess(next)) {
const data = hermesRecord(next.value.data);
if (action === "command" && data.type === "session")
setSelection({
connection,
id: hermesText(data.stored_session_id),
title: "New Hermes chat",
});
if (action === "send" || action === "command")
setPrompt(data.type === "prefill" ? hermesText(data.message) : "");
setCommands([]);
setOutput(action === "command" ? hermesPretty(next.value.data) : "");
registry.refresh(query);
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
};
const eventRows = AsyncResult.isSuccess(events) ? events.value : [];
const messages = AsyncResult.isSuccess(result) ? hermesMessages(result.value.data) : [];
const displayedMessages = mergeHermesMessages(older, messages);
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="min-h-0 flex-1 space-y-4 overflow-auto p-5">
{AsyncResult.isFailure(result) && <ErrorDetail message={Cause.pretty(result.cause)} />}
{messages.length === 100 && hasEarlier && (
<button
className={buttonClass}
onClick={async () => {
const next = await read({
environmentId: connection.environmentId,
input: {
...connection.target,
resource: "messages",
id,
offset: displayedMessages.length,
},
});
if (AsyncResult.isSuccess(next)) {
const page = hermesMessages(next.value.data);
setOlder((value) => mergeHermesMessages(page, value, messages));
setHasEarlier(page.length === 100);
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
}}
>
Load earlier messages
</button>
)}
{displayedMessages.map((message) => (
<article className="rounded-lg border border-border p-3" key={message.id}>
<h2 className="mb-2 text-xs font-semibold uppercase text-muted-foreground">
{message.role}
</h2>
{message.details ? (
<details>
<summary>Full command / tool details</summary>
<pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-words text-xs">
{message.details}
</pre>
</details>
) : (
<p className="whitespace-pre-wrap break-words text-sm">{message.content}</p>
)}
</article>
))}
<details open>
<summary className="text-sm text-muted-foreground">Live Hermes activity</summary>
<div className="mt-2 space-y-2">
{eventRows
.filter((event) => !event.sessionId || event.sessionId === id)
.map((event) => (
<details
key={event.sequence}
open={event.type === "message.delta" || event.type === "error"}
className="rounded border border-border p-2 text-sm"
>
<summary>{event.type}</summary>
<pre className="mt-2 max-h-96 overflow-auto whitespace-pre-wrap break-words text-xs">
{event.type === "message.delta"
? hermesText(hermesRecord(event.payload).text)
: hermesPretty(event.payload)}
</pre>
</details>
))}
</div>
</details>
{output && (
<pre className="whitespace-pre-wrap break-words rounded border border-border p-3 text-sm">
{output}
</pre>
)}
{pendingHermesRequests(eventRows, id).map((request) => (
<HermesRequestForm
key={request.id}
request={request}
onRespond={async (response) => {
const next = await write({
environmentId: connection.environmentId,
input: {
...connection.target,
action: "respond",
id,
fields: { requestId: request.id, response },
},
});
if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
}}
/>
))}
{error && <ErrorDetail message={error} />}
</div>
<form
className="space-y-2 border-t border-border p-4"
onSubmit={(event) => {
event.preventDefault();
if (prompt.trim()) void act(prompt.trim().startsWith("/") ? "command" : "send", prompt);
}}
>
{commands.length > 0 && (
<div className="max-h-40 overflow-auto rounded border border-border">
{commands.map((value) => {
const item = hermesRecord(value);
return (
<button
type="button"
key={`${hermesText(item.kind)}:${hermesText(item.text)}`}
className="block w-full px-3 py-2 text-left text-sm hover:bg-accent"
onClick={() => {
setPrompt(
applyHermesCompletion(completion.input, item.text, completion.replaceFrom),
);
setCommands([]);
}}
>
{hermesText(item.display) || hermesText(item.text)}{" "}
<span className="text-xs text-muted-foreground">{hermesText(item.meta)}</span>
</button>
);
})}
</div>
)}
<textarea
className={inputClass}
aria-label="Message Hermes"
placeholder="Message Hermes, or / for commands and skills"
rows={3}
value={prompt}
onChange={(event) => {
setPrompt(event.target.value);
setCommands([]);
}}
/>
<div className="flex gap-2">
<button className={buttonClass} disabled={busy || !prompt.trim()}>
Send
</button>
<button
type="button"
className={buttonClass}
disabled={busy}
onClick={() => void act("interrupt")}
>
Stop
</button>
<button
type="button"
className={buttonClass}
onClick={async () => {
const input = prompt.startsWith("/") ? prompt : "/";
const next = await read({
environmentId: connection.environmentId,
input: {
...connection.target,
resource: "commands",
text: input,
},
});
if (AsyncResult.isSuccess(next)) {
setCommands(hermesArray(hermesRecord(next.value.data).items));
setCompletion({ input, replaceFrom: hermesRecord(next.value.data).replace_from });
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
}}
>
/ Commands & skills
</button>
<button
type="button"
className={buttonClass}
disabled={busy}
onClick={() => void act("attach")}
>
Reconnect
</button>
</div>
</form>
</div>
);
}
function HermesRequestForm({
request,
onRespond,
}: {
request: ReturnType<typeof pendingHermesRequests>[number];
onRespond: (response: Record<string, unknown>) => Promise<void>;
}) {
const [answers, setAnswers] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const questions = hermesArray(request.params.questions).map(hermesRecord);
const fields =
questions.length > 0
? questions
: [
{
qid: "answer",
question:
hermesText(request.params.question) ||
hermesText(request.params.prompt) ||
request.method,
},
];
const respond = async (response: Record<string, unknown>) => {
setBusy(true);
try {
await onRespond(response);
} finally {
setBusy(false);
}
};
return (
<section className="space-y-2 rounded-lg border border-border p-3">
<h3 className="font-semibold">Hermes needs your input</h3>
<details>
<summary>{request.method}</summary>
<pre className="whitespace-pre-wrap text-xs">{hermesPretty(request.params)}</pre>
</details>
{request.method === "approval" ? (
<div className="flex flex-wrap gap-2">
{(hermesArray(request.params.choices).length
? hermesArray(request.params.choices)
: ["once", "deny"]
).map((choice) => (
<button
key={hermesText(choice)}
className={buttonClass}
disabled={busy}
onClick={() => void respond({ choice })}
>
{hermesText(choice)}
</button>
))}
</div>
) : (
<>
{fields.map((field) => (
<label className="block text-sm" key={hermesText(field.qid)}>
{hermesText(field.question)}
<input
className={inputClass}
type={request.method === "clarify" ? "text" : "password"}
value={answers[hermesText(field.qid)] ?? ""}
onChange={(event) =>
setAnswers({ ...answers, [hermesText(field.qid)]: event.target.value })
}
/>
</label>
))}
<div className="flex gap-2">
<button
className={buttonClass}
disabled={busy}
onClick={() =>
void respond(
request.method === "clarify"
? questions.length
? { answers }
: { answer: answers.answer ?? "" }
: { value: answers.answer ?? "" },
)
}
>
Respond
</button>
<button
className={buttonClass}
disabled={busy}
onClick={() => void respond(request.method === "clarify" ? {} : { value: "" })}
>
Cancel
</button>
</div>
</>
)}
</section>
);
}
function HermesManager({
connection,
section,
}: {
connection: HermesConnection;
section: Exclude<Section, "chat">;
}) {
const registry = useContext(RegistryContext);
const [logFile, setLogFile] = useState<"agent" | "gateway" | "errors">("agent");
const [logSearch, setLogSearch] = useState("");
const resource: HermesReadInput["resource"] = section;
const query = (section === "logs" ? hermes.live : hermes.read)({
environmentId: connection.environmentId,
input: {
...connection.target,
resource,
...(section === "logs" ? { logFile, text: logSearch } : {}),
},
});
const result = useAtomValue(query);
const read = useAtomCommand(hermes.request, { reportFailure: false });
const write = useAtomCommand(hermes.write, { reportFailure: false });
const [editor, setEditor] = useState<{ id: string; text: string; original: string } | null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const data = AsyncResult.isSuccess(result) ? result.value.data : null;
const rows =
section === "skills"
? hermesArray(data)
: section === "memories"
? hermesArray(hermesRecord(data).nodes).filter((row) => hermesRecord(row).kind === "memory")
: hermesCronJobs(data);
const mutate = async (input: Omit<HermesWriteInput, "instanceId">) => {
setBusy(true);
setError("");
const next = await write({
environmentId: connection.environmentId,
input: { ...connection.target, ...input },
});
setBusy(false);
if (AsyncResult.isSuccess(next)) {
setEditor(null);
registry.refresh(query);
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
};
return (
<div className="min-h-0 flex-1 space-y-3 overflow-auto p-5">
<div className="flex flex-wrap gap-2">
<button className={buttonClass} onClick={() => registry.refresh(query)}>
Refresh
</button>
{section === "cron" && (
<button
className={buttonClass}
onClick={() =>
setEditor({
id: "",
original: "",
text: JSON.stringify(
{ name: "", schedule: "0 9 * * *", prompt: "", deliver: "local" },
null,
2,
),
})
}
>
Create cron job
</button>
)}
{section === "logs" && (
<>
<select
aria-label="Hermes log file"
className={buttonClass}
value={logFile}
onChange={(event) => setLogFile(event.target.value as typeof logFile)}
>
<option value="agent">Agent</option>
<option value="gateway">Gateway</option>
<option value="errors">Errors</option>
</select>
<input
aria-label="Filter Hermes logs"
className={inputClass}
placeholder="Filter log lines"
value={logSearch}
onChange={(event) => setLogSearch(event.target.value)}
/>
</>
)}
</div>
{AsyncResult.isFailure(result) && <ErrorDetail message={Cause.pretty(result.cause)} />}
{error && <ErrorDetail message={error} />}
{section === "logs" ? (
<pre className="max-h-full overflow-auto whitespace-pre-wrap break-words rounded border border-border p-3 text-xs">
{hermesArray(hermesRecord(data).lines).map(hermesPretty).join("\n") ||
"No log lines. Updates every 5 seconds while open."}
</pre>
) : editor ? (
<div className="space-y-3">
<h2 className="font-semibold">{editor.id || "New cron job"}</h2>
<textarea
className={`${inputClass} min-h-80 font-mono`}
aria-label={`Edit ${section}`}
value={editor.text}
onChange={(event) => setEditor({ ...editor, text: event.target.value })}
/>
<div className="flex gap-2">
<button
className={buttonClass}
disabled={busy}
onClick={() => {
if (section === "cron") {
try {
const fields = JSON.parse(editor.text) as unknown;
if (fields === null || typeof fields !== "object" || Array.isArray(fields))
throw new Error("Enter a JSON object.");
void mutate({
action: editor.id ? "updateCron" : "createCron",
...(editor.id ? { id: editor.id } : {}),
fields: hermesRecord(fields),
});
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Invalid JSON");
}
} else
void mutate({
action: section === "skills" ? "saveSkill" : "saveMemory",
id: editor.id,
text: editor.text,
fields: { expectedContent: editor.original },
});
}}
>
Save
</button>
<button className={buttonClass} disabled={busy} onClick={() => setEditor(null)}>
Cancel
</button>
</div>
</div>
) : (
rows.map((value, index) => {
const row = hermesRecord(value);
const id = hermesText(row.id) || hermesText(row.name);
const label = hermesText(row.name) || hermesText(row.label) || id;
return (
<article key={id || index} className="space-y-2 rounded-lg border border-border p-3">
<h2 className="font-semibold">{label}</h2>
<p className="text-sm text-muted-foreground">
{hermesText(row.description) || hermesText(row.prompt)}
</p>
<div className="flex flex-wrap gap-2">
<button
className={buttonClass}
onClick={async () => {
setError("");
if (section === "cron") {
setEditor({ id, original: "", text: hermesPretty(hermesCronEditor(row)) });
return;
}
const next = await read({
environmentId: connection.environmentId,
input: {
...connection.target,
resource: section === "skills" ? "skill" : "memory",
id,
},
});
if (AsyncResult.isSuccess(next)) {
const content = hermesText(hermesRecord(next.value.data).content);
setEditor({ id, text: content, original: content });
} else if (AsyncResult.isFailure(next)) setError(Cause.pretty(next.cause));
}}
>
View / edit
</button>
{section === "cron" && (
<>
<button
className={buttonClass}
disabled={busy}
onClick={() =>
void mutate({
action: hermesCronPaused(row) ? "resumeCron" : "pauseCron",
id,
})
}
>
{hermesCronPaused(row) ? "Resume" : "Pause"}
</button>
<button
className={buttonClass}
disabled={busy}
onClick={() => {
if (window.confirm(`Run ${label} now?`))
void mutate({ action: "runCron", id });
}}
>
Run now
</button>
<button
className={buttonClass}
disabled={busy}
onClick={() => {
if (window.confirm(`Delete ${label}? This cannot be undone.`))
void mutate({ action: "deleteCron", id });
}}
>
Delete
</button>
</>
)}
</div>
<details>
<summary className="text-sm">Full details</summary>
<pre className="overflow-auto whitespace-pre-wrap text-xs">{hermesPretty(row)}</pre>
</details>
</article>
);
})
)}
{data !== null && section !== "logs" && !editor && rows.length === 0 && (
<p className="text-sm text-muted-foreground">No {section} found in this Hermes profile.</p>
)}
</div>
);
}
@@ -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,
],
);
}
+4
View File
@@ -0,0 +1,4 @@
import { createHermesState } from "@t3tools/client-runtime/hermes";
import { connectionAtomRuntime } from "../connection/runtime";
export const hermes = createHermesState(connectionAtomRuntime);
+3
View File
@@ -22,5 +22,8 @@ describe("areProjectPathSearchTargetsEqual", () => {
expect(areProjectPathSearchTargetsEqual(target, { ...target, query: "readme" })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, kind: "file" })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, imageOnly: true })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, includeIgnored: true })).toBe(
false,
);
});
});
+13 -2
View File
@@ -205,6 +205,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
}
type ProjectPathSearchTarget = ComposerPathSearchTarget & {
readonly includeIgnored?: boolean | undefined;
readonly kind?: ProjectEntryKind | undefined;
readonly imageOnly?: boolean | undefined;
};
@@ -218,7 +219,8 @@ export function areProjectPathSearchTargetsEqual(
left.cwd === right.cwd &&
left.query === right.query &&
left.kind === right.kind &&
left.imageOnly === right.imageOnly
left.imageOnly === right.imageOnly &&
left.includeIgnored === right.includeIgnored
);
}
@@ -235,8 +237,16 @@ export function useProjectPathSearch(
query: target.query == null ? null : target.query.trim(),
kind: target.kind,
imageOnly: target.imageOnly,
includeIgnored: target.includeIgnored,
}),
[target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
[
target.cwd,
target.environmentId,
target.imageOnly,
target.includeIgnored,
target.kind,
target.query,
],
);
const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
const result = useEnvironmentQuery(
@@ -252,6 +262,7 @@ export function useProjectPathSearch(
limit,
...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
...(debouncedTarget.includeIgnored ? { includeIgnored: true } : {}),
},
})
: null,
+24 -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.
@@ -50,6 +50,26 @@ and distribute an APK built for the new repository URL. Keep the same signing ke
across the move and ensure the release token has write access to the new owner’s
repository.
## Local release
For a local build from a checkout, copy the example configuration and run the
release script exactly like the MG Utility release flow:
```sh
cp .env.release.example .env.release
$EDITOR .env.release
./scripts/release-apk.sh --dry-run # prints the next apk-<versionCode>
./scripts/release-apk.sh # builds, signs, uploads, publishes
```
`GITEA_TOKEN` (or `APK_RELEASE_TOKEN`) must be present in `.env.release`. The
keystore, Android SDK, NDK, and Expo toolchain still need to match the build
script. The release body defaults to a `production` JSON envelope
(`schema: 1, channel, versionCode, versionName, branch, commit, sha256`);
`APK_RELEASE_BODY` overrides the entire body when set. `APK_VERSION_CODE` pins
the next release only when it exceeds the highest existing `apk-*` tag on the
target Gitea repository.
## Publish an update
Push a tag of the form `apk-<versionCode>` on the commit to release. For example,
+12
View File
@@ -196,6 +196,18 @@ File links refer to the environment's machine, including when you connect remote
Previews use the original file, even outside the workspace. Moving or deleting it
can break the preview, so save a copy if you need to keep it.
## Downloading files
To download a workspace file, right-click it in the file explorer on web or desktop,
or touch and hold it in Files on mobile, then choose **Download file**. Files such
as APKs and archives offer a download instead of a preview when you follow an
agent's file link. Nothing downloads until you choose to proceed. Mobile uses the
device's save/share sheet so you can choose where to keep or send the file.
File explorer search includes hidden and Git-ignored files, including generated
build outputs. Refresh the file explorer to pick up newly created or deleted files.
Broad searches show up to 200 matches; narrow the query if results are truncated.
## Files outside the workspace
Follow an agent's file link to read a report or other file outside the workspace.
+45 -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,58 @@ 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
In the Hermes workspace, 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.
## 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 +85,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"
+191
View File
@@ -0,0 +1,191 @@
import { describe, expect, it } from "vite-plus/test";
import {
appendHermesEvent,
hermesCronEditor,
hermesCronJobs,
hermesMessages,
hermesSessions,
pendingHermesRequests,
applyHermesCompletion,
hermesCronPaused,
mergeHermesSessions,
mergeHermesMessages,
} from "./hermes.ts";
import type { HermesEvent } from "@t3tools/contracts";
describe("native Hermes presentation", () => {
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([]);
});
});
+242
View File
@@ -0,0 +1,242 @@
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 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
+6 -2
View File
@@ -14,19 +14,23 @@ const ASSET_PATH_MAX_LENGTH = 1024;
export const AssetResource = Schema.Union([
Schema.TaggedStruct("workspace-file", {
threadId: ThreadId,
download: Schema.optionalKey(Schema.Boolean),
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
// One file served in place from anywhere the environment host can read:
// images, videos, HTML, and PDF. An absolute path may lie outside the
// workspace; a relative one resolves against the thread's workspace.
// previews of images, videos, HTML, and PDF, or explicit downloads of any type.
// An absolute path may lie outside the workspace; a relative one resolves
// against the thread's workspace.
Schema.TaggedStruct("media-file", {
threadId: ThreadId,
download: Schema.optionalKey(Schema.Boolean),
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
// A workspace file named by a draft that has no thread yet. The draft names
// its workspace root explicitly instead of resolving one from a thread.
Schema.TaggedStruct("draft-workspace-file", {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
download: Schema.optionalKey(Schema.Boolean),
path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
Schema.TaggedStruct("attachment", {
+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";
+5
View File
@@ -14,6 +14,11 @@ const decodeSearchEntriesInput = Schema.decodeUnknownSync(ProjectSearchEntriesIn
const decodeSearchContentsInput = Schema.decodeUnknownSync(ProjectSearchContentsInput);
describe("project search inputs", () => {
it("allows file browsers to include ignored files without changing legacy requests", () => {
const input = { cwd: "/workspace", query: ".apk", limit: 200 };
expect(decodeSearchEntriesInput(input).includeIgnored).toBeUndefined();
expect(decodeSearchEntriesInput({ ...input, includeIgnored: true }).includeIgnored).toBe(true);
});
it("allows an empty entries query for bounded frecency browsing", () => {
const decoded = decodeSearchEntriesInput({
cwd: "/workspace",
+1
View File
@@ -22,6 +22,7 @@ export const ProjectSearchEntriesInput = Schema.Struct({
limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),
kind: Schema.optional(ProjectEntryKind),
imageOnly: Schema.optional(Schema.Boolean),
includeIgnored: Schema.optional(Schema.Boolean),
});
export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;
+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)),
+14
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
filePreviewKind,
isDownloadOnlyFile,
decodeFilePreviewText,
FILE_TEXT_PREVIEW_MAX_BYTES,
hostPreviewMimeTypeFromExtension,
@@ -14,6 +15,19 @@ import {
} from "./filePreview.ts";
describe("workspace file previews", () => {
it.each(["app.apk", "APP.APK", "build/app.aab", "archive.tar.gz", "installer.exe"])(
"offers a download instead of previewing %s",
(path) => {
expect(isDownloadOnlyFile(path)).toBe(true);
},
);
it.each(["app.apk.ts", "README", "source.custom", "image.png", "report.pdf"])(
"retains preview behavior for %s",
(path) => {
expect(isDownloadOnlyFile(path)).toBe(false);
},
);
it.each(["report.html", "report.HTM", "document.pdf?download=1"])(
"recognizes browser preview path %s",
(path) => {
+6
View File
@@ -10,6 +10,12 @@ export type FilePreviewKind =
| "text"
| "unsupported";
export function isDownloadOnlyFile(path: string): boolean {
return /\.(apk|aab|ipa|exe|msi|dmg|iso|zip|tar|gz|bz2|xz|7z|rar|jar|war|dll|so|dylib|wasm|bin)$/i.test(
path,
);
}
/** Content classification is identical for captured attachments and workspace references. */
export function filePreviewKind(file: {
readonly name: string;
Regular → Executable
+1 -1
View File
@@ -28,7 +28,7 @@ bash apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
cd apps/mobile
EXPO_NO_GIT_STATUS=1 node_modules/.bin/expo prebuild --clean --platform android --no-install
cd android
./gradlew --no-daemon :app:assembleRelease
./gradlew --no-daemon -PreactNativeArchitectures="${ANDROID_ARCHITECTURES:-arm64-v8a}" :app:assembleRelease
)
build_tools="${ANDROID_HOME}/build-tools/${ANDROID_BUILD_TOOLS_VERSION:-36.0.0}"
+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;
+11
View File
@@ -65,6 +65,17 @@ describe("fork APK publishing", () => {
}
});
it("passes a configured release body to the repository release", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response("{}"));
request.mockResolvedValueOnce(Response.json({ id: 123 }));
await publishForkApk({ ...options, body: "Local release notes", request });
expect(JSON.parse(String(request.mock.calls[0]?.[1]?.body))).toMatchObject({
body: "Local release notes",
});
});
it("does not publish an incomplete release after an upload failure", async () => {
const request = vi
.fn<typeof fetch>()
+4 -1
View File
@@ -14,6 +14,7 @@ export async function publishForkApk(options: {
apk: Blob;
checksum: Blob;
request?: typeof fetch;
body?: string;
}) {
const versionCode = parseAndroidApkReleaseTag(options.tag);
const request = options.request ?? fetch;
@@ -36,7 +37,9 @@ export async function publishForkApk(options: {
tag_name: options.tag,
target_commitish: options.commit,
name: `Android APK · build ${versionCode}`,
body: "Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.",
body:
options.body ??
"Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.",
draft: true,
prerelease: false,
}),
+149
View File
@@ -0,0 +1,149 @@
#!/bin/sh
# Build and publish the next t3code Android APK release.
#
# Without flags: build and publish the next APK version.
# With --dry-run: calculate and print the next version without building or publishing.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
DRY_RUN=0
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=1 ;;
--help|-h)
printf '%s\n' 'Usage: ./scripts/release-apk.sh [--dry-run]'
printf '%s\n' ' (default) build and publish the next APK release'
printf '%s\n' ' --dry-run calculate and print the next version without building or publishing'
exit 0
;;
*) echo "Unknown option: $arg" >&2; exit 2 ;;
esac
done
CONFIG_FILE=${CONFIG_FILE:-$ROOT/.env.release}
case "$CONFIG_FILE" in
/*) ;;
*) CONFIG_FILE="$ROOT/$CONFIG_FILE" ;;
esac
if [ -f "$CONFIG_FILE" ]; then
set -a
# shellcheck disable=SC1090
. "$CONFIG_FILE"
set +a
fi
API=${GITEA_API_URL:-https://git.molberg.cloud/api/v1/repos/alex/t3code}
REPOSITORY_URL=${T3CODE_APK_REPOSITORY_URL:-https://git.molberg.cloud/alex/t3code}
TOKEN=${APK_RELEASE_TOKEN:-${GITEA_TOKEN:-}}
if [ "$DRY_RUN" -eq 0 ] && [ -z "$TOKEN" ]; then
echo "Set GITEA_TOKEN or APK_RELEASE_TOKEN in $CONFIG_FILE or the environment" >&2
exit 2
fi
RELEASES_JSON=$(mktemp)
trap 'rm -f "$RELEASES_JSON"' EXIT HUP INT TERM
if [ -n "$TOKEN" ]; then
curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \
-H "Authorization: token $TOKEN" "$API/releases?limit=50" > "$RELEASES_JSON"
else
curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \
"$API/releases?limit=50" > "$RELEASES_JSON"
fi
VERSION_CODE=$(python3 - "$RELEASES_JSON" "${APK_VERSION_CODE:-}" <<'PY'
import json
import re
import sys
path, override = sys.argv[1:]
if override:
print(override)
raise SystemExit
highest = 0
with open(path, encoding="utf-8") as handle:
for release in json.load(handle):
tag = str(release.get("tag_name", ""))
match = re.fullmatch(r"apk-([1-9][0-9]*)", tag)
if match:
highest = max(highest, int(match.group(1)))
print(highest + 1)
PY
)
case "$VERSION_CODE" in
*[!0-9]*|'') echo "APK_VERSION_CODE must be a positive integer" >&2; exit 2 ;;
esac
[ "$VERSION_CODE" -gt 0 ] || { echo "APK_VERSION_CODE must be positive" >&2; exit 2; }
[ "$VERSION_CODE" -le 2100000000 ] || { echo "APK_VERSION_CODE must be at most 2100000000" >&2; exit 2; }
TAG="apk-$VERSION_CODE"
VERSION_NAME=$(sed -n 's/.*version: "\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)".*/\1/p' "$ROOT/apps/mobile/app.config.ts" | head -n 1)
VERSION_NAME=${VERSION_NAME:-unknown}
printf 'Next APK release: %s (versionName %s)\n' "$TAG" "$VERSION_NAME"
[ "$DRY_RUN" -eq 0 ] || exit 0
export T3CODE_APK_RELEASE_TAG="$TAG"
export T3CODE_APK_RELEASE_COMMIT=$(git -C "$ROOT" rev-parse HEAD)
export T3CODE_APK_REPOSITORY_URL="$REPOSITORY_URL"
export APK_RELEASE_TOKEN="$TOKEN"
export APP_VARIANT=production
export T3CODE_MOBILE_UPDATES_ENABLED=0
cd "$ROOT"
bash scripts/build-fork-apk.sh
APK="release/t3code-$TAG.apk"
CHECKSUM="$APK.sha256"
[ -s "$APK" ] || { echo "Build did not produce $APK" >&2; exit 1; }
[ -s "$CHECKSUM" ] || { echo "Build did not produce $CHECKSUM" >&2; exit 1; }
# build-fork-apk.sh runs `sha256sum` from inside release/, so the file references
# only the bare filename. Verify from that directory.
(
cd release
sha256sum -c "$(basename "$CHECKSUM")"
)
if [ -z "${APK_RELEASE_BODY:-}" ]; then
APK_RELEASE_BODY=$(python3 - "$TAG" "$VERSION_CODE" "$VERSION_NAME" "$T3CODE_APK_RELEASE_COMMIT" "$(sha256sum "$APK" | cut -d' ' -f1)" <<'PY'
import json
import sys
print(json.dumps({
"schema": 1,
"channel": "production",
"versionCode": int(sys.argv[2]),
"versionName": sys.argv[3],
"branch": "main",
"commit": sys.argv[4],
"sha256": sys.argv[5],
}, separators=(",", ":")))
PY
)
fi
APK_RELEASE_BODY="$APK_RELEASE_BODY" node --input-type=module <<'NODE'
import * as NodeFS from "node:fs/promises";
import { publishForkApk } from "./scripts/publish-fork-apk.ts";
const tag = process.env.T3CODE_APK_RELEASE_TAG;
const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL;
const token = process.env.APK_RELEASE_TOKEN;
const commit = process.env.T3CODE_APK_RELEASE_COMMIT;
if (!tag || !repositoryUrl || !token || !commit) throw new Error("Release environment is incomplete.");
await publishForkApk({
tag,
repositoryUrl,
token,
commit,
body: process.env.APK_RELEASE_BODY,
apk: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk`)], { type: "application/vnd.android.package-archive" }),
checksum: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk.sha256`)], { type: "text/plain" }),
});
NODE
printf 'Published %s\n' "$TAG"