feat: give every Hermes instance a Home thread for proactive delivery

Hermes has a first-class "home channel": the default destination for output
nobody asked for at a specific address — a cron result, an agent-initiated
`send_message`, a gateway lifecycle notice, a `/handoff`. The T3 plugin opted
out, suppressing Hermes' "Type /sethome" nudge without designating anything.
A cron job with `deliver=t3` went nowhere, `send_message` to a bare `t3`
target errored, and `/handoff t3` hard-failed.

Each enrolled instance now gets one Home thread, pinned first in its agent
project, fully conversational, undeletable, created automatically.

Protocol v3. `connection.hello` gains `role: "gateway" | "delivery"`;
`connection.accepted` carries `homeThreadId`. Two new frames: `home.deliver`
and `home.deliver.ack`.

Designation converges on read, like agent projects — a precondition every
handshake runs rather than an event one caller owns, so an instance enrolled
before this shipped, or one whose thread creation failed once, heals on the
next connect. It lives in the instance's settings blob beside `connectorUrl`
and `revoked`; the plugin's `T3_HOME_CHANNEL` is a cache of it, reconciled
every handshake.

The existence check deliberately ignores archive state. Every other thread
read filters `archived_at IS NULL`, which is right for "what should the user
see" and wrong for "does this row exist" — an archived Home read as deleted
and the self-healing path replaced it, stranding the history in a thread the
user had merely parked. A delivery to an archived Home now un-archives it,
the same way incoming activity wakes a settled or snoozed thread.

Deliveries bypass the turn machinery entirely. One may arrive while the home
thread has a live user turn, so it appends as a turnless assistant message
carrying `notification` provenance rather than joining the turn — attributing
it would fold it away behind that turn's "Worked for …". Everything except a
lifecycle notice un-settles the thread and pushes; lifecycle notices land
quietly.

Idempotency is load-bearing, because the plugin's durable queue retries
anything it has not seen acked. T3 dedupes on `deliveryId` against
`projection_thread_messages` before dispatching — the decider's own scan sees
the in-memory read model, which is built with `messages: []`, so it cannot
catch a replay after a restart. The ack is sent only after the write lands.

An out-of-process cron run dials in with `role: "delivery"`: authenticated
identically, but never registered as the instance's primary connection, so it
cannot displace a live gateway socket or answer its pending requests.

Plugin side, the proactive branch in `send()` gates on provenance rather than
turn absence. The naive rule — "no active turn, so deliver" — would let a
notify-stamped cron delivery complete a user's live turn with cron output as
its answer. A bare session-key mismatch is not enough either, since
`HERMES_SESSION_KEY` resolves empty whenever the context did not propagate;
that would tear a genuine reply out of its turn. Bypassing a live turn
requires positively identified cron/lifecycle/handoff provenance.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Ben DavisandClaude Opus 5 committed 2026-07-26 13:10:35 -07:00
1 parent 5bfb90db61
commit 784fcb71e6
73 files changed
+5907 -119

No files matched your search

@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
import {
archiveSelectedThreadEntries,
buildAgentSidebarEntries,
buildHomeThreadIdByProjectKey,
buildMultiSelectThreadContextMenuItems,
createThreadJumpHintVisibilityController,
formatAgentSidebarLabel,
@@ -42,6 +43,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { sortThreads, type ThreadSortInput } from "../lib/threadSort";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -1557,4 +1559,151 @@ describe("agents sidebar section", () => {
expect(entries).toHaveLength(1);
expect(entries[0]?.instanceId).toBe(instanceId);
});
it("carries the provider's designated home thread onto the entry", () => {
const entries = buildAgentSidebarEntries({
projects: [makeAgentProject()],
providerByInstanceId: new Map([
[String(instanceId), makeServerProvider({ homeThreadId: "thread-home" as never })],
]),
});
expect(entries[0]?.homeThreadId).toBe("thread-home");
});
it("reports no home thread for a driver that designates none", () => {
// Every non-Hermes driver, and a Hermes instance before its first
// handshake — both must read as "this list has no pinned row".
const entries = buildAgentSidebarEntries({
projects: [makeAgentProject()],
providerByInstanceId: new Map([[String(instanceId), makeServerProvider()]]),
});
expect(entries[0]?.homeThreadId).toBeNull();
});
});
describe("buildHomeThreadIdByProjectKey", () => {
function makeEntry(input: {
readonly instanceId: string;
readonly projectKey: string;
readonly homeThreadId: string | null;
}) {
return {
instanceId: input.instanceId as never,
project: {
agentInstanceId: input.instanceId as never,
title: input.instanceId,
displayName: input.instanceId,
projectKey: input.projectKey,
},
label: input.instanceId,
statusKey: "ready" as const,
statusLabel: "Connected",
statusPulse: false,
homeThreadId: input.homeThreadId as never,
};
}
it("maps each agent's project key to its home thread", () => {
const map = buildHomeThreadIdByProjectKey([
makeEntry({ instanceId: "hermes-a", projectKey: "project-a", homeThreadId: "thread-home-a" }),
makeEntry({ instanceId: "hermes-b", projectKey: "project-b", homeThreadId: "thread-home-b" }),
]);
expect(map.get("project-a")).toBe("thread-home-a");
expect(map.get("project-b")).toBe("thread-home-b");
});
it("omits agents with no designation", () => {
const map = buildHomeThreadIdByProjectKey([
makeEntry({ instanceId: "hermes-a", projectKey: "project-a", homeThreadId: null }),
]);
expect(map.size).toBe(0);
});
it("keeps the first entry when two agents collapse onto one project key", () => {
// `visibleSidebarSections` de-duplicates by `projectKey` and keeps the
// first section, so the pin must resolve to the same one.
const map = buildHomeThreadIdByProjectKey([
makeEntry({ instanceId: "hermes-a", projectKey: "shared", homeThreadId: "thread-home-a" }),
makeEntry({ instanceId: "hermes-b", projectKey: "shared", homeThreadId: "thread-home-b" }),
]);
expect(map.get("shared")).toBe("thread-home-a");
});
});
describe("home thread pinning across both sidebar sort sites", () => {
// `SidebarProjectItem` (the rendered rows) and `visibleSidebarThreadKeys`
// (jump shortcuts, prev/next, prewarming) each call `sortThreads` with the
// same pinned id. These assert the shared helper produces one ordering, and
// that the ordering survives the prewarm slice.
function makeSortableThread(input: {
readonly id: string;
readonly updatedAt: string;
}): { id: string } & ThreadSortInput {
return {
id: input.id,
createdAt: input.updatedAt,
updatedAt: input.updatedAt,
latestUserMessageAt: input.updatedAt,
messages: [],
};
}
const threads = [
makeSortableThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }),
makeSortableThread({ id: "thread-middle", updatedAt: "2026-03-09T10:00:00.000Z" }),
// Deliberately the oldest row in the list: a home thread whose last cron
// ran a month ago must still hold position one.
makeSortableThread({ id: "thread-home", updatedAt: "2026-01-01T00:00:00.000Z" }),
];
it("sorts the home thread first even when it is the oldest", () => {
expect(sortThreads(threads, "updated_at", "thread-home").map((thread) => thread.id)).toEqual([
"thread-home",
"thread-newest",
"thread-middle",
]);
});
it("produces an identical ordering at both sort sites", () => {
const renderOrder = sortThreads(threads, "updated_at", "thread-home");
const traversalOrder = sortThreads(threads, "updated_at", "thread-home");
expect(renderOrder.map((thread) => thread.id)).toEqual(
traversalOrder.map((thread) => thread.id),
);
});
it("leaves a provider list with no designation unchanged", () => {
// Non-Hermes drivers and pre-handshake Hermes instances both land here.
expect(sortThreads(threads, "updated_at", null).map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-middle",
"thread-home",
]);
expect(sortThreads(threads, "updated_at").map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-middle",
"thread-home",
]);
});
it("ignores a pinned id that matches no thread", () => {
expect(sortThreads(threads, "updated_at", "thread-gone").map((thread) => thread.id)).toEqual([
"thread-newest",
"thread-middle",
"thread-home",
]);
});
it("puts the home thread in the prewarm slice even when the limit is one", () => {
// Pinning happens before the prewarm slice, so Home is always warm.
const ordered = sortThreads(threads, "updated_at", "thread-home").map((thread) => thread.id);
expect(getSidebarThreadIdsToPrewarm(ordered, 1)).toEqual(["thread-home"]);
});
});
+42 -1
View File
@@ -1,5 +1,10 @@
import * as React from "react";
import type { ContextMenuItem, ProviderInstanceId, ServerProvider } from "@t3tools/contracts";
import type {
ContextMenuItem,
ProviderInstanceId,
ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { ProviderStatusKey } from "./settings/providerStatus";
import {
@@ -879,6 +884,39 @@ export interface AgentSidebarEntry<TProject extends AgentSidebarProjectInput> {
readonly statusLabel: string;
/** True while the instance is mid-handshake, so the dot can pulse. */
readonly statusPulse: boolean;
/**
* The instance's home thread, pinned first in its thread list and withheld
* from Delete.
*
* `null` for every driver that designates none, and for a Hermes instance
* whose first handshake has not landed — both mean "this list has no pinned
* row", which is the same rendering.
*/
readonly homeThreadId: ThreadId | null;
}
/**
* Home thread per sidebar section key.
*
* The two thread-ordering sites (the rendered project row and the flat
* `visibleSidebarThreadKeys` used by jump shortcuts, prev/next, and
* prewarming) both need this, and they MUST agree — a section whose visual
* order differs from the traversal order desyncs the keyboard from the eye.
* One map derived once is what keeps them honest.
*/
export function buildHomeThreadIdByProjectKey<
TProject extends AgentSidebarProjectInput & { readonly projectKey: string },
>(entries: ReadonlyArray<AgentSidebarEntry<TProject>>): ReadonlyMap<string, ThreadId> {
const byProjectKey = new Map<string, ThreadId>();
for (const entry of entries) {
if (entry.homeThreadId === null) continue;
// First writer wins: `visibleSidebarSections` de-duplicates by
// `projectKey`, keeping the first section for a key, so the pin has to
// resolve to that same one.
if (byProjectKey.has(entry.project.projectKey)) continue;
byProjectKey.set(entry.project.projectKey, entry.homeThreadId);
}
return byProjectKey;
}
const AGENT_STATUS_LABELS: Record<ProviderStatusKey, string> = {
@@ -960,6 +998,9 @@ export function buildAgentSidebarEntries<TProject extends AgentSidebarProjectInp
statusKey,
statusLabel: AGENT_STATUS_LABELS[statusKey],
statusPulse: statusKey === "warning" && provider?.auth.status === "unauthenticated",
// Re-emitted on every provider status tick, so a designation made after
// the sidebar mounted pins on the next push without a refetch.
homeThreadId: provider?.homeThreadId ?? null,
});
}
+58 -2
View File
@@ -6,6 +6,7 @@ import {
ContainerIcon,
FolderPlusIcon,
Globe2Icon,
HouseIcon,
LoaderIcon,
SearchIcon,
SquarePenIcon,
@@ -174,6 +175,7 @@ import { openCommandPalette } from "../commandPaletteBus";
import {
archiveSelectedThreadEntries,
buildAgentSidebarEntries,
buildHomeThreadIdByProjectKey,
buildMultiSelectThreadContextMenuItems,
type AgentSidebarEntry,
getSidebarThreadIdsToPrewarm,
@@ -312,6 +314,11 @@ interface SidebarThreadRowProps {
projectCwd: string | null;
orderedProjectThreadKeys: readonly string[];
isActive: boolean;
/**
* The agent's home thread. Pinned first and marked with a small leading
* icon; the title stays the plain thread title ("Home"), no emoji.
*/
isHomeThread: boolean;
jumpLabel: string | null;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
@@ -349,6 +356,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
const {
orderedProjectThreadKeys,
isActive,
isHomeThread,
jumpLabel,
appSettingsConfirmThreadArchive,
renamingThreadKey,
@@ -705,6 +713,28 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{/* Restrained: one muted leading glyph, no emoji and no badge. The
row is a normal thread in every other respect — the mark only
explains why it never moves out of first position. */}
{isHomeThread && (
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label="Home thread"
data-testid={`thread-home-marker-${thread.id}`}
className="inline-flex shrink-0 items-center justify-center text-sidebar-muted-foreground/70"
/>
}
>
<HouseIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
Home thread — this agent&rsquo;s proactive messages land here
</TooltipPopup>
</Tooltip>
)}
{renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
@@ -890,6 +920,8 @@ interface SidebarProjectThreadListProps {
hiddenThreadStatus: ThreadStatusPill | null;
orderedProjectThreadKeys: readonly string[];
renderedThreads: readonly SidebarThreadSummary[];
/** Agent's home thread, or `null` for a workspace row. */
homeThreadId: ThreadId | null;
showEmptyThreadState: boolean;
shouldShowThreadPanel: boolean;
isThreadListExpanded: boolean;
@@ -941,6 +973,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
hiddenThreadStatus,
orderedProjectThreadKeys,
renderedThreads,
homeThreadId,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
@@ -998,6 +1031,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
projectCwd={projectCwd}
orderedProjectThreadKeys={orderedProjectThreadKeys}
isActive={activeRouteThreadKey === threadKey}
isHomeThread={homeThreadId !== null && thread.id === homeThreadId}
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
@@ -1179,6 +1213,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
},
});
const openPrLink = useOpenPrLink();
// The agent's designated home thread. Pinned first, and Delete is withheld
// from it (the server rejects the delete regardless — the UI just must not
// offer an action that always fails). `null` for workspace rows and for an
// agent that has not completed a handshake.
const homeThreadId = agent?.homeThreadId ?? null;
const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
const sidebarThreadByKey = useMemo(
() =>
@@ -1272,6 +1311,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const visibleProjectThreads = sortThreads(
projectThreads.filter((thread) => thread.archivedAt === null),
threadSortOrder,
homeThreadId,
);
const projectStatus = resolveProjectStatusIndicator(
visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)),
@@ -1283,7 +1323,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
projectStatus,
visibleProjectThreads,
};
}, [projectThreads, threadLastVisitedAts, threadSortOrder]);
}, [homeThreadId, projectThreads, threadLastVisitedAts, threadSortOrder]);
const pinnedCollapsedThread = useMemo(() => {
const activeThreadKey = activeRouteThreadKey ?? undefined;
if (!activeThreadKey || projectExpanded) {
@@ -2157,6 +2197,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const threadWorkspacePath =
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
// The agent's home thread is undeletable — the server's decider rejects
// it, so offering the action would only ever produce an error toast.
const isHomeThread = homeThreadId !== null && thread.id === homeThreadId;
const clicked = await api.contextMenu.show(
[
...(thread.branch
@@ -2166,7 +2209,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
...(isHomeThread
? []
: [{ id: "delete", label: "Delete", destructive: true, icon: "trash" } as const]),
],
position,
);
@@ -2252,6 +2297,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
homeThreadId,
markThreadUnread,
memberProjectByScopedKey,
project.workspaceRoot,
@@ -2438,6 +2484,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
hiddenThreadStatus={hiddenThreadStatus}
orderedProjectThreadKeys={orderedProjectThreadKeys}
renderedThreads={renderedThreads}
homeThreadId={homeThreadId}
showEmptyThreadState={showEmptyThreadState}
shouldShowThreadPanel={shouldShowThreadPanel}
isThreadListExpanded={isThreadListExpanded}
@@ -3571,6 +3618,13 @@ export default function Sidebar() {
}
return sections;
}, [agentEntries, sortedProjects]);
// Same pin the rendered rows use (`SidebarProjectItem`), keyed the same way.
// These two orderings are the visual list and the traversal list; if they
// disagree, thread-jump numbers land on the wrong row.
const homeThreadIdByProjectKey = useMemo(
() => buildHomeThreadIdByProjectKey(agentEntries),
[agentEntries],
);
const visibleSidebarThreadKeys = useMemo(
() =>
visibleSidebarSections.flatMap((project) => {
@@ -3579,6 +3633,7 @@ export default function Sidebar() {
(thread) => thread.archivedAt === null,
),
sidebarThreadSortOrder,
homeThreadIdByProjectKey.get(project.projectKey) ?? null,
);
const projectExpanded = resolveProjectExpanded(
projectExpandedById,
@@ -3609,6 +3664,7 @@ export default function Sidebar() {
);
}),
[
homeThreadIdByProjectKey,
sidebarThreadSortOrder,
sidebarThreadPreviewCount,
expandedThreadListsByProject,
@@ -1,6 +1,7 @@
import type {
ProviderInstanceDescription,
ProviderInstanceId,
ServerProvider,
ServerProviderSkill,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -25,8 +26,10 @@ import {
isAgentPageBusy,
messageFromAgentPageError,
nextExpandedSkillName,
resolveAgentHomeThreadId,
resolveAgentRouteInstanceId,
shouldFetchAgentSkillBody,
sortAgentPageThreads,
supportsGatewayReconnect,
upsertAgentSkillBody,
type AgentConnectionStatus,
@@ -334,3 +337,101 @@ describe("resolveAgentRouteInstanceId", () => {
expect(resolveAgentRouteInstanceId({ instanceId: " " })).toBe(null);
});
});
describe("agent thread list", () => {
function makeProvider(overrides: Partial<ServerProvider> = {}): ServerProvider {
return {
instanceId: "hermes-main" as ProviderInstanceId,
driver: "hermes",
displayName: "Hermes · Main",
enabled: true,
installed: true,
version: null,
status: "ready",
auth: { status: "authenticated", type: "gateway" },
checkedAt: "2026-03-09T10:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
...overrides,
} as ServerProvider;
}
function makeThread(input: {
readonly id: string;
readonly updatedAt: string;
readonly archivedAt?: string | null;
}) {
return {
id: input.id,
createdAt: input.updatedAt,
updatedAt: input.updatedAt,
latestUserMessageAt: input.updatedAt,
messages: [],
archivedAt: input.archivedAt ?? null,
};
}
const threads = [
makeThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }),
makeThread({ id: "thread-middle", updatedAt: "2026-03-09T10:00:00.000Z" }),
makeThread({ id: "thread-home", updatedAt: "2026-01-01T00:00:00.000Z" }),
];
it("reads the designation off the matching provider snapshot", () => {
expect(
resolveAgentHomeThreadId(
[makeProvider({ homeThreadId: "thread-home" as never })],
"hermes-main" as ProviderInstanceId,
),
).toBe("thread-home");
});
it("reports no designation for an undesignated or absent provider", () => {
expect(resolveAgentHomeThreadId([makeProvider()], "hermes-main" as ProviderInstanceId)).toBe(
null,
);
expect(resolveAgentHomeThreadId([], "hermes-main" as ProviderInstanceId)).toBe(null);
expect(
resolveAgentHomeThreadId(
[makeProvider({ homeThreadId: "thread-home" as never })],
"hermes-other" as ProviderInstanceId,
),
).toBe(null);
});
it("pins the home thread first even when it is the oldest", () => {
expect(
sortAgentPageThreads({
threads,
sortOrder: "updated_at",
homeThreadId: "thread-home" as never,
}).map((thread) => thread.id),
).toEqual(["thread-home", "thread-newest", "thread-middle"]);
});
it("leaves an undesignated agent's list in plain recency order", () => {
expect(
sortAgentPageThreads({ threads, sortOrder: "updated_at", homeThreadId: null }).map(
(thread) => thread.id,
),
).toEqual(["thread-newest", "thread-middle", "thread-home"]);
});
it("excludes archived threads", () => {
expect(
sortAgentPageThreads({
threads: [
...threads,
makeThread({
id: "thread-archived",
updatedAt: "2026-03-09T13:00:00.000Z",
archivedAt: "2026-03-09T13:30:00.000Z",
}),
],
sortOrder: "updated_at",
homeThreadId: "thread-home" as never,
}).map((thread) => thread.id),
).toEqual(["thread-home", "thread-newest", "thread-middle"]);
});
});
@@ -2,11 +2,15 @@ import type {
ProviderInstanceConnection,
ProviderInstanceDescription,
ProviderInstanceId,
ServerProvider,
ServerProviderSkill,
ThreadId,
} from "@t3tools/contracts";
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import { getProviderVersionLabel, type ProviderStatusKey } from "../settings/providerStatus";
import { searchProviderSkills } from "../../providerSkillSearch";
import { sortThreads, type ThreadSortInput } from "../../lib/threadSort";
/**
* Placeholder for any field the driver did not report.
@@ -283,6 +287,45 @@ export function isAgentInstanceNotFoundError(error: unknown): boolean {
);
}
/**
* The instance's designated home thread, off the pushed provider snapshot.
*
* Read from `ServerProvider` rather than `ProviderInstanceDescription`: the
* snapshot is re-emitted on every status tick, so a designation made after
* the page mounted arrives without a re-describe. Absent for every non-Hermes
* driver and for a Hermes instance that has never completed a handshake —
* both are `null`, because both mean "this list has no pinned row".
*/
export function resolveAgentHomeThreadId(
providers: ReadonlyArray<ServerProvider>,
instanceId: ProviderInstanceId | string,
): ThreadId | null {
const provider = providers.find((candidate) => candidate.instanceId === instanceId);
return provider?.homeThreadId ?? null;
}
/**
* The agent's thread list for the page, home first.
*
* Archived threads are excluded for the same reason the sidebar excludes
* them — this list is "what can I open right now?", and the sort is the same
* shared `sortThreads` the sidebar uses so the two surfaces cannot disagree
* about order.
*/
export function sortAgentPageThreads<
T extends { readonly id: string; readonly archivedAt: string | null } & ThreadSortInput,
>(input: {
readonly threads: ReadonlyArray<T>;
readonly sortOrder: SidebarThreadSortOrder;
readonly homeThreadId: ThreadId | null;
}): T[] {
return sortThreads(
input.threads.filter((thread) => thread.archivedAt === null),
input.sortOrder,
input.homeThreadId,
);
}
/**
* Route param → branded instance id.
*
+156 -1
View File
@@ -1,18 +1,22 @@
"use client";
import { useAtomValue } from "@effect/atom-react";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
ProviderInstanceDescription,
ProviderInstanceId,
ServerProviderSkill,
} from "@t3tools/contracts";
import type { SidebarThreadSortOrder, TimestampFormat } from "@t3tools/contracts/settings";
import { useNavigate } from "@tanstack/react-router";
import {
ChevronRightIcon,
CpuIcon,
HouseIcon,
LoaderIcon,
MessageSquareIcon,
MessageSquarePlusIcon,
PlugZapIcon,
RefreshCwIcon,
@@ -20,19 +24,25 @@ import {
ServerIcon,
SettingsIcon,
SparklesIcon,
Trash2Icon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
import { useClientSettings } from "../../hooks/useSettings";
import { useThreadActions } from "../../hooks/useThreadActions";
import { cn } from "../../lib/utils";
import { formatProviderDriverKindLabel } from "../../providerModels";
import {
formatProviderSkillDisplayName,
formatProviderSkillInstallSource,
} from "../../providerSkillPresentation";
import { useProjects, useThreadShellsForProjectRefs } from "../../state/entities";
import { usePrimaryEnvironment } from "../../state/environments";
import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { buildThreadRouteParams } from "../../threadRoutes";
import { formatShortTimestamp } from "../../timestampFormat";
import ChatMarkdown from "../ChatMarkdown";
import { hermesGatewayProviderSignal } from "../settings/HermesGatewayInstanceSection.logic";
import { PROVIDER_STATUS_STYLES } from "../settings/providerStatus";
@@ -61,7 +71,9 @@ import {
isAgentPageBusy,
messageFromAgentPageError,
nextExpandedSkillName,
resolveAgentHomeThreadId,
shouldFetchAgentSkillBody,
sortAgentPageThreads,
supportsGatewayReconnect,
upsertAgentSkillBody,
type AgentPageAction,
@@ -173,6 +185,61 @@ function AgentSkillRow(props: {
);
}
/**
* One row in the agent's thread list.
*
* The home row gets the same restrained treatment the sidebar uses: a muted
* leading glyph and no Delete. The title is whatever the thread is called
* ("Home") — plain text, no emoji.
*/
function AgentThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly isHomeThread: boolean;
readonly timestampFormat: TimestampFormat;
readonly onOpen: (thread: EnvironmentThreadShell) => void;
readonly onDelete: ((thread: EnvironmentThreadShell) => void) | null;
}) {
const { isHomeThread, thread } = props;
return (
<div className="group/agent-thread relative flex items-center border-b border-border/50 last:border-b-0">
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2.5 text-left hover:bg-accent/40"
data-testid={`agent-thread-row-${thread.id}`}
onClick={() => props.onOpen(thread)}
>
{isHomeThread ? (
<HouseIcon
aria-label="Home thread"
className="size-3.5 shrink-0 text-muted-foreground/70"
/>
) : (
<MessageSquareIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground/40" />
)}
<span className="min-w-0 flex-1 truncate text-sm text-foreground" title={thread.title}>
{thread.title}
</span>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
{formatShortTimestamp(thread.updatedAt, props.timestampFormat)}
</span>
</button>
{/* Withheld for the home thread: the server's decider rejects the
delete, so the button could only ever produce an error. */}
{props.onDelete && !isHomeThread ? (
<button
type="button"
aria-label={`Delete ${thread.title}`}
data-testid={`agent-thread-delete-${thread.id}`}
className="mr-1.5 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/12 hover:text-destructive focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover/agent-thread:opacity-100"
onClick={() => props.onDelete?.(thread)}
>
<Trash2Icon className="size-3.5" />
</button>
) : null}
</div>
);
}
export function AgentPage({ instanceId }: { readonly instanceId: ProviderInstanceId }) {
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
const navigate = useNavigate();
@@ -194,6 +261,7 @@ export function AgentPage({ instanceId }: { readonly instanceId: ProviderInstanc
const getGatewayStatus = useAtomCommand(serverEnvironment.hermesGatewayGetInstanceStatus, {
reportFailure: false,
});
const { deleteThread } = useThreadActions();
const [description, setDescription] = useState<ProviderInstanceDescription | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -323,6 +391,62 @@ export function AgentPage({ instanceId }: { readonly instanceId: ProviderInstanc
})();
};
// Threads come off the same shell projection every other surface reads —
// the sidebar, the command palette — rather than a page-local fetch, so the
// list repaints live as the agent works and never disagrees with the
// sidebar's copy of the same rows. The agent's synthetic project is found by
// its `agentInstanceId` discriminator, which is exactly how the sidebar
// recognizes an agent row.
const projects = useProjects();
const agentProjectRefs = useMemo(
() =>
projects
.filter((project) => project.agentInstanceId === instanceId)
.map((project) => scopeProjectRef(project.environmentId, project.id)),
[instanceId, projects],
);
const agentThreads = useThreadShellsForProjectRefs(agentProjectRefs);
const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
(settings) => settings.sidebarThreadSortOrder,
);
const timestampFormat = useClientSettings<TimestampFormat>(
(settings) => settings.timestampFormat,
);
const homeThreadId = useMemo(
() => resolveAgentHomeThreadId(providers, instanceId),
[instanceId, providers],
);
const visibleThreads = useMemo(
() => sortAgentPageThreads({ threads: agentThreads, sortOrder: threadSortOrder, homeThreadId }),
[agentThreads, homeThreadId, threadSortOrder],
);
const handleOpenThread = useCallback(
(thread: EnvironmentThreadShell) => {
void navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
});
},
[navigate],
);
const handleDeleteThread = useCallback(
(thread: EnvironmentThreadShell) => {
void (async () => {
const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id));
if (result._tag === "Failure") {
const failure = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: "Failed to delete thread",
description: messageFromAgentPageError(failure),
});
}
})();
},
[deleteThread],
);
const status = description?.connection.status ?? "offline";
const isBusy = isAgentPageBusy(pendingAction);
const title = agentPageTitle(description, instanceId);
@@ -580,6 +704,37 @@ export function AgentPage({ instanceId }: { readonly instanceId: ProviderInstanc
</SectionCard>
</SettingsSection>
<SettingsSection
title="Threads"
icon={<MessageSquareIcon className="size-4" />}
headerAction={
visibleThreads.length > 0 ? (
<span className="text-xs text-muted-foreground">{visibleThreads.length}</span>
) : null
}
>
<SectionCard>
{visibleThreads.length === 0 ? (
<p className="text-xs text-muted-foreground/70 italic">
No threads yet. Start one with “New thread” above.
</p>
) : (
<div className="min-w-0 rounded-lg border border-border/60 bg-background/60">
{visibleThreads.map((thread) => (
<AgentThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
isHomeThread={homeThreadId !== null && thread.id === homeThreadId}
timestampFormat={timestampFormat}
onOpen={handleOpenThread}
onDelete={handleDeleteThread}
/>
))}
</div>
)}
</SectionCard>
</SettingsSection>
<SettingsSection title="MCP servers" icon={<ServerIcon className="size-4" />}>
<SectionCard>
<p className="text-xs text-muted-foreground/70 italic">
@@ -39,6 +39,7 @@ import {
} from "../../lib/diffRendering";
import ChatMarkdown from "../ChatMarkdown";
import {
BellIcon,
BotIcon,
CheckIcon,
ChevronDownIcon,
@@ -81,6 +82,10 @@ import {
TIMELINE_MINIMAP_MIN_ITEMS,
type TimelineLatestTurn,
} from "./MessagesTimeline.logic";
import {
resolveNotificationBadge,
type NotificationBadgePresentation,
} from "./notificationBadge.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
@@ -1015,13 +1020,39 @@ function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-
);
}
/**
* Provenance chip above a proactive agent delivery.
*
* Deliberately not a status pill: it is inline, unpadded on the left, and
* sits in the message's own column so the body below reads as the same
* assistant message it would have been without it.
*/
function NotificationBadge({ badge }: { badge: NotificationBadgePresentation }) {
return (
<div
className={cn(
"mb-1 inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide",
badge.muted
? "bg-muted/50 text-muted-foreground/80"
: "bg-accent/60 text-accent-foreground",
)}
data-notification-badge
>
<BellIcon className="size-3 opacity-70" />
<span className="min-w-0 truncate normal-case tracking-normal">{badge.label}</span>
</div>
);
}
function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
const notificationBadge = resolveNotificationBadge(row.message.notification);
return (
<>
<div className="relative min-w-0 px-1 py-0.5">
{notificationBadge ? <NotificationBadge badge={notificationBadge} /> : null}
<ChatMarkdown
text={messageText}
cwd={ctx.markdownCwd}
@@ -0,0 +1,63 @@
import type { OrchestrationMessageNotification } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveNotificationBadge } from "./notificationBadge.logic";
function makeNotification(
overrides: Partial<OrchestrationMessageNotification> = {},
): OrchestrationMessageNotification {
return {
kind: "cron",
label: "daily-digest",
deliveryId: "delivery-1",
...overrides,
} as OrchestrationMessageNotification;
}
describe("resolveNotificationBadge", () => {
it("renders no badge for an ordinary assistant message", () => {
// The overwhelmingly common case — a reply to a turn the user started.
expect(resolveNotificationBadge(undefined)).toBe(null);
});
it("joins the kind and the label for a cron delivery", () => {
expect(resolveNotificationBadge(makeNotification())).toEqual({
label: "Cron · daily-digest",
muted: false,
});
});
it("labels an agent-initiated send as Agent, not Message", () => {
expect(
resolveNotificationBadge(makeNotification({ kind: "message", label: "check-in" })),
).toEqual({ label: "Agent · check-in", muted: false });
});
it("mutes lifecycle notices", () => {
expect(
resolveNotificationBadge(makeNotification({ kind: "lifecycle", label: "gateway online" })),
).toEqual({ label: "Gateway · gateway online", muted: true });
});
it("keeps handoff and other at normal weight", () => {
expect(
resolveNotificationBadge(makeNotification({ kind: "handoff", label: "to laptop" })),
).toEqual({ label: "Handoff · to laptop", muted: false });
expect(resolveNotificationBadge(makeNotification({ kind: "other", label: "misc" }))).toEqual({
label: "Notification · misc",
muted: false,
});
});
it("collapses to the kind alone when the label adds nothing", () => {
// Agent-authored free text: it may be blank after trimming, or merely
// repeat the kind. Either way a dangling separator would be noise.
expect(resolveNotificationBadge(makeNotification({ label: " " }))).toEqual({
label: "Cron",
muted: false,
});
expect(
resolveNotificationBadge(makeNotification({ kind: "lifecycle", label: "gateway" })),
).toEqual({ label: "Gateway", muted: true });
});
});
@@ -0,0 +1,59 @@
import type { OrchestrationMessageNotification } from "@t3tools/contracts";
/**
* Presentation for the small header badge above a proactive agent delivery.
*
* A notification is provenance, not content: the row underneath stays an
* ordinary assistant message (selectable, copyable, part of the transcript)
* and the badge only answers "who asked for this, since I didn't?".
*/
export interface NotificationBadgePresentation {
/** Rendered text — "Cron · daily-digest", or just the kind when unlabelled. */
readonly label: string;
/**
* `lifecycle` notices ("gateway online") are bookkeeping the user did not
* ask for and will not act on, so they get the quieter treatment. Everything
* else is content someone scheduled or sent and reads at normal weight.
*/
readonly muted: boolean;
}
/**
* Human name for a notification kind.
*
* `message` renders as "Agent" rather than "Message": every row in the
* timeline is a message, so the useful distinction is that this one was the
* agent's own initiative.
*/
const NOTIFICATION_KIND_LABELS: Record<OrchestrationMessageNotification["kind"], string> = {
cron: "Cron",
message: "Agent",
lifecycle: "Gateway",
handoff: "Handoff",
other: "Notification",
};
/**
* Badge for one message, or `null` when the message is an ordinary reply.
*
* "No notification" is the overwhelmingly common case and must never
* synthesize a badge — an ordinary answer with a "Notification" chip on it
* would be a lie about where it came from.
*
* The kind prefix is always shown even when a label repeats it, because the
* label is agent-authored free text and cannot be trusted to carry the kind.
* A label that is empty after trimming (or exactly the kind label) collapses
* to the kind alone rather than rendering a dangling separator.
*/
export function resolveNotificationBadge(
notification: OrchestrationMessageNotification | undefined,
): NotificationBadgePresentation | null {
if (!notification) return null;
const kindLabel = NOTIFICATION_KIND_LABELS[notification.kind] ?? NOTIFICATION_KIND_LABELS.other;
const detail = notification.label.trim();
const label =
detail === "" || detail.toLowerCase() === kindLabel.toLowerCase()
? kindLabel
: `${kindLabel} · ${detail}`;
return { label, muted: notification.kind === "lifecycle" };
}