diff --git a/apps/mobile/src/widgets/AgentActivity.tsx b/apps/mobile/src/widgets/AgentActivity.tsx index 88c8564827..d74337a0bb 100644 --- a/apps/mobile/src/widgets/AgentActivity.tsx +++ b/apps/mobile/src/widgets/AgentActivity.tsx @@ -23,6 +23,7 @@ export type AgentActivityPhase = | "running" | "waiting_for_approval" | "waiting_for_input" + | "notification" | "completed" | "failed" | "stale"; @@ -81,6 +82,8 @@ export function AgentActivity( return isLightScheme ? "#d97706" : "#fcd34d"; // amber-600 / amber-300 case "waiting_for_input": return isLightScheme ? "#4f46e5" : "#a5b4fc"; // indigo-600 / indigo-300 + case "notification": + return isLightScheme ? "#7c3aed" : "#c4b5fd"; // violet-600 / violet-300 case "failed": return isLightScheme ? "#dc2626" : "#fca5a5"; // red-600 / red-300 case "completed": @@ -97,7 +100,9 @@ export function AgentActivity( const phasePriority = (phase: AgentActivityPhase): number => { if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0; if (phase === "failed") return 1; - if (phase === "running" || phase === "starting") return 2; + // A proactive delivery is unread news, so it outranks finished/stale rows + // but never a human who is actually blocked. + if (phase === "running" || phase === "starting" || phase === "notification") return 2; return 3; }; const ordered = [...props.activities].sort( @@ -163,6 +168,8 @@ export function AgentActivity( return "exclamationmark.circle.fill"; case "waiting_for_input": return "questionmark.circle.fill"; + case "notification": + return "bell.badge.fill"; case "failed": return "xmark.octagon.fill"; case "completed": diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index 938733b363..748a0c6739 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -107,6 +107,7 @@ describe("CheckpointDiffQuery.layer", () => { }); }), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -201,6 +202,7 @@ describe("CheckpointDiffQuery.layer", () => { getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -285,6 +287,7 @@ describe("CheckpointDiffQuery.layer", () => { getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -354,6 +357,7 @@ describe("CheckpointDiffQuery.layer", () => { getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -408,6 +412,7 @@ describe("CheckpointDiffQuery.layer", () => { getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index 3209f6bf56..d80987e553 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -203,6 +203,7 @@ describe("OrchestrationEngine", () => { getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 42b5d7624c..c795ae4557 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2368,6 +2368,139 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { }), ); + it.effect("projects notification deliveries into the message row and shell summary", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + const createdAt = "2026-07-01T09:00:00.000Z"; + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.make("evt-notify-project"), + aggregateKind: "project", + aggregateId: ProjectId.make("project-notify"), + occurredAt: createdAt, + commandId: CommandId.make("cmd-notify-project"), + causationEventId: null, + correlationId: CommandId.make("cmd-notify-project"), + metadata: {}, + payload: { + projectId: ProjectId.make("project-notify"), + title: "Hermes", + workspaceRoot: "/tmp/project-notify", + defaultModelSelection: null, + scripts: [], + createdAt, + updatedAt: createdAt, + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.make("evt-notify-thread"), + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-notify"), + occurredAt: createdAt, + commandId: CommandId.make("cmd-notify-thread"), + causationEventId: null, + correlationId: CommandId.make("cmd-notify-thread"), + metadata: {}, + payload: { + threadId: ThreadId.make("thread-notify"), + projectId: ProjectId.make("project-notify"), + title: "Home", + modelSelection: { + instanceId: ProviderInstanceId.make("hermes"), + model: "hermes", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }); + + const deliveredAt = "2026-07-01T09:05:00.000Z"; + yield* appendAndProject({ + type: "thread.notification-delivered", + eventId: EventId.make("evt-notify-delivery"), + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-notify"), + occurredAt: deliveredAt, + commandId: CommandId.make("cmd-notify-delivery"), + causationEventId: null, + correlationId: CommandId.make("cmd-notify-delivery"), + metadata: {}, + payload: { + threadId: ThreadId.make("thread-notify"), + messageId: MessageId.make("message-notify"), + text: "Digest ready.", + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: deliveredAt, + updatedAt: deliveredAt, + }, + }); + + const messageRows = yield* sql<{ + readonly messageId: string; + readonly text: string; + readonly turnId: string | null; + readonly role: string; + readonly isStreaming: number; + readonly notification: string | null; + }>` + SELECT + message_id AS "messageId", + text, + turn_id AS "turnId", + role, + is_streaming AS "isStreaming", + notification_json AS "notification" + FROM projection_thread_messages + WHERE thread_id = 'thread-notify' + `; + assert.equal(messageRows.length, 1); + assert.equal(messageRows[0]?.messageId, "message-notify"); + assert.equal(messageRows[0]?.turnId, null); + assert.equal(messageRows[0]?.role, "assistant"); + assert.equal(messageRows[0]?.isStreaming, 0); + assert.deepEqual( + // @effect-diagnostics-next-line preferSchemaOverJson:off + JSON.parse(messageRows[0]?.notification ?? "null"), + { kind: "cron", label: "Cron: daily-digest", deliveryId: "delivery-1" }, + ); + + // The shell summary is what the sidebar and the push relay read; the + // provenance is invisible to them unless it is flattened here. + const threadRows = yield* sql<{ + readonly updatedAt: string; + readonly latestNotification: string | null; + }>` + SELECT + updated_at AS "updatedAt", + latest_notification_json AS "latestNotification" + FROM projection_threads + WHERE thread_id = 'thread-notify' + `; + assert.equal(threadRows[0]?.updatedAt, deliveredAt); + assert.deepEqual( + // @effect-diagnostics-next-line preferSchemaOverJson:off + JSON.parse(threadRows[0]?.latestNotification ?? "null"), + { kind: "cron", label: "Cron: daily-digest", deliveredAt }, + ); + }), + ); + it.effect("does not fallback-retain messages whose turnId is removed by revert", () => Effect.gen(function* () { const projectionPipeline = yield* OrchestrationProjectionPipeline; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 7e6f2df10b..e40bde7a39 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -34,7 +34,10 @@ import { type ProjectionTurn, ProjectionTurnRepository, } from "../../persistence/Services/ProjectionTurns.ts"; -import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts"; +import { + type ProjectionThread, + ProjectionThreadRepository, +} from "../../persistence/Services/ProjectionThreads.ts"; import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts"; import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts"; import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts"; @@ -564,6 +567,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ]); let latestUserMessageAt: string | null = null; + // Newest proactive delivery, flattened for shell readers that never load + // messages (sidebar rows, agent awareness). Ties break on message id so + // two deliveries stamped in the same millisecond resolve deterministically. + let latestNotification: ProjectionThread["latestNotification"] = null; + let latestNotificationKey: string | null = null; for (const message of messages) { if ( message.role === "user" && @@ -571,6 +579,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ) { latestUserMessageAt = message.createdAt; } + if (message.notification !== undefined) { + const key = `${message.createdAt}${message.messageId}`; + if (latestNotificationKey === null || key > latestNotificationKey) { + latestNotificationKey = key; + latestNotification = { + kind: message.notification.kind, + label: message.notification.label, + deliveredAt: message.createdAt, + }; + } + } } const pendingApprovalCount = pendingApprovals.filter( @@ -588,6 +607,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti pendingApprovalCount, pendingUserInputCount, hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0, + latestNotification, }); }); @@ -617,6 +637,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti pendingApprovalCount: 0, pendingUserInputCount: 0, hasActionableProposedPlan: 0, + latestNotification: null, deletedAt: null, }); return; @@ -784,6 +805,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti } case "thread.message-sent": + case "thread.notification-delivered": case "thread.proposed-plan-upserted": case "thread.activity-appended": case "thread.approval-response-requested": @@ -917,6 +939,24 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } + case "thread.notification-delivered": { + // No merge accounting: a delivery is written whole, never streamed, + // and a replay re-emits the identical payload (the decider rebuilds + // it from the persisted row), so the upsert is idempotent. + yield* projectionThreadMessageRepository.upsert({ + messageId: event.payload.messageId, + threadId: event.payload.threadId, + turnId: null, + role: "assistant", + text: event.payload.text, + notification: event.payload.notification, + isStreaming: false, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }); + return; + } + case "thread.reverted": { const existingRows = yield* projectionThreadMessageRepository.listByThreadId({ threadId: event.payload.threadId, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 47870b43a9..9f8f5a5eea 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -441,6 +441,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { hasPendingApprovals: true, hasPendingUserInput: false, hasActionableProposedPlan: false, + latestNotification: null, }, ]); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 8bbff755be..27198a035e 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -5,6 +5,7 @@ import { MessageId, NonNegativeInt, OrchestrationCheckpointFile, + OrchestrationMessageNotification, OrchestrationProposedPlanId, OrchestrationReadModel, OrchestrationShellSnapshot, @@ -22,6 +23,7 @@ import { type OrchestrationThreadActivity, type OrchestrationThreadShell, ModelSelection, + OrchestrationThreadNotificationSummary, ProjectId, ProviderInstanceId, ThreadId, @@ -73,12 +75,19 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( Struct.assign({ isStreaming: Schema.Number, attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), + notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)), }), ); const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan; const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( Struct.assign({ modelSelection: Schema.fromJsonString(ModelSelection), + // Stored as a JSON string, like `modelSelection`. Every column the row + // schema does not decode here arrives as raw text and fails the field's + // object schema — which takes the whole thread read down with it. + latestNotification: Schema.NullOr( + Schema.fromJsonString(OrchestrationThreadNotificationSummary), + ), }), ); const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields( @@ -348,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads ORDER BY created_at ASC, thread_id ASC @@ -380,6 +390,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads WHERE deleted_at IS NULL @@ -414,6 +425,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads WHERE deleted_at IS NULL @@ -434,6 +446,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { role, text, attachments_json AS "attachments", + notification_json AS "notification", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -786,6 +799,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { `, }); + // Existence, not visibility: deliberately no `archived_at IS NULL`. Selects + // only the two columns it needs so it cannot be broken by an undecoded + // JSON column elsewhere in the row. + const getThreadArchiveStateRowById = SqlSchema.findOneOption({ + Request: ThreadIdLookupInput, + Result: Schema.Struct({ + archivedAt: Schema.NullOr(Schema.String), + deletedAt: Schema.NullOr(Schema.String), + }), + execute: ({ threadId }) => + sql` + SELECT + archived_at AS "archivedAt", + deleted_at AS "deletedAt" + FROM projection_threads + WHERE thread_id = ${threadId} + LIMIT 1 + `, + }); + const getActiveThreadRowById = SqlSchema.findOneOption({ Request: ThreadIdLookupInput, Result: ProjectionThreadDbRowSchema, @@ -812,6 +845,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads WHERE thread_id = ${threadId} @@ -833,6 +867,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { role, text, attachments_json AS "attachments", + notification_json AS "notification", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -1104,6 +1139,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { role: row.role, text: row.text, ...(row.attachments !== null ? { attachments: row.attachments } : {}), + ...(row.notification !== null ? { notification: row.notification } : {}), turnId: row.turnId, streaming: row.isStreaming === 1, createdAt: row.createdAt, @@ -1586,6 +1622,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { hasPendingApprovals: row.pendingApprovalCount > 0, hasPendingUserInput: row.pendingUserInputCount > 0, hasActionableProposedPlan: row.hasActionableProposedPlan > 0, + latestNotification: row.latestNotification, } satisfies OrchestrationThreadShell) : Result.failVoid, ), @@ -1724,6 +1761,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { hasPendingApprovals: row.pendingApprovalCount > 0, hasPendingUserInput: row.pendingUserInputCount > 0, hasActionableProposedPlan: row.hasActionableProposedPlan > 0, + latestNotification: row.latestNotification, }), ), updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z", @@ -1946,6 +1984,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { }); }); + const getThreadArchiveStateById: ProjectionSnapshotQueryShape["getThreadArchiveStateById"] = ( + threadId, + ) => + getThreadArchiveStateRowById({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadArchiveStateById:query", + "ProjectionSnapshotQuery.getThreadArchiveStateById:decodeRow", + ), + ), + Effect.map( + Option.flatMap((row) => + // A soft-deleted row is gone; an archived one is merely parked. + row.deletedAt !== null + ? Option.none<{ readonly archivedAt: string | null }>() + : Option.some({ archivedAt: row.archivedAt }), + ), + ), + ); + const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) => Effect.gen(function* () { const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([ @@ -2001,6 +2059,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { hasPendingApprovals: threadRow.value.pendingApprovalCount > 0, hasPendingUserInput: threadRow.value.pendingUserInputCount > 0, hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0, + latestNotification: threadRow.value.latestNotification, } satisfies OrchestrationThreadShell); }); @@ -2096,7 +2155,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { snoozedAt: threadRow.value.snoozedAt, deletedAt: null, messages: messageRows.map((row) => { - const message = { + const message: OrchestrationMessage = { id: row.messageId, role: row.role, text: row.text, @@ -2104,10 +2163,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { streaming: row.isStreaming === 1, createdAt: row.createdAt, updatedAt: row.updatedAt, + ...(row.attachments !== null ? { attachments: row.attachments } : {}), + ...(row.notification !== null ? { notification: row.notification } : {}), }; - if (row.attachments !== null) { - return Object.assign(message, { attachments: row.attachments }); - } return message; }), proposedPlans: proposedPlanRows.map(mapProposedPlanRow), @@ -2190,6 +2248,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { getThreadCheckpointContext, getFullThreadDiffContext, getThreadShellById, + getThreadArchiveStateById, getThreadDetailById, getThreadDetailSnapshot, } satisfies ProjectionSnapshotQueryShape; diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index 3b558d2473..d189d8bf6f 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -19,6 +19,7 @@ import { ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema, ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema, ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema, + ThreadNotificationDeliveredPayload as ContractsThreadNotificationDeliveredPayloadSchema, ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema, ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema, ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema, @@ -49,6 +50,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema; export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema; export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema; export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema; +export const ThreadNotificationDeliveredPayload = ContractsThreadNotificationDeliveredPayloadSchema; export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema; export const ThreadTurnInterruptRequestedPayload = diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index d65207b470..cdd7b8b9d2 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -165,6 +165,24 @@ export interface ProjectionSnapshotQueryShape { threadId: ThreadId, ) => Effect.Effect, ProjectionRepositoryError>; + /** + * Answer "does this thread row exist", independent of archive state. + * + * Every other thread read here filters `archived_at IS NULL`, which is right + * for "what should the user see" and wrong for existence: an archived thread + * is parked, not gone. Callers holding a durable reference to a specific + * thread — the Hermes home-thread designation — need this distinction, or + * archiving reads as deletion and they replace a thread the user still has. + * + * A soft-deleted row still reports absent. + */ + readonly getThreadArchiveStateById: ( + threadId: ThreadId, + ) => Effect.Effect< + Option.Option<{ readonly archivedAt: string | null }>, + ProjectionRepositoryError + >; + /** * Read a single active thread detail snapshot by id. */ diff --git a/apps/server/src/orchestration/agentProjects.test.ts b/apps/server/src/orchestration/agentProjects.test.ts index 0126232ed3..2c468c3594 100644 --- a/apps/server/src/orchestration/agentProjects.test.ts +++ b/apps/server/src/orchestration/agentProjects.test.ts @@ -68,6 +68,7 @@ const makeQueryLayer = ( getThreadCheckpointContext: () => Effect.die("unused"), getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }); diff --git a/apps/server/src/orchestration/decider.notification.test.ts b/apps/server/src/orchestration/decider.notification.test.ts new file mode 100644 index 0000000000..dd5e3c36ad --- /dev/null +++ b/apps/server/src/orchestration/decider.notification.test.ts @@ -0,0 +1,237 @@ +import { + CommandId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationReadModel, + type OrchestrationThread, +} from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { decideOrchestrationCommand } from "./decider.ts"; + +const NOW = "2026-07-01T00:00:00.000Z"; +const DELIVERED_AT = "2026-06-30T09:00:00.000Z"; +const SETTLED_AT = "2026-06-29T00:00:00.000Z"; +const SNOOZED_UNTIL = "2026-07-02T00:00:00.000Z"; + +function makeReadModel(input: { + readonly settledOverride?: OrchestrationThread["settledOverride"]; + readonly snoozedUntil?: string | null; + readonly messages?: OrchestrationThread["messages"]; +}): OrchestrationReadModel { + const settledOverride = input.settledOverride ?? null; + return { + snapshotSequence: 0, + projects: [], + threads: [ + { + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), + title: "Home", + modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: NOW, + updatedAt: NOW, + archivedAt: null, + settledOverride, + settledAt: settledOverride === "settled" ? SETTLED_AT : null, + snoozedUntil: input.snoozedUntil ?? null, + snoozedAt: input.snoozedUntil != null ? SETTLED_AT : null, + deletedAt: null, + messages: input.messages ?? [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }, + ], + updatedAt: NOW, + }; +} + +function deliverCommand(overrides: { + readonly commandId: string; + readonly kind?: "cron" | "message" | "lifecycle" | "handoff" | "other"; + readonly deliveryId?: string; + readonly messageId?: string; + readonly text?: string; +}) { + return { + type: "thread.notification.deliver", + commandId: CommandId.make(overrides.commandId), + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make(overrides.messageId ?? "message-1"), + deliveryId: overrides.deliveryId ?? "delivery-1", + kind: overrides.kind ?? "cron", + label: "Cron: daily-digest", + text: overrides.text ?? "Digest ready.", + createdAt: NOW, + } as const; +} + +const deliveredMessage: OrchestrationThread["messages"][number] = { + id: MessageId.make("message-1"), + role: "assistant", + text: "Digest ready.", + turnId: null, + streaming: false, + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: DELIVERED_AT, + updatedAt: DELIVERED_AT, +}; + +it.layer(NodeServices.layer)("notification delivery decider", (it) => { + it.effect("appends a turnless notification message and un-settles the thread", () => + Effect.gen(function* () { + const result = yield* decideOrchestrationCommand({ + command: deliverCommand({ commandId: "cmd-deliver" }), + readModel: makeReadModel({ settledOverride: "settled" }), + }); + const events = Array.isArray(result) ? result : [result]; + expect(events.map((event) => event.type)).toEqual([ + "thread.unsettled", + "thread.notification-delivered", + ]); + + const unsettled = events[0]; + if (unsettled?.type === "thread.unsettled") { + expect(unsettled.payload.reason).toBe("activity"); + } + + const delivered = events[1]; + if (delivered?.type === "thread.notification-delivered") { + expect(delivered.payload.messageId).toBe("message-1"); + expect(delivered.payload.text).toBe("Digest ready."); + expect(delivered.payload.notification).toEqual({ + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }); + // Nothing about a delivery belongs to a turn; attributing it to the + // thread's live turn would fold it behind that turn's summary. + expect("turnId" in delivered.payload).toBe(false); + } + }), + ); + + it.effect("un-snoozes as well as un-settles, and does neither when neither applies", () => + Effect.gen(function* () { + const both = yield* decideOrchestrationCommand({ + command: deliverCommand({ commandId: "cmd-deliver-both" }), + readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }), + }); + expect((Array.isArray(both) ? both : [both]).map((event) => event.type)).toEqual([ + "thread.unsettled", + "thread.unsnoozed", + "thread.notification-delivered", + ]); + + const neither = yield* decideOrchestrationCommand({ + command: deliverCommand({ commandId: "cmd-deliver-neither" }), + readModel: makeReadModel({}), + }); + expect((Array.isArray(neither) ? neither : [neither]).map((event) => event.type)).toEqual([ + "thread.notification-delivered", + ]); + }), + ); + + it.effect("appends lifecycle notices quietly, leaving settled and snoozed state alone", () => + Effect.gen(function* () { + const result = yield* decideOrchestrationCommand({ + command: deliverCommand({ commandId: "cmd-lifecycle", kind: "lifecycle" }), + readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }), + }); + const events = Array.isArray(result) ? result : [result]; + // Unread indicator only: a restart notice must not drag a thread the + // user has parked back into the inbox. + expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]); + }), + ); + + it.effect("dedupes a replayed deliveryId without appending or waking the thread", () => + Effect.gen(function* () { + const result = yield* decideOrchestrationCommand({ + // The plugin's retry queue resends with a fresh command id, a new + // message id, and possibly edited text — only deliveryId is stable. + command: deliverCommand({ + commandId: "cmd-deliver-retry", + messageId: "message-retry", + text: "Digest ready (retry).", + }), + readModel: makeReadModel({ + settledOverride: "settled", + snoozedUntil: SNOOZED_UNTIL, + messages: [deliveredMessage], + }), + }); + const events = Array.isArray(result) ? result : [result]; + + // No un-settle/un-snooze: a replay is not new activity. + expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]); + + const delivered = events[0]; + if (delivered?.type === "thread.notification-delivered") { + // Re-emitted from the persisted row, so reducing it a second time is + // a byte-identical no-op rather than a duplicate or an overwrite. + expect(delivered.payload.messageId).toBe("message-1"); + expect(delivered.payload.text).toBe("Digest ready."); + expect(delivered.payload.createdAt).toBe(DELIVERED_AT); + expect(delivered.payload.updatedAt).toBe(DELIVERED_AT); + expect(delivered.occurredAt).toBe(DELIVERED_AT); + } + }), + ); + + it.effect("treats a different deliveryId on the same thread as a new delivery", () => + Effect.gen(function* () { + const result = yield* decideOrchestrationCommand({ + command: deliverCommand({ + commandId: "cmd-deliver-second", + deliveryId: "delivery-2", + messageId: "message-2", + text: "Second digest.", + }), + readModel: makeReadModel({ + settledOverride: "settled", + messages: [deliveredMessage], + }), + }); + const events = Array.isArray(result) ? result : [result]; + expect(events.map((event) => event.type)).toEqual([ + "thread.unsettled", + "thread.notification-delivered", + ]); + const delivered = events[1]; + if (delivered?.type === "thread.notification-delivered") { + expect(delivered.payload.messageId).toBe("message-2"); + expect(delivered.payload.notification.deliveryId).toBe("delivery-2"); + } + }), + ); + + it.effect("rejects a delivery for a thread that does not exist", () => + Effect.gen(function* () { + const error = yield* decideOrchestrationCommand({ + command: { + ...deliverCommand({ commandId: "cmd-deliver-missing" }), + threadId: ThreadId.make("thread-missing"), + }, + readModel: makeReadModel({}), + }).pipe(Effect.flip); + expect(error._tag).toBe("OrchestrationCommandInvariantError"); + }), + ); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index a154face18..ea12a4679b 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1197,6 +1197,102 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return [unsettledEvent, activityAppendedEvent]; } + case "thread.notification.deliver": { + const thread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + // Dedupe on deliveryId: the plugin's durable queue retries anything it + // has not seen acked, so the same delivery legitimately arrives more + // than once. Idempotency is by re-emission (see thread.settle) because + // the engine rejects a command that produces no events — but unlike + // settle, the payload must be rebuilt from the ALREADY-WRITTEN message + // rather than from the command, so reducing it a second time lands on + // byte-identical state instead of rewriting the row from a retry whose + // messageId or text may differ. + // + // NOT SUFFICIENT ON ITS OWN. This scans the in-memory read model, which + // `getCommandReadModel` builds with `messages: []` on every thread — it + // deliberately does not hydrate message bodies at boot. So this catches + // only replays of deliveries appended since the process started, and + // sees nothing after a restart. The delivery path re-checks against + // `projection_thread_messages` before dispatching + // (`hermesGatewayHttp.ts`), and that read is what actually holds across + // a restart. Keep both: this one keeps the aggregate self-consistent for + // any future caller, the other one is load-bearing. + const duplicate = thread.messages.find( + (message) => message.notification?.deliveryId === command.deliveryId, + ); + const notificationEvent: Omit = { + ...(yield* withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: duplicate?.createdAt ?? command.createdAt, + commandId: command.commandId, + })), + type: "thread.notification-delivered", + payload: { + threadId: command.threadId, + messageId: duplicate?.id ?? command.messageId, + text: duplicate?.text ?? command.text, + notification: duplicate?.notification ?? { + kind: command.kind, + label: command.label, + deliveryId: command.deliveryId, + }, + createdAt: duplicate?.createdAt ?? command.createdAt, + updatedAt: duplicate?.updatedAt ?? command.createdAt, + }, + }; + // A replay is not new activity: it must never wake a thread the user + // has since settled or snoozed. + if (duplicate !== undefined) { + return notificationEvent; + } + // A lifecycle notice ("agent restarted") is bookkeeping, not a claim on + // the user's attention: it appends quietly and leaves a settled or + // snoozed thread where it is. Every other kind is the agent raising its + // hand and resets the lifecycle exactly like a user message does. + if (command.kind === "lifecycle") { + return notificationEvent; + } + const lifecycleResetEvents: Array> = []; + if (thread.settledOverride !== null) { + lifecycleResetEvents.push({ + ...(yield* withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + })), + type: "thread.unsettled", + payload: { + threadId: command.threadId, + reason: "activity", + updatedAt: command.createdAt, + }, + }); + } + if (thread.snoozedUntil != null) { + lifecycleResetEvents.push({ + ...(yield* withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + })), + type: "thread.unsnoozed", + payload: { + threadId: command.threadId, + reason: "activity", + updatedAt: command.createdAt, + }, + }); + } + return [...lifecycleResetEvents, notificationEvent]; + } + default: { command satisfies never; const fallback = command as never as { type: string }; diff --git a/apps/server/src/orchestration/homeThreads.test.ts b/apps/server/src/orchestration/homeThreads.test.ts new file mode 100644 index 0000000000..63335aa608 --- /dev/null +++ b/apps/server/src/orchestration/homeThreads.test.ts @@ -0,0 +1,408 @@ +import { assert, it } from "@effect/vitest"; +import { + DEFAULT_HERMES_MODEL, + HERMES_DRIVER_KIND, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationCommand, + type OrchestrationProject, + type OrchestrationThreadShell, +} from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; + +import { ServerConfig } from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { OrchestrationCommandInvariantError } from "./Errors.ts"; +import { + HOME_THREAD_TITLE, + getDesignatedHomeThreadId, + getOrCreateHomeThread, + isHomeThread, + readHomeThreadId, +} from "./homeThreads.ts"; +import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts"; + +const INSTANCE_ID = ProviderInstanceId.make("hermes-siva-local-abc123"); +const OTHER_INSTANCE_ID = ProviderInstanceId.make("hermes-other-def456"); +const HOME_THREAD_ID = ThreadId.make("thread-home-1"); +const BASE_DIR = "/tmp/t3-home-threads-test"; + +const agentProject: OrchestrationProject = { + id: ProjectId.make("agent-project-1"), + title: "Hermes Siva Local", + workspaceRoot: `${BASE_DIR}/agents/${INSTANCE_ID}`, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + agentInstanceId: INSTANCE_ID, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, +}; + +const threadShell = (id: ThreadId): OrchestrationThreadShell => + ({ + id, + projectId: agentProject.id, + title: HOME_THREAD_TITLE, + modelSelection: { instanceId: INSTANCE_ID, model: DEFAULT_HERMES_MODEL }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + archivedAt: null, + settledOverride: null, + settledAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + }) as OrchestrationThreadShell; + +const hermesInstance = (config: Record) => ({ + driver: HERMES_DRIVER_KIND, + displayName: "Hermes Siva Local", + enabled: true, + config, +}); + +/** + * Query stub answering thread reads from a mutable queue, so a test can model + * "designated but deleted" — the self-healing path this module exists for. + */ +const makeQueryLayer = ( + threads: Ref.Ref>>, + archiveStates?: ReadonlyArray>, +) => + Layer.succeed(ProjectionSnapshotQuery, { + getCommandReadModel: () => Effect.die("unused"), + getSnapshot: () => Effect.die("unused"), + getShellSnapshot: () => Effect.die("unused"), + getArchivedShellSnapshot: () => Effect.die("unused"), + getSnapshotSequence: () => Effect.die("unused"), + getCounts: () => Effect.die("unused"), + getActiveProjectByWorkspaceRoot: () => Effect.die("unused"), + getActiveAgentProject: () => Effect.succeed(Option.some(agentProject)), + getProjectShellById: () => Effect.die("unused"), + getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), + getThreadCheckpointContext: () => Effect.die("unused"), + getFullThreadDiffContext: () => Effect.die("unused"), + getThreadArchiveStateById: () => + Effect.gen(function* () { + if (archiveStates?.[0] !== undefined) return archiveStates[0]; + // Default: mirror the shell queue, since a thread visible to the shell + // query is also present. Tests about archiving pass this explicitly. + const queue = yield* Ref.get(threads); + return Option.map(queue[0] ?? Option.none(), () => ({ archivedAt: null })); + }), + getThreadShellById: () => + Effect.gen(function* () { + const queue = yield* Ref.get(threads); + const [head, ...rest] = queue; + if (head === undefined) return Option.none(); + yield* Ref.set(threads, rest.length > 0 ? rest : [head]); + return head; + }), + getThreadDetailById: () => Effect.die("unused"), + getThreadDetailSnapshot: () => Effect.die("unused"), + } as unknown as ProjectionSnapshotQuery["Service"]); + +const makeEngineLayer = ( + dispatched: Ref.Ref>, + options: { readonly fail?: boolean } = {}, +) => + Layer.succeed(OrchestrationEngine.OrchestrationEngineService, { + readEvents: () => Stream.empty, + dispatch: (command: OrchestrationCommand) => + Ref.update(dispatched, (calls) => [...calls, command]).pipe( + Effect.andThen( + options.fail + ? Effect.fail( + new OrchestrationCommandInvariantError({ + commandType: "thread.create", + detail: "Simulated dispatch failure.", + }), + ) + : Effect.succeed({ sequence: 1 }), + ), + ), + streamDomainEvents: Stream.empty, + latestSequence: Effect.succeed(0), + } as OrchestrationEngine.OrchestrationEngineService["Service"]); + +const configLayer = Layer.succeed(ServerConfig, { + baseDir: BASE_DIR, +} as unknown as ServerConfig["Service"]); + +const testLayer = (input: { + readonly threads: Ref.Ref>>; + readonly dispatched: Ref.Ref>; + readonly providerInstances: Record; + readonly failDispatch?: boolean; + /** + * Archive-state rows. Unlike the shell queue these ignore archive state, so + * a test can model "archived, therefore invisible to the shell query but + * still very much present" — the case that used to mint a second Home. + */ + readonly archiveStates?: ReadonlyArray>; +}) => + Layer.mergeAll( + makeQueryLayer(input.threads, input.archiveStates), + makeEngineLayer(input.dispatched, input.failDispatch ? { fail: true } : {}), + configLayer, + ServerSettings.layerTest({ + providerInstances: input.providerInstances, + } as never), + NodeServices.layer, + ); + +it("reads a designation only from a Hermes envelope", () => { + assert.equal( + readHomeThreadId(hermesInstance({ homeThreadId: HOME_THREAD_ID }) as never), + HOME_THREAD_ID, + ); + assert.equal(readHomeThreadId(hermesInstance({}) as never), undefined); + // An empty string is "not designated", not a thread whose id is "". + assert.equal(readHomeThreadId(hermesInstance({ homeThreadId: "" }) as never), undefined); + // A designation on a non-Hermes envelope is not ours to honour. + assert.equal( + readHomeThreadId({ driver: "codex", homeThreadId: HOME_THREAD_ID } as never), + undefined, + ); +}); + +it.effect("returns the designated thread without dispatching anything", () => + Effect.gen(function* () { + const threads = yield* Ref.make>>([ + Option.some(threadShell(HOME_THREAD_ID)), + ]); + const dispatched = yield* Ref.make>([]); + + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + providerInstances: { + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + }, + }), + ), + ); + + assert.equal(resolved, HOME_THREAD_ID); + // This runs on every handshake; it must not create anything on the happy path. + assert.deepEqual(yield* Ref.get(dispatched), []); + }), +); + +it.effect("creates and persists a Home thread when none is designated", () => + Effect.gen(function* () { + const threads = yield* Ref.make>>([ + Option.none(), + ]); + const dispatched = yield* Ref.make>([]); + + yield* Effect.gen(function* () { + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }); + + const commands = yield* Ref.get(dispatched); + const created = commands.find((command) => command.type === "thread.create"); + assert.isDefined(created); + if (created?.type === "thread.create") { + assert.equal(created.threadId, resolved); + assert.equal(created.title, HOME_THREAD_TITLE); + assert.equal(created.projectId, agentProject.id); + // Binds to the fixed Hermes slug, not to whatever model the plugin + // currently reports — otherwise the thread orphans on a model change. + assert.equal(created.modelSelection.model, DEFAULT_HERMES_MODEL); + } + + // The designation must be durable, or the next handshake mints a second + // Home and the first one's history is stranded. + assert.equal(yield* getDesignatedHomeThreadId(INSTANCE_ID), resolved); + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + providerInstances: { [INSTANCE_ID]: hermesInstance({}) }, + }), + ), + ); + }), +); + +it.effect("self-heals a designation whose thread no longer exists", () => + Effect.gen(function* () { + // A deleted home thread must not strand the instance: it re-designates + // rather than failing every future delivery. + const threads = yield* Ref.make>>([ + Option.none(), + ]); + const dispatched = yield* Ref.make>([]); + + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + providerInstances: { + [INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-deleted-long-ago" }), + }, + }), + ), + ); + + assert.notEqual(resolved, "thread-deleted-long-ago"); + const commands = yield* Ref.get(dispatched); + assert.isDefined(commands.find((command) => command.type === "thread.create")); + }), +); + +it.effect("adopts a racing caller's designation when its own dispatch fails", () => + Effect.gen(function* () { + const threads = yield* Ref.make>>([ + Option.none(), + ]); + const dispatched = yield* Ref.make>([]); + + // The loser of the race sees a dispatch failure but must still return the + // winner's thread rather than surfacing an error to the handshake. + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + failDispatch: true, + providerInstances: { + // Designated, but the thread read says gone — so it falls through + // to create, fails, and re-reads the designation. + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + }, + }), + ), + ); + + assert.equal(resolved, HOME_THREAD_ID); + }), +); + +it.effect("recognizes any instance's home thread as undeletable", () => + Effect.gen(function* () { + const threads = yield* Ref.make>>([]); + const dispatched = yield* Ref.make>([]); + + yield* Effect.gen(function* () { + assert.isTrue(yield* isHomeThread(HOME_THREAD_ID)); + // Scans every instance, not just one — the delete path knows only a thread. + assert.isTrue(yield* isHomeThread(ThreadId.make("thread-home-2"))); + assert.isFalse(yield* isHomeThread(ThreadId.make("thread-ordinary"))); + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + providerInstances: { + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + [OTHER_INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-home-2" }), + }, + }), + ), + ); + }), +); + +it.effect("keeps an archived Home rather than minting a replacement", () => + Effect.gen(function* () { + // The bug this pins: `getThreadShellById` filters `archived_at IS NULL`, so + // an archived Home read as *deleted* and the self-healing path created a + // second one — stranding the real history and silently re-pointing the + // designation at an empty thread. + const threads = yield* Ref.make>>([ + Option.none(), + ]); + const dispatched = yield* Ref.make>([]); + + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + archiveStates: [Option.some({ archivedAt: "2026-01-02T00:00:00.000Z" })], + providerInstances: { + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + }, + }), + ), + ); + + assert.equal(resolved, HOME_THREAD_ID); + const commands = yield* Ref.get(dispatched); + assert.isUndefined( + commands.find((command) => command.type === "thread.create"), + "an archived Home must never be replaced by a new thread", + ); + // A delivery is the agent raising its hand, so it brings the thread back + // rather than landing somewhere the user cannot see. + const unarchive = commands.find((command) => command.type === "thread.unarchive"); + assert.isDefined(unarchive); + if (unarchive?.type === "thread.unarchive") { + assert.equal(unarchive.threadId, HOME_THREAD_ID); + } + }), +); + +it.effect("does not un-archive a Home that was never archived", () => + Effect.gen(function* () { + const threads = yield* Ref.make>>([ + Option.some(threadShell(HOME_THREAD_ID)), + ]); + const dispatched = yield* Ref.make>([]); + + yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + archiveStates: [Option.some({ archivedAt: null })], + providerInstances: { + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + }, + }), + ), + ); + + // The common path stays free of writes; this runs on every handshake. + assert.deepEqual(yield* Ref.get(dispatched), []); + }), +); diff --git a/apps/server/src/orchestration/homeThreads.ts b/apps/server/src/orchestration/homeThreads.ts new file mode 100644 index 0000000000..eb3c5189c7 --- /dev/null +++ b/apps/server/src/orchestration/homeThreads.ts @@ -0,0 +1,242 @@ +/** + * Home threads — the one thread per agent instance that receives its agent's + * proactive output. + * + * Hermes has a first-class "home channel" concept: a per-platform default + * destination for output nobody asked for at a specific address — a cron job's + * result, an agent-initiated `send_message`, a gateway online notice, a + * `/handoff`. Every other Hermes surface designates one interactively via + * `/sethome`. T3 designates one automatically instead, because there is no + * "current channel" here for a user to point at: threads are created on + * demand, and asking someone to pick one before their first cron job can fire + * is setup for a decision they have no basis to make. + * + * ## Converge-on-read, like agent projects + * + * `getOrCreateHomeThread` is a **precondition every caller runs**, not a + * lifecycle event one caller owns — the same reasoning as + * `getOrCreateAgentProject`, and for the same failure modes: an instance + * enrolled before this shipped has no designation, a dispatch that failed once + * would otherwise leave the instance permanently unable to receive, and a + * thread deleted out from under the designation would strand every future + * delivery. Each of those self-heals on the next handshake. + * + * ## Why settings and not a table + * + * The designation is per-instance enrollment metadata, exactly like + * `connectorUrl` and `revoked`, and it lives beside them in the Hermes + * instance's config blob. That keeps one source of truth for "facts about this + * enrollment" and avoids a migration for a single nullable id. + * + * The plugin's `T3_HOME_CHANNEL` env var is a *cache* of this value, reconciled + * on every `connection.accepted`. This module is authoritative; drift is + * bounded by one reconnect. + * + * @module orchestration/homeThreads + */ +import { + CommandId, + DEFAULT_HERMES_MODEL, + DEFAULT_PROVIDER_INTERACTION_MODE, + HERMES_DRIVER_KIND, + ThreadId, + type ProviderInstanceConfig, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { ServerSettingsService } from "../serverSettings.ts"; +import { getOrCreateAgentProject } from "./agentProjects.ts"; +import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts"; + +/** + * Title of the home thread. Plain, no emoji: it sits in the same list as the + * user's own threads and should not shout. + */ +export const HOME_THREAD_TITLE = "Home"; + +/** Read the designated home thread id out of a Hermes instance envelope. */ +export const readHomeThreadId = ( + config: ProviderInstanceConfig | undefined, +): ThreadId | undefined => { + if (!config || config.driver !== HERMES_DRIVER_KIND) return undefined; + const blob = config.config && typeof config.config === "object" ? config.config : {}; + const raw = (blob as Record).homeThreadId; + return typeof raw === "string" && raw !== "" ? ThreadId.make(raw) : undefined; +}; + +/** + * Read one instance's designation straight from settings. + * + * Callers that only need to *know* the designation — the snapshot builder, the + * delete guard — use this rather than `getOrCreateHomeThread`, so a read never + * has the side effect of creating a thread. + */ +export const getDesignatedHomeThreadId = Effect.fn("getDesignatedHomeThreadId")(function* ( + instanceId: ProviderInstanceId, +) { + const settings = yield* ServerSettingsService; + const current = yield* settings.getSettings; + return readHomeThreadId(current.providerInstances[instanceId]); +}); + +/** + * Whether a thread is some instance's home thread, and therefore undeletable. + * + * Scans every configured instance rather than taking an instance id, because + * the delete path knows only the thread. The map is small — one entry per + * configured provider instance — and this runs once per delete. + */ +export const isHomeThread = Effect.fn("isHomeThread")(function* (threadId: ThreadId) { + const settings = yield* ServerSettingsService; + const current = yield* settings.getSettings; + for (const config of Object.values(current.providerInstances)) { + if (readHomeThreadId(config) === threadId) return true; + } + return false; +}); + +/** + * Read the designated thread's row regardless of archive state. + * + * The snapshot query's thread reads filter `archived_at IS NULL`, which is + * correct for "what should the user see" and wrong for "does this row exist". + * Going to the repository directly is what keeps an archived Home from looking + * deleted — and thereby keeps this module from minting a second one. A + * soft-deleted row still counts as gone. + */ +const readHomeThreadRow = Effect.fn("readHomeThreadRow")(function* (threadId: ThreadId) { + const query = yield* ProjectionSnapshotQuery; + const row = yield* query.getThreadArchiveStateById(threadId); + return Option.getOrUndefined(row); +}); + +/** Persist a designation into the instance's Hermes config blob. */ +const persistHomeThreadId = (input: { + readonly instanceId: ProviderInstanceId; + readonly threadId: ThreadId; +}) => + Effect.gen(function* () { + const settings = yield* ServerSettingsService; + yield* settings.updateSettingsWith((latest) => { + // Re-read under the settings write lock: the envelope may have been + // replaced (or the driver changed) between our read and this write, and + // writing a Hermes designation onto a non-Hermes envelope would corrupt + // it. Returning an empty patch is the established no-op here. + const existing = latest.providerInstances[input.instanceId]; + if (!existing || existing.driver !== HERMES_DRIVER_KIND) return {}; + const currentConfig = + existing.config && typeof existing.config === "object" + ? (existing.config as Record) + : {}; + return { + providerInstances: { + ...latest.providerInstances, + [input.instanceId]: { + ...existing, + config: { ...currentConfig, homeThreadId: input.threadId }, + }, + }, + }; + }); + }); + +/** + * Resolve the home thread for one provider instance, creating it if absent. + * + * Safe to call on every handshake: the common path is one settings read plus + * one indexed thread read. Idempotent, and concurrent callers converge — + * the loser of a race re-reads and adopts the winner's thread. + */ +export const getOrCreateHomeThread = Effect.fn("getOrCreateHomeThread")(function* (input: { + readonly instanceId: ProviderInstanceId; + /** Instance nickname, used as the agent project's title on first creation. */ + readonly title: string; +}) { + const engine = yield* OrchestrationEngineService; + const crypto = yield* Crypto.Crypto; + + const designated = yield* getDesignatedHomeThreadId(input.instanceId); + if (designated !== undefined) { + // Deliberately NOT `getThreadShellById`: that query filters + // `archived_at IS NULL`, so an archived Home reads as absent and this + // function would "self-heal" by minting a second Home — stranding the + // history in the archived one and silently re-pointing the designation. + // Archiving is a user parking a thread, not destroying it; only a row + // that is really gone justifies a replacement. + const existing = yield* readHomeThreadRow(designated); + if (existing !== undefined) { + // Un-archive rather than deliver into a hidden thread. A delivery is + // the agent raising its hand, and the same rule the decider applies to + // settled/snoozed threads applies here: incoming activity brings the + // thread back. Best-effort — a failure here must not cost the delivery. + if (existing.archivedAt !== null) { + yield* engine + .dispatch({ + type: "thread.unarchive", + commandId: CommandId.make(yield* crypto.randomUUIDv4), + threadId: designated, + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("could not un-archive the home thread", { + instanceId: input.instanceId, + threadId: designated, + cause: Cause.pretty(cause), + }), + ), + ); + } + return designated; + } + } + + const project = yield* getOrCreateAgentProject({ + instanceId: input.instanceId, + title: input.title, + }); + + const threadId = ThreadId.make(yield* crypto.randomUUIDv4); + const createdAt = DateTime.formatIso(yield* DateTime.now); + + const dispatched = yield* Effect.result( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.make(yield* crypto.randomUUIDv4), + threadId, + projectId: project.id, + title: HOME_THREAD_TITLE, + // The same fixed slug every Hermes thread binds to — the reported model + // name is display-only, and following it here would orphan the thread + // whenever Hermes' own config changed. + modelSelection: { instanceId: input.instanceId, model: DEFAULT_HERMES_MODEL }, + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + createdAt, + }), + ); + + if (dispatched._tag === "Failure") { + // A concurrent handshake may have won and already persisted its thread. + // Re-read before surfacing the error, matching getOrCreateAgentProject. + const raced = yield* getDesignatedHomeThreadId(input.instanceId); + if (raced !== undefined) return raced; + return yield* Effect.fail(dispatched.failure); + } + + yield* persistHomeThreadId({ instanceId: input.instanceId, threadId }); + + // Re-read rather than trusting our own write: if a racing caller persisted + // first, both callers must agree on one thread, and settings is the + // tiebreaker. Our orphaned thread stays as an empty thread in the project + // rather than becoming a second home. + const settled = yield* getDesignatedHomeThreadId(input.instanceId); + return settled ?? threadId; +}); diff --git a/apps/server/src/orchestration/projector.notification.test.ts b/apps/server/src/orchestration/projector.notification.test.ts new file mode 100644 index 0000000000..91f882dcf1 --- /dev/null +++ b/apps/server/src/orchestration/projector.notification.test.ts @@ -0,0 +1,149 @@ +import { + CommandId, + EventId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationEvent, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { createEmptyReadModel, projectEvent } from "./projector.ts"; + +const CREATED_AT = "2026-07-01T09:00:00.000Z"; +const DELIVERED_AT = "2026-07-01T09:05:00.000Z"; + +function makeEvent(input: { + readonly sequence: number; + readonly type: OrchestrationEvent["type"]; + readonly occurredAt: string; + readonly payload: unknown; +}): OrchestrationEvent { + return { + sequence: input.sequence, + eventId: EventId.make(`event-${input.sequence}`), + type: input.type, + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-home"), + occurredAt: input.occurredAt, + commandId: CommandId.make(`command-${input.sequence}`), + causationEventId: null, + correlationId: null, + metadata: {}, + payload: input.payload as never, + } as OrchestrationEvent; +} + +const threadCreatedEvent = makeEvent({ + sequence: 1, + type: "thread.created", + occurredAt: CREATED_AT, + payload: { + threadId: ThreadId.make("thread-home"), + projectId: ProjectId.make("project-1"), + title: "Home", + modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: CREATED_AT, + updatedAt: CREATED_AT, + }, +}); + +const deliveryEvent = makeEvent({ + sequence: 2, + type: "thread.notification-delivered", + occurredAt: DELIVERED_AT, + payload: { + threadId: ThreadId.make("thread-home"), + messageId: MessageId.make("notification:msg-1"), + text: "Digest ready.", + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: DELIVERED_AT, + updatedAt: DELIVERED_AT, + }, +}); + +const expectedMessage = { + id: "notification:msg-1", + role: "assistant", + text: "Digest ready.", + // A delivery belongs to no turn and is never streamed. + turnId: null, + streaming: false, + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: DELIVERED_AT, + updatedAt: DELIVERED_AT, +}; + +it.effect("appends a notification delivery as a turnless assistant message", () => + Effect.gen(function* () { + const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent); + const delivered = yield* projectEvent(created, deliveryEvent); + + const thread = delivered.threads[0]; + expect(thread?.messages).toHaveLength(1); + expect(thread?.messages[0]).toEqual(expectedMessage); + expect(thread?.updatedAt).toBe(DELIVERED_AT); + // Nothing about a delivery touches turn state — attributing it to the + // thread's live turn would fold it behind that turn's summary. + expect(thread?.latestTurn).toBeNull(); + }), +); + +it.effect("replays a delivery onto the same message instead of duplicating it", () => + Effect.gen(function* () { + const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent); + const delivered = yield* projectEvent(created, deliveryEvent); + // The decider re-emits the persisted row for a replayed deliveryId, so + // reducing the event twice must be a no-op rather than an append. + const replayed = yield* projectEvent(delivered, { ...deliveryEvent, sequence: 3 }); + + expect(replayed.threads[0]?.messages).toHaveLength(1); + expect(replayed.threads[0]?.messages[0]).toEqual(expectedMessage); + }), +); + +it.effect("keeps deliveries alongside ordinary turn messages", () => + Effect.gen(function* () { + const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent); + const withUserMessage = yield* projectEvent( + created, + makeEvent({ + sequence: 2, + type: "thread.message-sent", + occurredAt: "2026-07-01T09:01:00.000Z", + payload: { + threadId: ThreadId.make("thread-home"), + messageId: MessageId.make("msg-user"), + role: "user", + text: "hi", + turnId: null, + streaming: false, + createdAt: "2026-07-01T09:01:00.000Z", + updatedAt: "2026-07-01T09:01:00.000Z", + }, + }), + ); + const delivered = yield* projectEvent(withUserMessage, { ...deliveryEvent, sequence: 3 }); + + expect(delivered.threads[0]?.messages.map((message) => message.id)).toEqual([ + "msg-user", + "notification:msg-1", + ]); + // Absence of `notification` is what marks an ordinary message; it must + // never be synthesized onto one. + expect(delivered.threads[0]?.messages[0]?.notification).toBeUndefined(); + }), +); diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index cd2208ced3..a8a8ed7352 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -21,6 +21,7 @@ import { ThreadDeletedPayload, ThreadInteractionModeSetPayload, ThreadMetaUpdatedPayload, + ThreadNotificationDeliveredPayload, ThreadProposedPlanUpsertedPayload, ThreadRuntimeModeSetPayload, ThreadSettledPayload, @@ -722,6 +723,55 @@ export function projectEvent( }), ); + case "thread.notification-delivered": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadNotificationDeliveredPayload, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const message: OrchestrationMessage = yield* decodeForEvent( + OrchestrationMessage, + { + id: payload.messageId, + role: "assistant", + text: payload.text, + // A delivery belongs to no turn: it arrives outside the turn + // machinery and may land while an unrelated turn is live. + turnId: null, + streaming: false, + notification: payload.notification, + createdAt: payload.createdAt, + updatedAt: payload.updatedAt, + }, + event.type, + "message", + ); + + // Replays of an already-written delivery re-emit the persisted row, so + // replacing in place is a byte-identical no-op rather than a duplicate. + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = ( + existingMessage + ? thread.messages.map((entry) => (entry.id === message.id ? message : entry)) + : [...thread.messages, message] + ).slice(-MAX_THREAD_MESSAGES); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + messages, + updatedAt: event.occurredAt, + }), + }; + }); + case "thread.activity-appended": return decodeForEvent( ThreadActivityAppendedPayload, diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index 44425a42b4..32744eb304 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -100,6 +100,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { pendingApprovalCount: 0, pendingUserInputCount: 0, hasActionableProposedPlan: 0, + latestNotification: null, deletedAt: null, }); @@ -162,6 +163,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { pendingApprovalCount: 0, pendingUserInputCount: 0, hasActionableProposedPlan: 0, + latestNotification: null, deletedAt: null, }); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts index b1f394a9e5..d901c20b13 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts @@ -66,6 +66,80 @@ layer("ProjectionThreadMessageRepository", (it) => { }), ); + it.effect("round-trips notification provenance and preserves it across later upserts", () => + Effect.gen(function* () { + const repository = yield* ProjectionThreadMessageRepository; + const threadId = ThreadId.make("thread-notification"); + const messageId = MessageId.make("message-notification"); + const createdAt = "2026-07-01T09:00:00.000Z"; + const notification = { + kind: "cron" as const, + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }; + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "Digest ready.", + notification, + isStreaming: false, + createdAt, + updatedAt: createdAt, + }); + + const rows = yield* repository.listByThreadId({ threadId }); + assert.equal(rows.length, 1); + assert.deepEqual(rows[0]?.notification, notification); + + // Same COALESCE rule as attachments: an unrelated update that omits the + // field must not erase a delivery's provenance. + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "Digest ready (edited).", + isStreaming: false, + createdAt, + updatedAt: "2026-07-01T09:00:02.000Z", + }); + + const rowById = yield* repository.getByMessageId({ messageId }); + assert.equal(rowById._tag, "Some"); + if (rowById._tag === "Some") { + assert.equal(rowById.value.text, "Digest ready (edited)."); + assert.deepEqual(rowById.value.notification, notification); + } + }), + ); + + it.effect("leaves notification absent on ordinary messages", () => + Effect.gen(function* () { + const repository = yield* ProjectionThreadMessageRepository; + const threadId = ThreadId.make("thread-ordinary-message"); + const messageId = MessageId.make("message-ordinary"); + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "user", + text: "hello", + isStreaming: false, + createdAt: "2026-07-01T09:10:00.000Z", + updatedAt: "2026-07-01T09:10:00.000Z", + }); + + const rows = yield* repository.listByThreadId({ threadId }); + // Absent, not a synthesized default — consumers key on its absence to + // tell an ordinary message from a proactive delivery. + assert.equal(rows[0]?.notification, undefined); + }), + ); + it.effect("allows explicit attachment clearing with an empty array", () => Effect.gen(function* () { const repository = yield* ProjectionThreadMessageRepository; diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index 7191916688..0b3ab859b0 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -5,7 +5,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; -import { ChatAttachment } from "@t3tools/contracts"; +import { ChatAttachment, OrchestrationMessageNotification } from "@t3tools/contracts"; import { toPersistenceSqlError } from "../Errors.ts"; import { @@ -21,6 +21,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( Struct.assign({ isStreaming: Schema.Number, attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), + notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)), }), ); @@ -37,6 +38,7 @@ function toProjectionThreadMessage( createdAt: row.createdAt, updatedAt: row.updatedAt, ...(row.attachments !== null ? { attachments: row.attachments } : {}), + ...(row.notification !== null ? { notification: row.notification } : {}), }; } @@ -48,6 +50,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { execute: (row) => { const nextAttachmentsJson = row.attachments !== undefined ? JSON.stringify(row.attachments) : null; + const nextNotificationJson = + row.notification !== undefined ? JSON.stringify(row.notification) : null; return sql` INSERT INTO projection_thread_messages ( message_id, @@ -56,6 +60,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { role, text, attachments_json, + notification_json, is_streaming, created_at, updated_at @@ -74,6 +79,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { WHERE message_id = ${row.messageId} ) ), + COALESCE( + ${nextNotificationJson}, + ( + SELECT notification_json + FROM projection_thread_messages + WHERE message_id = ${row.messageId} + ) + ), ${row.isStreaming ? 1 : 0}, ${row.createdAt}, ${row.updatedAt} @@ -88,6 +101,10 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { excluded.attachments_json, projection_thread_messages.attachments_json ), + notification_json = COALESCE( + excluded.notification_json, + projection_thread_messages.notification_json + ), is_streaming = excluded.is_streaming, created_at = excluded.created_at, updated_at = excluded.updated_at @@ -107,6 +124,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { role, text, attachments_json AS "attachments", + notification_json AS "notification", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -128,6 +146,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { role, text, attachments_json AS "attachments", + notification_json AS "notification", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 7e86d49eac..253634ead6 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -14,11 +14,14 @@ import { ProjectionThreadRepository, type ProjectionThreadRepositoryShape, } from "../Services/ProjectionThreads.ts"; -import { ModelSelection } from "@t3tools/contracts"; +import { ModelSelection, OrchestrationThreadNotificationSummary } from "@t3tools/contracts"; const ProjectionThreadDbRow = ProjectionThread.mapFields( Struct.assign({ modelSelection: Schema.fromJsonString(ModelSelection), + latestNotification: Schema.NullOr( + Schema.fromJsonString(OrchestrationThreadNotificationSummary), + ), }), ); type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type; @@ -28,8 +31,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () { const upsertProjectionThreadRow = SqlSchema.void({ Request: ProjectionThread, - execute: (row) => - sql` + execute: (row) => { + const latestNotificationJson = + row.latestNotification === null ? null : JSON.stringify(row.latestNotification); + return sql` INSERT INTO projection_threads ( thread_id, project_id, @@ -51,6 +56,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_approval_count, pending_user_input_count, has_actionable_proposed_plan, + latest_notification_json, deleted_at ) VALUES ( @@ -74,6 +80,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.pendingApprovalCount}, ${row.pendingUserInputCount}, ${row.hasActionableProposedPlan}, + ${latestNotificationJson}, ${row.deletedAt} ) ON CONFLICT (thread_id) @@ -97,8 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_approval_count = excluded.pending_approval_count, pending_user_input_count = excluded.pending_user_input_count, has_actionable_proposed_plan = excluded.has_actionable_proposed_plan, + latest_notification_json = excluded.latest_notification_json, deleted_at = excluded.deleted_at - `, + `; + }, }); const getProjectionThreadRow = SqlSchema.findOneOption({ @@ -127,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads WHERE thread_id = ${threadId} @@ -159,6 +169,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_approval_count AS "pendingApprovalCount", pending_user_input_count AS "pendingUserInputCount", has_actionable_proposed_plan AS "hasActionableProposedPlan", + latest_notification_json AS "latestNotification", deleted_at AS "deletedAt" FROM projection_threads WHERE project_id = ${projectId} diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index ab7d44ec9c..5d7fed78cc 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -48,6 +48,8 @@ import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts"; import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts"; import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts"; import Migration0035 from "./Migrations/035_ProjectionProjectsAgentInstance.ts"; +import Migration0036 from "./Migrations/036_ProjectionThreadMessageNotification.ts"; +import Migration0037 from "./Migrations/037_ProjectionThreadsLatestNotification.ts"; /** * Migration loader with all migrations defined inline. @@ -95,6 +97,8 @@ export const migrationEntries = [ [33, "ProjectionThreadsSettled", Migration0033], [34, "ProjectionThreadsSnoozed", Migration0034], [35, "ProjectionProjectsAgentInstance", Migration0035], + [36, "ProjectionThreadMessageNotification", Migration0036], + [37, "ProjectionThreadsLatestNotification", Migration0037], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.test.ts b/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.test.ts new file mode 100644 index 0000000000..f5a7bd9627 --- /dev/null +++ b/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.test.ts @@ -0,0 +1,109 @@ +import { assert, it } from "@effect/vitest"; +import { OrchestrationMessageNotification } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("036_ProjectionThreadMessageNotification", (it) => { + it.effect("adds the notification column without disturbing existing messages", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 35 }); + + // An ordinary message written before the column existed. Proactive + // deliveries are the exception, so every pre-existing row must survive + // the migration with no notification rather than a synthesized default. + yield* sql` + INSERT INTO projection_thread_messages ( + message_id, + thread_id, + turn_id, + role, + text, + is_streaming, + created_at, + updated_at + ) VALUES ( + 'message-1', + 'thread-1', + 'turn-1', + 'assistant', + 'an ordinary answer', + 0, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z' + ) + `; + + yield* runMigrations({ toMigrationInclusive: 36 }); + + const rows = yield* sql<{ + readonly message_id: string; + readonly text: string; + readonly notification_json: string | null; + }>` + SELECT message_id, text, notification_json + FROM projection_thread_messages + WHERE message_id = 'message-1' + `; + + assert.equal(rows.length, 1); + assert.equal(rows[0]?.text, "an ordinary answer"); + assert.equal(rows[0]?.notification_json, null); + + // And the new column accepts a delivery's provenance. + yield* sql` + INSERT INTO projection_thread_messages ( + message_id, + thread_id, + turn_id, + role, + text, + is_streaming, + created_at, + updated_at, + notification_json + ) VALUES ( + 'message-2', + 'thread-1', + NULL, + 'assistant', + 'Your digest is ready.', + 0, + '2026-01-01T00:01:00.000Z', + '2026-01-01T00:01:00.000Z', + '{"kind":"cron","label":"Cron: daily-digest","deliveryId":"delivery-1"}' + ) + `; + + const delivered = yield* sql<{ + readonly notification_json: string | null; + readonly turn_id: string | null; + }>` + SELECT notification_json, turn_id + FROM projection_thread_messages + WHERE message_id = 'message-2' + `; + + assert.equal(delivered.length, 1); + // A delivery belongs to no turn — attributing it to the thread's live + // turn would fold it away behind that turn's "Worked for …" row. + assert.equal(delivered[0]?.turn_id, null); + const decodedNotification = yield* Schema.decodeUnknownEffect( + Schema.fromJsonString(OrchestrationMessageNotification), + )(delivered[0]?.notification_json ?? ""); + assert.deepEqual(decodedNotification, { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.ts b/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.ts new file mode 100644 index 0000000000..7adf2bbeb9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/036_ProjectionThreadMessageNotification.ts @@ -0,0 +1,11 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_messages + ADD COLUMN notification_json TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.test.ts b/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.test.ts new file mode 100644 index 0000000000..5cec4aa89d --- /dev/null +++ b/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.test.ts @@ -0,0 +1,80 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("037_ProjectionThreadsLatestNotification", (it) => { + it.effect("adds a nullable latest_notification_json column, leaving existing rows null", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 36 }); + + const before = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + assert.ok(!before.some((column) => column.name === "latest_notification_json")); + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + deleted_at + ) + VALUES ( + 'thread-pre-037', + 'project-pre-037', + 'Existing thread', + '{"instanceId":"codex","model":"gpt-5.4"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-07-01T00:00:00.000Z', + '2026-07-01T00:00:00.000Z', + NULL + ) + `; + + yield* runMigrations({ toMigrationInclusive: 37 }); + + const after = yield* sql<{ + readonly name: string; + readonly type: string; + readonly notnull: number; + readonly dflt_value: string | null; + }>` + PRAGMA table_info(projection_threads) + `; + const column = after.find((entry) => entry.name === "latest_notification_json"); + assert.ok(column); + assert.strictEqual(column.type, "TEXT"); + assert.strictEqual(column.notnull, 0); + assert.strictEqual(column.dflt_value, null); + + // No backfill is needed or possible: notification_json (migration 036) + // is newer than every pre-existing row, so nothing to summarize. + const rows = yield* sql<{ readonly latestNotification: string | null }>` + SELECT latest_notification_json AS "latestNotification" + FROM projection_threads + WHERE thread_id = 'thread-pre-037' + `; + assert.deepStrictEqual(rows, [{ latestNotification: null }]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.ts b/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.ts new file mode 100644 index 0000000000..8cd62432c5 --- /dev/null +++ b/apps/server/src/persistence/Migrations/037_ProjectionThreadsLatestNotification.ts @@ -0,0 +1,22 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +/** + * Materializes the thread's newest proactive delivery onto the shell row. + * + * Shell consumers (sidebar, agent-awareness/push) never read a thread's + * messages, so notification provenance that lives on the message row is + * invisible to them unless it is summarized here — the same reason + * `latest_user_message_at` exists. + * + * No backfill: `projection_thread_messages.notification_json` is introduced by + * migration 036, so no delivery predates this column. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN latest_notification_json TEXT + `; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index d50ff32025..970eda3f49 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -9,6 +9,7 @@ import { ChatAttachment, MessageId, + OrchestrationMessageNotification, OrchestrationMessageRole, ThreadId, TurnId, @@ -28,6 +29,14 @@ export const ProjectionThreadMessage = Schema.Struct({ role: OrchestrationMessageRole, text: Schema.String, attachments: Schema.optional(Schema.Array(ChatAttachment)), + /** + * Proactive-delivery provenance, present only on notification rows. + * + * Optional like `attachments`, and persisted with the same + * `COALESCE(excluded, existing)` upsert rule: an ordinary update that omits + * it must not erase the provenance of a row that has it. + */ + notification: Schema.optional(OrchestrationMessageNotification), isStreaming: Schema.Boolean, createdAt: IsoDateTime, updatedAt: IsoDateTime, diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 056425ae88..b98c4271a0 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -10,6 +10,7 @@ import { IsoDateTime, ModelSelection, NonNegativeInt, + OrchestrationThreadNotificationSummary, ProjectId, ProviderInteractionMode, RuntimeMode, @@ -44,6 +45,12 @@ export const ProjectionThread = Schema.Struct({ pendingApprovalCount: NonNegativeInt, pendingUserInputCount: NonNegativeInt, hasActionableProposedPlan: NonNegativeInt, + /** + * Newest proactive delivery on this thread, summarized so shell readers do + * not have to load messages. Refreshed alongside the other shell-summary + * columns; `null` on every thread that has never received a delivery. + */ + latestNotification: Schema.NullOr(OrchestrationThreadNotificationSummary), deletedAt: Schema.NullOr(IsoDateTime), }); export type ProjectionThread = typeof ProjectionThread.Type; diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index a9669d30db..d67fd3ee00 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -44,6 +44,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) => getThreadCheckpointContext: () => Effect.die("unused"), getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }); diff --git a/apps/server/src/provider/Drivers/HermesDriver.ts b/apps/server/src/provider/Drivers/HermesDriver.ts index c8ae4eabab..c38a0887a3 100644 --- a/apps/server/src/provider/Drivers/HermesDriver.ts +++ b/apps/server/src/provider/Drivers/HermesDriver.ts @@ -4,13 +4,17 @@ import { HermesSettings, TextGenerationError, type ServerProvider, + type ServerSettings, } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import { readHomeThreadId } from "../../orchestration/homeThreads.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts"; import { makeHermesAdapter } from "../Layers/HermesAdapter.ts"; import { @@ -23,7 +27,7 @@ import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts"; const decodeHermesSettings = Schema.decodeSync(HermesSettings); -export type HermesDriverEnv = Crypto.Crypto; +export type HermesDriverEnv = Crypto.Crypto | ServerSettingsService; const unsupportedTextGeneration = ( operation: @@ -57,6 +61,9 @@ export const HermesDriver: ProviderDriver = { create: ({ instanceId, displayName, accentColor, enabled }) => Effect.gen(function* () { const broker = yield* HermesGatewayBroker; + // Captured once at construction: `getSnapshot` must be context-free + // (`R = never`) because the registry calls it outside this scope. + const settings = yield* ServerSettingsService; const adapter = yield* makeHermesAdapter({ instanceId }); const continuationIdentity = defaultProviderContinuationIdentity({ driverKind: HERMES_DRIVER_KIND, @@ -71,7 +78,19 @@ export const HermesDriver: ProviderDriver = { const status = yield* broker .getInstanceStatus(instanceId) .pipe(Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined))); + // Read-only: a snapshot must never create the thread as a side effect + // (this runs on every status tick). The handshake owns creation. + // A settings read that fails degrades to "no designation" rather than + // failing the whole snapshot — the pin is cosmetic, the status is not. + const currentSettings = yield* settings.getSettings.pipe( + Effect.map(Option.some), + Effect.orElseSucceed(() => Option.none()), + ); + const homeThreadId = Option.isSome(currentSettings) + ? readHomeThreadId(currentSettings.value.providerInstances[instanceId]) + : undefined; return { + ...(homeThreadId !== undefined ? { homeThreadId } : {}), instanceId, driver: HERMES_DRIVER_KIND, ...(displayName ? { displayName } : {}), diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts index 501df004e4..32ad53b93d 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts @@ -39,6 +39,13 @@ import { makeHermesGatewayBroker, } from "./HermesGatewayBroker.ts"; +/** + * A version this server does not speak. Expressed relative to the supported + * version rather than as a literal, so bumping the protocol does not turn + * these "must be rejected" cases into "is the current version" cases. + */ +const UNSUPPORTED_PROTOCOL_VERSION = HERMES_GATEWAY_PROTOCOL_VERSION + 1; + const instanceId = ProviderInstanceId.make("hermes_remote"); const otherInstanceId = ProviderInstanceId.make("hermes_other"); const defaultHermesInstanceId = ProviderInstanceId.make("hermes"); @@ -94,7 +101,10 @@ const testLayer = Layer.mergeAll( const hello = ( authentication: HermesGatewayConnectionHello["authentication"], protocolVersion: number = HERMES_GATEWAY_PROTOCOL_VERSION, - overrides: { readonly model?: string } = {}, + overrides: { + readonly model?: string; + readonly role?: HermesGatewayConnectionHello["role"]; + } = {}, ): HermesGatewayConnectionHello => ({ type: "connection.hello", requestId: HermesGatewayRequestId.make(`hello-${protocolVersion}`), @@ -103,6 +113,7 @@ const hello = ( hermesVersion: "1.0.0", capabilities: { ...capabilities, protocolVersion }, authentication, + role: overrides.role ?? "gateway", ...(overrides.model !== undefined ? { model: overrides.model } : {}), }); @@ -174,7 +185,7 @@ it.effect("authenticates before applying incompatible connection state", () => instanceId, credential: HermesGatewayCredential.make("not-the-real-credential"), }, - 3, + UNSUPPORTED_PROTOCOL_VERSION, ), second.transport, ), @@ -202,7 +213,7 @@ it.effect("authenticates before applying incompatible connection state", () => instanceId, credential: registered.accepted.credential!, }, - 3, + UNSUPPORTED_PROTOCOL_VERSION, ), second.transport, ), @@ -214,7 +225,10 @@ it.effect("authenticates before applying incompatible connection state", () => const otherEnrollment = yield* enroll(broker, otherInstanceId, "Other Hermes"); const incompatibleEnrollment = yield* Effect.flip( broker.registerConnection( - hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }, 3), + hello( + { type: "enrollment-token", token: otherEnrollment.oneTimeToken }, + UNSUPPORTED_PROTOCOL_VERSION, + ), second.transport, ), ); @@ -1226,3 +1240,85 @@ it.effect("migrates a revoked legacy instance and drops its credential", () => assert.equal(reconnect.code, "invalid-authentication"); }).pipe(Effect.provide(testLayer)), ); + +it.effect("a delivery connection never displaces the live gateway connection", () => + Effect.gen(function* () { + // The failure this guards: an out-of-process cron run dials in to hand + // over one delivery, `registerConnection` treats it as a replacement, and + // the real plugin gets closed with 4001 — knocking Hermes offline for the + // duration of a cron job. + const broker = yield* makeBroker(makeSecretStore()); + const enrollment = yield* enroll(broker, instanceId, "Remote Hermes"); + const live = recordingTransport(); + const gateway = yield* broker.registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + live.transport, + ); + assert.equal(gateway.role, "gateway"); + assert.isTrue(yield* broker.isConnected(instanceId)); + + const credential = gateway.accepted.credential!; + const cron = recordingTransport(); + const delivery = yield* broker.registerConnection( + hello( + { type: "instance-credential", instanceId, credential }, + HERMES_GATEWAY_PROTOCOL_VERSION, + { role: "delivery" }, + ), + cron.transport, + ); + + assert.equal(delivery.role, "delivery"); + // No generation: it was never registered, so there is nothing for it to + // be stale against — and a generation would let it be compared with, and + // mistaken for, the live connection. + assert.equal(delivery.generation, null); + assert.deepEqual(live.closes, [], "the live gateway socket must not be closed"); + assert.isTrue(yield* broker.isConnected(instanceId)); + + // A delivery socket holds no session, so it must not be able to answer + // the live connection's outstanding requests — otherwise a throwaway cron + // socket could speak for the real plugin. + const threadId = ThreadId.make("delivery-fencing-thread"); + const pendingRequestId = HermesGatewayRequestId.make("delivery-fencing-session"); + const pending = yield* broker + .request(instanceId, { + type: "session.ensure", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: pendingRequestId, + threadId, + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + yield* broker.receive(delivery, { + type: "session.ready", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: pendingRequestId, + threadId, + sessionId: HermesGatewaySessionId.make("delivery-forged-session"), + resumed: false, + }); + yield* Effect.yieldNow; + assert.isUndefined( + pending.pollUnsafe(), + "a delivery connection must not complete the live connection's requests", + ); + + // The live connection still can. + yield* broker.receive(gateway, { + type: "session.ready", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + requestId: pendingRequestId, + threadId, + sessionId: HermesGatewaySessionId.make("real-session"), + resumed: false, + }); + assert.equal((yield* Fiber.join(pending)).type, "session.ready"); + + // Closing the delivery socket is its normal lifecycle and must leave the + // instance's liveness untouched. + yield* broker.disconnect(delivery); + assert.isTrue(yield* broker.isConnected(instanceId)); + assert.deepEqual(live.closes, []); + }).pipe(Effect.provide(testLayer)), +); diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.ts index 37b936fb50..6926b62748 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.ts @@ -965,6 +965,31 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } + // ── Delivery connections: authenticated, but never the primary. + // + // An out-of-process cron run dials in only to hand over a `home.deliver` + // and leave. Registering it would displace the instance's live gateway + // socket ("replaced by a newer connection") and bump the generation, + // knocking the real plugin offline for the duration of a cron job. So it + // is accepted and then deliberately left out of the connection registry: + // no generation, no liveness ping, no status publish, nothing to + // disconnect. The existing primary is untouched. + if (hello.role === "delivery") { + return { + instanceId, + generation: null, + role: "delivery", + accepted: { + type: "connection.accepted", + requestId: hello.requestId, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId, + nickname: record.nickname, + ...(credential ? { credential } : {}), + }, + } as const satisfies HermesGatewayConnectionRegistration; + } + const observed: HermesObservedConnection = { pluginVersion: hello.pluginVersion, hermesVersion: hello.hermesVersion, @@ -986,6 +1011,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { const registration = { instanceId, generation: accepted.generation, + role: "gateway", accepted: { type: "connection.accepted", requestId: hello.requestId, @@ -1009,6 +1035,14 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { const receive = (registration: HermesGatewayConnectionRegistration, message: PluginMessage) => Effect.gen(function* () { + // A delivery connection's one frame — `home.deliver` — is handled at the + // transport layer, because its ack has to go back to that specific + // short-lived socket. Anything else it sends is outside its remit and is + // dropped here: it holds no session, so completing a correlated request + // or publishing a status off it would let a throwaway cron socket speak + // for the live connection. + if (registration.role === "delivery") return; + if (message.type === "connection.status") { // Generation-fenced inside the Ref update; a stale registration is a // no-op rather than an overwrite. @@ -1031,6 +1065,10 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { const disconnect = (registration: HermesGatewayConnectionRegistration) => Effect.gen(function* () { + // Delivery sockets close as a matter of course — that is their whole + // lifecycle. They were never in the registry, so retiring one must not + // touch the instance's liveness or fail the live connection's requests. + if (registration.role === "delivery") return; const retired = yield* connections.disconnect(registration); if (!retired) return; yield* publishCurrentStatus(registration.instanceId, "get-status"); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index bf0c4f7bc0..ac12d6d7c2 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -205,6 +205,7 @@ describe("ProviderSessionReaper", () => { getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), getThreadCheckpointContext: () => Effect.die("unused"), getFullThreadDiffContext: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadShellById: (threadId) => Effect.succeed( input.readModel.threads.find((thread) => thread.id === threadId) diff --git a/apps/server/src/provider/Services/HermesGatewayBroker.ts b/apps/server/src/provider/Services/HermesGatewayBroker.ts index 76dd979105..d1e428a896 100644 --- a/apps/server/src/provider/Services/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Services/HermesGatewayBroker.ts @@ -1,5 +1,6 @@ import type { HermesGatewayConnectionHello, + HermesGatewayConnectionRole, HermesGatewayCreateEnrollmentInput, HermesGatewayEnrollmentResult, HermesGatewayInstanceStatus, @@ -27,7 +28,22 @@ export interface HermesGatewayTransport { export interface HermesGatewayConnectionRegistration { readonly instanceId: ProviderInstanceId; - readonly generation: number; + /** + * Fencing token for the instance's primary connection, or `null` for a + * delivery connection. + * + * A delivery connection is deliberately outside the generation scheme: it + * was never registered as the primary, so there is nothing for it to be + * stale against, and giving it a generation would let it be compared — + * and therefore mistaken for a replacement — against the live socket. + */ + readonly generation: number | null; + /** + * What this socket registered as. `delivery` sockets may only hand over + * `home.deliver` frames; they carry no session, take no ping loop, and + * their disconnect must not disturb the instance's liveness state. + */ + readonly role: HermesGatewayConnectionRole; readonly accepted: Extract< HermesGatewayT3ToPluginMessage, { readonly type: "connection.accepted" } diff --git a/apps/server/src/provider/hermesGatewayHttp.ts b/apps/server/src/provider/hermesGatewayHttp.ts index 8cb4266305..334c0fc6b9 100644 --- a/apps/server/src/provider/hermesGatewayHttp.ts +++ b/apps/server/src/provider/hermesGatewayHttp.ts @@ -1,8 +1,14 @@ import { + CommandId, + HERMES_GATEWAY_PROTOCOL_VERSION, HermesGatewayConnectionHello, HermesGatewayPluginToT3Message, HermesGatewayT3ToPluginMessage, + MessageId, + type ThreadId, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -11,6 +17,9 @@ import * as Schema from "effect/Schema"; import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; import * as Socket from "effect/unstable/socket/Socket"; +import { getOrCreateHomeThread } from "../orchestration/homeThreads.ts"; +import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { HermesGatewayBroker, type HermesGatewayConnectionRegistration, @@ -28,6 +37,107 @@ const isConnectionHello = Schema.is(HermesGatewayConnectionHello); export const hermesGatewayWebSocketRouteLayer = Layer.unwrap( Effect.gen(function* () { const broker = yield* HermesGatewayBroker; + const engine = yield* OrchestrationEngineService; + const query = yield* ProjectionSnapshotQuery; + const crypto = yield* Crypto.Crypto; + + /** + * Write one proactive delivery into the instance's home thread and ack it. + * + * The ack is sent **only after the dispatch succeeds**. The plugin purges + * its queued copy on the ack and on nothing else, so acking optimistically + * would silently drop deliveries whenever a write failed. An unacked + * delivery is retried on the next connect and deduped there by + * `deliveryId`, which makes the pessimistic order the safe one. + * + * Accepted from either connection role, and deliberately not generation- + * fenced: a delivery carries no session and cannot conflict with the live + * connection's turns, and fencing it would reject exactly the out-of- + * process cron case this exists to serve. + */ + const deliverHomeNotification = ( + registration: HermesGatewayConnectionRegistration, + message: Extract, + transport: { + readonly send: ( + frame: HermesGatewayT3ToPluginMessage, + ) => Effect.Effect; + }, + ) => + Effect.gen(function* () { + // Re-resolve rather than trusting the plugin's threadId: its cached + // T3_HOME_CHANNEL may name a thread from a previous designation, and a + // delivery must never land in an arbitrary caller-named thread. + const homeThreadId = yield* getOrCreateHomeThread({ + instanceId: registration.instanceId, + title: registration.accepted.nickname, + }); + + // Dedupe here, against the projection, before dispatching. + // + // The decider also dedupes, but it can only see the in-memory command + // read model — which is built with `messages: []` on every thread + // (`getCommandReadModel`, deliberately, to avoid hydrating message + // bodies at boot). Its scan therefore matches nothing, and a replay + // after a server restart appends a second copy. This read hits + // `projection_thread_messages`, where the delivery actually lives, so + // it is the check that holds across a restart — exactly the case the + // plugin's durable queue exists to produce. + const alreadyDelivered = (threadId: ThreadId) => + query.getThreadDetailById(threadId).pipe( + Effect.map( + Option.match({ + onNone: () => false, + onSome: (thread) => + thread.messages.some( + (candidate) => candidate.notification?.deliveryId === message.deliveryId, + ), + }), + ), + Effect.orElseSucceed(() => false), + ); + + if (!(yield* alreadyDelivered(homeThreadId))) { + const dispatched = yield* Effect.result( + engine.dispatch({ + type: "thread.notification.deliver", + commandId: CommandId.make(yield* crypto.randomUUIDv4), + threadId: homeThreadId, + messageId: MessageId.make(yield* crypto.randomUUIDv4), + deliveryId: message.deliveryId, + kind: message.kind, + label: message.label, + text: message.text, + createdAt: message.createdAt, + }), + ); + + // A dispatch failure is not proof the delivery is absent — a racing + // socket may have won between the read above and this write. Re-read + // before giving up, or that delivery goes unacked forever and the + // plugin replays it on every single reconnect. + if (dispatched._tag === "Failure" && !(yield* alreadyDelivered(homeThreadId))) { + return yield* Effect.fail(dispatched.failure); + } + } + + yield* transport.send({ + type: "home.deliver.ack", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + deliveryId: message.deliveryId, + }); + }).pipe( + Effect.catchCause((cause) => + // Deliberately no ack: the plugin keeps the delivery queued and + // retries it on the next connect. + Effect.logWarning("Hermes home delivery failed", { + instanceId: registration.instanceId, + deliveryId: message.deliveryId, + cause: Cause.pretty(cause), + }), + ), + ); + return HttpRouter.add( "GET", HERMES_GATEWAY_WEBSOCKET_PATH, @@ -76,7 +186,31 @@ export const hermesGatewayWebSocketRouteLayer = Layer.unwrap( ), ); yield* Ref.set(registration, Option.some(registered)); - yield* transport.send(registered.accepted); + + // Resolve the home thread here rather than inside + // `registerConnection`, whose error channel is exactly + // `connection.rejected`: a thread-creation failure is not a + // reason to refuse an authenticated plugin. On failure the + // handshake completes without `homeThreadId`, the plugin keeps + // whatever designation it already had, and the next connect + // converges — which is the whole point of converge-on-read. + const homeThreadId = yield* getOrCreateHomeThread({ + instanceId: registered.instanceId, + title: registered.accepted.nickname, + }).pipe( + Effect.map(Option.some), + Effect.catchCause((cause) => + Effect.logWarning("home thread resolution failed", { + instanceId: registered.instanceId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(Option.none())), + ), + ); + + yield* transport.send({ + ...registered.accepted, + ...(Option.isSome(homeThreadId) ? { homeThreadId: homeThreadId.value } : {}), + }); return; } @@ -84,6 +218,17 @@ export const hermesGatewayWebSocketRouteLayer = Layer.unwrap( yield* transport.close(4002, "connection.hello may only be sent once"); return; } + + // Deliveries are handled on the socket that carried them rather + // than through the broker's event stream, because the ack has to + // go back to *this* connection — which for an out-of-process cron + // run is a short-lived delivery socket that no stream subscriber + // can address. + if (message.type === "home.deliver") { + yield* deliverHomeNotification(current.value, message, transport); + return; + } + yield* broker.receive(current.value, message); }).pipe( Effect.catch((cause) => diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index ffb02198ec..31ccf944ed 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -201,6 +201,30 @@ describe.sequential("signRelayAgentActivityPublishProof", () => { }, } as unknown as OrchestrationEvent), ).toBe(false); + // A cron result or agent-initiated message is exactly the news push + // exists for; a lifecycle notice appends quietly and must never ring. + for (const kind of ["cron", "message", "handoff", "other"] as const) { + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.notification-delivered", + payload: { + threadId: "thread-1" as ThreadId, + notification: { kind, label: "Cron: daily-digest", deliveryId: "delivery-1" }, + }, + } as unknown as OrchestrationEvent), + ).toBe(true); + } + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.notification-delivered", + payload: { + threadId: "thread-1" as ThreadId, + notification: { kind: "lifecycle", label: "Agent restarted", deliveryId: "delivery-2" }, + }, + } as unknown as OrchestrationEvent), + ).toBe(false); }); it("deduplicates awareness state updates whose only change is their event timestamp", () => { diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 58de98f1ca..dde9ff156c 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -78,6 +78,11 @@ export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boo case "thread.runtime-mode-set": case "thread.interaction-mode-set": return false; + case "thread.notification-delivered": + // A cron result or agent-initiated message is exactly the kind of news + // push exists for. A lifecycle notice ("agent restarted") is not: it + // appends quietly and must never ring a device. + return event.payload.notification.kind !== "lifecycle"; case "thread.activity-appended": return ( event.payload.activity.kind === "approval.requested" || diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index a5f8011f53..50deb3a549 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -96,6 +96,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), + getThreadArchiveStateById: () => Effect.succeed(Option.none()), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -161,6 +162,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), @@ -206,6 +208,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), @@ -257,6 +260,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa getThreadCheckpointContext: () => Effect.succeed(Option.none()), getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), + getThreadArchiveStateById: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 510389b7ef..c0febc9911 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -73,6 +73,7 @@ import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts"; import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts"; import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { getOrCreateAgentProject } from "./orchestration/agentProjects.ts"; +import { isHomeThread } from "./orchestration/homeThreads.ts"; import { observeRpcEffect as instrumentRpcEffect, observeRpcStream as instrumentRpcStream, @@ -262,6 +263,7 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< { type: | "thread.message-sent" + | "thread.notification-delivered" | "thread.proposed-plan-upserted" | "thread.activity-appended" | "thread.turn-diff-completed" @@ -271,6 +273,9 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< > { return ( event.type === "thread.message-sent" || + // A proactive delivery appends a transcript message, so an open detail + // subscription has to receive it or the row only appears on reload. + event.type === "thread.notification-delivered" || event.type === "thread.proposed-plan-upserted" || event.type === "thread.activity-appended" || event.type === "thread.turn-diff-completed" || @@ -1124,6 +1129,23 @@ const makeWsRpcLayer = ( ORCHESTRATION_WS_METHODS.dispatchCommand, Effect.gen(function* () { const normalizedCommand = yield* normalizeDispatchCommand(command); + + // A home thread is a fixed designation, not a movable one: + // deleting it would leave its agent with nowhere to deliver, and + // the next handshake would silently mint a replacement, orphaning + // the history in the old one. This is the real guard — the UI + // only declines to offer the action. + if ( + normalizedCommand.type === "thread.delete" && + (yield* isHomeThread(normalizedCommand.threadId)) + ) { + return yield* Effect.fail( + new OrchestrationDispatchCommandError({ + message: "This agent's Home thread cannot be deleted.", + }), + ); + } + const shouldStopSessionAfterArchive = normalizedCommand.type === "thread.archive" ? yield* projectionSnapshotQuery diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 3d6090aa26..772a198ebd 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -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"]); + }); }); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 555072a538..88108e00f2 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -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 { 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>): ReadonlyMap { + const byProjectKey = new Map(); + 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 = { @@ -960,6 +998,9 @@ export function buildAgentSidebarEntries )} {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 && ( + + + } + > + + + + Home thread — this agent’s proactive messages land here + + + )} {renamingThreadKey === threadKey ? ( @@ -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, diff --git a/apps/web/src/components/agents/AgentPage.logic.test.ts b/apps/web/src/components/agents/AgentPage.logic.test.ts index 55bfba1221..b3956174a7 100644 --- a/apps/web/src/components/agents/AgentPage.logic.test.ts +++ b/apps/web/src/components/agents/AgentPage.logic.test.ts @@ -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 { + 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"]); + }); +}); diff --git a/apps/web/src/components/agents/AgentPage.logic.ts b/apps/web/src/components/agents/AgentPage.logic.ts index f198200cb3..14f311cb74 100644 --- a/apps/web/src/components/agents/AgentPage.logic.ts +++ b/apps/web/src/components/agents/AgentPage.logic.ts @@ -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, + 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; + 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. * diff --git a/apps/web/src/components/agents/AgentPage.tsx b/apps/web/src/components/agents/AgentPage.tsx index 470c6c17bb..710641b8ad 100644 --- a/apps/web/src/components/agents/AgentPage.tsx +++ b/apps/web/src/components/agents/AgentPage.tsx @@ -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 ( +
+ + {/* Withheld for the home thread: the server's decider rejects the + delete, so the button could only ever produce an error. */} + {props.onDelete && !isHomeThread ? ( + + ) : null} +
+ ); +} + 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(null); const [error, setError] = useState(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( + (settings) => settings.sidebarThreadSortOrder, + ); + const timestampFormat = useClientSettings( + (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 + } + headerAction={ + visibleThreads.length > 0 ? ( + {visibleThreads.length} + ) : null + } + > + + {visibleThreads.length === 0 ? ( +

+ No threads yet. Start one with “New thread” above. +

+ ) : ( +
+ {visibleThreads.map((thread) => ( + + ))} +
+ )} +
+
+ }>

diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index ae190e0006..775de684f4 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -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 + + {badge.label} + + ); +} + function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)"); + const notificationBadge = resolveNotificationBadge(row.message.notification); return ( <>

+ {notificationBadge ? : null} = {}, +): 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 }); + }); +}); diff --git a/apps/web/src/components/chat/notificationBadge.logic.ts b/apps/web/src/components/chat/notificationBadge.logic.ts new file mode 100644 index 0000000000..14bdc2ccb1 --- /dev/null +++ b/apps/web/src/components/chat/notificationBadge.logic.ts @@ -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 = { + 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" }; +} diff --git a/docs/project/hermes-home-channel-plan.md b/docs/project/hermes-home-channel-plan.md index 84af95c876..b846812164 100644 --- a/docs/project/hermes-home-channel-plan.md +++ b/docs/project/hermes-home-channel-plan.md @@ -23,7 +23,10 @@ Three independent gates block Hermes-initiated messages into T3: 1. **Plugin turn gate** — every emitter requires `_active_turns[thread_id]`, populated only by a T3-issued `turn.start`; `send()` fails with `"no active T3 turn"` - (`adapter.py:207-209`, `:254-256`). + (`adapter.py:209`, `:256`). Since the finalize-bug fixes (`3f71c601a`), turn + completion is keyed **exclusively** off `notify=True` metadata on `send()` + (`adapter.py:212-217`); `finalize` on `edit_message` is ignored outright. Any + proactive branch added to `send()` must respect that contract — see Part 3. 2. **Contract gate** — no plugin→T3 frame in protocol v2 opens a session or turn (`packages/contracts/src/hermesGateway.ts:672-694`); everything is a reply carrying a T3-minted `requestId`. @@ -190,19 +193,63 @@ env-only resolution path is always in sync with T3's durable designation. ### Adapter delivery path -`T3PlatformAdapter.send(chat_id, content, metadata)` grows a proactive branch: when -there is **no active turn** for the target and `chat_id` equals the home thread id, -emit `home.deliver` instead of failing with `"no active T3 turn"`. Kind/label -classification is best-effort from what Hermes passes in `metadata` and the send -context (cron deliveries are identifiable; gateway startup/shutdown broadcasts match -known message shapes; everything else defaults to `kind: "message"`, label "Hermes"). -Sends to a non-home thread without an active turn keep the current explicit error — -scope creep into "message any thread unprompted" is deliberately excluded. +`T3PlatformAdapter.send(chat_id, content, metadata)` grows a proactive branch for the +home thread. **The gate must be provenance, not merely turn absence.** The naive rule +("no active turn for this thread → `home.deliver`") deadlocks against the +notify-completion contract when the home thread itself has a live turn: a cron or +`send_message` delivery targeting the home chat while the user is mid-conversation +there would fall into the active-turn path, be streamed as that turn's assistant +content, and — because final cron deliveries arrive notify-stamped — **complete the +user's live turn with the cron output as its answer**. That is the same +keyed-off-the-wrong-signal defect class COMPATIBILITY.md documents for `finalize`. -The `/sethome` nudge suppression (`adapter.py:41-46`, `:211-214`, `:258-259`) stays: -once `env_enablement_fn` seeds a home channel Hermes stops emitting the nudge +The discriminator already exists: `_gateway_session_key()` (`adapter.py`, added in +`3f71c601a`) reads `HERMES_SESSION_KEY` from Hermes' session contextvar. A genuine +turn reply is produced inside the turn's session context, so the key resolves to this +plugin's `build_session_key` id for that thread; cron deliveries run in their own +`cron_*` session and broadcasts run in none, so the key is absent or names a different +session. The branch rule in `send()` is therefore: + +- Active turn for `chat_id` **and** session key matches that turn's session → normal + turn path (`_emit_assistant_content`, `notify` completes the turn). +- `chat_id` is the home thread and the session key does **not** match an active turn + there (or no turn exists) → emit `home.deliver`. Never touch `_active_turns`. +- Non-home thread without a matching active turn → keep the current explicit + `"no active T3 turn"` error; "message any thread unprompted" stays out of scope. + +Kind/label classification is best-effort from `metadata` and the send context (cron +deliveries are identifiable; gateway startup/shutdown broadcasts match known message +shapes; everything else defaults to `kind: "message"`, label "Hermes"). + +Three constraints from the turn-lifecycle fixes (`3f71c601a`, `a4000b86d`, +COMPATIBILITY.md "Turn completion is keyed off `notify`, never `finalize`") shape +this branch: + +- **Ordering inside `send()`.** The steer-control capture + (`_capture_steer_control_response`, `adapter.py:205`) must stay first — steer + acknowledgements arrive with `notify=True` and must never be misread as proactive + deliveries. The proactive branch slots after capture, gated by the provenance rule + above. +- **`notify` does not end anything here.** In the active-turn path `notify=True` + triggers `_complete_turn`; in the proactive branch there is no turn to complete — + the metadata is consumed only as a classification hint (final cron deliveries + arrive notify-stamped via `_mark_notify_metadata`, `gateway/platforms/base.py:89`). + The branch must not touch `_active_turns` or emit any turn/item frames — only + `home.deliver`. +- **Proactive edits are not supported.** Hermes' progress loop may follow a `send` + with `edit_message` calls against the returned `message_id` (the tool-progress + bubble pattern). `edit_message` outside an active turn keeps returning + `"no active T3 turn"` — a delivery is an atomic document, not a streaming surface. + In practice cron/`send_message`/lifecycle deliveries are single sends; if an + upstream path ever streams a home delivery, revisit with a + `home.deliver`-supersedes-by-`deliveryId` scheme rather than edit frames. + +The `/sethome` nudge suppression (`adapter.py:41-46`; checks at `:211`, `:258`) +stays: once `env_enablement_fn` seeds a home channel Hermes stops emitting the nudge naturally, but the suppression covers the pre-designation window (first connect before -any `connection.accepted` has written the env var). +any `connection.accepted` has written the env var). Note the nudge check now also +gates on `notify` for turn completion (`adapter.py:211-214`) — the suppression tests +in `tests/test_adapter.py` pin this and must keep passing. ### Durable plugin-side queue @@ -238,6 +285,88 @@ location and any metadata fields read for classification are new entries). (server-side decider rejection is the real guard; UI just avoids offering it). - Composer in the home thread is the normal Hermes composer — replying starts an ordinary `session.ensure`/`turn.start` flow on the same `threadId`. +- **Pinning must survive the sidebar dedupe.** `visibleSidebarSections` now + de-duplicates by `projectKey` (`Sidebar.tsx:3555+`, added in `3f71c601a`'s batch) + and `getSidebarThreadIdsToPrewarm` dedupes thread ids. Home-thread pinning is a + sort inside one section's thread list, so it composes with both — but the pinned + ordering must be applied before the prewarm slice so Home is always warm. + +--- + +## Part 5 — Bundled fix: settled-turn activity escapes the "Worked for …" fold + +Not home-channel machinery, but it lands in the same surfaces (Hermes activity +ordering in the timeline) and the home thread will render notification + turn +activity constantly, so it ships with this work. + +**Symptom.** After a Hermes turn settles, its activity should collapse behind the +"Worked for …" fold above the final answer. Instead the activity splits: one cluster +(work summary) folds correctly above, and a second cluster (the steps taken / +"Work Log" with rows like "Hermes activity is running …") renders **below** the final +assistant message, outside the fold. Both belong above. + +**What's already fixed.** `a4000b86d` reordered `_complete_turn` to close the live +status item before the assistant message, because T3's fold only captures entries +preceding the turn's terminal message — the status item was being stamped ~2ms after +the answer and escaping. That fix is correct but insufficient: the symptom still +reproduces (observed post-fix with a "Work Log — Hermes activity" section below the +answer), which means at least one more path produces late- or mis-attributed entries. + +**How the fold actually works** (`MessagesTimeline.logic.ts`): + +- `deriveTimelineEntries` (`session-logic.ts:1340-1366`) merges messages, plans, and + work entries and sorts **purely by `createdAt` string compare**. Assistant messages + sort at their _creation_ time (early in the turn); activities re-stamp `createdAt` + on every update (the projector replaces by id and re-sorts, + `projector.ts:725-753`), so a turn's activities always sort _after_ its assistant + message. Position alone is therefore expected to be "activities below". +- The fold compensates: `deriveTurnFolds` (`MessagesTimeline.logic.ts:285-404`) + groups entries by `turnId` and hides **every non-terminal entry of a settled turn + regardless of timestamp position**. So a trailing activity row that carries the + right `turnId` cannot escape the fold. +- Consequently, an entry rendering below the final message **must have failed turn + attribution** — grouping skips entries whose `turnId` resolves null + (`MessagesTimeline.logic.ts:311-318`), and unattributed entries can never be hidden. + +**Candidate mechanisms to run down, in likelihood order:** + +1. **Late frames lose their turn.** Plugin tool hooks run on Hermes tool worker + threads; a `post_tool_call` → `item.completed` frame can arrive after + `turn.completed`. `ProviderRuntimeIngestion`'s turn-conflict gate + (`ProviderRuntimeIngestion.ts:1370-1411`) rejects events naming a non-active turn + — but any acceptance path that strips or nulls `turnId` (or an ingestion branch + that emits the activity with `toTurnId(...) ?? null`) produces exactly this + symptom. Check what happens to an `item.*` frame for a just-completed turn. +2. **Command-dispatch race.** Activity appends and message finalization are separate + orchestration commands; wire order (status completed before assistant, per + `a4000b86d`) does not guarantee commit order. If the activity append commits after + the turn record settles, does any code path re-key or drop its `turnId`? +3. **Fallback attribution gap.** `_turn_for_tool_hook`'s sole-active-turn fallback + emits nothing when it cannot resolve — but the _generic status_ item + (`_ensure_generic_activity`) and any frames emitted between `notify` completion + and socket flush should be audited for a window where `turn.turn_id` is stale or + the frame is built without it. + +The decisive experiment: reproduce, then inspect the projected thread — the escaping +activity row's `turnId` in `projection_thread_activities`. Null confirms attribution +loss (mechanisms 1/3); a correct `turnId` with the row still visible would falsify +the fold analysis and point back at web-side grouping. + +**Fix direction.** Two layers, both worth doing: + +- Root cause: guarantee `turnId` attribution end-to-end for every activity a turn + produces, including frames that land after `turn.completed` (accept-and-attribute + late items for a recently-completed turn rather than dropping/nulling). +- Defense: the fold should not depend on perfect attribution. For a settled turn, + any work entry timestamped between the turn's first entry and its terminal + message's `updatedAt` (plus a small trailing grace window) with no other turn + claiming it belongs to that turn's fold. This also future-proofs the home thread, + where notification rows and turn activity will interleave. + +Regression test: replay the recorded frame sequence of a real Hermes turn (the +existing `test_adapter.py` frame-replay pattern) plus a late `item.completed`, and +assert the derived timeline rows place no work/activity row after the terminal +assistant message of a settled turn. --- @@ -259,6 +388,9 @@ Each step typechecks and is testable on its own: 6. **Web UI** — snapshot `homeThreadId`, pinned row, notification badges, delete suppression. 7. **Push** — `AgentAwarenessRelay` acceptance + headline mapping. +8. **Fold-escape fix (Part 5)** — independent of 1–7; can land first. Doing it + before the home-channel UI keeps notification rows from inheriting the same + mis-ordering. Steps 1–3 make T3 able to receive; step 4 makes the flagship flows (cron via live gateway, `send_message`, lifecycle, `/handoff`) work end to end; 5–7 complete it. @@ -293,6 +425,14 @@ Manual checks: generation-bumping a live gateway socket (verify with a concurrent live connection). 9. Regression: Claude/Codex threads and non-home Hermes threads unchanged; unsolicited sends to non-home threads still error. +10. Turn/delivery interleave in Home: while a user turn is running in the home + thread, fire a `deliver=t3` cron job → the delivery lands as a notification row + and the live turn keeps streaming and completes normally on its own `notify` + (this is the provenance-gate check from Part 3 — the failure mode is the cron + output completing the user's turn). +11. Part 5: settle a Hermes turn that used tools → all activity, including the + status line and every tool row, folds behind "Worked for …"; nothing renders + between or below the final answer. Automated: `pnpm typecheck`, `pnpm test`, `pnpm lint`; plugin tests in `integrations/hermes-t3-gateway/tests` (queue FIFO + ack purge, nudge suppression @@ -313,3 +453,15 @@ still pinned, proactive-send branch, standalone sender against a mock server); - **Lifecycle notice volume.** Frequent gateway restarts write quiet rows into Home. If that proves noisy, Hermes' per-platform `gateway_restart_notification: false` opt-out is the escape hatch (a one-line config change, no code). +- **The sole-active-turn tool-hook fallback misattributes cron tool activity.** + `_turn_for_tool_hook` (added in `3f71c601a`) falls back to "the sole active turn" + when no routing key resolves. The plugin's `pre/post_tool_call` hooks are + process-global, so a **cron job running tools** while exactly one T3 turn is + active resolves through that fallback and paints the cron job's tool calls into + the unrelated live turn. Upstream is aware of the general hazard (the cron + scheduler deliberately avoids the process-global env var for exactly this + routing risk, `cron/scheduler.py:3077`). Low-frequency today; this feature makes + `deliver=t3` cron jobs common, so fix alongside Part 3: before the sole-turn + fallback, exclude hook calls whose `session_id` is a cron run id (`cron_*` + prefix, `cron/scheduler.py:3017`) — their activity belongs to the eventual + `home.deliver`, not to any live turn. diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.ts index 9b3bcf2298..b66b59b1ad 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.ts @@ -187,6 +187,8 @@ function statusForPhase(phase: RelayAgentActivityState["phase"]): string { return "Approval"; case "waiting_for_input": return "Input"; + case "notification": + return "Update"; case "completed": return "Done"; case "failed": diff --git a/integrations/hermes-t3-gateway/COMPATIBILITY.md b/integrations/hermes-t3-gateway/COMPATIBILITY.md index b56877bf51..021addf840 100644 --- a/integrations/hermes-t3-gateway/COMPATIBILITY.md +++ b/integrations/hermes-t3-gateway/COMPATIBILITY.md @@ -3,6 +3,11 @@ The plugin deliberately uses only the public Hermes plugin and platform-adapter surfaces audited at Hermes Agent upstream commit `62e07223` (v0.19.0). +Scope note: this file inventories **upstream Hermes** surfaces only. T3-side +machinery the plugin talks to over the wire — `withHermesConfig`, the broker's +generation fencing, `getOrCreateHomeThread` — is not a Python concern and is +documented on the T3 side; only the wire contract those produce appears here. + Audited surfaces, all present at that commit: | Surface | Location at 62e07223 | @@ -35,9 +40,37 @@ Audited surfaces, all present at that commit: | Active-command inline dispatch | `gateway/platforms/base.py:4926` | | User-plugin path `$HERMES_HOME/plugins/` | `hermes_cli/plugins.py:10`, `:1350` | -This inventory describes gateway wire protocol v2. Protocol v2 adds active-turn -recovery in `session.ready` and authoritative `content.snapshot` replacement; -older server/plugin pairs are rejected during the handshake. +Home-channel surfaces, added for protocol v3: + +| Surface | Location at 62e07223 | +| ------------------------------------------ | ---------------------------------- | +| `cron_deliver_env_var` registration flag | `gateway/platform_registry.py:143` | +| `standalone_sender_fn` registration flag | `gateway/platform_registry.py:159` | +| Standalone-sender invocation | `tools/send_message_tool.py:741` | +| `_home_target_env_var` fallback convention | `gateway/run.py:1541` | +| `_resolve_home_env_var` (plugin lookup) | `cron/scheduler.py:1025` | +| `env_enablement_fn` `home_channel` promote | `gateway/config.py:2648` | +| `HomeChannel` dataclass | `gateway/config.py:421` | +| `get_home_channel` | `gateway/config.py:1022` | +| `get_hermes_home` (queue/state base) | `hermes_constants.py:106` | +| `get_hermes_home` re-export | `hermes_cli/config.py:686` | +| Cron run-id shape (`cron_*`) | `cron/scheduler.py:3017`, `:3484` | +| Cron session-var clearing | `cron/scheduler.py:3066-3091` | +| Cron `job_id` in routed metadata | `cron/scheduler.py:1782` | +| Cron metadata reaching `adapter.send` | `gateway/delivery.py:606` | +| Cron wrap header (`Cronjob Response: …`) | `cron/scheduler.py:1513` | +| Gateway online notice | `gateway/run.py:17277` | +| Gateway restart notice | `gateway/run.py:17236` | +| Gateway shutdown/restarting notice | `gateway/run.py:6599` | +| `/handoff` synthetic source identity | `gateway/run.py:8854` | +| `HERMES_SESSION_USER_ID` binding | `gateway/run.py:17372` | +| Session-context lifetime around a turn | `gateway/run.py:12972` → `:14626` | + +This inventory describes gateway wire protocol v3. Protocol v2 added active-turn +recovery in `session.ready` and authoritative `content.snapshot` replacement; v3 +adds `role` on `connection.hello`, `homeThreadId` on `connection.accepted`, and +the `home.deliver` / `home.deliver.ack` pair. Older server/plugin pairs are +rejected during the handshake — the version policy stays fail-closed. ## Mapped in the initial scope @@ -55,6 +88,7 @@ older server/plugin pairs are rejected during the handshake. | `load_config_readonly()["agent"]["reasoning_effort"]` | Optional `reasoningEffort` on `describe.response` | | `skills_list()` metadata | `skills` on `describe.response` | | `skill_view(name, preprocess=False)` | `markdown` on `skill.body.response` | +| Cron `deliver=t3`, `send_message t3`, lifecycle | `home.deliver` / `home.deliver.ack` | ## Known limitations @@ -195,7 +229,18 @@ older server/plugin pairs are rejected during the handshake. and the wire type is non-empty. That takes the ordinary correlated `protocol.error` path. - Attachments are not accepted. They are the first planned post-stability - feature; the capability is reserved and fixed to `false` in protocol v2. + feature; the capability is reserved and fixed to `false` in protocol v3. The + `standalone_sender_fn` signature accepts `media_files` / `force_document` for + parity with `gateway/platform_registry.py:150-158`, but the v3 wire contract + has no attachment framing, so both are ignored (logged, not silently + dropped). +- **Kind/label classification is heuristic.** `adapter.send()` carries no + structured "this is a cron delivery" marker on every path, so the plugin + reads what does exist (see "Home-channel delivery" below). A + misclassification costs a wrong badge — and, for `lifecycle`, a delivery that + raises its hand when it should have landed quietly — never a lost delivery. + If upstream ever exposes delivery provenance in metadata, adopt it and + replace the heuristics here. ## Turn completion is keyed off `notify`, never `finalize` @@ -221,7 +266,7 @@ boundary, and `_complete_turn` is reached from nowhere else on the output path. ### The signal that does NOT end a turn: `finalize=True` on `edit_message` `finalize` reads like "last edit of the response", and the base class documents -it that way (`gateway/platforms/base.py:3178-3186`). It is **not** a turn +it that way (`gateway/platforms/base.py:3176-3183`). It is **not** a turn boundary. Two upstream paths set it mid-turn: 1. **The tool-progress loop.** When an adapter declares @@ -266,6 +311,145 @@ would hang in the running state with the full answer streamed but no `turn.completed`. That is the opposite failure mode from the original bug and would show up as spinners that never resolve, not truncated answers. +## Home-channel delivery: the gate is provenance, not turn absence + +Hermes-initiated output — cron results, `send_message` with a bare `t3` target, +gateway lifecycle notices, `/handoff t3` — has no T3-issued turn to stream into. +It is emitted as `home.deliver` against the instance's durable home thread. + +### The deadlock this design exists to avoid + +The naive rule — "no active turn for this thread → deliver" — is wrong, and +wrong in the same keyed-off-the-wrong-signal way as the `finalize` bug above. +When the home thread itself has a live user turn, a cron delivery targeting it +would fall into the active-turn path, stream as that turn's assistant content, +and — because final cron deliveries arrive notify-stamped via +`_mark_notify_metadata` (`gateway/platforms/base.py:89`) — **complete the user's +live turn with the cron output as its answer**. + +The discriminator is `HERMES_SESSION_KEY`. The gateway binds it onto the turn's +context for the whole handler (`gateway/run.py:12972` → `:14626`, read via +`get_session_env`), and every send a turn produces — streamed or final — happens +inside that scope, so a genuine turn reply resolves to this plugin's +`build_session_key` id for its thread. Cron runs under its own +`cron__` session with the gateway routing keys explicitly +cleared (`cron/scheduler.py:3066-3091`), and lifecycle broadcasts run in no +session at all. + +`_is_proactive_delivery` therefore decides in this order: + +1. Session key matches an active turn on this thread → **turn content**, never + a delivery. Checked first, so a turn reply can never be rerouted. +2. Not the home thread → never a delivery. "Message any thread unprompted" + stays out of scope and the existing `"no active T3 turn"` error is returned + verbatim. +3. Home thread, no active turn → delivery. There is nothing it could belong to. +4. Home thread **with** a non-matching active turn → delivery only when + provenance is positively established. This is the conservative half: an + unattributable send in that window stays with the turn (at worst misplaced + inside the same thread) rather than being torn out of a turn it may belong + to. So an unclassifiable send can never steal a live answer, and a + recognisable cron/lifecycle/handoff delivery never completes one. + +Ordering inside `send()` is load-bearing: `_capture_steer_control_response` +stays first, because steer acknowledgements arrive with `notify=True` and must +never be read as deliveries. + +`edit_message` has **no** proactive branch and keeps returning `"no active T3 +turn"` outside a turn. A delivery is an atomic document, not a streaming +surface. If an upstream path ever streams a home delivery, revisit with a +`home.deliver`-supersedes-by-`deliveryId` scheme rather than edit frames. + +### What classification keys off + +All best-effort, in precedence order, all degrading to +`("message", "Hermes", uncertain)`: + +- `metadata["job_id"]` — the only structured signal. The cron scheduler stamps + it into the routed metadata (`cron/scheduler.py:1782`) and + `DeliveryRouter._deliver_to_platform` passes the dict through to + `adapter.send` unchanged (`gateway/delivery.py:606`). +- The cron wrap header `Cronjob Response: ` (`cron/scheduler.py:1513`), + present whenever `cron.wrap_response` is on (the default), which also + supplies the human job name for the badge. +- Lifecycle literals: `gateway/run.py:17277`, `:17236`, `:6599`. These are + inline f-strings upstream, not exported constants, so they carry the same + drift risk as the `/sethome` notice and the `⏩ Steer queued` prefix. +- `HERMES_SESSION_USER_ID == "system:handoff"`, the synthetic source identity + `/handoff` dispatches under (`gateway/run.py:8854`, bound at `:17372`). + +### Registration contracts + +- **`cron_deliver_env_var="T3_HOME_CHANNEL"`.** The name is not free-form. + `_home_target_env_var` (`gateway/run.py:1541`) consults built-ins, then the + plugin registry via `_resolve_home_env_var` (`cron/scheduler.py:1025`), then + falls back to `f"{PLATFORM.upper()}_HOME_CHANNEL"` — exactly this string for + platform `t3`. Matching the fallback means `send_message`'s error hints and + cron's env-only resolution agree with what the plugin writes, with no + upstream override-table entry. Without the flag, `deliver=t3` is silently + dropped by cron. +- **`env_enablement_fn` seeds `home_channel`.** That key is magic: core pops it + out of the returned dict and promotes it to a real `HomeChannel` dataclass + (`gateway/config.py:2648-2660`, reading only `chat_id` / `name` / + `thread_id`). The promotion is what makes `get_home_channel("t3")` + (`gateway/config.py:1022`) resolve, which is what makes `send_message`, + lifecycle broadcasts, and `/handoff` work — core hardcodes env promotion only + for built-ins. T3 threads are the addressing unit, so `chat_id` **is** the + thread id and `thread_id` stays unset. +- **`standalone_sender_fn`.** Out-of-process cron has no live adapter + (`tools/send_message_tool.py:741`). The plugin dials T3 itself over a + short-lived socket announcing `role: "delivery"`. That role is load-bearing: + T3's broker registers a `gateway` connection under generation fencing and + displaces its predecessor, so a cron dial-in announcing the default role + would kick the live gateway socket off its own instance mid-turn. + +### Designation is a synced cache, not local state + +`T3_HOME_CHANNEL` is written by the plugin, never by the user. T3's settings +blob is authoritative and republishes `homeThreadId` on every +`connection.accepted`; the plugin compares and persists via `save_env_value` +(the same profile-aware helper enrollment uses) and mirrors into `os.environ` +so a running gateway needs no restart. A hand-edited value is overwritten on +the next reconnect — documented in the README. A read-only or managed `.env` +degrades to the in-process mirror only: routing works for the life of the +process and re-reconciles on the next connect. + +### Queue and state location + +The plugin previously persisted nothing to disk. It now keeps one JSONL outbox +at `/gateway/t3_home_delivery_queue.jsonl`, using +`get_hermes_home()` (`hermes_constants.py:106`, re-exported at +`hermes_cli/config.py:686`) as the base — the same accessor and the same +`gateway/` subdirectory Hermes' own Discord adapter uses for per-profile +adapter state (`plugins/platforms/discord/adapter.py:52`, `:272`, `:1694`). +Resolving through that accessor rather than `~/.hermes` makes the queue +profile-scoped: a second profile cannot replay another profile's deliveries +into its own home thread. + +Correctness rests on one rule: an entry is removed **only** on its +`home.deliver.ack`. Everything else — a socket that dropped mid-send, a server +that died before writing, a plugin restart — leaves the entry to be replayed, +which is safe because T3 dedupes on `deliveryId`. Acking before the durable +write on the server side would break this. The queue is capped at 300 entries +and drops oldest-first with a logged warning; one flush replays at most 50 +entries so a reconnect does not stall live traffic. + +### Cron tool-hook misattribution + +`_turn_for_tool_hook`'s sole-active-turn fallback is now skipped for cron runs. +The hooks are process-global, so a cron job running tools while exactly one T3 +turn happens to be live would resolve through that fallback and paint the cron +job's tool calls into an unrelated live conversation. Cron runs are identifiable +by the `cron__` session id the scheduler mints +(`cron/scheduler.py:3017`, passed to the agent at `:3484`) — the exact value the +hooks receive. Upstream treats the same routing hazard as real, clearing the +process-global session env vars for it (`cron/scheduler.py:3066-3091`). A cron +job's activity belongs to the eventual `home.deliver`, never to a live turn. + +Prefix matching carries the usual drift risk: if upstream renames the shape, +this degrades to the previous behaviour (cron tool rows may again be +misattributed to a sole live turn) rather than breaking anything. + ## Tool-progress chrome: the `format_tool_event` override is not the defence The plugin overrides `format_tool_event` to return `None` diff --git a/integrations/hermes-t3-gateway/README.md b/integrations/hermes-t3-gateway/README.md index 8d9fa49cfe..5e84c8aa77 100644 --- a/integrations/hermes-t3-gateway/README.md +++ b/integrations/hermes-t3-gateway/README.md @@ -4,7 +4,7 @@ Experimental Hermes platform plugin for connecting one already-running Hermes process to T3 Code. The plugin makes an outbound WebSocket connection; Hermes does not need to listen on a public port. -The gateway wire protocol is v2. The T3 server and Hermes plugin must be updated +The gateway wire protocol is v3. The T3 server and Hermes plugin must be updated together; mismatched versions fail the connection handshake closed. Each T3 thread maps deterministically to one Hermes gateway session. A new T3 @@ -54,6 +54,36 @@ The handshake also reports Hermes' configured default model so T3 can show a truthful label in its picker. It is read-only — Hermes owns model selection — and is omitted entirely if it cannot be read. +## The Home thread + +Every enrolled instance gets one **Home** thread in T3, created automatically — +there is nothing to set up and nothing to choose. It receives all of Hermes' +proactive output: cron results (`deliver=t3`), the agent's `send_message` tool +with a bare `t3` target, gateway online/shutdown notices, and `/handoff t3`. +Replying in it runs an ordinary Hermes turn in the same thread. + +**T3 owns the designation, and `T3_HOME_CHANNEL` is a synced cache of it.** The +plugin writes that variable itself: T3 republishes the home thread id on every +successful handshake, and the plugin compares and persists it with Hermes' +profile-aware `save_env_value` helper. A hand-edited `T3_HOME_CHANNEL` will +therefore be **overwritten on the next reconnect** — to move the Home thread, +change it in T3, not in `.env`. (`/sethome` is likewise inert for this platform: +the designation is fixed, so Hermes' "set a home channel" nudge is suppressed.) + +Deliveries are durable in both directions. Each one is written to a small JSONL +queue at `/gateway/t3_home_delivery_queue.jsonl` before it is sent +and removed only once T3 acknowledges it, so nothing is lost if either side +restarts mid-flight; queued deliveries flush on the next connect, and T3 +deduplicates so a replay is harmless. The queue is capped and drops oldest-first +with a logged warning rather than growing without bound. + +Cron works whether or not the gateway is co-resident. When `hermes cron` runs in +its own process there is no live adapter, so the plugin dials T3 over a +short-lived delivery connection — authenticated the same way, but never +registered as the instance's primary connection, so it cannot disturb a running +`hermes gateway`. If T3 is unreachable the delivery is queued and the cron job +still reports success. + ## Initial scope - Text input and live assistant streaming @@ -66,9 +96,11 @@ and is omitted entirely if it cannot be read. - Reconnect with bounded backoff - Version-incompatible and revoked credentials fail closed -T3 threads are session-only in the initial scope. The adapter suppresses Hermes' exact -first-chat `/sethome` notice without assigning a home channel or redirecting -cron and cross-platform delivery. +- Proactive delivery into the Home thread: cron, `send_message`, lifecycle + notices, `/handoff` — with a durable queue and out-of-process cron support + +Non-home T3 threads remain session-only: Hermes cannot message them unprompted, +and an unsolicited send to one still fails with `no active T3 turn`. Attachments intentionally advertise `false`. Adding bounded image/file input is the first post-stability feature and should not reuse arbitrary raw payloads. diff --git a/integrations/hermes-t3-gateway/__init__.py b/integrations/hermes-t3-gateway/__init__.py index b0acafb2c3..dfb9cfcc28 100644 --- a/integrations/hermes-t3-gateway/__init__.py +++ b/integrations/hermes-t3-gateway/__init__.py @@ -10,6 +10,8 @@ from .adapter import ( validate_config, ) from .cli import register_cli, t3_command +from .home import HOME_CHANNEL_ENV, standalone_send +from .home import HOME_CHANNEL_ENV, standalone_send def _pre_tool_call( @@ -53,6 +55,22 @@ def register(ctx) -> None: "HERMES_T3_GATEWAY_CREDENTIAL", ], env_enablement_fn=env_enablement, + # Cron home-channel delivery. The name is not free-form: Hermes + # resolves a platform's cron home target through `_home_target_env_var` + # (`gateway/run.py:1541`), which falls back to + # f"{PLATFORM.upper()}_HOME_CHANNEL" for any platform without a + # built-in override entry — exactly this string for platform `t3`. So + # `send_message`'s error hints, `/sethome` messaging, and cron's + # env-only resolution all agree with the value the plugin writes, with + # no upstream override table entry. Without this, `deliver=t3` is + # silently dropped by cron. + cron_deliver_env_var=HOME_CHANNEL_ENV, + # Out-of-process cron delivery: when `hermes cron` runs in a separate + # process from `hermes gateway` there is no live adapter, and without + # this hook `deliver=t3` fails with "No live adapter for platform". + # Dials T3 over a short-lived `role: "delivery"` socket so it cannot + # displace the live gateway connection. + standalone_sender_fn=standalone_send, max_message_length=120_000, emoji="🔺", pii_safe=True, diff --git a/integrations/hermes-t3-gateway/adapter.py b/integrations/hermes-t3-gateway/adapter.py index c33b4156b5..056f0d1128 100644 --- a/integrations/hermes-t3-gateway/adapter.py +++ b/integrations/hermes-t3-gateway/adapter.py @@ -23,6 +23,15 @@ from gateway.session import build_session_key from .cli import CREDENTIAL_ENV, INSTANCE_ID_ENV, NICKNAME_ENV, URL_ENV from .connection import T3GatewayConnection, dependency_available +from .home import ( + HOME_CHANNEL_ENV, + MAX_FLUSH_PER_CONNECT, + HomeDeliveryQueue, + build_delivery, + classify_delivery, + home_thread_id, + save_home_thread_id, +) from .protocol import ( canonical_tool_data, canonical_tool_item_type, @@ -139,6 +148,7 @@ class T3PlatformAdapter(BasePlatformAdapter): self._active_turns: dict[str, _TurnState] = {} self._approval_requests: dict[str, tuple[str, str]] = {} self._user_input_requests: dict[str, tuple[str, str]] = {} + self._home_queue = HomeDeliveryQueue() # Strong references to fire-and-forget tasks. asyncio only holds a weak # reference to a running task, so without this the GC may collect one # mid-flight and its exception surfaces as a bare warning. @@ -172,6 +182,7 @@ class T3PlatformAdapter(BasePlatformAdapter): hermes_version=_hermes_version(), on_message=self._handle_server_frame, on_state=self._handle_connection_state, + on_accepted=self._handle_connection_accepted, ) try: connected = await self._connection.connect() @@ -204,7 +215,10 @@ class T3PlatformAdapter(BasePlatformAdapter): captured = self._capture_steer_control_response(chat_id, content, reply_to) if captured is not None: return captured - turn = self._active_turns.get(str(chat_id)) + thread_id = str(chat_id) + turn = self._active_turns.get(thread_id) + if self._is_proactive_delivery(thread_id, turn, content, metadata): + return await self._deliver_to_home(thread_id, content, metadata) if turn is None: return SendResult(success=False, error="no active T3 turn") try: @@ -265,6 +279,170 @@ class T3PlatformAdapter(BasePlatformAdapter): async def get_chat_info(self, chat_id: str) -> dict[str, Any]: return {"name": f"T3 thread {chat_id}", "type": "dm"} + # ── proactive home delivery ──────────────────────────────────────── + + def _is_proactive_delivery( + self, + thread_id: str, + turn: _TurnState | None, + content: str, + metadata: dict[str, Any] | None, + ) -> bool: + """Decide whether this send is Hermes-initiated home delivery. + + **The gate is provenance, not turn absence.** The naive rule ("no + active turn for this thread → deliver") deadlocks against the + notify-completion contract the moment the home thread has a live turn: + a cron result or `send_message` targeting the home chat mid-conversation + would take the active-turn path, stream as that turn's assistant + content, and — because final cron deliveries arrive notify-stamped via + `_mark_notify_metadata` (`gateway/platforms/base.py:89`) — **complete + the user's live turn with the cron output as its answer.** That is the + same keyed-off-the-wrong-signal defect class as the `finalize` bug. + + The discriminator is `_gateway_session_key()`: the gateway binds + `HERMES_SESSION_KEY` onto the turn's context for the whole handler + (`gateway/run.py:12972` → `:14626`), and every send a turn produces — + streamed or final — happens inside that scope. A genuine turn reply + therefore resolves to this plugin's `build_session_key` id for its + thread. Cron runs in its own `cron_*` session with the gateway keys + explicitly cleared (`cron/scheduler.py:3066-3091`), and lifecycle + broadcasts run in no session at all, so neither resolves to the live + turn's key. + + The rules, in order: + + * A send whose session key matches an active turn on this thread is + that turn's own output. Never a delivery — checked first so a turn + reply can never be rerouted. + * A send to a non-home thread is never a delivery: "message any thread + unprompted" is deliberately out of scope, and the existing + `"no active T3 turn"` error stays verbatim for it. + * On the home thread with no active turn, any send is a delivery. + There is nothing it could belong to. + * On the home thread **with** an active turn whose session key does not + match, provenance must be positively established (`classify_delivery` + returning certain) before the send bypasses the turn. This is the + conservative half of the gate: an unattributable send in that window + falls through to the turn path — a possible misplacement inside the + same thread — rather than being torn out of a turn it may belong to. + An unclassifiable send can therefore never steal a live answer, and a + recognisable cron/lifecycle/handoff delivery never completes one. + """ + if turn is not None and self._gateway_session_key() == turn.session_id: + return False + home = home_thread_id() + if not home or thread_id != home: + return False + if turn is None: + return True + _kind, _label, certain = classify_delivery( + content, + metadata, + session_user_id=self._session_user_id(), + ) + return certain + + async def _deliver_to_home( + self, + thread_id: str, + content: str, + metadata: dict[str, Any] | None, + ) -> SendResult: + """Emit one `home.deliver`, queueing it until T3 acknowledges it. + + Deliberately touches none of the turn machinery. `_active_turns` is not + read or written, no turn/item frame is emitted, and `notify` — which + arrives True on every final cron delivery — is consumed only as a + classification hint. A delivery landing while the user has a live turn + in this same thread must leave that turn running. + """ + kind, label, _certain = classify_delivery( + content, + metadata, + session_user_id=self._session_user_id(), + ) + delivery = build_delivery( + thread_id=thread_id, + text=str(content or ""), + kind=kind, + label=label, + ) + delivery_id_value = str(delivery["deliveryId"]) + # Persist BEFORE sending. The queue is the durability guarantee: if the + # socket dies between here and the ack, the entry survives to be + # replayed on the next connect, and T3's `deliveryId` dedupe makes the + # replay harmless. + self._home_queue.append(delivery) + try: + await self._send_frame(delivery) + except Exception as exc: # noqa: BLE001 - adapter send must return SendResult + logger.warning( + "T3 home delivery %s could not be sent (%s); it is queued for " + "the next connect", + delivery_id_value, + exc, + ) + # Reported successful either way: the delivery is durably queued, and + # failing the send would make a cron job report an error for output + # that will in fact arrive. + return SendResult(success=True, message_id=delivery_id_value) + + async def _handle_connection_accepted(self, accepted: dict[str, Any]) -> None: + """Reconcile the home designation, then flush the delivery queue. + + T3's settings blob is the authoritative designation and it republishes + it on every successful handshake, so the plugin's `T3_HOME_CHANNEL` is + a synced cache: a differing local value — including a hand-edited one — + is overwritten. Reconciling on every accept bounds drift to a single + reconnect. + """ + thread_id = str(accepted.get("homeThreadId") or "").strip() + if thread_id and thread_id != home_thread_id(): + logger.info("T3 designated home thread %s", thread_id) + save_home_thread_id(thread_id) + elif thread_id: + save_home_thread_id(thread_id) + await self._flush_home_queue() + + async def _flush_home_queue(self) -> None: + """Replay unacknowledged deliveries oldest-first. + + Entries are NOT removed here — only a `home.deliver.ack` purges one. + Re-sending an entry T3 already durably wrote is harmless (it dedupes on + `deliveryId`); dropping one it never wrote is not. + """ + pending = self._home_queue.entries() + if not pending: + return + logger.info("Flushing %d queued T3 home deliver(y|ies)", len(pending)) + for entry in pending[:MAX_FLUSH_PER_CONNECT]: + try: + await self._send_frame(entry) + except Exception as exc: # noqa: BLE001 - the rest rides the next connect + logger.warning("T3 home delivery flush stopped: %s", exc) + return + + async def _acknowledge_home_delivery(self, message: dict[str, Any]) -> None: + """Purge a delivery T3 has durably written.""" + delivery_id_value = str(message.get("deliveryId") or "").strip() + if not delivery_id_value: + raise ValueError("home.deliver.ack requires a deliveryId") + self._home_queue.purge(delivery_id_value) + + @staticmethod + def _session_user_id() -> str: + """Read the bound session's user id, for `/handoff` classification. + + Returns `""` on any failure, exactly like `_gateway_session_key`. + """ + try: + from gateway.session_context import get_session_env + + return str(get_session_env("HERMES_SESSION_USER_ID", "") or "") + except Exception: # noqa: BLE001 - classification must never raise + return "" + def format_tool_event( self, event: Any, *, mode: str = "all", preview_max_len: int = 40 ) -> str | None: @@ -410,6 +588,8 @@ class T3PlatformAdapter(BasePlatformAdapter): await self._describe(message) elif frame_type == "skill.body.request": await self._send_skill_body(message) + elif frame_type == "home.deliver.ack": + await self._acknowledge_home_delivery(message) except ValueError as exc: await self._send_frame( protocol_error( @@ -965,19 +1145,47 @@ class T3PlatformAdapter(BasePlatformAdapter): 2. `HERMES_SESSION_KEY` from the Hermes session context. 3. The sole active turn, when exactly one exists — a single-threaded Hermes process has no ambiguity to resolve, and dropping the - activity would be strictly worse. + activity would be strictly worse. **Cron runs are excluded from + this step** (see below). Anything unresolved returns `None` and the item is simply not emitted; tool activity is decorative, so this must never raise or misroute. + + The cron exclusion: these hooks are process-global, so a cron job + running tools while exactly one T3 turn happens to be live would + resolve through the sole-turn fallback and paint the cron job's tool + calls into an unrelated live conversation. Cron runs are identifiable — + the scheduler builds its agent with + `session_id=f"cron_{job_id}_{timestamp}"` (`cron/scheduler.py:3017`, + passed at `:3484`), which is exactly the value these hooks receive as + `session_id`. Upstream treats the same routing hazard as real: the + scheduler deliberately clears the process-global session env vars for + it (`cron/scheduler.py:3066-3091`). A cron job's activity belongs to + the eventual `home.deliver`, never to a live turn, so it is dropped + rather than guessed at. """ thread_id = self._thread_by_session.get(str(session_id)) if thread_id is None: thread_id = self._thread_by_session.get(self._gateway_session_key()) if thread_id is not None: return self._active_turns.get(thread_id) + if self._is_cron_session(session_id): + return None if len(self._active_turns) == 1: return next(iter(self._active_turns.values())) return None + @staticmethod + def _is_cron_session(session_id: str) -> bool: + """True when this hook call belongs to a cron run, not a gateway turn. + + Keyed on the `cron_` prefix the scheduler mints at + `cron/scheduler.py:3017`. Matching a prefix rather than an exported + constant carries the usual drift risk: if upstream renames the shape, + this degrades to today's behaviour (cron tool rows may again be + misattributed to a sole live turn) rather than breaking anything. + """ + return str(session_id or "").startswith("cron_") + @staticmethod def _gateway_session_key() -> str: """Read the turn's gateway routing key from Hermes' session context. @@ -1181,15 +1389,45 @@ def validate_config(config: PlatformConfig) -> bool: ) -def env_enablement() -> dict[str, str] | None: +def env_enablement() -> dict[str, Any] | None: + """Seed `PlatformConfig.extra` from the environment at config-load time. + + Called by the platform registry's env-enablement hook before the adapter is + constructed, so `gateway status` and `get_connected_platforms()` reflect an + env-only enrollment without instantiating a connection. + + `home_channel` is a **magic key**, not an ordinary extra: core pops it out + of the returned dict and promotes it to a real `HomeChannel` dataclass on + the `PlatformConfig` (`gateway/config.py:2648-2660`, reading only + `chat_id` / `name` / `thread_id`). That promotion is what makes + `get_home_channel("t3")` resolve, which is in turn what makes + `send_message` with a bare `t3` target, the gateway's lifecycle broadcasts, + and `/handoff t3` work at all — core hardcodes env promotion only for + built-in platforms, so a plugin must supply it here. Pattern copied from + IRC (`plugins/platforms/irc/adapter.py:653-701`). + + The thread id comes from `T3_HOME_CHANNEL`, which T3 owns: the plugin + rewrites it from `homeThreadId` on every `connection.accepted`. Before the + first accept there is nothing to seed and the key is simply absent — Hermes + then behaves exactly as it did pre-home-channel, which is why the + `/sethome` nudge suppression is still needed for that window. + """ url = os.environ.get(URL_ENV, "").strip() instance_id = os.environ.get(INSTANCE_ID_ENV, "").strip() credential = os.environ.get(CREDENTIAL_ENV, "").strip() if not (url and instance_id and credential): return None - return { + seed: dict[str, Any] = { "url": url, "instance_id": instance_id, "credential": credential, "nickname": os.environ.get(NICKNAME_ENV, "").strip() or "Hermes", } + home = os.environ.get(HOME_CHANNEL_ENV, "").strip() + if home: + # T3 threads are the addressing unit end to end: `chat_id` IS the + # thread id, and the separate `thread_id` field stays unset. Setting + # both would make Hermes route `chat_id` + `thread_id` metadata at a + # platform whose `send(chat_id, ...)` already resolves the thread. + seed["home_channel"] = {"chat_id": home, "name": "Home"} + return seed diff --git a/integrations/hermes-t3-gateway/connection.py b/integrations/hermes-t3-gateway/connection.py index e143641924..d2300f70b5 100644 --- a/integrations/hermes-t3-gateway/connection.py +++ b/integrations/hermes-t3-gateway/connection.py @@ -21,6 +21,8 @@ except ImportError: # pragma: no cover - Hermes currently installs websockets MessageHandler = Callable[[dict[str, Any]], Awaitable[None]] StateHandler = Callable[[bool, str | None], Awaitable[None] | None] +AcceptedHandler = Callable[[dict[str, Any]], Awaitable[None]] +AcceptedHandler = Callable[[dict[str, Any]], Awaitable[None]] class ConnectionRejected(RuntimeError): @@ -72,10 +74,12 @@ async def authenticate_socket( authentication: dict[str, str], hermes_version: str, timeout: float = 20, + role: str = "gateway", ) -> dict[str, Any]: hello = connection_hello( hermes_version=hermes_version, authentication=authentication, + role=role, ) await socket.send(json.dumps(hello, separators=(",", ":"), ensure_ascii=False)) @@ -165,6 +169,7 @@ class T3GatewayConnection: hermes_version: str, on_message: MessageHandler, on_state: StateHandler | None = None, + on_accepted: AcceptedHandler | None = None, ): self.url = websocket_url(url) self.instance_id = instance_id @@ -172,6 +177,7 @@ class T3GatewayConnection: self.hermes_version = hermes_version self._on_message = on_message self._on_state = on_state + self._on_accepted = on_accepted self._socket: Any = None self._supervisor: asyncio.Task[None] | None = None self._send_lock = asyncio.Lock() @@ -266,7 +272,7 @@ class T3GatewayConnection: try: socket = await _open_socket(self.url) self._socket = socket - await authenticate_socket( + accepted = await authenticate_socket( socket, authentication={ "type": "instance-credential", @@ -278,6 +284,10 @@ class T3GatewayConnection: self._connected.set() if self._first_result is not None and not self._first_result.done(): self._first_result.set_result(True) + # Deliberately after `_connected.set()`: the accepted callback + # reconciles the home designation and flushes the durable + # delivery queue, and both send frames back over this socket. + await self._notify_accepted(accepted) await self._notify_state(True, None) delay = 1.0 async for raw in socket: @@ -322,6 +332,34 @@ class T3GatewayConnection: await asyncio.sleep(delay) delay = min(delay * 2, 30.0) + async def _notify_accepted(self, accepted: dict[str, Any]) -> None: + """Hand the `connection.accepted` frame to the adapter, best-effort. + + A failure here — a read-only `.env`, an unwritable queue file — must + not tear down a connection that authenticated successfully, so it is + logged and swallowed exactly like the state callback. + """ + if self._on_accepted is None: + return + try: + await self._on_accepted(accepted) + except Exception: # noqa: BLE001 - reconciliation must not fail a good handshake + logger.warning("T3 connection accepted callback failed", exc_info=True) + + async def _notify_accepted(self, accepted: dict[str, Any]) -> None: + """Hand the `connection.accepted` frame to the adapter, best-effort. + + A failure here — a read-only `.env`, an unwritable queue file — must + not tear down a connection that authenticated successfully, so it is + logged and swallowed exactly like the state callback. + """ + if self._on_accepted is None: + return + try: + await self._on_accepted(accepted) + except Exception: # noqa: BLE001 - reconciliation must not fail a good handshake + logger.warning("T3 connection accepted callback failed", exc_info=True) + async def _notify_state(self, connected: bool, reason: str | None) -> None: if self._on_state is None: return diff --git a/integrations/hermes-t3-gateway/home.py b/integrations/hermes-t3-gateway/home.py new file mode 100644 index 0000000000..e63ea6d8fd --- /dev/null +++ b/integrations/hermes-t3-gateway/home.py @@ -0,0 +1,605 @@ +"""Home-channel delivery: durable queue, classification, standalone sender. + +Hermes-initiated output — cron results, the agent's `send_message` tool with a +bare `t3` target, gateway lifecycle notices, `/handoff t3` — has no T3-issued +turn to stream into. It is delivered as a `home.deliver` frame against the +instance's durable **home thread**, whose id T3 owns and republishes on every +`connection.accepted`. + +Three concerns live here rather than in the adapter: + +* **The durable queue.** A delivery is written to disk before it is sent and + removed only when T3 acknowledges it, so nothing is lost when either side + restarts mid-flight. T3 dedupes on `deliveryId`, which is what makes + re-flushing the whole queue safe. +* **Kind/label classification.** Best-effort provenance recovery from the send + context — see `classify_delivery`. +* **The standalone sender.** Out-of-process cron has no live adapter, so it + dials T3 itself over a short-lived `role: "delivery"` socket. +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +from pathlib import Path +from typing import Any + +from .protocol import ( + HOME_DELIVERY_KINDS, + delivery_id, + home_deliver, + iso_now, +) + +logger = logging.getLogger(__name__) + +try: # POSIX advisory locking; absent on Windows. + import fcntl +except ImportError: # pragma: no cover - Windows fallback + fcntl = None # type: ignore[assignment] + +# The env var carrying T3's home-thread designation. +# +# The name is NOT arbitrary. Hermes resolves a platform's cron home target with +# `_home_target_env_var` (`gateway/run.py:1541`), which falls back to +# `f"{PLATFORM.upper()}_HOME_CHANNEL"` for any platform without an override +# entry. Platform `t3` therefore resolves to exactly this string, so the +# `send_message` error hints, `/sethome` messaging, and cron's env-only +# resolution path all agree with the value the plugin writes — with no upstream +# override table entry required. +HOME_CHANNEL_ENV = "T3_HOME_CHANNEL" + +# Queue location. `gateway/` under the Hermes home is the subdirectory Hermes' +# own bundled plugins use for per-profile adapter state (the Discord adapter's +# command-sync and non-conversational stores, `plugins/platforms/discord/ +# adapter.py:52`, `:272`, `:1694`). Using `get_hermes_home()` as the base means +# the queue is profile-scoped for free: a second profile with its own +# `HERMES_HOME` gets its own queue rather than replaying another profile's +# deliveries into its own home thread. +QUEUE_SUBDIR = "gateway" +QUEUE_FILENAME = "t3_home_delivery_queue.jsonl" + +# Bound the queue. Deliveries are small (a cron brief, a lifecycle line), so a +# few hundred is generous for any realistic outage while keeping the file +# readable and the flush bounded. Overflow drops the OLDEST entries: a +# fortnight-old cron brief is worth less than this morning's, and dropping +# newest would make a wedged queue permanently swallow current output. +MAX_QUEUE_ENTRIES = 300 + +# Bound one flush attempt. A reconnect must not spend minutes replaying before +# the connection is usable for live traffic; the remainder rides the next +# reconnect. +MAX_FLUSH_PER_CONNECT = 50 + + +def hermes_home() -> Path: + """Resolve Hermes' home directory, degrading to the documented default. + + Prefers Hermes' own accessor so a context-local profile override + (`set_hermes_home_override`) is honoured, then `HERMES_HOME`, then the + platform default. The plugin must not create state outside the active + profile, but it also must not fail to queue a delivery merely because + Hermes could not be imported (the standalone cron path can run in a very + thin process). + """ + try: + from hermes_cli.config import get_hermes_home + + return Path(get_hermes_home()) + except Exception: # noqa: BLE001 - queueing must never depend on Hermes importing + pass + try: + from hermes_constants import get_hermes_home + + return Path(get_hermes_home()) + except Exception: # noqa: BLE001 - same + pass + override = os.environ.get("HERMES_HOME", "").strip() + return Path(override) if override else Path.home() / ".hermes" + + +def queue_path() -> Path: + return hermes_home() / QUEUE_SUBDIR / QUEUE_FILENAME + + +def home_thread_id() -> str: + """Read the currently designated home thread from the environment.""" + return os.environ.get(HOME_CHANNEL_ENV, "").strip() + + +def save_home_thread_id(thread_id: str) -> bool: + """Persist T3's home designation, mirroring it into this process. + + T3's settings blob is authoritative and this env var is a synced cache, so + a differing local value is overwritten rather than merged — including one a + user hand-edited (documented in the plugin README). + + Returns True when the value was durably written. A read-only or managed + `.env` degrades to the in-process mirror only: routing works for the life + of this gateway and re-reconciles on the next connect. + """ + value = str(thread_id or "").strip() + if not value: + return False + saved = False + try: + from hermes_cli.config import save_env_value + + save_env_value(HOME_CHANNEL_ENV, value) + saved = True + except Exception: # noqa: BLE001 - a read-only .env must not break the handshake + logger.warning( + "Could not persist %s; T3 home delivery will use the in-process " + "value until the next reconnect", + HOME_CHANNEL_ENV, + exc_info=True, + ) + # Mirror into this process exactly as enrollment does (`cli.py`): the + # running gateway resolves the home channel from the environment and must + # not need a restart to see a freshly designated thread. + os.environ[HOME_CHANNEL_ENV] = value + return saved + + +class HomeDeliveryQueue: + """Append-only JSONL outbox of unacknowledged `home.deliver` frames. + + Correctness rests on one rule: an entry is removed **only** when T3 acks + its `deliveryId`. Everything else — a socket that dropped mid-send, a + server that died before writing, a plugin that restarted — leaves the entry + on disk to be replayed. Replay is safe because T3 dedupes on `deliveryId`, + so the failure mode of this design is a duplicate suppressed server-side, + never a lost delivery. + + Two processes can hold the same queue: the gateway adapter and an + out-of-process cron run using the standalone sender. Writes take a POSIX + advisory lock on a sidecar file where `fcntl` is available; on Windows the + in-process lock alone applies and a concurrent cron process could in + principle interleave a rewrite. The consequence there is a duplicate + delivery (deduped by T3), not corruption of an already-acked entry. + """ + + def __init__(self, path: Path | None = None, max_entries: int = MAX_QUEUE_ENTRIES): + self._path = Path(path) if path is not None else None + self._max_entries = max(1, int(max_entries)) + self._lock = threading.RLock() + + @property + def path(self) -> Path: + # Resolved lazily, not in __init__: `get_hermes_home()` honours a + # context-local profile override that may be installed after the + # adapter is constructed. + return self._path if self._path is not None else queue_path() + + def _ensure_parent(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + + def _read_lines(self) -> list[dict[str, Any]]: + path = self.path + if not path.exists(): + return [] + entries: list[dict[str, Any]] = [] + try: + raw = path.read_text(encoding="utf-8") + except OSError: + logger.warning("Could not read the T3 home delivery queue", exc_info=True) + return [] + for line in raw.splitlines(): + line = line.strip() + if not line: + continue + try: + entry = json.loads(line) + except ValueError: + # A torn write from a killed process. Skip the line rather than + # discarding the whole queue. + continue + if isinstance(entry, dict) and entry.get("deliveryId"): + entries.append(entry) + return entries + + def _write_all(self, entries: list[dict[str, Any]]) -> None: + self._ensure_parent() + payload = "".join( + json.dumps(entry, separators=(",", ":"), ensure_ascii=False) + "\n" + for entry in entries + ) + temporary = self.path.with_suffix(".jsonl.tmp") + temporary.write_text(payload, encoding="utf-8") + temporary.replace(self.path) + + def _file_lock(self): + """Advisory cross-process lock, or a no-op where unavailable.""" + + class _NoLock: + def __enter__(self): + return None + + def __exit__(self, *args): + return False + + if fcntl is None: + return _NoLock() + + queue = self.path + try: + queue.parent.mkdir(parents=True, exist_ok=True) + except OSError: + return _NoLock() + + class _FileLock: + def __init__(self, lock_path: Path): + self._lock_path = lock_path + self._handle: Any = None + + def __enter__(self): + try: + self._handle = open(self._lock_path, "a+") # noqa: SIM115 + fcntl.flock(self._handle, fcntl.LOCK_EX) + except OSError: + if self._handle is not None: + self._handle.close() + self._handle = None + return None + + def __exit__(self, *args): + if self._handle is not None: + try: + fcntl.flock(self._handle, fcntl.LOCK_UN) + finally: + self._handle.close() + self._handle = None + return False + + return _FileLock(queue.with_suffix(".jsonl.lock")) + + def append(self, frame: dict[str, Any]) -> bool: + """Persist one delivery. Returns False when it could not be written.""" + if not isinstance(frame, dict) or not frame.get("deliveryId"): + return False + with self._lock, self._file_lock(): + entries = self._read_lines() + if any( + entry.get("deliveryId") == frame["deliveryId"] for entry in entries + ): + return True + entries.append(dict(frame)) + dropped = len(entries) - self._max_entries + if dropped > 0: + logger.warning( + "T3 home delivery queue is full (%d entries); dropping the " + "%d oldest undelivered %s", + self._max_entries, + dropped, + "delivery" if dropped == 1 else "deliveries", + ) + entries = entries[dropped:] + try: + self._write_all(entries) + except OSError: + logger.error( + "Could not persist a T3 home delivery to %s", + self.path, + exc_info=True, + ) + return False + return True + + def entries(self) -> list[dict[str, Any]]: + """Every unacknowledged delivery, oldest first.""" + with self._lock: + return self._read_lines() + + def purge(self, delivery_id_value: str) -> bool: + """Remove one acknowledged delivery. Returns True when it was present.""" + target = str(delivery_id_value or "").strip() + if not target: + return False + with self._lock, self._file_lock(): + entries = self._read_lines() + remaining = [ + entry for entry in entries if entry.get("deliveryId") != target + ] + if len(remaining) == len(entries): + return False + try: + self._write_all(remaining) + except OSError: + logger.error( + "Could not purge acknowledged T3 home delivery %s from %s", + target, + self.path, + exc_info=True, + ) + return False + return True + + def __len__(self) -> int: + return len(self.entries()) + + +# ── classification ──────────────────────────────────────────────────────── + +# Hermes' lifecycle broadcasts, matched by their literal shapes at 62e07223. +# These are inline f-strings upstream, not exported constants, so the same +# drift risk documented for the `/sethome` notice applies: a wording change +# upstream downgrades these to `kind: "message"`, which costs a badge and a +# quiet-delivery classification, never the delivery itself. +_LIFECYCLE_EXACT = frozenset( + { + # gateway/run.py:17277 + "♻️ Gateway online — Hermes is back and ready.", + # gateway/run.py:17236 + "♻ Gateway restarted successfully. Your session continues.", + } +) +_LIFECYCLE_PREFIXES = ( + # gateway/run.py:6599 — f"⚠️ Gateway {action} — {hint}" + "⚠️ Gateway restarting — ", + "⚠️ Gateway shutting down — ", +) + +# cron/scheduler.py:1513 builds this header when `cron.wrap_response` is on +# (the default). +_CRON_HEADER = "Cronjob Response: " + +# gateway/run.py:8854 — the handoff destination's synthetic source identity. +_HANDOFF_USER_ID = "system:handoff" + + +def classify_delivery( + content: str, + metadata: dict[str, Any] | None = None, + *, + session_user_id: str = "", +) -> tuple[str, str, bool]: + """Best-effort `(kind, label, provenance_certain)` for a proactive send. + + Hermes' `adapter.send()` contract carries no structured "this is a cron + delivery" marker on every path, so this reads the signals that do exist: + + * **`metadata["job_id"]`** — the cron scheduler stamps it into the routed + metadata for every live-gateway delivery (`cron/scheduler.py:1782`), and + `DeliveryRouter._deliver_to_platform` passes that dict through to + `adapter.send` unchanged (`gateway/delivery.py:606`). This is the + strongest signal available and the only structured one. + * **The cron wrap header** — `cron.wrap_response` (default on) prefixes the + brief with `Cronjob Response: ` (`cron/scheduler.py:1513`), which + also supplies a human job name for the badge. + * **Lifecycle literals** — the gateway's online/restart/shutdown notices. + * **The bound session identity** — `/handoff` dispatches its synthetic turn + under `user_id="system:handoff"` (`gateway/run.py:8854`), bound onto the + session context by `_set_session_env` (`gateway/run.py:17372`). + + The third element reports whether provenance was *positively* established. + The adapter uses it as the tiebreaker when a live turn exists in the home + thread: only a positively-identified proactive send may bypass that turn, + so an unclassifiable send can never steal a user's answer. + + Worst case for the first two elements is a wrong badge, never a lost + delivery — an unrecognised send is `("message", "Hermes", False)`. + """ + text = str(content or "") + meta = metadata or {} + + job_id = str(meta.get("job_id") or "").strip() + job_name = _cron_job_name(text) + if job_id or job_name: + label = f"Cron: {job_name or job_id}" + return "cron", label, True + + stripped = text.strip() + if stripped in _LIFECYCLE_EXACT or stripped.startswith(_LIFECYCLE_PREFIXES): + return "lifecycle", "Gateway", True + + if str(session_user_id or "").strip() == _HANDOFF_USER_ID: + return "handoff", "Handoff", True + + return "message", "Hermes", False + + +def _cron_job_name(text: str) -> str: + """Recover the job name from the cron wrap header, if present.""" + first_line = text.lstrip().split("\n", 1)[0] + if not first_line.startswith(_CRON_HEADER): + return "" + return first_line[len(_CRON_HEADER) :].strip() + + +def build_delivery( + *, + thread_id: str, + text: str, + kind: str = "message", + label: str = "Hermes", + created_at: str | None = None, +) -> dict[str, Any]: + """Mint one `home.deliver` frame, id and timestamp included. + + `createdAt` is stamped here — when Hermes produced the content — not when + the frame reaches T3, so a delivery flushed after a two-hour outage still + reports the moment it was written. + """ + normalized_kind = kind if kind in HOME_DELIVERY_KINDS else "other" + return home_deliver( + delivery_id_value=delivery_id(), + thread_id=thread_id, + kind=normalized_kind, + label=label, + text=text, + created_at=created_at or iso_now(), + ) + + +# ── standalone (out-of-process) sender ──────────────────────────────────── + + +async def standalone_send( + pconfig: Any, + chat_id: str, + message: str, + *, + thread_id: str | None = None, + media_files: list[str] | None = None, + force_document: bool = False, +) -> dict[str, Any]: + """Deliver to the home thread with no live gateway adapter in this process. + + Registered as `standalone_sender_fn` and called by + `tools/send_message_tool._send_via_adapter` when the in-process adapter + weakref is empty — the `hermes cron` process running separately from + `hermes gateway`. Without it, `deliver=t3` cron jobs fail with "No live + adapter for platform". + + The socket announces `role: "delivery"`. That is load-bearing: T3's broker + registers a `gateway` connection under generation fencing and displaces the + previous one, so a naive cron dial-in would kick the live gateway socket + off its own instance mid-turn. A `delivery` connection is authenticated + identically, never becomes the primary, and is expected to close promptly. + + A connection failure is **not** a cron failure. The delivery is already on + disk before the socket is opened, so the job reports success-with-queued + and the live gateway flushes it on its next `connection.accepted`. + + `media_files` and `force_document` are accepted for signature parity + (`gateway/platform_registry.py:150-158`); the v3 wire contract carries no + attachment framing, so they are ignored. + """ + del force_document + if media_files: + logger.info( + "T3 standalone send ignoring %d media file(s): the v3 gateway " + "contract has no attachment framing", + len(media_files), + ) + + extra = getattr(pconfig, "extra", None) or {} + + def _setting(key: str, env: str) -> str: + return str(extra.get(key) or os.environ.get(env, "") or "").strip() + + url = _setting("url", "HERMES_T3_GATEWAY_URL") + instance_id = _setting("instance_id", "HERMES_T3_GATEWAY_INSTANCE_ID") + credential = _setting("credential", "HERMES_T3_GATEWAY_CREDENTIAL") + if not (url and instance_id and credential): + return { + "error": ( + "T3 standalone send: this Hermes is not enrolled. Run " + "`hermes t3 connect --url --token ` first." + ) + } + + target = str(chat_id or "").strip() or str(thread_id or "").strip() + if not target: + target = home_thread_id() + if not target: + return { + "error": ( + "T3 standalone send: no home thread is designated. Start " + "`hermes gateway` once so T3 can publish one." + ) + } + + kind, label, _certain = classify_delivery(message, None) + frame = build_delivery(thread_id=target, text=message, kind=kind, label=label) + delivery = str(frame["deliveryId"]) + + queue = HomeDeliveryQueue() + queued = queue.append(frame) + + try: + acked = await _deliver_over_short_lived_socket( + url=url, + instance_id=instance_id, + credential=credential, + frame=frame, + ) + except Exception as exc: # noqa: BLE001 - cron delivery must not raise + logger.debug("T3 standalone send raised", exc_info=True) + if queued: + return { + "success": True, + "message_id": delivery, + "queued": True, + "detail": f"T3 unreachable ({exc}); queued for the next connect", + } + return {"error": f"T3 standalone send failed: {exc}"} + + if acked: + queue.purge(delivery) + return {"success": True, "message_id": delivery} + if queued: + return { + "success": True, + "message_id": delivery, + "queued": True, + "detail": "T3 did not acknowledge the delivery; queued for retry", + } + return {"error": "T3 standalone send: the delivery was neither acked nor queued"} + + +async def _deliver_over_short_lived_socket( + *, + url: str, + instance_id: str, + credential: str, + frame: dict[str, Any], + timeout: float = 20.0, +) -> bool: + """Open, authenticate as `delivery`, send, await the ack, close.""" + import asyncio + + from .connection import _open_socket, authenticate_socket + + hermes_version = _hermes_version() + socket = await _open_socket(url) + try: + await authenticate_socket( + socket, + authentication={ + "type": "instance-credential", + "instanceId": instance_id, + "credential": credential, + }, + hermes_version=hermes_version, + role="delivery", + ) + await socket.send( + json.dumps(frame, separators=(",", ":"), ensure_ascii=False) + ) + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while True: + remaining = deadline - loop.time() + if remaining <= 0: + return False + raw = await asyncio.wait_for(socket.recv(), timeout=remaining) + try: + reply = json.loads(raw) + except ValueError: + continue + if not isinstance(reply, dict): + continue + if reply.get("type") == "home.deliver.ack" and str( + reply.get("deliveryId") or "" + ) == str(frame["deliveryId"]): + return True + # Anything else (a liveness ping, an unrelated frame) is ignored: + # this socket exists only to hand over one delivery. + finally: + try: + await socket.close() + except Exception: # noqa: BLE001 - a failed close must not fail the send + logger.debug("T3 standalone socket close failed", exc_info=True) + + +def _hermes_version() -> str: + try: + from hermes_cli import __version__ + + return str(__version__) + except Exception: # noqa: BLE001 - version discovery must not block delivery + return "unknown" diff --git a/integrations/hermes-t3-gateway/plugin.yaml b/integrations/hermes-t3-gateway/plugin.yaml index 5b99ccea11..dfd86b14bd 100644 --- a/integrations/hermes-t3-gateway/plugin.yaml +++ b/integrations/hermes-t3-gateway/plugin.yaml @@ -1,7 +1,7 @@ name: hermes-t3-gateway label: T3 Code kind: platform -version: 0.2.0 +version: 0.3.0 description: > Experimental outbound gateway that exposes one Hermes Agent process as a named T3 Code provider instance over an authenticated WebSocket. diff --git a/integrations/hermes-t3-gateway/protocol.py b/integrations/hermes-t3-gateway/protocol.py index dd31a1be93..85803fe951 100644 --- a/integrations/hermes-t3-gateway/protocol.py +++ b/integrations/hermes-t3-gateway/protocol.py @@ -7,10 +7,17 @@ import uuid from datetime import datetime, timezone from typing import Any -PROTOCOL_VERSION = 2 -PLUGIN_VERSION = "0.2.0" +PROTOCOL_VERSION = 3 +PLUGIN_VERSION = "0.3.0" WEBSOCKET_PATH = "/api/hermes-gateway/ws" +# What a connecting socket intends to be. `gateway` is the instance's one live +# plugin connection; `delivery` is a short-lived socket (an out-of-process cron +# run) that hands over a `home.deliver` and leaves. T3 never registers a +# `delivery` socket as the primary connection, so it cannot displace a healthy +# gateway connection under the broker's generation fencing. +CONNECTION_ROLES = frozenset({"gateway", "delivery"}) + CAPABILITIES = { "protocolVersion": PROTOCOL_VERSION, "streaming": True, @@ -34,9 +41,21 @@ SERVER_COMMANDS = frozenset( "ping", "describe.request", "skill.body.request", + "home.deliver.ack", } ) +# Kinds a `home.deliver` may carry. Mirrors the T3 contract's +# `HermesGatewayHomeDeliveryKind`; anything not classified lands on "message". +HOME_DELIVERY_KINDS = frozenset({"cron", "message", "lifecycle", "handoff", "other"}) + +# Wire bounds from the T3 contract (`HermesGatewayHomeDeliver`): `label` is a +# trimmed non-empty string of at most 200 chars, `text` is 1..120000 chars. +# Enforced here so a pathological Hermes payload is clamped rather than +# rejected by the server after the plugin already dropped its local copy. +MAX_HOME_DELIVERY_LABEL_CHARS = 200 +MAX_HOME_DELIVERY_TEXT_CHARS = 120_000 + # Ceiling on a single skill body crossing the wire. Skill markdown is # human-authored documentation, not data: 512 KiB is far past any real # SKILL.md while still bounding a pathological file from stalling the socket. @@ -51,6 +70,26 @@ def item_id() -> str: return str(uuid.uuid4()) +def delivery_id() -> str: + """Mint the idempotency key for one home delivery. + + Stable across retries by construction: the id is minted once, when the + delivery is created, and the queued copy carries it verbatim through every + flush. T3 dedupes on it, which is what makes double-flushing safe. + """ + return str(uuid.uuid4()) + + +def delivery_id() -> str: + """Mint the idempotency key for one home delivery. + + Stable across retries by construction: the id is minted once, when the + delivery is created, and the queued copy carries it verbatim through every + flush. T3 dedupes on it, which is what makes double-flushing safe. + """ + return str(uuid.uuid4()) + + def iso_now() -> str: return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") @@ -261,8 +300,19 @@ def connection_hello( authentication: dict[str, str], hello_request_id: str | None = None, model: str | None = None, + role: str = "gateway", ) -> dict[str, Any]: + """Build the handshake frame. + + `role` is sent explicitly even though the T3 contract decodes a missing + value as `"gateway"`: an out-of-process cron sender MUST announce + `"delivery"` or the broker registers it as the instance's primary + connection and generation-fences the live gateway socket off. + """ resolved_model = model if model is not None else configured_model() + normalized_role = str(role or "gateway").strip().lower() + if normalized_role not in CONNECTION_ROLES: + normalized_role = "gateway" hello: dict[str, Any] = { "type": "connection.hello", "requestId": hello_request_id or request_id(), @@ -271,6 +321,7 @@ def connection_hello( "hermesVersion": hermes_version, "capabilities": dict(CAPABILITIES), "authentication": authentication, + "role": normalized_role, } # Optional on the wire: omit entirely rather than send null/empty so a # server that has the field still falls back to its generic label. @@ -279,6 +330,94 @@ def connection_hello( return hello +def home_deliver( + *, + delivery_id_value: str, + thread_id: str, + kind: str, + label: str, + text: str, + created_at: str | None = None, +) -> dict[str, Any]: + """Build a `home.deliver` frame with every wire bound already applied. + + Like `protocol_error`, this wraps the generic `frame()` helper rather than + assembling the envelope itself — but unlike the plain outbound frames the + adapter builds inline, a delivery has server-side validation the plugin + must not trip: `label` is trimmed non-empty ≤200 chars and `text` is + 1..120000 chars in the T3 contract. Normalizing here rather than at the + call sites means a queued delivery is already wire-valid on disk, so a + flush after a plugin upgrade cannot resurrect a payload the server will + reject — the plugin would purge it only on an ack that never comes. + + An unknown `kind` degrades to `"other"` and an empty label to `"Hermes"`: + a misclassified badge is the documented worst case, a dropped delivery is + not. + """ + normalized_kind = str(kind or "").strip().lower() + if normalized_kind not in HOME_DELIVERY_KINDS: + normalized_kind = "other" + normalized_label = str(label or "").strip()[:MAX_HOME_DELIVERY_LABEL_CHARS].strip() + if not normalized_label: + normalized_label = "Hermes" + normalized_text = str(text or "")[:MAX_HOME_DELIVERY_TEXT_CHARS] + if not normalized_text: + normalized_text = " " + return frame( + "home.deliver", + deliveryId=delivery_id_value, + threadId=str(thread_id), + kind=normalized_kind, + label=normalized_label, + text=normalized_text, + createdAt=created_at or iso_now(), + ) + + +def home_deliver( + *, + delivery_id_value: str, + thread_id: str, + kind: str, + label: str, + text: str, + created_at: str | None = None, +) -> dict[str, Any]: + """Build a `home.deliver` frame with every wire bound already applied. + + Like `protocol_error`, this wraps the generic `frame()` helper rather than + assembling the envelope itself — but unlike the plain outbound frames the + adapter builds inline, a delivery has server-side validation the plugin + must not trip: `label` is trimmed non-empty <=200 chars and `text` is + 1..120000 chars in the T3 contract. Normalizing here rather than at the + call sites means a queued delivery is already wire-valid on disk, so a + flush after a plugin upgrade cannot resurrect a payload the server will + reject — the plugin would purge it only on an ack that never comes. + + An unknown `kind` degrades to `"other"` and an empty label to `"Hermes"`: + a misclassified badge is the documented worst case, a dropped delivery is + not. + """ + normalized_kind = str(kind or "").strip().lower() + if normalized_kind not in HOME_DELIVERY_KINDS: + normalized_kind = "other" + normalized_label = str(label or "").strip()[:MAX_HOME_DELIVERY_LABEL_CHARS].strip() + if not normalized_label: + normalized_label = "Hermes" + normalized_text = str(text or "")[:MAX_HOME_DELIVERY_TEXT_CHARS] + if not normalized_text: + normalized_text = " " + return frame( + "home.deliver", + deliveryId=delivery_id_value, + threadId=str(thread_id), + kind=normalized_kind, + label=normalized_label, + text=normalized_text, + createdAt=created_at or iso_now(), + ) + + def protocol_error( code: str, message: str, diff --git a/integrations/hermes-t3-gateway/tests/test_adapter.py b/integrations/hermes-t3-gateway/tests/test_adapter.py index 91f0099567..baac40b698 100644 --- a/integrations/hermes-t3-gateway/tests/test_adapter.py +++ b/integrations/hermes-t3-gateway/tests/test_adapter.py @@ -7,6 +7,7 @@ import enum import importlib.util import pathlib import sys +import tempfile import types import unittest import unittest.mock @@ -146,7 +147,7 @@ def load_plugin_modules(): package = types.ModuleType(PACKAGE) package.__path__ = [str(ROOT)] sys.modules[PACKAGE] = package - for name in ("protocol", "connection", "cli", "adapter"): + for name in ("protocol", "connection", "cli", "home", "adapter"): spec = importlib.util.spec_from_file_location( f"{PACKAGE}.{name}", ROOT / f"{name}.py" ) @@ -159,6 +160,7 @@ def load_plugin_modules(): adapter_module = load_plugin_modules() protocol_module = sys.modules[f"{PACKAGE}.protocol"] +home_module = sys.modules[f"{PACKAGE}.home"] @contextlib.contextmanager @@ -217,7 +219,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": f"ensure-{thread_id}", "threadId": thread_id, } @@ -226,7 +228,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": f"start-{thread_id}", "threadId": thread_id, "sessionId": session_id, @@ -240,7 +242,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-1", "threadId": "thread-1", } @@ -253,7 +255,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "start-1", "threadId": "thread-1", "sessionId": ready["sessionId"], @@ -833,7 +835,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-reconnect", "threadId": "thread-reconnect", "resumeSessionId": session_id, @@ -849,7 +851,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-2", "threadId": "thread-2", } @@ -858,7 +860,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "start-2", "threadId": "thread-2", "sessionId": session_id, @@ -877,7 +879,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "steer-2", "threadId": "thread-2", "sessionId": session_id, @@ -949,7 +951,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "steer-race", "threadId": "thread-steer-race", "sessionId": session_id, @@ -998,7 +1000,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "steer-edit", "threadId": "thread-steer-edit", "sessionId": session_id, @@ -1017,7 +1019,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-rejected-steer", "threadId": "thread-rejected-steer", } @@ -1026,7 +1028,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "start-rejected-steer", "threadId": "thread-rejected-steer", "sessionId": session_id, @@ -1043,7 +1045,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "steer-rejected", "threadId": "thread-rejected-steer", "sessionId": session_id, @@ -1090,7 +1092,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-failed-steer", "threadId": "thread-failed-steer", } @@ -1099,7 +1101,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "start-failed-steer", "threadId": "thread-failed-steer", "sessionId": session_id, @@ -1116,7 +1118,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "steer-failed", "threadId": "thread-failed-steer", "sessionId": session_id, @@ -1204,7 +1206,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "ensure-3", "threadId": "thread-3", } @@ -1214,7 +1216,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.stop", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "stop-3", "threadId": "thread-3", "sessionId": session_id, @@ -1235,7 +1237,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "describe.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "describe-1", } ) @@ -1244,7 +1246,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(reply["type"], "describe.response") # Correlation, exactly like ping -> pong. self.assertEqual(reply["requestId"], "describe-1") - self.assertEqual(reply["protocolVersion"], 2) + self.assertEqual(reply["protocolVersion"], 3) self.assertEqual(reply["hermesVersion"], "0.19.0") self.assertIsInstance(reply["skills"], list) self.assertIn("capabilities", reply) @@ -1258,7 +1260,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "describe.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "describe-degraded", } ) @@ -1275,7 +1277,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "body-degraded", "skillName": "codex", } @@ -1293,7 +1295,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "body-1", "skillName": "codex", } @@ -1310,7 +1312,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "body-2", "skillName": "does-not-exist", } @@ -1330,7 +1332,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "body-3", } ) @@ -1344,12 +1346,12 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): for message in ( { "type": "describe.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "describe-no-error", }, { "type": "skill.body.request", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "body-no-error", "skillName": "codex", }, @@ -1535,6 +1537,442 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): types_after = [m["type"] for m in self.connection.messages[order_start:]] self.assertEqual(types_after[-2:], ["turn.completed", "connection.status"]) + async def test_cron_tool_hooks_are_excluded_from_the_sole_turn_fallback(self): + """A cron job's tool calls must never land in an unrelated live turn. + + The hooks are process-global, so a cron job running tools while exactly + one T3 turn happens to be active would otherwise resolve through the + sole-active-turn fallback and paint its tool rows into a conversation + it has nothing to do with. Cron runs are identifiable by the + `cron__` session id the scheduler mints + (`cron/scheduler.py:3017`); their activity belongs to the eventual + `home.deliver`, not to any turn. + """ + self.adapter._event_loop = asyncio.get_running_loop() + await self._start_turn("thread-live", "turn-live") + frames_before = len(self.connection.messages) + cron_session = "cron_daily-digest_20260726_090000" + + with unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, + "_gateway_session_key", + staticmethod(lambda: ""), + ): + self.adapter.emit_tool_started( + cron_session, "web_search", {"query": "weather"}, "cron-call-1" + ) + self.adapter.emit_tool_completed( + cron_session, "web_search", "sunny", 12, "cron-call-1" + ) + await asyncio.sleep(0) + + self.assertEqual(self.connection.messages[frames_before:], []) + # The unrelated turn is untouched and still streaming. + self.assertIn("thread-live", self.adapter._active_turns) + + # A genuine gateway run id still takes the fallback — the exclusion is + # scoped to cron, not a blanket removal of the fallback. + with unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, + "_gateway_session_key", + staticmethod(lambda: ""), + ): + self.adapter.emit_tool_started( + "20260726_090000_ab12cd34", "read_file", {"path": "a.py"}, "call-9" + ) + await asyncio.sleep(0) + fallback_frames = self.connection.messages[frames_before:] + self.assertEqual([m["type"] for m in fallback_frames], ["item.started"]) + self.assertEqual(fallback_frames[0]["threadId"], "thread-live") + + +class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): + """The proactive `home.deliver` branch and its durable queue.""" + + HOME = "home-thread" + + async def asyncSetUp(self): + self.adapter = adapter_module.T3PlatformAdapter( + PlatformConfig( + extra={ + "url": "wss://t3.example/api/hermes-gateway/ws", + "instance_id": "instance", + "credential": "credential", + } + ) + ) + self.connection = FakeConnection() + self.adapter._connection = self.connection + + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + queue_file = pathlib.Path(self._tmp.name) / "gateway" / "queue.jsonl" + self.queue = home_module.HomeDeliveryQueue(path=queue_file) + self.adapter._home_queue = self.queue + + environment = unittest.mock.patch.dict( + adapter_module.os.environ, + {home_module.HOME_CHANNEL_ENV: self.HOME}, + ) + environment.start() + self.addCleanup(environment.stop) + + # No Hermes session context is bound in tests, so the real accessors + # would fall through to os.environ. Pin them to "no session" — the + # state a cron run or a lifecycle broadcast is actually in. + for name in ("_gateway_session_key", "_session_user_id"): + patch = unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, name, staticmethod(lambda: "") + ) + patch.start() + self.addCleanup(patch.stop) + + async def _start_turn(self, thread_id: str, turn_id: str) -> str: + await self.adapter._handle_server_frame( + { + "type": "session.ensure", + "protocolVersion": 3, + "requestId": f"ensure-{thread_id}", + "threadId": thread_id, + } + ) + session_id = self.adapter._sessions[thread_id] + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 3, + "requestId": f"start-{thread_id}", + "threadId": thread_id, + "sessionId": session_id, + "turnId": turn_id, + "text": "Start", + } + ) + return session_id + + async def test_a_proactive_send_to_home_emits_home_deliver(self): + frames_before = len(self.connection.messages) + + result = await self.adapter.send( + self.HOME, + "Cronjob Response: nightly\n(job_id: nightly)\n-------------\n\nDone.", + metadata={"notify": True, "job_id": "nightly"}, + ) + + frames = self.connection.messages[frames_before:] + self.assertEqual([frame["type"] for frame in frames], ["home.deliver"]) + delivery = frames[0] + self.assertEqual(delivery["protocolVersion"], 3) + self.assertEqual(delivery["threadId"], self.HOME) + self.assertEqual(delivery["kind"], "cron") + self.assertEqual(delivery["label"], "Cron: nightly") + self.assertTrue(delivery["createdAt"].endswith("Z")) + self.assertTrue(result.success) + self.assertEqual(result.message_id, delivery["deliveryId"]) + + # No turn was invented, and none was completed. + self.assertEqual(self.adapter._active_turns, {}) + + async def test_a_delivery_never_emits_turn_or_item_frames(self): + frames_before = len(self.connection.messages) + await self.adapter.send(self.HOME, "♻️ Gateway online — Hermes is back and ready.") + emitted = {frame["type"] for frame in self.connection.messages[frames_before:]} + self.assertEqual(emitted, {"home.deliver"}) + self.assertEqual(self.adapter._active_turns, {}) + + async def test_a_notify_stamped_delivery_does_not_complete_the_live_turn(self): + """THE deadlock regression. + + A cron delivery landing in Home while the user has a live turn there + arrives notify-stamped (`_mark_notify_metadata`, + `gateway/platforms/base.py:89`). Under a naive "no active turn → + deliver" gate it would fall into the active-turn path, stream as that + turn's assistant content, and its notify stamp would COMPLETE the + user's turn with the cron output as the answer. The gate is provenance, + not turn absence: the cron send does not carry the turn's session key, + so it becomes a `home.deliver` and the turn keeps running. + """ + session_id = await self._start_turn(self.HOME, "turn-user") + # The user's turn has already streamed some of its real answer. + await self.adapter.send(self.HOME, "Working on it") + frames_before = len(self.connection.messages) + + # A cron delivery fires mid-turn, notify-stamped as every final cron + # delivery is. + result = await self.adapter.send( + self.HOME, + "Cronjob Response: nightly\n(job_id: nightly)\n-------------\n\nDone.", + metadata={"notify": True, "job_id": "nightly"}, + ) + + frames = self.connection.messages[frames_before:] + self.assertEqual([frame["type"] for frame in frames], ["home.deliver"]) + self.assertTrue(result.success) + + # The user's turn is untouched: still active, still owning its stream. + self.assertIn(self.HOME, self.adapter._active_turns) + turn = self.adapter._active_turns[self.HOME] + self.assertEqual(turn.turn_id, "turn-user") + self.assertEqual(turn.visible_text, "Working on it") + self.assertNotIn( + "turn.completed", [frame["type"] for frame in self.connection.messages] + ) + + # …and it still completes normally on its own notify, inside its own + # session context. + with unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, + "_gateway_session_key", + staticmethod(lambda: session_id), + ): + await self.adapter.send( + self.HOME, "Here is the answer", metadata={"notify": True} + ) + self.assertNotIn(self.HOME, self.adapter._active_turns) + self.assertIn( + "turn.completed", [frame["type"] for frame in self.connection.messages] + ) + + async def test_a_turn_reply_in_home_is_never_rerouted_to_a_delivery(self): + """Output produced inside the turn's session context is turn content.""" + session_id = await self._start_turn(self.HOME, "turn-user") + frames_before = len(self.connection.messages) + + with unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, + "_gateway_session_key", + staticmethod(lambda: session_id), + ): + await self.adapter.send(self.HOME, "Streaming answer") + + types = [frame["type"] for frame in self.connection.messages[frames_before:]] + self.assertEqual(types, ["item.started", "content.delta"]) + self.assertNotIn("home.deliver", types) + + async def test_an_unclassifiable_send_during_a_live_home_turn_stays_with_it(self): + """The conservative half of the gate. + + With a live turn in Home and no positive provenance, the send may well + be that turn's own output arriving from a context where the session key + did not resolve. Routing it to `home.deliver` would tear a real answer + out of the turn; leaving it with the turn is at worst a misplacement + inside the same thread. + """ + await self._start_turn(self.HOME, "turn-user") + frames_before = len(self.connection.messages) + + await self.adapter.send(self.HOME, "Something unclassifiable") + + types = [frame["type"] for frame in self.connection.messages[frames_before:]] + self.assertEqual(types, ["item.started", "content.delta"]) + self.assertIn(self.HOME, self.adapter._active_turns) + + async def test_a_non_home_thread_without_a_turn_still_errors(self): + """"Message any thread unprompted" stays out of scope.""" + frames_before = len(self.connection.messages) + + result = await self.adapter.send( + "some-other-thread", + "Cronjob Response: nightly\n(job_id: nightly)\n-------------\n\nDone.", + metadata={"notify": True, "job_id": "nightly"}, + ) + + self.assertFalse(result.success) + self.assertEqual(result.error, "no active T3 turn") + self.assertEqual(self.connection.messages[frames_before:], []) + + async def test_no_designated_home_means_no_proactive_delivery(self): + """Before the first `connection.accepted` there is nowhere to deliver.""" + with unittest.mock.patch.dict( + adapter_module.os.environ, {home_module.HOME_CHANNEL_ENV: ""} + ): + result = await self.adapter.send(self.HOME, "Nowhere to go") + self.assertFalse(result.success) + self.assertEqual(result.error, "no active T3 turn") + + async def test_edit_message_has_no_proactive_branch(self): + """A delivery is an atomic document, not a streaming surface.""" + result = await self.adapter.edit_message( + self.HOME, "some-message", "Revised delivery", finalize=True + ) + self.assertFalse(result.success) + self.assertEqual(result.error, "no active T3 turn") + self.assertEqual( + [frame["type"] for frame in self.connection.messages], [] + ) + + async def test_a_delivery_is_queued_before_it_is_sent_and_purged_on_ack(self): + result = await self.adapter.send(self.HOME, "Queued then acked") + delivery_id = result.message_id + self.assertEqual( + [entry["deliveryId"] for entry in self.queue.entries()], [delivery_id] + ) + + await self.adapter._handle_server_frame( + { + "type": "home.deliver.ack", + "protocolVersion": 3, + "deliveryId": delivery_id, + } + ) + self.assertEqual(self.queue.entries(), []) + + async def test_a_delivery_survives_a_dead_socket_and_flushes_on_reconnect(self): + """Offline delivery: nothing is lost across either side restarting.""" + + class DeadConnection: + connected = False + + async def send(self, message): + raise ConnectionError("T3 Code gateway is offline") + + self.adapter._connection = DeadConnection() + with self.assertLogs(adapter_module.logger, level="WARNING"): + offline = await self.adapter.send(self.HOME, "Sent while offline") + # Reported successful: it is durably queued and WILL arrive, so a cron + # job must not log a failure for it. + self.assertTrue(offline.success) + self.assertEqual( + [entry["text"] for entry in self.queue.entries()], ["Sent while offline"] + ) + + # Reconnect: the accepted frame reconciles the designation and flushes. + self.adapter._connection = self.connection + await self.adapter._handle_connection_accepted( + { + "type": "connection.accepted", + "protocolVersion": 3, + "requestId": "hello-1", + "instanceId": "instance", + "nickname": "Hermes", + "homeThreadId": self.HOME, + } + ) + + flushed = self.connection.messages + self.assertEqual([frame["type"] for frame in flushed], ["home.deliver"]) + self.assertEqual(flushed[0]["text"], "Sent while offline") + self.assertEqual(flushed[0]["deliveryId"], offline.message_id) + # Still queued — only the ack purges it. + self.assertEqual(len(self.queue.entries()), 1) + + await self.adapter._handle_server_frame( + { + "type": "home.deliver.ack", + "protocolVersion": 3, + "deliveryId": offline.message_id, + } + ) + self.assertEqual(self.queue.entries(), []) + + async def test_the_queue_flushes_in_fifo_order(self): + class DeadConnection: + connected = False + + async def send(self, message): + raise ConnectionError("T3 Code gateway is offline") + + self.adapter._connection = DeadConnection() + with self.assertLogs(adapter_module.logger, level="WARNING"): + for text in ("first", "second", "third"): + await self.adapter.send(self.HOME, text) + + self.adapter._connection = self.connection + await self.adapter._flush_home_queue() + + self.assertEqual( + [frame["text"] for frame in self.connection.messages], + ["first", "second", "third"], + ) + + async def test_connection_accepted_reconciles_the_home_designation(self): + """T3 owns the designation; a differing local value is overwritten.""" + with unittest.mock.patch.dict( + adapter_module.os.environ, + {home_module.HOME_CHANNEL_ENV: "stale-hand-edited-thread"}, + ), unittest.mock.patch.object( + adapter_module, "save_home_thread_id" + ) as save: + await self.adapter._handle_connection_accepted( + { + "type": "connection.accepted", + "protocolVersion": 3, + "requestId": "hello-1", + "instanceId": "instance", + "nickname": "Hermes", + "homeThreadId": "authoritative-thread", + } + ) + save.assert_called_once_with("authoritative-thread") + + async def test_an_accepted_frame_without_a_home_thread_changes_nothing(self): + """Resolving the home thread must never fail a handshake.""" + with unittest.mock.patch.object( + adapter_module, "save_home_thread_id" + ) as save: + await self.adapter._handle_connection_accepted( + { + "type": "connection.accepted", + "protocolVersion": 3, + "requestId": "hello-1", + "instanceId": "instance", + "nickname": "Hermes", + } + ) + save.assert_not_called() + self.assertEqual(adapter_module.home_thread_id(), self.HOME) + + async def test_a_nameless_ack_is_a_correlated_protocol_error(self): + await self.adapter._handle_server_frame( + {"type": "home.deliver.ack", "protocolVersion": 3, "requestId": "ack-1"} + ) + reply = self.connection.messages[-1] + self.assertEqual(reply["type"], "protocol.error") + self.assertEqual(reply["code"], "unsupported-message") + + +class EnvEnablementTests(unittest.TestCase): + """`home_channel` is the magic key that makes `get_home_channel` resolve.""" + + ENROLLED = { + "HERMES_T3_GATEWAY_URL": "wss://t3.example/api/hermes-gateway/ws", + "HERMES_T3_GATEWAY_INSTANCE_ID": "instance", + "HERMES_T3_GATEWAY_CREDENTIAL": "credential", + } + + def test_a_designated_home_seeds_the_magic_home_channel_key(self): + with unittest.mock.patch.dict( + adapter_module.os.environ, + {**self.ENROLLED, home_module.HOME_CHANNEL_ENV: "home-thread"}, + ): + seed = adapter_module.env_enablement() + # Core pops this key and promotes it to a real HomeChannel dataclass + # (gateway/config.py:2648-2660), reading only chat_id/name/thread_id. + # T3 threads are the addressing unit, so chat_id IS the thread id and + # thread_id stays unset. + self.assertEqual( + seed["home_channel"], {"chat_id": "home-thread", "name": "Home"} + ) + + def test_no_designation_yet_seeds_no_home_channel(self): + with unittest.mock.patch.dict( + adapter_module.os.environ, + {**self.ENROLLED, home_module.HOME_CHANNEL_ENV: ""}, + ): + seed = adapter_module.env_enablement() + # The pre-designation window — first connect, before any + # `connection.accepted`. This is exactly why the `/sethome` nudge + # suppression is still needed. + self.assertNotIn("home_channel", seed) + self.assertEqual(seed["instance_id"], "instance") + + def test_an_unenrolled_hermes_seeds_nothing_at_all(self): + with unittest.mock.patch.dict( + adapter_module.os.environ, + {**self.ENROLLED, "HERMES_T3_GATEWAY_CREDENTIAL": ""}, + ): + self.assertIsNone(adapter_module.env_enablement()) + if __name__ == "__main__": unittest.main() diff --git a/integrations/hermes-t3-gateway/tests/test_connection.py b/integrations/hermes-t3-gateway/tests/test_connection.py index 6151ade507..67ffcd9ebd 100644 --- a/integrations/hermes-t3-gateway/tests/test_connection.py +++ b/integrations/hermes-t3-gateway/tests/test_connection.py @@ -65,7 +65,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): socket = FakeSocket( { "type": "connection.accepted", - "protocolVersion": 2, + "protocolVersion": 3, "instanceId": "provider-instance", "nickname": "Research", "credential": "persistent-secret", @@ -86,7 +86,9 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): socket = FakeSocket( { "type": "connection.accepted", - "protocolVersion": 1, + # A v2 server: the version policy stays fail-closed across the + # v3 bump, so this must not be silently accepted. + "protocolVersion": 2, "instanceId": "provider-instance", "nickname": "Research", } @@ -108,7 +110,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): "type": "connection.rejected", "code": "version-incompatible", "message": "upgrade required", - "expectedProtocolVersion": 2, + "expectedProtocolVersion": 3, } ) with self.assertRaises(connection.ConnectionRejected) as raised: @@ -148,14 +150,14 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): json.dumps( { "type": "ping", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": "server-ping-1", } ), json.dumps( { "type": "connection.accepted", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": hello_id, "instanceId": "provider-instance", "nickname": "Hermes", @@ -206,7 +208,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): return json.dumps( { "type": "connection.accepted", - "protocolVersion": 2, + "protocolVersion": 3, "requestId": self.sent[0]["requestId"], "instanceId": "provider-instance", "nickname": "Hermes", @@ -220,7 +222,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): async def frames(): yield json.dumps({"type": "turn.start", "requestId": "turn-1"}) yield json.dumps( - {"type": "ping", "protocolVersion": 2, "requestId": "ping-1"} + {"type": "ping", "protocolVersion": 3, "requestId": "ping-1"} ) await released.wait() diff --git a/integrations/hermes-t3-gateway/tests/test_home.py b/integrations/hermes-t3-gateway/tests/test_home.py new file mode 100644 index 0000000000..ef2bb64f67 --- /dev/null +++ b/integrations/hermes-t3-gateway/tests/test_home.py @@ -0,0 +1,473 @@ +from __future__ import annotations + +import importlib.util +import json +import pathlib +import sys +import tempfile +import types +import unittest +import unittest.mock + +ROOT = pathlib.Path(__file__).resolve().parents[1] +PACKAGE = "hermes_t3_gateway_home_test" + +# `home.py` depends only on `protocol.py` at import time (`connection.py` is +# imported lazily inside the standalone sender), so this loader needs none of +# the fake `gateway.*` modules the adapter tests install. +package = types.ModuleType(PACKAGE) +package.__path__ = [str(ROOT)] +sys.modules.setdefault(PACKAGE, package) + +for _name in ("protocol", "connection", "home"): + _spec = importlib.util.spec_from_file_location( + f"{PACKAGE}.{_name}", ROOT / f"{_name}.py" + ) + assert _spec and _spec.loader + _module = importlib.util.module_from_spec(_spec) + sys.modules[f"{PACKAGE}.{_name}"] = _module + _spec.loader.exec_module(_module) + +home = sys.modules[f"{PACKAGE}.home"] +protocol = sys.modules[f"{PACKAGE}.protocol"] +connection = sys.modules[f"{PACKAGE}.connection"] + + +def make_delivery(text: str, thread_id: str = "home-thread", **kwargs): + return home.build_delivery(thread_id=thread_id, text=text, **kwargs) + + +class QueueTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.path = pathlib.Path(self._tmp.name) / "gateway" / "queue.jsonl" + self.queue = home.HomeDeliveryQueue(path=self.path) + + def test_queue_replays_in_fifo_order(self): + """Deliveries flush oldest-first, so a Home transcript reads in order.""" + first = make_delivery("first") + second = make_delivery("second") + third = make_delivery("third") + for entry in (first, second, third): + self.assertTrue(self.queue.append(entry)) + + self.assertEqual( + [entry["text"] for entry in self.queue.entries()], + ["first", "second", "third"], + ) + + def test_an_entry_is_purged_only_by_its_own_ack(self): + """The durability guarantee: nothing leaves the queue without an ack. + + T3 acks only after a durable write, so purging on anything else — a + successful `send()`, a reconnect, a flush — would drop deliveries the + server never actually stored. + """ + first = make_delivery("first") + second = make_delivery("second") + self.queue.append(first) + self.queue.append(second) + + # Sending, flushing, or re-reading changes nothing. + self.assertEqual(len(self.queue.entries()), 2) + self.assertEqual(len(self.queue.entries()), 2) + + # An unknown id purges nothing at all. + self.assertFalse(self.queue.purge("never-sent")) + self.assertEqual(len(self.queue.entries()), 2) + + self.assertTrue(self.queue.purge(first["deliveryId"])) + self.assertEqual( + [entry["deliveryId"] for entry in self.queue.entries()], + [second["deliveryId"]], + ) + + # A duplicate ack (a replayed flush T3 deduped) is inert. + self.assertFalse(self.queue.purge(first["deliveryId"])) + self.assertEqual(len(self.queue.entries()), 1) + + def test_the_queue_is_capped_and_drops_the_oldest(self): + """A wedged queue must not grow without bound — and must not go stale. + + Dropping newest would make an over-full queue permanently swallow + current output; dropping oldest loses the least valuable entries and + keeps today's cron brief. + """ + queue = home.HomeDeliveryQueue(path=self.path, max_entries=3) + deliveries = [make_delivery(f"delivery-{index}") for index in range(5)] + with self.assertLogs(home.logger, level="WARNING") as captured: + for entry in deliveries: + queue.append(entry) + + self.assertTrue( + any("queue is full" in line for line in captured.output), + captured.output, + ) + self.assertEqual( + [entry["text"] for entry in queue.entries()], + ["delivery-2", "delivery-3", "delivery-4"], + ) + + def test_appending_the_same_delivery_twice_is_idempotent(self): + """A retried standalone send must not double-queue its own payload.""" + entry = make_delivery("once") + self.assertTrue(self.queue.append(entry)) + self.assertTrue(self.queue.append(dict(entry))) + self.assertEqual(len(self.queue.entries()), 1) + + def test_a_torn_line_does_not_discard_the_whole_queue(self): + """A process killed mid-write must cost one entry, not the outbox.""" + good = make_delivery("survivor") + self.queue.append(good) + with self.path.open("a", encoding="utf-8") as handle: + handle.write('{"deliveryId": "truncated"\n') + + self.assertEqual( + [entry["deliveryId"] for entry in self.queue.entries()], + [good["deliveryId"]], + ) + + def test_the_queue_survives_a_process_restart(self): + """Durability across a plugin restart is the entire point of the file.""" + entry = make_delivery("across-restart") + self.queue.append(entry) + + reopened = home.HomeDeliveryQueue(path=self.path) + self.assertEqual( + [item["deliveryId"] for item in reopened.entries()], + [entry["deliveryId"]], + ) + + def test_the_queue_lives_under_the_active_hermes_home(self): + """Profile-scoped: a second profile must not replay the first's output.""" + with unittest.mock.patch.object( + home, "hermes_home", return_value=pathlib.Path("/tmp/profile-b") + ): + self.assertEqual( + home.queue_path(), + pathlib.Path("/tmp/profile-b/gateway/t3_home_delivery_queue.jsonl"), + ) + + +class ClassificationTests(unittest.TestCase): + def test_the_cron_job_id_metadata_is_the_strongest_signal(self): + kind, label, certain = home.classify_delivery( + "Anything at all", {"job_id": "daily-digest", "notify": True} + ) + self.assertEqual(kind, "cron") + self.assertEqual(label, "Cron: daily-digest") + self.assertTrue(certain) + + def test_the_cron_wrap_header_supplies_a_human_job_name(self): + content = ( + "Cronjob Response: Morning digest\n" + "(job_id: abc123)\n" + "-------------\n\n" + "Three things happened.\n" + ) + kind, label, certain = home.classify_delivery(content, None) + self.assertEqual(kind, "cron") + self.assertEqual(label, "Cron: Morning digest") + self.assertTrue(certain) + + def test_gateway_lifecycle_notices_land_quietly(self): + for content in ( + "♻️ Gateway online — Hermes is back and ready.", + "♻ Gateway restarted successfully. Your session continues.", + "⚠️ Gateway shutting down — Your current task will be interrupted.", + "⚠️ Gateway restarting — Your current task will be interrupted. " + "Send any message after restart and I'll try to resume where you " + "left off.", + ): + with self.subTest(content=content[:32]): + kind, label, certain = home.classify_delivery(content, None) + self.assertEqual(kind, "lifecycle") + self.assertEqual(label, "Gateway") + self.assertTrue(certain) + + def test_a_handoff_is_recognised_from_its_synthetic_session_identity(self): + kind, label, certain = home.classify_delivery( + "Picking up where the CLI left off.", + None, + session_user_id="system:handoff", + ) + self.assertEqual(kind, "handoff") + self.assertEqual(label, "Handoff") + self.assertTrue(certain) + + def test_an_unrecognised_send_defaults_to_an_uncertain_message(self): + """Worst case is a wrong badge — and, in the live-turn window, a send + that stays with the turn rather than being torn out of it.""" + kind, label, certain = home.classify_delivery("Just checking in.", None) + self.assertEqual(kind, "message") + self.assertEqual(label, "Hermes") + self.assertFalse(certain) + + +class FrameTests(unittest.TestCase): + def test_home_deliver_applies_every_wire_bound(self): + frame = protocol.home_deliver( + delivery_id_value="delivery-1", + thread_id="home-thread", + kind="cron", + label=" " + "L" * 400 + " ", + text="x" * (protocol.MAX_HOME_DELIVERY_TEXT_CHARS + 500), + created_at="2026-07-26T00:00:00Z", + ) + self.assertEqual(frame["type"], "home.deliver") + self.assertEqual(frame["protocolVersion"], 3) + self.assertEqual(frame["deliveryId"], "delivery-1") + self.assertEqual(frame["threadId"], "home-thread") + self.assertEqual(frame["kind"], "cron") + self.assertEqual(len(frame["label"]), protocol.MAX_HOME_DELIVERY_LABEL_CHARS) + self.assertEqual( + len(frame["text"]), protocol.MAX_HOME_DELIVERY_TEXT_CHARS + ) + self.assertEqual(frame["createdAt"], "2026-07-26T00:00:00Z") + + def test_home_deliver_never_emits_an_invalid_kind_or_empty_label(self): + frame = protocol.home_deliver( + delivery_id_value="delivery-2", + thread_id="home-thread", + kind="not-a-kind", + label=" ", + text="", + ) + # A misclassification must cost a badge, never a server rejection of a + # delivery the plugin has already queued. + self.assertEqual(frame["kind"], "other") + self.assertEqual(frame["label"], "Hermes") + self.assertTrue(len(frame["text"]) >= 1) + + def test_home_deliver_ack_is_an_accepted_server_command(self): + message = {"type": "home.deliver.ack", "protocolVersion": 3} + self.assertEqual(protocol.validate_server_frame(message), message) + + def test_hello_declares_its_connection_role(self): + gateway = protocol.connection_hello( + hermes_version="0.19.0", + authentication={"type": "instance-credential"}, + ) + self.assertEqual(gateway["role"], "gateway") + delivery = protocol.connection_hello( + hermes_version="0.19.0", + authentication={"type": "instance-credential"}, + role="delivery", + ) + self.assertEqual(delivery["role"], "delivery") + # An unknown role must never silently become "delivery" — the safe + # default is the ordinary connection. + unknown = protocol.connection_hello( + hermes_version="0.19.0", + authentication={"type": "instance-credential"}, + role="nonsense", + ) + self.assertEqual(unknown["role"], "gateway") + + +class MockDeliveryServer: + """A T3 stand-in for the standalone sender's short-lived socket.""" + + def __init__(self, *, ack: bool = True): + self.ack = ack + self.sent: list[dict] = [] + self.closed = False + self._outbox: list[str] = [] + + async def send(self, raw): + message = json.loads(raw) + self.sent.append(message) + if message.get("type") == "connection.hello": + self._outbox.append( + json.dumps( + { + "type": "connection.accepted", + "protocolVersion": protocol.PROTOCOL_VERSION, + "requestId": message["requestId"], + "instanceId": "provider-instance", + "nickname": "Hermes", + "homeThreadId": "home-thread", + } + ) + ) + elif message.get("type") == "home.deliver" and self.ack: + self._outbox.append( + json.dumps( + { + "type": "home.deliver.ack", + "protocolVersion": protocol.PROTOCOL_VERSION, + "deliveryId": message["deliveryId"], + } + ) + ) + + async def recv(self): + if not self._outbox: + raise AssertionError("the mock server was polled with nothing to send") + return self._outbox.pop(0) + + async def close(self): + self.closed = True + + +class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.queue_file = pathlib.Path(self._tmp.name) / "gateway" / "queue.jsonl" + patch = unittest.mock.patch.object( + home, "hermes_home", return_value=pathlib.Path(self._tmp.name) + ) + patch.start() + self.addCleanup(patch.stop) + self.environment = unittest.mock.patch.dict( + home.os.environ, + { + "HERMES_T3_GATEWAY_URL": "wss://t3.example/api/hermes-gateway/ws", + "HERMES_T3_GATEWAY_INSTANCE_ID": "provider-instance", + "HERMES_T3_GATEWAY_CREDENTIAL": "secret", + home.HOME_CHANNEL_ENV: "home-thread", + }, + ) + self.environment.start() + self.addCleanup(self.environment.stop) + + def _serve(self, server): + async def _open(_url): + return server + + return unittest.mock.patch.object(connection, "_open_socket", _open) + + async def test_standalone_send_hellos_as_delivery_then_acks_and_closes(self): + """The full out-of-process cron path. + + `role: "delivery"` is load-bearing: T3's broker registers a `gateway` + connection under generation fencing and displaces its predecessor, so a + cron dial-in announcing the default role would kick the live gateway + socket off its own instance mid-turn. + """ + server = MockDeliveryServer() + with self._serve(server): + result = await home.standalone_send( + None, + "home-thread", + "Cronjob Response: nightly\n(job_id: nightly)\n-------------\n\nDone.", + ) + + self.assertTrue(result["success"]) + self.assertEqual( + [message["type"] for message in server.sent], + ["connection.hello", "home.deliver"], + ) + hello, delivery = server.sent + self.assertEqual(hello["role"], "delivery") + self.assertEqual(hello["protocolVersion"], 3) + self.assertEqual( + hello["authentication"], + { + "type": "instance-credential", + "instanceId": "provider-instance", + "credential": "secret", + }, + ) + self.assertEqual(delivery["threadId"], "home-thread") + self.assertEqual(delivery["kind"], "cron") + self.assertEqual(delivery["label"], "Cron: nightly") + self.assertEqual(result["message_id"], delivery["deliveryId"]) + self.assertTrue(server.closed, "the delivery socket must not linger") + + # Acked, so nothing is left queued for the live gateway to replay. + self.assertEqual(home.HomeDeliveryQueue().entries(), []) + + async def test_an_unreachable_t3_queues_rather_than_failing_the_cron_job(self): + """A cron job must not report failure for output that will arrive.""" + + async def _refuse(_url): + raise ConnectionRefusedError("T3 is down") + + with unittest.mock.patch.object(connection, "_open_socket", _refuse): + result = await home.standalone_send(None, "home-thread", "Nightly brief") + + self.assertTrue(result["success"]) + self.assertTrue(result["queued"]) + queued = home.HomeDeliveryQueue().entries() + self.assertEqual([entry["text"] for entry in queued], ["Nightly brief"]) + self.assertEqual(queued[0]["deliveryId"], result["message_id"]) + + async def test_an_unacknowledged_delivery_stays_queued(self): + """No ack, no purge — the live gateway retries it on the next connect.""" + server = MockDeliveryServer(ack=False) + with self._serve(server), unittest.mock.patch.object( + home, "_deliver_over_short_lived_socket", return_value=False + ): + result = await home.standalone_send(None, "home-thread", "Unacked brief") + + self.assertTrue(result["success"]) + self.assertTrue(result["queued"]) + self.assertEqual( + [entry["text"] for entry in home.HomeDeliveryQueue().entries()], + ["Unacked brief"], + ) + + async def test_standalone_send_refuses_when_hermes_is_not_enrolled(self): + with unittest.mock.patch.dict( + home.os.environ, {"HERMES_T3_GATEWAY_CREDENTIAL": ""} + ): + result = await home.standalone_send(None, "home-thread", "Brief") + self.assertIn("not enrolled", result["error"]) + + async def test_standalone_send_falls_back_to_the_designated_home_thread(self): + server = MockDeliveryServer() + with self._serve(server): + result = await home.standalone_send(None, "", "Brief with no chat id") + self.assertTrue(result["success"]) + self.assertEqual(server.sent[1]["threadId"], "home-thread") + + +class DesignationTests(unittest.TestCase): + def test_saving_the_designation_mirrors_it_into_this_process(self): + """The running gateway must not need a restart to see a new home.""" + saved = {} + + config = types.ModuleType("hermes_cli.config") + config.save_env_value = lambda key, value: saved.__setitem__(key, value) + package = types.ModuleType("hermes_cli") + package.__path__ = [] + with unittest.mock.patch.dict( + sys.modules, {"hermes_cli": package, "hermes_cli.config": config} + ), unittest.mock.patch.dict(home.os.environ, {}, clear=False): + self.assertTrue(home.save_home_thread_id("thread-home")) + self.assertEqual(saved, {home.HOME_CHANNEL_ENV: "thread-home"}) + self.assertEqual(home.home_thread_id(), "thread-home") + + def test_an_unwritable_env_still_routes_for_this_process(self): + """A managed or read-only `.env` degrades; it must not break routing.""" + + def refuse(key, value): + raise PermissionError("managed .env") + + config = types.ModuleType("hermes_cli.config") + config.save_env_value = refuse + package = types.ModuleType("hermes_cli") + package.__path__ = [] + with unittest.mock.patch.dict( + sys.modules, {"hermes_cli": package, "hermes_cli.config": config} + ), unittest.mock.patch.dict( + home.os.environ, {}, clear=False + ), self.assertLogs(home.logger, level="WARNING"): + self.assertFalse(home.save_home_thread_id("thread-home")) + # Not durable, but routable: this gateway delivers to the right + # thread until it restarts, and re-reconciles on the next connect. + self.assertEqual(home.home_thread_id(), "thread-home") + + def test_an_empty_designation_is_ignored(self): + with unittest.mock.patch.dict( + home.os.environ, {home.HOME_CHANNEL_ENV: "keep-me"} + ): + self.assertFalse(home.save_home_thread_id(" ")) + self.assertEqual(home.home_thread_id(), "keep-me") + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/hermes-t3-gateway/tests/test_protocol.py b/integrations/hermes-t3-gateway/tests/test_protocol.py index 2df9fe7431..8438383241 100644 --- a/integrations/hermes-t3-gateway/tests/test_protocol.py +++ b/integrations/hermes-t3-gateway/tests/test_protocol.py @@ -66,7 +66,7 @@ def fake_hermes_skills(skills_list=None, skill_view=None): class ProtocolTests(unittest.TestCase): - def test_hello_matches_v2_contract(self): + def test_hello_matches_v3_contract(self): hello = protocol.connection_hello( hermes_version="0.19.0", authentication={"type": "enrollment-token", "token": "once"}, @@ -75,7 +75,7 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(hello["type"], "connection.hello") self.assertEqual(hello["requestId"], "request-1") - self.assertEqual(hello["protocolVersion"], 2) + self.assertEqual(hello["protocolVersion"], 3) self.assertFalse(hello["capabilities"]["attachments"]) self.assertTrue(hello["capabilities"]["streaming"]) self.assertEqual(hello["model"], "gpt-5.6-terra") @@ -125,15 +125,15 @@ class ProtocolTests(unittest.TestCase): def test_server_frame_validation_is_closed(self): with self.assertRaisesRegex(ValueError, "unsupported"): - protocol.validate_server_frame({"type": "made.up", "protocolVersion": 2}) + protocol.validate_server_frame({"type": "made.up", "protocolVersion": 3}) with self.assertRaisesRegex(ValueError, "version"): - # Protocol v1 peers must upgrade before sending runtime frames. - protocol.validate_server_frame({"type": "ping", "protocolVersion": 1}) + # Protocol v2 peers must upgrade before sending runtime frames. + protocol.validate_server_frame({"type": "ping", "protocolVersion": 2}) def test_describe_frames_are_accepted_server_commands(self): for frame_type in ("describe.request", "skill.body.request"): with self.subTest(frame_type=frame_type): - message = {"type": frame_type, "protocolVersion": 2} + message = {"type": frame_type, "protocolVersion": 3} self.assertEqual(protocol.validate_server_frame(message), message) # ── describe.response ────────────────────────────────────────────── @@ -151,7 +151,7 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(response["type"], "describe.response") self.assertEqual(response["requestId"], "describe-1") - self.assertEqual(response["protocolVersion"], 2) + self.assertEqual(response["protocolVersion"], 3) self.assertEqual(response["pluginVersion"], protocol.PLUGIN_VERSION) self.assertEqual(response["hermesVersion"], "0.19.0") self.assertEqual(response["model"], "gpt-5.6-terra") @@ -282,7 +282,7 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(response["type"], "skill.body.response") self.assertEqual(response["requestId"], "body-1") - self.assertEqual(response["protocolVersion"], 2) + self.assertEqual(response["protocolVersion"], 3) self.assertEqual(response["skillName"], "codex") self.assertEqual(response["markdown"], "# Codex\n\nDelegate coding.") diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts index 4a1e280381..c181af4220 100644 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ b/packages/client-runtime/src/state/threadReducer.test.ts @@ -444,6 +444,88 @@ describe("applyThreadDetailEvent", () => { }); }); + describe("thread.notification-delivered", () => { + const deliveryEvent = { + ...baseEventFields, + sequence: 20, + occurredAt: "2026-04-01T07:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.notification-delivered", + payload: { + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("msg-notify"), + text: "Digest ready.", + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: "2026-04-01T07:00:00.000Z", + updatedAt: "2026-04-01T07:00:00.000Z", + }, + } as const; + + it("appends the delivery as a turnless assistant message carrying provenance", () => { + const result = applyThreadDetailEvent(baseThread, deliveryEvent); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.messages).toHaveLength(1); + expect(result.thread.messages[0]).toEqual({ + id: "msg-notify", + role: "assistant", + text: "Digest ready.", + turnId: null, + streaming: false, + notification: { + kind: "cron", + label: "Cron: daily-digest", + deliveryId: "delivery-1", + }, + createdAt: "2026-04-01T07:00:00.000Z", + updatedAt: "2026-04-01T07:00:00.000Z", + }); + expect(result.thread.updatedAt).toBe("2026-04-01T07:00:00.000Z"); + } + }); + + it("leaves an unrelated live turn untouched", () => { + // A delivery can land mid-turn; attributing it to that turn would fold + // it away behind the turn's summary and mis-settle the turn state. + const threadWithRunningTurn: OrchestrationThread = { + ...baseThread, + latestTurn: { + turnId: TurnId.make("turn-1"), + state: "running", + requestedAt: "2026-04-01T06:00:00.000Z", + startedAt: "2026-04-01T06:00:00.000Z", + completedAt: null, + assistantMessageId: null, + }, + }; + + const result = applyThreadDetailEvent(threadWithRunningTurn, deliveryEvent); + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.latestTurn).toEqual(threadWithRunningTurn.latestTurn); + } + }); + + it("replaces rather than duplicates on a replayed delivery", () => { + const first = applyThreadDetailEvent(baseThread, deliveryEvent); + expect(first.kind).toBe("updated"); + if (first.kind !== "updated") return; + + const second = applyThreadDetailEvent(first.thread, { ...deliveryEvent, sequence: 21 }); + expect(second.kind).toBe("updated"); + if (second.kind === "updated") { + expect(second.thread.messages).toHaveLength(1); + expect(second.thread.messages[0]).toEqual(first.thread.messages[0]); + } + }); + }); + describe("thread.session-set", () => { it("settles a running latestTurn when the session leaves the running status", () => { const threadWithRunningTurn: OrchestrationThread = { diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index 135375c576..160c5cf2fb 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -325,6 +325,36 @@ export function applyThreadDetailEvent( }; } + case "thread.notification-delivered": { + // A proactive delivery is an ordinary transcript message carrying + // provenance. It binds to no turn, so latestTurn and the checkpoint + // rebinding that `thread.message-sent` performs are deliberately + // untouched — attributing it to the live turn would fold it away + // behind that turn's summary. + const message: OrchestrationMessage = { + id: event.payload.messageId, + role: "assistant", + text: event.payload.text, + turnId: null, + streaming: false, + notification: event.payload.notification, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }; + + // Replays re-emit the persisted row verbatim, so replacing in place + // keeps the transcript stable instead of duplicating the delivery. + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = existingMessage + ? Arr.map(thread.messages, (entry) => (entry.id === message.id ? message : entry)) + : Arr.append(thread.messages, message); + + return { + kind: "updated", + thread: { ...thread, messages, updatedAt: event.occurredAt }, + }; + } + // ── Session ───────────────────────────────────────────────────── case "thread.session-set": { // Leaving the "running" session status is the turn-end signal: settle a diff --git a/packages/client-runtime/src/state/threadSort.test.ts b/packages/client-runtime/src/state/threadSort.test.ts index dd6f8c3a29..967073b7a0 100644 --- a/packages/client-runtime/src/state/threadSort.test.ts +++ b/packages/client-runtime/src/state/threadSort.test.ts @@ -68,4 +68,44 @@ describe("sortThreads", () => { expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]); }); + + it("pins the requested thread first regardless of its timestamp", () => { + // The agent home thread: a designated destination, not a conversation the + // user started, so staleness must not demote it. + const sorted = sortThreads( + [ + makeThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }), + makeThread({ id: "thread-home", updatedAt: "2026-01-01T00:00:00.000Z" }), + makeThread({ id: "thread-middle", updatedAt: "2026-03-09T10:00:00.000Z" }), + ], + "updated_at", + "thread-home", + ); + + expect(sorted.map((thread) => thread.id)).toEqual([ + "thread-home", + "thread-newest", + "thread-middle", + ]); + }); + + it("sorts unchanged when no thread is pinned or the pinned id is unknown", () => { + const threads = [ + makeThread({ id: "thread-newest", updatedAt: "2026-03-09T12:00:00.000Z" }), + makeThread({ id: "thread-oldest", updatedAt: "2026-01-01T00:00:00.000Z" }), + ]; + + expect(sortThreads(threads, "updated_at").map((thread) => thread.id)).toEqual([ + "thread-newest", + "thread-oldest", + ]); + expect(sortThreads(threads, "updated_at", null).map((thread) => thread.id)).toEqual([ + "thread-newest", + "thread-oldest", + ]); + expect(sortThreads(threads, "updated_at", "thread-gone").map((thread) => thread.id)).toEqual([ + "thread-newest", + "thread-oldest", + ]); + }); }); diff --git a/packages/client-runtime/src/state/threadSort.ts b/packages/client-runtime/src/state/threadSort.ts index aed63cd442..f411b427b6 100644 --- a/packages/client-runtime/src/state/threadSort.ts +++ b/packages/client-runtime/src/state/threadSort.ts @@ -69,18 +69,35 @@ export function getThreadSortTimestamp( return getLatestUserMessageTimestamp(thread); } +/** + * Sort threads for a list, optionally pinning one thread to the top. + * + * `pinnedThreadId` exists for the agent home thread: it is a designated + * destination rather than a conversation the user started, so it must hold + * position one no matter how stale it looks — an agent whose last cron ran a + * month ago still has to be the first row of its instance. The pin is a + * leading sort key rather than a splice so a single pass produces the whole + * ordering, and every downstream consumer of that ordering (preview slice, + * keyboard traversal, prewarming) inherits it for free. + * + * A pinned id that matches no thread changes nothing. + */ export function sortThreads( threads: readonly T[], sortOrder: SidebarThreadSortOrder, + pinnedThreadId?: string | null, ): T[] { return Arr.sort( threads, Order.mapInput( Order.Struct({ + // `Order.Boolean` puts `false` first; flipped, the pinned row leads. + pinned: Order.flip(Order.Boolean), timestamp: Order.flip(Order.Number), id: Order.flip(Order.String), }), (thread: T) => ({ + pinned: pinnedThreadId != null && thread.id === pinnedThreadId, timestamp: getThreadSortTimestamp(thread, sortOrder), id: thread.id, }), diff --git a/packages/contracts/src/hermesGateway.test.ts b/packages/contracts/src/hermesGateway.test.ts index f935c0cffd..5d4013304c 100644 --- a/packages/contracts/src/hermesGateway.test.ts +++ b/packages/contracts/src/hermesGateway.test.ts @@ -8,6 +8,7 @@ import { PROVIDER_DISPLAY_NAMES, } from "./model.ts"; import { + HERMES_GATEWAY_PROTOCOL_VERSION, HermesGatewayCapabilities, HermesGatewayConnectionHello, HermesGatewayCreateEnrollmentInput, @@ -72,9 +73,9 @@ describe("Hermes gateway management contracts", () => { model: "gpt-5.6-terra", connectionGeneration: 3, activeSessionCount: 2, - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, capabilities: { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, streaming: true, activity: true, approvals: true, @@ -107,11 +108,11 @@ describe("Hermes gateway handshake", () => { const hello = decodeHello({ type: "connection.hello", requestId: "hello-1", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, pluginVersion: "0.2.0", hermesVersion: "1.2.3", capabilities: { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, streaming: true, activity: true, approvals: true, @@ -131,11 +132,11 @@ describe("Hermes gateway handshake", () => { const hello = decodeHello({ type: "connection.hello", requestId: "hello-2", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, pluginVersion: "0.2.0", hermesVersion: "1.2.3", capabilities: { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, streaming: true, activity: true, approvals: true, @@ -161,11 +162,11 @@ describe("Hermes gateway handshake", () => { const hello = decodeHello({ type: "connection.hello", requestId: "hello-no-model", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, pluginVersion: "0.2.0", hermesVersion: "1.2.3", capabilities: { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, streaming: true, activity: true, approvals: true, @@ -210,7 +211,7 @@ describe("Hermes gateway handshake", () => { it("reserves attachments for a future protocol version", () => { expect(() => decodeCapabilities({ - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, streaming: true, activity: true, approvals: true, @@ -221,12 +222,12 @@ describe("Hermes gateway handshake", () => { }); }); -describe("T3 to Hermes v2 messages", () => { +describe("T3 to Hermes messages", () => { it("decodes session creation and opaque resume cursors", () => { expect( decodeT3Message({ type: "session.ensure", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "ensure-1", threadId: "thread-1", resumeSessionId: "opaque/hermes/session/value", @@ -235,7 +236,7 @@ describe("T3 to Hermes v2 messages", () => { expect( decodeResumeCursor({ - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, sessionId: "opaque/hermes/session/value", }).sessionId, ).toBe("opaque/hermes/session/value"); @@ -243,7 +244,7 @@ describe("T3 to Hermes v2 messages", () => { it("decodes start and steering as distinct turn operations", () => { const context = { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "turn-command-1", threadId: "thread-1", sessionId: "session-1", @@ -257,7 +258,7 @@ describe("T3 to Hermes v2 messages", () => { it("decodes interrupt, approval, structured input, stop, and ping", () => { const turnContext = { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, threadId: "thread-1", sessionId: "session-1", turnId: "turn-1", @@ -289,7 +290,7 @@ describe("T3 to Hermes v2 messages", () => { expect( decodeT3Message({ type: "session.stop", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "stop-1", threadId: "thread-1", sessionId: "session-1", @@ -298,7 +299,7 @@ describe("T3 to Hermes v2 messages", () => { expect( decodeT3Message({ type: "ping", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "ping-1", sentAt: "2026-07-23T12:00:00.000Z", }).type, @@ -316,11 +317,103 @@ describe("T3 to Hermes v2 messages", () => { }), ).toThrow(); }); + + it("defaults an unstated connection role to gateway", () => { + // The field is about intent, not tolerance: a hello that says nothing is + // the ordinary live plugin, which must never be read as a throwaway + // delivery socket. + const hello = decodeHello({ + type: "connection.hello", + requestId: "hello-role-default", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + pluginVersion: "0.2.0", + hermesVersion: "1.2.3", + capabilities: { + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + streaming: true, + activity: true, + approvals: true, + userInput: true, + attachments: false, + }, + authentication: { type: "instance-credential", instanceId: "hermes", credential: "secret" }, + }); + + expect(hello.role).toBe("gateway"); + }); + + it("carries the home thread designation on acceptance", () => { + const accepted = decodeT3Message({ + type: "connection.accepted", + requestId: "hello-1", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId: "hermes", + nickname: "Remote Hermes", + homeThreadId: "thread-home-1", + }); + + expect(accepted.type).toBe("connection.accepted"); + if (accepted.type === "connection.accepted") { + expect(accepted.homeThreadId).toBe("thread-home-1"); + } + + // Optional: a handshake whose home-thread resolution failed still accepts + // the plugin rather than refusing an authenticated connection. + const withoutHome = decodeT3Message({ + type: "connection.accepted", + requestId: "hello-2", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId: "hermes", + nickname: "Remote Hermes", + }); + expect(withoutHome.type).toBe("connection.accepted"); + }); }); -describe("Hermes to T3 v2 events", () => { +describe("Hermes home deliveries", () => { + const delivery = { + type: "home.deliver", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + deliveryId: "delivery-1", + threadId: "thread-home-1", + kind: "cron", + label: "Cron: daily-digest", + text: "Your digest is ready.", + createdAt: "2026-07-25T12:00:00.000Z", + } as const; + + it("decodes a delivery and its acknowledgement", () => { + const decoded = decodePluginMessage(delivery); + expect(decoded.type).toBe("home.deliver"); + if (decoded.type === "home.deliver") { + expect(decoded.kind).toBe("cron"); + expect(decoded.deliveryId).toBe("delivery-1"); + } + + const ack = decodeT3Message({ + type: "home.deliver.ack", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + deliveryId: "delivery-1", + }); + expect(ack.type).toBe("home.deliver.ack"); + }); + + it("requires a delivery id, since it is the dedupe key for retries", () => { + expect(() => decodePluginMessage({ ...delivery, deliveryId: "" })).toThrow(); + }); + + it("rejects an unknown delivery kind rather than guessing a badge", () => { + expect(() => decodePluginMessage({ ...delivery, kind: "surprise" })).toThrow(); + }); + + it("rejects empty delivery text", () => { + expect(() => decodePluginMessage({ ...delivery, text: "" })).toThrow(); + }); +}); + +describe("Hermes to T3 events", () => { const turnContext = { - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, threadId: "thread-1", sessionId: "session-1", turnId: "turn-1", @@ -329,7 +422,7 @@ describe("Hermes to T3 v2 events", () => { it("decodes session readiness, turn start, streaming text, and completion", () => { const legacyReady = decodePluginMessage({ type: "session.ready", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "ensure-1", threadId: "thread-1", sessionId: "session-1", @@ -338,7 +431,7 @@ describe("Hermes to T3 v2 events", () => { expect(legacyReady.type).toBe("session.ready"); const activeReady = decodePluginMessage({ type: "session.ready", - protocolVersion: 2, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, requestId: "ensure-2", threadId: "thread-1", sessionId: "session-1", diff --git a/packages/contracts/src/hermesGateway.ts b/packages/contracts/src/hermesGateway.ts index 74c693640d..925e38d1dd 100644 --- a/packages/contracts/src/hermesGateway.ts +++ b/packages/contracts/src/hermesGateway.ts @@ -7,6 +7,7 @@ * * @module hermesGateway */ +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { @@ -21,7 +22,7 @@ import { ProviderApprovalDecision, ProviderUserInputAnswers } from "./orchestrat import { ProviderInstanceId } from "./providerInstance.ts"; import { CanonicalItemType, CanonicalRequestType, UserInputQuestion } from "./providerRuntime.ts"; -export const HERMES_GATEWAY_PROTOCOL_VERSION = 2 as const; +export const HERMES_GATEWAY_PROTOCOL_VERSION = 3 as const; export const HermesGatewayProtocolVersion = Schema.Literal(HERMES_GATEWAY_PROTOCOL_VERSION); export type HermesGatewayProtocolVersion = typeof HermesGatewayProtocolVersion.Type; @@ -87,7 +88,7 @@ export type HermesGatewayCapabilities = typeof HermesGatewayCapabilities.Type; * * This deliberately permits capability shapes from a newer protocol so T3 can * return a structured `version-incompatible` rejection instead of failing the - * WebSocket frame decoder. Accepted v2 connections must subsequently validate + * WebSocket frame decoder. Accepted connections must subsequently validate * this advertisement with `HermesGatewayCapabilities`. */ export const HermesGatewayHelloCapabilities = Schema.Struct({ @@ -256,10 +257,23 @@ export const HermesGatewayAuthentication = Schema.Union([ ]); export type HermesGatewayAuthentication = typeof HermesGatewayAuthentication.Type; +/** + * What a connecting socket intends to be. + * + * `gateway` is the instance's one live plugin connection: registered under + * generation fencing, pinged for liveness, and displacing any predecessor. + * `delivery` is a short-lived socket — an out-of-process cron run dialing in + * only to hand over a `home.deliver` and leave. Delivery connections are + * authenticated identically but are never registered as the primary + * connection, so they cannot kick a healthy gateway socket off its instance. + */ +export const HermesGatewayConnectionRole = Schema.Literals(["gateway", "delivery"]); +export type HermesGatewayConnectionRole = typeof HermesGatewayConnectionRole.Type; + /** * `protocolVersion` accepts any positive integer at the initial boundary so * T3 can reject incompatible plugins with a structured upgrade response. - * Once accepted, all remaining v2 frames use the literal v2 schema. + * Once accepted, all remaining frames use the literal current-version schema. */ export const HermesGatewayConnectionHello = Schema.Struct({ type: Schema.Literal("connection.hello"), @@ -278,6 +292,12 @@ export const HermesGatewayConnectionHello = Schema.Struct({ * value degrades to the generic label rather than failing the handshake. */ model: Schema.optional(TrimmedNonEmptyString), + /** + * Defaults to `"gateway"` on decode so the field stays honest about intent + * rather than making every caller repeat the common case. v3 requires both + * sides updated regardless, so this default is ergonomics, not tolerance. + */ + role: HermesGatewayConnectionRole.pipe(Schema.withDecodingDefault(Effect.succeed("gateway"))), }); export type HermesGatewayConnectionHello = typeof HermesGatewayConnectionHello.Type; @@ -288,6 +308,17 @@ export const HermesGatewayConnectionAccepted = Schema.Struct({ instanceId: ProviderInstanceId, nickname: HermesGatewayNickname, credential: Schema.optional(HermesGatewayCredential), + /** + * The instance's durable home thread — where Hermes' proactive output lands + * when nothing named a destination. Sent on every successful handshake so + * the plugin reconciles its `T3_HOME_CHANNEL` cache each connect; T3's + * settings blob is the authoritative designation. + * + * Optional because resolving it must never fail a handshake: if the thread + * could not be created this connect, the plugin keeps whatever it had and + * reconciles on the next one. + */ + homeThreadId: Schema.optional(ThreadId), }); export type HermesGatewayConnectionAccepted = typeof HermesGatewayConnectionAccepted.Type; @@ -633,6 +664,68 @@ export const HermesGatewayPong = Schema.Struct({ }); export type HermesGatewayPong = typeof HermesGatewayPong.Type; +/** + * Plugin-minted, stable across retries. T3 dedupes on it, which is what makes + * the plugin's queue safe to flush more than once. + */ +export const HermesGatewayDeliveryId = TrimmedNonEmptyString.pipe( + Schema.brand("HermesGatewayDeliveryId"), +); +export type HermesGatewayDeliveryId = typeof HermesGatewayDeliveryId.Type; + +/** + * What produced a home delivery. Drives both the rendered badge and whether + * the delivery raises its hand: everything except `lifecycle` un-settles the + * thread and pushes; gateway online/shutdown notices land quietly. + * + * Classification is best-effort on the plugin side — Hermes' `adapter.send()` + * contract carries no structured provenance marker on every path — so a + * misclassification costs a wrong badge, never a lost delivery. + */ +export const HermesGatewayHomeDeliveryKind = Schema.Literals([ + "cron", + "message", + "lifecycle", + "handoff", + "other", +]); +export type HermesGatewayHomeDeliveryKind = typeof HermesGatewayHomeDeliveryKind.Type; + +/** + * Hermes-initiated delivery into the instance's home thread. + * + * Deliberately not a turn: there is no provider session, no turn id, and no + * request the delivery answers. A delivery may arrive while the home thread + * has a live user turn and must not disturb it. + */ +export const HermesGatewayHomeDeliver = Schema.Struct({ + type: Schema.Literal("home.deliver"), + protocolVersion: HermesGatewayProtocolVersion, + deliveryId: HermesGatewayDeliveryId, + threadId: ThreadId, + kind: HermesGatewayHomeDeliveryKind, + /** Human source label rendered as the badge — "Cron: daily-digest". */ + label: TrimmedNonEmptyString.check(Schema.isMaxLength(200)), + text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(120_000)), + /** + * When Hermes produced the content, not when it reached T3. These diverge + * whenever a queued delivery flushes after a reconnect. + */ + createdAt: IsoDateTime, +}); +export type HermesGatewayHomeDeliver = typeof HermesGatewayHomeDeliver.Type; + +/** + * Sent only after the delivery is durably written. The plugin purges its + * queued copy on this frame and nothing else, so acking early loses messages. + */ +export const HermesGatewayHomeDeliverAck = Schema.Struct({ + type: Schema.Literal("home.deliver.ack"), + protocolVersion: HermesGatewayProtocolVersion, + deliveryId: HermesGatewayDeliveryId, +}); +export type HermesGatewayHomeDeliverAck = typeof HermesGatewayHomeDeliverAck.Type; + export const HermesGatewayProtocolErrorCode = Schema.Literals([ "invalid-message", "unsupported-message", @@ -666,6 +759,7 @@ export const HermesGatewayT3ToPluginMessage = Schema.Union([ HermesGatewayDescribeRequest, HermesGatewaySkillBodyRequest, HermesGatewayPing, + HermesGatewayHomeDeliverAck, ]); export type HermesGatewayT3ToPluginMessage = typeof HermesGatewayT3ToPluginMessage.Type; @@ -690,6 +784,7 @@ export const HermesGatewayPluginToT3Message = Schema.Union([ HermesGatewaySkillBodyResponse, HermesGatewayPong, HermesGatewayProtocolError, + HermesGatewayHomeDeliver, ]); export type HermesGatewayPluginToT3Message = typeof HermesGatewayPluginToT3Message.Type; diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 158c00cfe6..0c33209194 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -238,6 +238,27 @@ export type OrchestrationProject = typeof OrchestrationProject.Type; export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]); export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type; +/** + * Provenance for a message an agent delivered on its own initiative rather + * than as the answer to a turn. + * + * Present only on proactive deliveries (a cron result, an agent-initiated + * `send_message`, a gateway lifecycle notice). Its absence is what makes a + * message an ordinary one, so consumers must treat "no notification" as the + * normal case and never synthesize a default. + */ +export const OrchestrationMessageNotification = Schema.Struct({ + kind: Schema.Literals(["cron", "message", "lifecycle", "handoff", "other"]), + /** Human source label rendered as the badge — "Cron: daily-digest". */ + label: TrimmedNonEmptyString, + /** + * The delivering agent's idempotency key. Retained on the row so a replayed + * delivery is recognized as one already written rather than appended twice. + */ + deliveryId: TrimmedNonEmptyString, +}); +export type OrchestrationMessageNotification = typeof OrchestrationMessageNotification.Type; + export const OrchestrationMessage = Schema.Struct({ id: MessageId, role: OrchestrationMessageRole, @@ -245,6 +266,11 @@ export const OrchestrationMessage = Schema.Struct({ attachments: Schema.optional(Schema.Array(ChatAttachment)), turnId: Schema.NullOr(TurnId), streaming: Schema.Boolean, + /** + * Set only on proactive agent deliveries. Optional so every existing + * producer, cached snapshot, and persisted row decodes unchanged. + */ + notification: Schema.optional(OrchestrationMessageNotification), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -417,6 +443,24 @@ export const OrchestrationProjectShell = Schema.Struct({ }); export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type; +/** + * The most recent proactive delivery in a thread, flattened onto the shell. + * + * Shell consumers (sidebar rows, the awareness/push projection) never load a + * thread's messages, so the notification provenance that lives on the message + * row has to be materialized here or those surfaces cannot see it at all. + * `deliveredAt` is the delivering message's `createdAt`, which is what lets a + * reader decide whether the notification is still the newest thing that + * happened to the thread or has been overtaken by a later turn. + */ +export const OrchestrationThreadNotificationSummary = Schema.Struct({ + kind: OrchestrationMessageNotification.fields.kind, + label: TrimmedNonEmptyString, + deliveredAt: IsoDateTime, +}); +export type OrchestrationThreadNotificationSummary = + typeof OrchestrationThreadNotificationSummary.Type; + export const OrchestrationThreadShell = Schema.Struct({ id: ThreadId, projectId: ProjectId, @@ -443,6 +487,12 @@ export const OrchestrationThreadShell = Schema.Struct({ hasPendingApprovals: Schema.Boolean, hasPendingUserInput: Schema.Boolean, hasActionableProposedPlan: Schema.Boolean, + /** + * Newest proactive delivery, or `null`/absent on every thread that has never + * received one. Optional (like `snoozedUntil`) so shells produced by + * pre-notification servers and every existing cached snapshot still decode. + */ + latestNotification: Schema.optional(Schema.NullOr(OrchestrationThreadNotificationSummary)), }); export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type; @@ -883,6 +933,28 @@ const ThreadActivityAppendCommand = Schema.Struct({ createdAt: IsoDateTime, }); +/** + * A proactive delivery from a connected agent into its home thread. + * + * Internal-only and deliberately outside the turn machinery: there is no + * provider session or turn behind it, and it may arrive while the thread has + * a live user turn, which it must not disturb. `deliveryId` is the agent's + * idempotency key — the decider drops a repeat rather than appending twice, + * which is what lets the plugin retry an unacked delivery safely. + */ +const ThreadNotificationDeliverCommand = Schema.Struct({ + type: Schema.Literal("thread.notification.deliver"), + commandId: CommandId, + threadId: ThreadId, + messageId: MessageId, + deliveryId: TrimmedNonEmptyString, + kind: Schema.Literals(["cron", "message", "lifecycle", "handoff", "other"]), + label: TrimmedNonEmptyString, + text: Schema.String, + /** When the agent produced the content, which may predate its arrival. */ + createdAt: IsoDateTime, +}); + const ThreadRevertCompleteCommand = Schema.Struct({ type: Schema.Literal("thread.revert.complete"), commandId: CommandId, @@ -899,6 +971,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadProposedPlanUpsertCommand, ThreadTurnDiffCompleteCommand, ThreadActivityAppendCommand, + ThreadNotificationDeliverCommand, ThreadRevertCompleteCommand, ]); export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type; @@ -936,6 +1009,7 @@ export const OrchestrationEventType = Schema.Literals([ "thread.proposed-plan-upserted", "thread.turn-diff-completed", "thread.activity-appended", + "thread.notification-delivered", ]); export type OrchestrationEventType = typeof OrchestrationEventType.Type; @@ -1179,6 +1253,23 @@ export const ThreadActivityAppendedPayload = Schema.Struct({ activity: OrchestrationThreadActivity, }); +/** + * A proactive agent delivery, materialized as an assistant message row. + * + * It is a real transcript message — selectable, copyable, part of history — + * distinguished only by carrying `notification` provenance. It has no + * `turnId`: nothing about it belongs to a turn, and attributing it to the + * thread's live turn would fold it away behind that turn's "Worked for …". + */ +export const ThreadNotificationDeliveredPayload = Schema.Struct({ + threadId: ThreadId, + messageId: MessageId, + text: Schema.String, + notification: OrchestrationMessageNotification, + createdAt: IsoDateTime, + updatedAt: IsoDateTime, +}); + export const OrchestrationEventMetadata = Schema.Struct({ providerTurnId: Schema.optional(TrimmedNonEmptyString), providerItemId: Schema.optional(ProviderItemId), @@ -1331,6 +1422,11 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.activity-appended"), payload: ThreadActivityAppendedPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.notification-delivered"), + payload: ThreadNotificationDeliveredPayload, + }), ]); export type OrchestrationEvent = typeof OrchestrationEvent.Type; diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 881f922ae7..37f098b2fd 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -19,6 +19,8 @@ export const RelayAgentAwarenessPhase = Schema.Literals([ "running", "waiting_for_approval", "waiting_for_input", + // A proactive agent delivery (cron result, agent-initiated message). + "notification", "completed", "failed", "stale", diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 4c74fa18ce..fe2d0dd7a8 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -203,6 +203,15 @@ export const ServerProvider = Schema.Struct({ skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))), versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory), updateState: Schema.optionalKey(ServerProviderUpdateState), + /** + * The instance's designated home thread, where its agent's proactive output + * lands. Clients use it to pin the thread first in the instance's list and + * to withhold Delete. + * + * Only Hermes instances designate one; absent everywhere else, and absent on + * a Hermes instance that has not completed a handshake yet. + */ + homeThreadId: Schema.optional(ThreadId), }); export type ServerProvider = typeof ServerProvider.Type; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 1e365e27b8..0e15f6fd9f 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -429,6 +429,19 @@ export const HermesSettings = makeProviderSettingsSchema({ revoked: Schema.optionalKey(Schema.Boolean).pipe( Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), + /** + * The instance's durable home thread — the authoritative designation for + * where Hermes' proactive output lands. + * + * Kept here rather than in a dedicated table for the same reason as the + * fields above: it is per-instance enrollment metadata, and settings avoids + * a migration. Absent means "not yet designated"; the next handshake + * converges it on read. The plugin's `T3_HOME_CHANNEL` env var is a synced + * cache of this value, never the source of truth. + */ + homeThreadId: Schema.optionalKey(TrimmedString).pipe( + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), }); export type HermesSettings = typeof HermesSettings.Type; diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.ts index 28e07c04e6..4f38eb6f59 100644 --- a/packages/shared/src/agentAwareness.test.ts +++ b/packages/shared/src/agentAwareness.test.ts @@ -29,6 +29,8 @@ function thread( | "updatedAt" | "hasPendingApprovals" | "hasPendingUserInput" + | "latestNotification" + | "latestUserMessageAt" > { return { id: "thread-1" as ThreadId, @@ -39,6 +41,8 @@ function thread( updatedAt: NOW, hasPendingApprovals: false, hasPendingUserInput: false, + latestNotification: null, + latestUserMessageAt: null, ...overrides, }; } @@ -102,6 +106,76 @@ describe("projectThreadAwareness", () => { }); }); + it("projects a fresh proactive delivery with the delivery's own label as the headline", () => { + const state = projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + latestNotification: { + kind: "cron", + label: "Cron: daily-digest", + deliveredAt: NOW, + }, + }), + }); + + expect(state?.phase).toBe("notification"); + // A generic headline would strip the only information the delivery carries. + expect(state?.headline).toBe("Cron: daily-digest"); + }); + + it("stops reporting a delivery once later thread activity supersedes it", () => { + const delivered = "2026-05-22T11:00:00.000Z"; + const later = "2026-05-22T11:30:00.000Z"; + const notification = { + kind: "message" as const, + label: "Hermes", + deliveredAt: delivered, + }; + + // A user reply after the delivery: the ordinary ladder takes over again. + expect( + projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ latestNotification: notification, latestUserMessageAt: later }), + }), + ).toBeNull(); + + // A turn that started after it likewise wins — otherwise "notification" + // would pin forever, since nothing ever marks it read. + expect( + projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + latestNotification: notification, + latestTurn: { + turnId: "turn-1" as TurnId, + state: "running", + requestedAt: later, + startedAt: later, + completedAt: null, + assistantMessageId: null, + }, + }), + })?.phase, + ).toBe("running"); + }); + + it("keeps blocked-on-you phases ahead of a delivery", () => { + const state = projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + hasPendingApprovals: true, + latestNotification: { kind: "cron", label: "Cron: nightly", deliveredAt: NOW }, + }), + }); + + expect(state?.phase).toBe("waiting_for_approval"); + }); + it("projects completed turns as completed even when teardown settled them as interrupted", () => { const finishedTurn = { turnId: "turn-1" as TurnId, diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts index c0f5842eb7..e6ba4594b6 100644 --- a/packages/shared/src/agentAwareness.ts +++ b/packages/shared/src/agentAwareness.ts @@ -10,6 +10,7 @@ export type AgentAwarenessPhase = | "running" | "waiting_for_approval" | "waiting_for_input" + | "notification" | "completed" | "failed" | "stale"; @@ -40,6 +41,8 @@ export interface ProjectThreadAwarenessInput { | "updatedAt" | "hasPendingApprovals" | "hasPendingUserInput" + | "latestNotification" + | "latestUserMessageAt" >; } @@ -66,7 +69,7 @@ export function projectThreadAwareness( projectTitle: project.title, threadTitle: thread.title, phase, - headline: headlineForPhase(phase), + headline: headlineForPhase(phase, thread), ...(detail === undefined ? {} : { detail }), modelTitle: thread.modelSelection.model, updatedAt: thread.updatedAt, @@ -83,6 +86,14 @@ function resolveThreadAwarenessPhase( if (thread.hasPendingUserInput) { return "waiting_for_input"; } + // A proactive delivery is news the user has not seen, but only while it is + // still the newest thing on the thread: once a turn or a user message lands + // after it, the ordinary ladder describes the thread better and pinning it + // to "notification" would suppress the real completion/running state + // indefinitely (there is no read state to clear it). + if (isLatestNotificationCurrent(thread)) { + return "notification"; + } if (thread.session?.status === "error" || thread.latestTurn?.state === "error") { return "failed"; } @@ -116,7 +127,42 @@ function resolveThreadAwarenessPhase( return null; } -function headlineForPhase(phase: AgentAwarenessPhase): string { +/** + * True while the thread's newest proactive delivery is also the newest thing + * that happened to the thread — nothing the user sent and no turn activity + * postdates it. + */ +function isLatestNotificationCurrent(thread: ProjectThreadAwarenessInput["thread"]): boolean { + const notification = thread.latestNotification ?? null; + if (!notification) { + return false; + } + const deliveredAtMs = Date.parse(notification.deliveredAt); + if (Number.isNaN(deliveredAtMs)) { + return false; + } + const supersedingTimestamps = [ + thread.latestUserMessageAt, + thread.latestTurn?.completedAt ?? null, + thread.latestTurn?.startedAt ?? null, + thread.latestTurn?.requestedAt ?? null, + ]; + for (const timestamp of supersedingTimestamps) { + if (timestamp === null) { + continue; + } + const timestampMs = Date.parse(timestamp); + if (!Number.isNaN(timestampMs) && timestampMs > deliveredAtMs) { + return false; + } + } + return true; +} + +function headlineForPhase( + phase: AgentAwarenessPhase, + thread: ProjectThreadAwarenessInput["thread"], +): string { switch (phase) { case "starting": return "Starting agent"; @@ -126,6 +172,10 @@ function headlineForPhase(phase: AgentAwarenessPhase): string { return "Approval needed"; case "waiting_for_input": return "Waiting for input"; + // The delivering agent's own label ("Cron: daily-digest") is the headline: + // a generic one would strip the only information the delivery carries. + case "notification": + return thread.latestNotification?.label ?? "New message"; case "completed": return "Agent finished"; case "failed":