fix: make Hermes pairing recoverable and self-updating
A failed enrollment left an orphaned provider instance in the picker, permanently `instance-not-found`, with no explanation and no way to clear it except editing settings by hand. Enrolling before persisting is not possible: `createEnrollment` reads `providerInstances[instanceId]` and fails unless the instance is already persisted with the Hermes driver, so the settings write is a hard precondition of the RPC. The failure path therefore cleans up after itself. The write registers a pending undo in a ref rather than closure state, and two effects drain it — the existing `!open` reset and a new unmount cleanup, since the parent renders this dialog conditionally and closing unmounts it, so the `!open` branch alone would never run. Rollback reads the latest settings map instead of restoring a captured pre-write snapshot, which would silently revert instances another client added in the interim, and no-ops when the entry is already gone or was replaced. The claimed instance id is retained across a rollback with a `persisted: false` flag so the retry path still refuses to mint a duplicate id while knowing it must re-write the instance. Pairing completes out-of-band on another host, so the dialog now shows an explicit waiting state: what to run, that `hermes gateway restart` is required rather than an error, and a ticking expiry with a way to mint a fresh command. It flips to connected on its own through the status stream already published by the broker — no new polling. That live update watches the snapshot's `checkedAt` revision rather than the connected flag, because `upgrade-required` closes the connection and is therefore indistinguishable from "still offline" through connectedness alone; keying on it would leave the panel waiting forever on a plugin that needs updating. An authoritative status re-read then distinguishes upgrade-required and revoked from a plain wait. Also surfaces the install step the flow always required but never mentioned, and stops labelling the terminal button "Done" while pairing is still pending. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
758f999f9b
commit
3261623f90
5 files changed
+714
-36
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import type { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type { HermesGatewayConnectionState, ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
export type WizardNavigation =
|
||||
| { readonly kind: "navigate"; readonly step: number }
|
||||
@@ -31,6 +31,16 @@ export function createHermesProviderInstanceId(label: string, randomUuid: () =>
|
||||
return labelSlug ? `hermes-${labelSlug}-${shortSuffix}` : `hermes-${shortSuffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command that installs the gateway plugin into the Hermes profile.
|
||||
*
|
||||
* Installation is a manual step performed on the Hermes host — T3 has no
|
||||
* remote access to it — so the dialog documents the command rather than
|
||||
* implying anything happens automatically. The script symlinks this repository
|
||||
* checkout into `~/.hermes/plugins` and enables the plugin.
|
||||
*/
|
||||
export const HERMES_PLUGIN_INSTALL_COMMAND = "./integrations/hermes-t3-gateway/install.sh" as const;
|
||||
|
||||
export function isHermesInstanceRemovedError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
@@ -40,6 +50,30 @@ export function isHermesInstanceRemovedError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop an instance the dialog itself just wrote, without clobbering anything
|
||||
* that changed underneath it.
|
||||
*
|
||||
* Used to roll back the settings write when Hermes enrollment fails. The
|
||||
* server is authoritative between the write and the rollback, so this reads
|
||||
* the *latest* map rather than restoring a captured pre-write snapshot — that
|
||||
* would silently revert instances added by another client in between. If the
|
||||
* id is already gone, or has been replaced by a different config object, the
|
||||
* write is not ours to undo and `null` signals "no rollback needed".
|
||||
*/
|
||||
export function rollbackProviderInstances<T>(input: {
|
||||
readonly latest: Readonly<Record<string, T>>;
|
||||
readonly instanceId: string;
|
||||
readonly written: T;
|
||||
}): Record<string, T> | null {
|
||||
const current = input.latest[input.instanceId];
|
||||
if (current === undefined) return null;
|
||||
if (current !== input.written) return null;
|
||||
const next = { ...input.latest };
|
||||
delete next[input.instanceId];
|
||||
return next;
|
||||
}
|
||||
|
||||
export function isOwnedHermesEnrollmentRetry(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly instanceId: string;
|
||||
@@ -52,6 +86,69 @@ export function isOwnedHermesEnrollmentRetry(input: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presentation state of the post-enrollment "waiting for Hermes" panel.
|
||||
*
|
||||
* `waiting` is the expected steady state immediately after the command is
|
||||
* generated — the user still has to paste it and restart the gateway — so it
|
||||
* is deliberately not modelled as an error. `expired` and `blocked` are the
|
||||
* two states that need a fresh command, and `connected` is terminal success.
|
||||
*/
|
||||
export type HermesWaitingPhase = "waiting" | "connected" | "blocked" | "expired";
|
||||
|
||||
export interface HermesWaitingState {
|
||||
readonly phase: HermesWaitingPhase;
|
||||
readonly statusLabelState: HermesGatewayConnectionState;
|
||||
/** True while T3 legitimately has nothing to report yet. */
|
||||
readonly isPending: boolean;
|
||||
/** True when the only way forward is minting a replacement command. */
|
||||
readonly needsNewCommand: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve what the waiting panel should show.
|
||||
*
|
||||
* Connection wins over expiry: once the gateway has dialled in, the one-time
|
||||
* token has already been consumed and its expiry is irrelevant. `revoked` and
|
||||
* `upgrade-required` are surfaced ahead of the generic wait because neither
|
||||
* resolves by waiting longer.
|
||||
*/
|
||||
export function resolveHermesWaitingState(input: {
|
||||
readonly connectionState: HermesGatewayConnectionState | null;
|
||||
readonly isExpired: boolean;
|
||||
}): HermesWaitingState {
|
||||
if (input.connectionState === "connected") {
|
||||
return {
|
||||
phase: "connected",
|
||||
statusLabelState: "connected",
|
||||
isPending: false,
|
||||
needsNewCommand: false,
|
||||
};
|
||||
}
|
||||
if (input.connectionState === "upgrade-required" || input.connectionState === "revoked") {
|
||||
return {
|
||||
phase: "blocked",
|
||||
statusLabelState: input.connectionState,
|
||||
isPending: false,
|
||||
needsNewCommand: input.connectionState === "revoked",
|
||||
};
|
||||
}
|
||||
if (input.isExpired) {
|
||||
return {
|
||||
phase: "expired",
|
||||
statusLabelState: input.connectionState ?? "offline",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: "waiting",
|
||||
statusLabelState: input.connectionState ?? "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function validateProviderInstanceIdForWizard(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly instanceId: string;
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
createHermesProviderInstanceId,
|
||||
isHermesInstanceRemovedError,
|
||||
isOwnedHermesEnrollmentRetry,
|
||||
resolveHermesWaitingState,
|
||||
resolveWizardNavigation,
|
||||
rollbackProviderInstances,
|
||||
validateProviderInstanceIdForWizard,
|
||||
} from "./AddProviderInstanceDialog.logic";
|
||||
|
||||
@@ -131,3 +133,105 @@ describe("Hermes enrollment retry ownership", () => {
|
||||
).toContain("already exists");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rollbackProviderInstances", () => {
|
||||
interface TestInstance {
|
||||
readonly driver: string;
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
const written: TestInstance = { driver: "hermes", enabled: true };
|
||||
const other: TestInstance = { driver: "codex", enabled: true };
|
||||
|
||||
it("removes only the instance this dialog wrote", () => {
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": written, codex_work: other },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toEqual({ codex_work: other });
|
||||
});
|
||||
|
||||
it("preserves instances another client added between the write and the rollback", () => {
|
||||
const concurrent: TestInstance = { driver: "claude", enabled: true };
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": written, "added-elsewhere": concurrent },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toEqual({ "added-elsewhere": concurrent });
|
||||
});
|
||||
|
||||
it("does nothing when the id is already gone or was replaced by a different config", () => {
|
||||
expect(
|
||||
rollbackProviderInstances({ latest: { codex_work: other }, instanceId: "hermes-a", written }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
rollbackProviderInstances({
|
||||
latest: { "hermes-a": { ...written } },
|
||||
instanceId: "hermes-a",
|
||||
written,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHermesWaitingState", () => {
|
||||
it("treats a not-yet-dialled-in gateway as an expected pending wait, not an error", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: null, isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "offline", isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "offline",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "connecting", isExpired: false })).toEqual({
|
||||
phase: "waiting",
|
||||
statusLabelState: "connecting",
|
||||
isPending: true,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("flips to connected and ignores expiry once the gateway has dialled in", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: "connected", isExpired: true })).toEqual({
|
||||
phase: "connected",
|
||||
statusLabelState: "connected",
|
||||
isPending: false,
|
||||
needsNewCommand: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("offers a fresh command when the one-time token expired unused", () => {
|
||||
expect(resolveHermesWaitingState({ connectionState: "offline", isExpired: true })).toEqual({
|
||||
phase: "expired",
|
||||
statusLabelState: "offline",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces upgrade-required and revoked ahead of waiting, since neither resolves by waiting", () => {
|
||||
expect(
|
||||
resolveHermesWaitingState({ connectionState: "upgrade-required", isExpired: false }),
|
||||
).toEqual({
|
||||
phase: "blocked",
|
||||
statusLabelState: "upgrade-required",
|
||||
isPending: false,
|
||||
// A protocol upgrade needs a new plugin, not a new token.
|
||||
needsNewCommand: false,
|
||||
});
|
||||
expect(resolveHermesWaitingState({ connectionState: "revoked", isExpired: false })).toEqual({
|
||||
phase: "blocked",
|
||||
statusLabelState: "revoked",
|
||||
isPending: false,
|
||||
needsNewCommand: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
|
||||
import { CheckIcon, CopyIcon, LoaderIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { CheckIcon, CopyIcon, LoaderIcon, TriangleAlertIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type HermesGatewayConnectionState,
|
||||
type HermesGatewayEnrollmentResult,
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
@@ -35,19 +37,26 @@ import { AnimatedHeight } from "../AnimatedHeight";
|
||||
import {
|
||||
ADD_PROVIDER_WIZARD_STEPS,
|
||||
createHermesProviderInstanceId,
|
||||
HERMES_PLUGIN_INSTALL_COMMAND,
|
||||
isHermesInstanceRemovedError,
|
||||
isOwnedHermesEnrollmentRetry,
|
||||
resolveHermesWaitingState,
|
||||
resolveWizardNavigation,
|
||||
rollbackProviderInstances,
|
||||
type WizardNavigation,
|
||||
validateProviderInstanceIdForWizard,
|
||||
} from "./AddProviderInstanceDialog.logic";
|
||||
import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
hermesGatewayProviderSignal,
|
||||
hermesGatewayStatusGuidance,
|
||||
hermesGatewayStatusLabel,
|
||||
isHermesEnrollmentExpired,
|
||||
messageFromUnknownError,
|
||||
} from "./HermesGatewayInstanceSection.logic";
|
||||
|
||||
@@ -113,6 +122,17 @@ const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const HERMES_BADGE_VARIANT_BY_STATUS: Record<
|
||||
HermesGatewayConnectionState,
|
||||
"success" | "warning" | "error" | "secondary"
|
||||
> = {
|
||||
connected: "success",
|
||||
connecting: "warning",
|
||||
offline: "secondary",
|
||||
"upgrade-required": "warning",
|
||||
revoked: "error",
|
||||
};
|
||||
|
||||
interface AddProviderInstanceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -128,6 +148,10 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
const createHermesEnrollment = useAtomCommand(serverEnvironment.hermesGatewayCreateEnrollment, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const getHermesStatus = useAtomCommand(serverEnvironment.hermesGatewayGetInstanceStatus, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
|
||||
const [wizardStep, setWizardStep] = useState(0);
|
||||
const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
|
||||
@@ -154,7 +178,17 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
const [createdHermesIdentity, setCreatedHermesIdentity] = useState<{
|
||||
readonly instanceId: string;
|
||||
readonly nickname: string;
|
||||
/**
|
||||
* False once a failed enrollment rolled the settings write back. The id
|
||||
* stays claimed by this dialog session (so validation keeps exempting it
|
||||
* and no duplicate is ever created), but the next attempt has to write it
|
||||
* again before the server will accept an enrollment for it.
|
||||
*/
|
||||
readonly persisted: boolean;
|
||||
} | null>(null);
|
||||
const [hermesConnectionState, setHermesConnectionState] =
|
||||
useState<HermesGatewayConnectionState | null>(null);
|
||||
const [nowMillis, setNowMillis] = useState(() => Date.now());
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard({
|
||||
target: "Hermes enrollment command",
|
||||
onCopy: () =>
|
||||
@@ -164,9 +198,53 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
description: "Run it in the terminal where Hermes is installed.",
|
||||
}),
|
||||
});
|
||||
const { copyToClipboard: copyInstallCommand, isCopied: isInstallCommandCopied } =
|
||||
useCopyToClipboard({
|
||||
target: "Hermes plugin install command",
|
||||
onCopy: () =>
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Install command copied",
|
||||
description: "Run it from the T3 Code checkout on the Hermes host.",
|
||||
}),
|
||||
});
|
||||
|
||||
// Rollback of a failed Hermes enrollment must survive the dialog closing
|
||||
// mid-failure, so the pending undo lives in a ref that an unmount-safe
|
||||
// effect drains rather than in the `handleSave` closure alone.
|
||||
const pendingRollbackRef = useRef<{
|
||||
readonly instanceId: string;
|
||||
readonly written: ProviderInstanceConfig;
|
||||
} | null>(null);
|
||||
const latestProviderInstancesRef = useRef(settings.providerInstances);
|
||||
latestProviderInstancesRef.current = settings.providerInstances;
|
||||
const environmentIdRef = useRef(environmentId);
|
||||
environmentIdRef.current = environmentId;
|
||||
const updateServerSettingsRef = useRef(updateServerSettings);
|
||||
updateServerSettingsRef.current = updateServerSettings;
|
||||
|
||||
const rollbackPendingHermesInstance = useCallback(async () => {
|
||||
const pending = pendingRollbackRef.current;
|
||||
pendingRollbackRef.current = null;
|
||||
const rollbackEnvironmentId = environmentIdRef.current;
|
||||
if (pending === null || rollbackEnvironmentId === null) return;
|
||||
const providerInstances = rollbackProviderInstances({
|
||||
latest: latestProviderInstancesRef.current ?? {},
|
||||
instanceId: pending.instanceId,
|
||||
written: pending.written,
|
||||
});
|
||||
if (providerInstances === null) return;
|
||||
await updateServerSettingsRef.current({
|
||||
environmentId: rollbackEnvironmentId,
|
||||
input: { patch: { providerInstances } },
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Fires both when the dialog is closed and when it is unmounted outright
|
||||
// (its parent renders it conditionally), so an orphan is never left behind.
|
||||
useEffect(() => {
|
||||
if (open) return;
|
||||
void rollbackPendingHermesInstance();
|
||||
setWizardStep(0);
|
||||
setDriver(DEFAULT_DRIVER_KIND);
|
||||
setLabel("");
|
||||
@@ -184,7 +262,70 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
setSaveError(null);
|
||||
setIsSaving(false);
|
||||
setCreatedHermesIdentity(null);
|
||||
}, [open]);
|
||||
setHermesConnectionState(null);
|
||||
}, [open, rollbackPendingHermesInstance]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
void rollbackPendingHermesInstance();
|
||||
},
|
||||
[rollbackPendingHermesInstance],
|
||||
);
|
||||
|
||||
const enrolledInstanceId = hermesEnrollment?.instanceId ?? null;
|
||||
// The server pushes a fresh `ServerProvider` snapshot over the already-open
|
||||
// `subscribeServerConfig` stream every time the broker publishes a gateway
|
||||
// status change, so this flips the moment Hermes dials in — no polling.
|
||||
const hermesProviderSignal = useMemo(
|
||||
() =>
|
||||
enrolledInstanceId === null
|
||||
? null
|
||||
: hermesGatewayProviderSignal(serverProviders, enrolledInstanceId),
|
||||
[serverProviders, enrolledInstanceId],
|
||||
);
|
||||
const hermesProviderSignalKey = hermesProviderSignal
|
||||
? `${hermesProviderSignal.present}:${hermesProviderSignal.connected}:${hermesProviderSignal.revision ?? ""}`
|
||||
: null;
|
||||
|
||||
// The pushed snapshot only tells us connected/not. Resolve the authoritative
|
||||
// `HermesGatewayConnectionState` once per change so `upgrade-required` and
|
||||
// `revoked` are distinguishable from a plain wait.
|
||||
useEffect(() => {
|
||||
if (enrolledInstanceId === null || environmentId === null) return;
|
||||
if (hermesProviderSignalKey === null) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const result = await getHermesStatus({
|
||||
environmentId,
|
||||
input: { instanceId: ProviderInstanceId.make(enrolledInstanceId) },
|
||||
});
|
||||
if (cancelled) return;
|
||||
if (result._tag === "Success") setHermesConnectionState(result.value.status);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [enrolledInstanceId, environmentId, getHermesStatus, hermesProviderSignalKey]);
|
||||
|
||||
// Re-evaluate the enrollment expiry on a coarse tick so the panel switches
|
||||
// itself to the "mint a new command" affordance without a manual refresh.
|
||||
useEffect(() => {
|
||||
if (hermesEnrollment === null) return;
|
||||
setNowMillis(Date.now());
|
||||
const interval = window.setInterval(() => setNowMillis(Date.now()), 15_000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [hermesEnrollment]);
|
||||
|
||||
const hermesWaitingState = useMemo(
|
||||
() =>
|
||||
hermesEnrollment === null
|
||||
? null
|
||||
: resolveHermesWaitingState({
|
||||
connectionState: hermesConnectionState,
|
||||
isExpired: isHermesEnrollmentExpired(hermesEnrollment.expiresAt, nowMillis),
|
||||
}),
|
||||
[hermesEnrollment, hermesConnectionState, nowMillis],
|
||||
);
|
||||
|
||||
const existingIds = useMemo(
|
||||
() => new Set(Object.keys(settings.providerInstances ?? {})),
|
||||
@@ -261,11 +402,15 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
// keeps the type boundary honest and guards against any future drift in
|
||||
// the slug rules.
|
||||
const brandedId = ProviderInstanceId.make(instanceId);
|
||||
const isOwnedHermesRetry = isOwnedHermesEnrollmentRetry({
|
||||
driver,
|
||||
instanceId,
|
||||
createdHermesInstanceId: createdHermesIdentity?.instanceId ?? null,
|
||||
});
|
||||
// Only skip the settings write when the instance this dialog created is
|
||||
// still persisted. After a rolled-back failure the id is still ours, but
|
||||
// it has to be written again before the server will enroll it.
|
||||
const isOwnedHermesRetry =
|
||||
isOwnedHermesEnrollmentRetry({
|
||||
driver,
|
||||
instanceId,
|
||||
createdHermesInstanceId: createdHermesIdentity?.instanceId ?? null,
|
||||
}) && createdHermesIdentity?.persisted === true;
|
||||
const nextMap = {
|
||||
...settings.providerInstances,
|
||||
[brandedId]: nextInstance,
|
||||
@@ -277,6 +422,12 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
if (environmentId === null) {
|
||||
throw new Error("Connect this browser to a T3 server before pairing Hermes.");
|
||||
}
|
||||
// The server rejects `create-enrollment` unless the instance already
|
||||
// exists in `providerInstances` with the Hermes driver, so the write
|
||||
// genuinely has to come first. Instead of enroll-first, the write is
|
||||
// registered as a pending rollback that the failure path — and the
|
||||
// close/unmount effects — undo, so a failed enrollment never leaves a
|
||||
// visible `instance-not-found` orphan in the model picker.
|
||||
if (!isOwnedHermesRetry) {
|
||||
const settingsResult = await updateServerSettings({
|
||||
environmentId,
|
||||
@@ -285,9 +436,11 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
if (settingsResult._tag === "Failure") {
|
||||
throw squashAtomCommandFailure(settingsResult);
|
||||
}
|
||||
pendingRollbackRef.current = { instanceId, written: nextInstance };
|
||||
setCreatedHermesIdentity({
|
||||
instanceId,
|
||||
nickname: label.trim(),
|
||||
persisted: true,
|
||||
});
|
||||
}
|
||||
const enrollmentResult = await createHermesEnrollment({
|
||||
@@ -300,12 +453,24 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
});
|
||||
if (enrollmentResult._tag === "Failure") {
|
||||
const enrollmentError = squashAtomCommandFailure(enrollmentResult);
|
||||
// The server already deleted the tombstoned instance itself, so
|
||||
// there is nothing left for us to roll back — just rotate the nonce
|
||||
// so the next attempt uses a fresh, untainted id.
|
||||
if (isHermesInstanceRemovedError(enrollmentError)) {
|
||||
pendingRollbackRef.current = null;
|
||||
setCreatedHermesIdentity(null);
|
||||
setHermesIdentityNonce(randomUUID());
|
||||
} else {
|
||||
await rollbackPendingHermesInstance();
|
||||
setCreatedHermesIdentity((current) =>
|
||||
current ? { ...current, persisted: false } : current,
|
||||
);
|
||||
}
|
||||
throw enrollmentError;
|
||||
}
|
||||
// Enrollment succeeded: the instance is legitimately persisted now.
|
||||
pendingRollbackRef.current = null;
|
||||
setHermesConnectionState(null);
|
||||
setHermesEnrollment(enrollmentResult.value);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -336,6 +501,50 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Mint a replacement one-time command for the instance already persisted by
|
||||
* this dialog session. The instance itself is untouched, so there is nothing
|
||||
* to roll back here — only the expired/revoked token is replaced.
|
||||
*/
|
||||
const handleRegenerateEnrollment = async () => {
|
||||
const identity = createdHermesIdentity;
|
||||
if (identity === null || environmentId === null) return;
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setSaveError(null);
|
||||
const enrollmentResult = await createHermesEnrollment({
|
||||
environmentId,
|
||||
input: {
|
||||
instanceId: ProviderInstanceId.make(identity.instanceId),
|
||||
nickname: identity.nickname,
|
||||
connectorUrl: hermesConnectorUrl,
|
||||
},
|
||||
});
|
||||
if (enrollmentResult._tag === "Failure") {
|
||||
const enrollmentError = squashAtomCommandFailure(enrollmentResult);
|
||||
if (isHermesInstanceRemovedError(enrollmentError)) {
|
||||
setCreatedHermesIdentity(null);
|
||||
setHermesIdentityNonce(randomUUID());
|
||||
setHermesEnrollment(null);
|
||||
}
|
||||
throw enrollmentError;
|
||||
}
|
||||
setHermesConnectionState(null);
|
||||
setHermesEnrollment(enrollmentResult.value);
|
||||
setNowMillis(Date.now());
|
||||
} catch (error) {
|
||||
const message = messageFromUnknownError(error);
|
||||
setSaveError(message);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not create a new Hermes command",
|
||||
description: message,
|
||||
});
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPopup className="max-w-xl overflow-hidden">
|
||||
@@ -360,29 +569,137 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
data-slot="dialog-panel"
|
||||
className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"
|
||||
>
|
||||
{hermesEnrollment ? (
|
||||
<div className="grid gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">Connect Hermes</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This one-time command expires{" "}
|
||||
{formatHermesLastConnected(hermesEnrollment.expiresAt)}.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded bg-muted px-2 py-2 text-[11px]">
|
||||
{hermesEnrollment.command}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
onClick={() => copyToClipboard(hermesEnrollment.command, undefined)}
|
||||
aria-label="Copy Hermes enrollment command"
|
||||
{hermesEnrollment && hermesWaitingState ? (
|
||||
<div className="grid gap-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{hermesWaitingState.phase === "connected"
|
||||
? "Hermes is connected"
|
||||
: "Waiting for Hermes"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{hermesGatewayStatusGuidance(hermesWaitingState.statusLabelState)}
|
||||
</p>
|
||||
</div>
|
||||
<Badge
|
||||
variant={HERMES_BADGE_VARIANT_BY_STATUS[hermesWaitingState.statusLabelState]}
|
||||
size="sm"
|
||||
>
|
||||
{isCopied ? <CheckIcon /> : <CopyIcon />}
|
||||
</Button>
|
||||
{hermesWaitingState.isPending ? (
|
||||
<LoaderIcon className="animate-spin" />
|
||||
) : hermesWaitingState.phase === "connected" ? (
|
||||
<CheckIcon />
|
||||
) : null}
|
||||
{hermesGatewayStatusLabel(hermesWaitingState.statusLabelState)}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{hermesWaitingState.phase === "connected" ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The gateway dialled in and its persistent credential is stored on the Hermes
|
||||
host. You can close this dialog and start a thread against it.
|
||||
</p>
|
||||
) : (
|
||||
<ol className="grid gap-3">
|
||||
<li className="grid gap-1.5">
|
||||
<p className="text-xs font-medium text-foreground">
|
||||
1. Install the plugin on the Hermes host
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Run this from your T3 Code checkout on the machine running Hermes. It
|
||||
symlinks the plugin into <code>~/.hermes/plugins</code> and enables it. T3
|
||||
Code cannot do this for you — skip it only if you already installed the
|
||||
plugin there.
|
||||
</p>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded bg-muted px-2 py-2 text-[11px]">
|
||||
{HERMES_PLUGIN_INSTALL_COMMAND}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
copyInstallCommand(HERMES_PLUGIN_INSTALL_COMMAND, undefined)
|
||||
}
|
||||
aria-label="Copy Hermes plugin install command"
|
||||
>
|
||||
{isInstallCommandCopied ? <CheckIcon /> : <CopyIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<li className="grid gap-1.5">
|
||||
<p className="text-xs font-medium text-foreground">
|
||||
2. Run the one-time connect command
|
||||
</p>
|
||||
{hermesWaitingState.phase === "expired" ? (
|
||||
<p className="flex items-start gap-1.5 text-[11px] text-warning-foreground">
|
||||
<TriangleAlertIcon className="mt-px size-3.5 shrink-0" aria-hidden />
|
||||
<span>
|
||||
This command expired{" "}
|
||||
{formatHermesLastConnected(hermesEnrollment.expiresAt)}. Generate a new
|
||||
one below — the instance itself is unchanged.
|
||||
</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Expires {formatHermesLastConnected(hermesEnrollment.expiresAt)}.
|
||||
</p>
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-2",
|
||||
hermesWaitingState.needsNewCommand && "opacity-55",
|
||||
)}
|
||||
>
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded bg-muted px-2 py-2 text-[11px]">
|
||||
{hermesEnrollment.command}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
disabled={hermesWaitingState.needsNewCommand}
|
||||
onClick={() => copyToClipboard(hermesEnrollment.command, undefined)}
|
||||
aria-label="Copy Hermes enrollment command"
|
||||
>
|
||||
{isCopied ? <CheckIcon /> : <CopyIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<li className="grid gap-1.5">
|
||||
<p className="text-xs font-medium text-foreground">
|
||||
3. Restart the gateway on that host
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Run <code>hermes gateway restart</code>. This step is required — the plugin
|
||||
only dials T3 Code after the restart, so nothing is wrong while this panel
|
||||
still says {hermesGatewayStatusLabel(hermesWaitingState.statusLabelState)}.
|
||||
This page updates itself the moment Hermes connects.
|
||||
</p>
|
||||
</li>
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{hermesWaitingState.needsNewCommand ? (
|
||||
<div>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={isSaving || environmentId === null}
|
||||
onClick={() => void handleRegenerateEnrollment()}
|
||||
>
|
||||
{isSaving ? <LoaderIcon className="animate-spin" /> : null}
|
||||
Generate a new command
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{saveError ? <p className="text-xs text-destructive">{saveError}</p> : null}
|
||||
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
The persistent gateway credential is delivered directly to the plugin and is never
|
||||
shown in T3 Code.
|
||||
@@ -577,8 +894,9 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
{saveError ? <p className="text-xs text-destructive">{saveError}</p> : null}
|
||||
{createdHermesIdentity ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The Hermes instance was added. Retry enrollment for this exact instance, or
|
||||
close this dialog and finish pairing from its Settings card.
|
||||
{createdHermesIdentity.persisted
|
||||
? "The Hermes instance was added. Retry enrollment for this exact instance, or close this dialog and finish pairing from its Settings card."
|
||||
: "Nothing was left behind — the half-created instance was removed. Retry to create it again with the same identity."}
|
||||
</p>
|
||||
) : null}
|
||||
</AnimatedHeight>
|
||||
@@ -587,8 +905,12 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
|
||||
<DialogFooter variant="bare">
|
||||
{hermesEnrollment ? (
|
||||
<Button size="sm" onClick={() => onOpenChange(false)}>
|
||||
Done
|
||||
<Button
|
||||
size="sm"
|
||||
variant={hermesWaitingState?.phase === "connected" ? "default" : "outline"}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{hermesWaitingState?.phase === "connected" ? "Done" : "Close and keep waiting"}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
|
||||
@@ -5,7 +5,10 @@ import {
|
||||
defaultHermesConnectorUrl,
|
||||
formatHermesLastConnected,
|
||||
hermesGatewayLifecycleAction,
|
||||
hermesGatewayProviderSignal,
|
||||
hermesGatewayStatusGuidance,
|
||||
hermesGatewayStatusLabel,
|
||||
isHermesEnrollmentExpired,
|
||||
isHermesInstanceNotFoundError,
|
||||
messageFromUnknownError,
|
||||
shouldApplyHermesConnectorStatusUrl,
|
||||
@@ -64,3 +67,84 @@ describe("Hermes gateway settings logic", () => {
|
||||
expect(shouldApplyHermesConnectorStatusUrl(true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes waiting-state helpers", () => {
|
||||
it("tells the user the restart is expected rather than reporting a bare status", () => {
|
||||
expect(hermesGatewayStatusGuidance("offline")).toContain("hermes gateway restart");
|
||||
expect(hermesGatewayStatusGuidance("connected")).toContain("connected");
|
||||
});
|
||||
|
||||
it("makes upgrade-required actionable by naming the plugin reinstall", () => {
|
||||
const guidance = hermesGatewayStatusGuidance("upgrade-required");
|
||||
expect(guidance).toContain("plugin");
|
||||
expect(guidance).toContain("install script");
|
||||
});
|
||||
|
||||
it("points a revoked gateway at a new pairing command", () => {
|
||||
expect(hermesGatewayStatusGuidance("revoked")).toContain("new command");
|
||||
});
|
||||
|
||||
it("expires a one-time token at its deadline but trusts the server on garbage input", () => {
|
||||
const expiresAt = "2026-07-24T12:00:00.000Z";
|
||||
const expiryMillis = Date.parse(expiresAt);
|
||||
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis - 1)).toBe(false);
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis)).toBe(true);
|
||||
expect(isHermesEnrollmentExpired(expiresAt, expiryMillis + 60_000)).toBe(true);
|
||||
expect(isHermesEnrollmentExpired("not-a-date", expiryMillis)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hermesGatewayProviderSignal", () => {
|
||||
const provider = (
|
||||
instanceId: string,
|
||||
status: "authenticated" | "unauthenticated",
|
||||
checkedAt = "2026-07-24T12:00:00.000Z",
|
||||
) =>
|
||||
({
|
||||
instanceId,
|
||||
driver: "hermes",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status, type: "gateway", label: "Hermes" },
|
||||
checkedAt,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
}) as never;
|
||||
|
||||
it("reports a connected gateway from the pushed provider snapshot", () => {
|
||||
expect(
|
||||
hermesGatewayProviderSignal([provider("hermes-a", "authenticated")], "hermes-a"),
|
||||
).toEqual({ present: true, connected: true, revision: "2026-07-24T12:00:00.000Z" });
|
||||
});
|
||||
|
||||
it("distinguishes an enrolled-but-not-yet-dialled-in gateway from a missing one", () => {
|
||||
expect(
|
||||
hermesGatewayProviderSignal([provider("hermes-a", "unauthenticated")], "hermes-a"),
|
||||
).toEqual({ present: true, connected: false, revision: "2026-07-24T12:00:00.000Z" });
|
||||
expect(hermesGatewayProviderSignal([], "hermes-a")).toEqual({
|
||||
present: false,
|
||||
connected: false,
|
||||
revision: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("changes revision when a republished snapshot leaves the connected flag untouched", () => {
|
||||
// An `upgrade-required` transition closes the connection, so `connected`
|
||||
// stays false across the republish; only `revision` moves.
|
||||
const before = hermesGatewayProviderSignal(
|
||||
[provider("hermes-a", "unauthenticated")],
|
||||
"hermes-a",
|
||||
);
|
||||
const after = hermesGatewayProviderSignal(
|
||||
[provider("hermes-a", "unauthenticated", "2026-07-24T12:05:00.000Z")],
|
||||
"hermes-a",
|
||||
);
|
||||
|
||||
expect(after.connected).toBe(before.connected);
|
||||
expect(after.revision).not.toBe(before.revision);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HermesGatewayConnectionState } from "@t3tools/contracts";
|
||||
import type { HermesGatewayConnectionState, ServerProvider } from "@t3tools/contracts";
|
||||
|
||||
export const HERMES_GATEWAY_SOCKET_PATH = "/api/hermes-gateway/ws";
|
||||
|
||||
@@ -25,10 +25,68 @@ export function hermesGatewayStatusLabel(status: HermesGatewayConnectionState):
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Actionable follow-up for each connection state.
|
||||
*
|
||||
* `upgrade-required` in particular is not a transient condition: the plugin
|
||||
* negotiated an incompatible protocol version and the connection was closed,
|
||||
* so the user has to reinstall the plugin rather than wait.
|
||||
*/
|
||||
export function hermesGatewayStatusGuidance(status: HermesGatewayConnectionState): string {
|
||||
switch (status) {
|
||||
case "connected":
|
||||
return "Hermes is connected. You can start sending it messages.";
|
||||
case "connecting":
|
||||
return "Hermes is completing its handshake with T3 Code.";
|
||||
case "upgrade-required":
|
||||
return "This Hermes host runs an incompatible T3 Code gateway plugin. Re-run the install script on that host to update the plugin, then run 'hermes gateway restart'.";
|
||||
case "revoked":
|
||||
return "This gateway's credential was revoked. Generate a new command to pair it again.";
|
||||
case "offline":
|
||||
return "Hermes has not dialled in yet. Run the command on the Hermes host, then run 'hermes gateway restart'.";
|
||||
}
|
||||
}
|
||||
|
||||
export function canRemoveHermesGatewayInstance(status: HermesGatewayConnectionState): boolean {
|
||||
return status === "revoked";
|
||||
}
|
||||
|
||||
/**
|
||||
* Coarse liveness read of a Hermes instance taken from the server-pushed
|
||||
* provider snapshot.
|
||||
*
|
||||
* `ServerProvider` already streams to every client over `subscribeServerConfig`
|
||||
* whenever the broker publishes a gateway status change, so surfaces that only
|
||||
* need "has Hermes dialled in yet?" can flip off it without polling. The
|
||||
* snapshot deliberately does not carry the full `HermesGatewayConnectionState`,
|
||||
* so callers that need `upgrade-required` / `revoked` still read the
|
||||
* authoritative status once this signal changes.
|
||||
*/
|
||||
export interface HermesGatewayProviderSignal {
|
||||
readonly present: boolean;
|
||||
readonly connected: boolean;
|
||||
/**
|
||||
* Changes on every republished snapshot, including ones whose connected flag
|
||||
* is unchanged. `upgrade-required` closes the connection, so it looks
|
||||
* identical to "still offline" through `connected` alone — watching this
|
||||
* instead means such a transition still triggers an authoritative re-read.
|
||||
*/
|
||||
readonly revision: string | null;
|
||||
}
|
||||
|
||||
export function hermesGatewayProviderSignal(
|
||||
providers: readonly ServerProvider[],
|
||||
instanceId: string,
|
||||
): HermesGatewayProviderSignal {
|
||||
const provider = providers.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (provider === undefined) return { present: false, connected: false, revision: null };
|
||||
return {
|
||||
present: true,
|
||||
connected: provider.auth.status === "authenticated",
|
||||
revision: provider.checkedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function isHermesInstanceNotFoundError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
@@ -52,6 +110,19 @@ export function formatHermesLastConnected(value: string | null): string {
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a one-time enrollment token has aged out.
|
||||
*
|
||||
* An unparseable timestamp is treated as still valid: the server is the real
|
||||
* authority on expiry, and refusing to show a command the user may well be
|
||||
* able to run would be worse than letting the paste fail loudly.
|
||||
*/
|
||||
export function isHermesEnrollmentExpired(expiresAt: string, nowMillis: number): boolean {
|
||||
const expiryMillis = new Date(expiresAt).getTime();
|
||||
if (Number.isNaN(expiryMillis)) return false;
|
||||
return expiryMillis <= nowMillis;
|
||||
}
|
||||
|
||||
export function messageFromUnknownError(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
if (
|
||||
|
||||
Reference in new issue
Block a user