diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index 748a0c6739..55d238852a 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -108,6 +108,7 @@ describe("CheckpointDiffQuery.layer", () => { }), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -203,6 +204,7 @@ describe("CheckpointDiffQuery.layer", () => { getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -288,6 +290,7 @@ describe("CheckpointDiffQuery.layer", () => { getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -358,6 +361,7 @@ describe("CheckpointDiffQuery.layer", () => { getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -413,6 +417,7 @@ describe("CheckpointDiffQuery.layer", () => { getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), 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 d80987e553..feb5ee343a 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -204,6 +204,7 @@ describe("OrchestrationEngine", () => { getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 9f8f5a5eea..d0ea11d858 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -1552,6 +1552,128 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { assert.equal(shellSnapshot.threads.length, 0); }), ); + + it.effect("finds a notification delivery in an archived thread", () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_thread_messages`; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + latest_user_message_at, + pending_approval_count, + pending_user_input_count, + has_actionable_proposed_plan, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES ( + 'thread-archived-home', + 'project-1', + 'Home', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + NULL, + 0, + 0, + 0, + '2026-04-07T00:00:00.000Z', + '2026-04-07T00:00:01.000Z', + '2026-04-07T00:00:02.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_thread_messages ( + message_id, + thread_id, + turn_id, + role, + text, + attachments_json, + notification_json, + is_streaming, + created_at, + updated_at + ) + VALUES + ( + 'message-delivered', + 'thread-archived-home', + NULL, + 'assistant', + 'Nightly brief', + NULL, + '{"kind":"cron","label":"Cron: nightly","deliveryId":"delivery-abc"}', + 0, + '2026-04-07T00:00:03.000Z', + '2026-04-07T00:00:03.000Z' + ), + ( + 'message-ordinary', + 'thread-archived-home', + NULL, + 'user', + 'delivery-abc appears in this body, but not as provenance', + NULL, + NULL, + 0, + '2026-04-07T00:00:04.000Z', + '2026-04-07T00:00:04.000Z' + ) + `; + + // Archiving parks a thread; it does not unwrite what is in it. The + // thread-detail read filters archived rows, so a dedupe check built on + // it reports every delivery as new and the plugin's retries append a + // duplicate per reconnect. + const detail = yield* snapshotQuery.getThreadDetailById( + ThreadId.make("thread-archived-home"), + ); + assert.equal(detail._tag, "None"); + + assert.isTrue( + yield* snapshotQuery.hasThreadNotificationDelivery({ + threadId: ThreadId.make("thread-archived-home"), + deliveryId: "delivery-abc", + }), + ); + // Matched on the provenance field, not a substring of the row: a + // deliveryId a user happened to type must not suppress a real delivery. + assert.isFalse( + yield* snapshotQuery.hasThreadNotificationDelivery({ + threadId: ThreadId.make("thread-archived-home"), + deliveryId: "delivery-never-written", + }), + ); + // Scoped to the thread — one instance's delivery id cannot mask another's. + assert.isFalse( + yield* snapshotQuery.hasThreadNotificationDelivery({ + threadId: ThreadId.make("thread-elsewhere"), + deliveryId: "delivery-abc", + }), + ); + }), + ); }); it.effect( diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 27198a035e..68cccbce69 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -819,6 +819,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { `, }); + // Dedupe, not display: deliberately no join to `projection_threads` and so + // no archive/delete filter. A delivery written into a thread the user later + // archived is still written, and treating it as absent would re-append it on + // every retry. `json_extract` rather than a LIKE over the blob, so a + // deliveryId occurring inside some other field cannot false-positive. + const findThreadNotificationDeliveryRow = SqlSchema.findOneOption({ + Request: Schema.Struct({ threadId: ThreadId, deliveryId: Schema.String }), + Result: Schema.Struct({ messageId: Schema.String }), + execute: ({ threadId, deliveryId }) => + sql` + SELECT message_id AS "messageId" + FROM projection_thread_messages + WHERE thread_id = ${threadId} + AND json_extract(notification_json, '$.deliveryId') = ${deliveryId} + LIMIT 1 + `, + }); + const getActiveThreadRowById = SqlSchema.findOneOption({ Request: ThreadIdLookupInput, Result: ProjectionThreadDbRowSchema, @@ -2063,6 +2081,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { } satisfies OrchestrationThreadShell); }); + const hasThreadNotificationDelivery: ProjectionSnapshotQueryShape["hasThreadNotificationDelivery"] = + (input) => + findThreadNotificationDeliveryRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.hasThreadNotificationDelivery:query", + "ProjectionSnapshotQuery.hasThreadNotificationDelivery:decodeRow", + ), + ), + Effect.map(Option.isSome), + ); + const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) => Effect.gen(function* () { const [ @@ -2249,6 +2279,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { getFullThreadDiffContext, getThreadShellById, getThreadArchiveStateById, + hasThreadNotificationDelivery, getThreadDetailById, getThreadDetailSnapshot, } satisfies ProjectionSnapshotQueryShape; diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index cdd7b8b9d2..70fe3891ec 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -183,6 +183,21 @@ export interface ProjectionSnapshotQueryShape { ProjectionRepositoryError >; + /** + * Answer "has this proactive delivery already been written to this thread", + * independent of archive state. + * + * The idempotency check behind `deliveryId` dedupe, kept off the detail read + * for the same reason `getThreadArchiveStateById` exists: `archived_at IS + * NULL` would make an archived thread report every delivery as absent, and + * each retry of one delivery would then append another copy. Reads only the + * provenance column, so it costs nothing near the message bodies. + */ + readonly hasThreadNotificationDelivery: (input: { + readonly threadId: ThreadId; + readonly deliveryId: string; + }) => Effect.Effect; + /** * 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 2c468c3594..9889c0533c 100644 --- a/apps/server/src/orchestration/agentProjects.test.ts +++ b/apps/server/src/orchestration/agentProjects.test.ts @@ -69,6 +69,7 @@ const makeQueryLayer = ( getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.die("unused"), + hasThreadNotificationDelivery: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index d67fd3ee00..fe69205904 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -45,6 +45,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) => getFullThreadDiffContext: () => Effect.die("unused"), getThreadShellById: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.die("unused"), + hasThreadNotificationDelivery: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index ac12d6d7c2..77c9cb96a0 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -206,6 +206,7 @@ describe("ProviderSessionReaper", () => { getThreadCheckpointContext: () => Effect.die("unused"), getFullThreadDiffContext: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadShellById: (threadId) => Effect.succeed( input.readModel.threads.find((thread) => thread.id === threadId) diff --git a/apps/server/src/provider/hermesGatewayHttp.test.ts b/apps/server/src/provider/hermesGatewayHttp.test.ts index b92ed7ffff..dc59beab60 100644 --- a/apps/server/src/provider/hermesGatewayHttp.test.ts +++ b/apps/server/src/provider/hermesGatewayHttp.test.ts @@ -11,7 +11,6 @@ import { type HermesGatewayMediaDeliver, type HermesGatewayT3ToPluginMessage, type OrchestrationCommand, - type OrchestrationThread, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -67,24 +66,6 @@ const mediaFrame = ( ...overrides, }) as HermesGatewayMediaDeliver; -/** A thread detail carrying one already-written delivery, for dedupe reads. */ -const threadWithDelivery = (threadId: ThreadId, deliveryId: string) => - ({ - id: threadId, - messages: [ - { - id: "message-existing", - role: "assistant", - text: "already here", - turnId: null, - streaming: false, - notification: { kind: "cron", label: "Cron: daily-digest", deliveryId }, - createdAt: CREATED_AT, - updatedAt: CREATED_AT, - }, - ], - }) as unknown as OrchestrationThread; - /** * The handlers only reach `adapter.hasSession` on the turn-scoped path, so * everything else can stay unimplemented. @@ -101,6 +82,8 @@ const makeHarness = (options?: { readonly existingDeliveries?: ReadonlyArray<{ threadId: ThreadId; deliveryId: string }>; readonly trackedThreadId?: ThreadId; readonly failDispatch?: boolean; + /** Archive state of the designated home thread, as the projection sees it. */ + readonly homeThreadArchivedAt?: string; }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -134,17 +117,19 @@ const makeHarness = (options?: { }); const queryLayer = Layer.mock(ProjectionSnapshotQuery)({ - getThreadDetailById: (threadId) => + // Row-level, and deliberately indifferent to archive state — the whole + // point of the lookup under test. `getThreadDetailById` is left + // unimplemented so a regression back to it fails loudly here. + hasThreadNotificationDelivery: ({ threadId, deliveryId }) => Effect.succeed( - Option.fromUndefinedOr( - options?.existingDeliveries - ?.filter((entry) => entry.threadId === threadId) - .map((entry) => threadWithDelivery(entry.threadId, entry.deliveryId))[0], + (options?.existingDeliveries ?? []).some( + (entry) => entry.threadId === threadId && entry.deliveryId === deliveryId, ), ), // The home thread is designated in settings and exists, so home-thread // resolution takes the fast path without dispatching a thread.create. - getThreadArchiveStateById: () => Effect.succeed(Option.some({ archivedAt: null })), + getThreadArchiveStateById: () => + Effect.succeed(Option.some({ archivedAt: options?.homeThreadArchivedAt ?? null })), }); const registryLayer = Layer.mock(ProviderInstanceRegistry)({ @@ -253,6 +238,24 @@ it.effect("acks a duplicate deliveryId without dispatching a second message", () }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect("dedupes a delivery into an ARCHIVED home thread", () => + Effect.gen(function* () { + // The retry loop this guards against: the dedupe read used to go through + // `getThreadDetailById`, which filters `archived_at IS NULL`. A home + // thread the user archived therefore reported every delivery as new, so a + // failed un-archive (best-effort by design) turned each of the plugin's + // retries into another appended row — all of them acked. + const harness = yield* makeHarness({ + homeThreadArchivedAt: CREATED_AT, + existingDeliveries: [{ threadId: HOME_THREAD_ID, deliveryId: "media-delivery-1" }], + }); + yield* harness.deliverMedia(registration, mediaFrame(), harness.transport); + + assert.equal(dispatchedDeliveries(yield* Ref.get(harness.dispatched)).length, 0); + assert.equal(harness.sent[0]?.type, "media.deliver.ack"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("routes turn-scoped media into the tracked thread and carries the turnId", () => Effect.gen(function* () { const harness = yield* makeHarness({ trackedThreadId: SESSION_THREAD_ID }); diff --git a/apps/server/src/provider/hermesGatewayHttp.ts b/apps/server/src/provider/hermesGatewayHttp.ts index 883ae88df6..70f7399120 100644 --- a/apps/server/src/provider/hermesGatewayHttp.ts +++ b/apps/server/src/provider/hermesGatewayHttp.ts @@ -74,17 +74,17 @@ export const makeHermesDeliveryHandlers = Effect.fn("makeHermesDeliveryHandlers" // `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. + // + // Deliberately NOT `getThreadDetailById`: that read filters `archived_at + // IS NULL`, so an archived Home reported every delivery as new. Combined + // with a failed un-archive (best-effort by design in `getOrCreateHomeThread`) + // that turned the plugin's retry loop into an append loop — one row per + // reconnect, all acked. This is the only durable dedupe after a restart, so + // it has to be archive-independent. const alreadyDelivered = (threadId: ThreadId, deliveryId: string) => - query.getThreadDetailById(threadId).pipe( - Effect.map( - Option.match({ - onNone: () => false, - onSome: (thread) => - thread.messages.some((candidate) => candidate.notification?.deliveryId === deliveryId), - }), - ), - Effect.orElseSucceed(() => false), - ); + query + .hasThreadNotificationDelivery({ threadId, deliveryId }) + .pipe(Effect.orElseSucceed(() => false)); /** * Write one proactive delivery into the instance's home thread and ack it. diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 50deb3a549..320f6d4a3c 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -97,6 +97,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.succeed(Option.none()), getThreadArchiveStateById: () => Effect.succeed(Option.none()), + hasThreadNotificationDelivery: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getThreadDetailSnapshot: () => Effect.succeed(Option.none()), }), @@ -163,6 +164,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.die("unused"), + hasThreadNotificationDelivery: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), @@ -209,6 +211,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.die("unused"), + hasThreadNotificationDelivery: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), @@ -261,6 +264,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa getFullThreadDiffContext: () => Effect.succeed(Option.none()), getThreadShellById: () => Effect.die("unused"), getThreadArchiveStateById: () => Effect.die("unused"), + hasThreadNotificationDelivery: () => Effect.die("unused"), getThreadDetailById: () => Effect.die("unused"), getThreadDetailSnapshot: () => Effect.die("unused"), }), diff --git a/integrations/hermes-t3-gateway/adapter.py b/integrations/hermes-t3-gateway/adapter.py index 4ae11a9f79..cf5c58d667 100644 --- a/integrations/hermes-t3-gateway/adapter.py +++ b/integrations/hermes-t3-gateway/adapter.py @@ -461,19 +461,29 @@ class T3PlatformAdapter(BasePlatformAdapter): # 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) + queued = self._home_queue.append(delivery) + sent = True try: await self._send_frame(delivery) except Exception as exc: # noqa: BLE001 - adapter send must return SendResult + sent = False 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. + # Success needs EITHER leg to have held. Queued-and-unsent arrives on + # the next connect; sent-but-unqueued is already at T3 (the ack simply + # finds nothing to purge). Neither means the content is gone, and + # reporting success then would tell a cron job its brief was delivered + # when nothing on this machine still holds it. + if not (queued or sent): + return SendResult( + success=False, + message_id=delivery_id_value, + error="T3 home delivery could not be sent or queued", + ) return SendResult(success=True, message_id=delivery_id_value) async def _handle_connection_accepted(self, accepted: dict[str, Any]) -> None: @@ -721,16 +731,29 @@ class T3PlatformAdapter(BasePlatformAdapter): logger.warning("T3 media delivery for %s failed to build: %s", path, exc) return SendResult(success=False, error=str(exc)) delivery_id_value = str(delivery["deliveryId"]) - self._home_queue.append(delivery) + queued = self._home_queue.append(delivery) + sent = True try: await self._send_frame(delivery) except Exception as exc: # noqa: BLE001 - adapter send must return SendResult + sent = False logger.warning( "T3 media delivery %s could not be sent (%s); it is queued for " "the next connect", delivery_id_value, exc, ) + # Neither queued nor sent means the file is gone — the only copy was + # the bytes in this frame, and Hermes' temp file may be reaped before + # anyone could retry. Fail before the completion below, so the turn is + # not closed on media that never arrived. See `_deliver_to_home` for + # why either leg alone is honest success. + if not (queued or sent): + return SendResult( + success=False, + message_id=delivery_id_value, + error="T3 media delivery could not be sent or queued", + ) # The same notify-completion contract `send()` honors for text. The # base adapter notify-marks every send of a reply's FINAL delivery # batch (`_mark_notify_metadata`, `gateway/platforms/base.py:5220`) — @@ -1101,31 +1124,44 @@ class T3PlatformAdapter(BasePlatformAdapter): request_id=str(message["requestId"]), ) self._active_turns[thread_id] = turn - await self._send_frame( - frame( - "turn.started", - requestId=turn.request_id, - threadId=thread_id, - sessionId=session_id, - turnId=turn.turn_id, + # Roll the registration back if starting the turn raises. Without this + # a failed `turn.started` send (a socket that dropped between the + # decode and the write) leaves a phantom turn no completion path will + # ever reach, and the `thread_id in self._active_turns` guard above + # then rejects every future `turn.start` on this thread for the life of + # the process. Guarded on identity: an error handler that already + # replaced the entry owns it now, and clobbering that would strand the + # replacement instead. + try: + await self._send_frame( + frame( + "turn.started", + requestId=turn.request_id, + threadId=thread_id, + sessionId=session_id, + turnId=turn.turn_id, + ) ) - ) - await self._send_status() - await self.handle_message( - MessageEvent( - text=str(message["text"]), - message_type=( - MessageType.COMMAND - if str(message["text"]).lstrip().startswith("/") - else MessageType.TEXT - ), - source=self._source(thread_id, turn.request_id), - message_id=turn.request_id, - metadata={"t3_turn_id": turn.turn_id}, - media_urls=media_paths, - media_types=media_types, + await self._send_status() + await self.handle_message( + MessageEvent( + text=str(message["text"]), + message_type=( + MessageType.COMMAND + if str(message["text"]).lstrip().startswith("/") + else MessageType.TEXT + ), + source=self._source(thread_id, turn.request_id), + message_id=turn.request_id, + metadata={"t3_turn_id": turn.turn_id}, + media_urls=media_paths, + media_types=media_types, + ) ) - ) + except BaseException: + if self._active_turns.get(thread_id) is turn: + del self._active_turns[thread_id] + raise async def _steer_turn(self, message: dict[str, Any]) -> None: turn = self._active_turns.get(str(message["threadId"])) diff --git a/integrations/hermes-t3-gateway/home.py b/integrations/hermes-t3-gateway/home.py index 12299447cd..1464fe30dd 100644 --- a/integrations/hermes-t3-gateway/home.py +++ b/integrations/hermes-t3-gateway/home.py @@ -186,18 +186,25 @@ class HomeDeliveryQueue: 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) + # 0700: queued frames carry message text and base64 media, so the + # outbox must not be readable by other users of the machine. Only a + # directory this call creates is affected — an existing `gateway/` is + # shared with Hermes' own plugin state and is not re-permissioned here. + self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) def _read_lines(self) -> list[dict[str, Any]]: + """Parse every queued entry. Raises `OSError` when the file is unreadable. + + The distinction callers depend on: a MISSING file is an empty queue, + while an unreadable one is an unknown queue. Collapsing the two into + `[]` is what would let a rewrite-based caller overwrite live entries it + merely failed to read. + """ 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 [] + raw = path.read_text(encoding="utf-8") for line in raw.splitlines(): line = line.strip() if not line: @@ -212,16 +219,39 @@ class HomeDeliveryQueue: entries.append(entry) return entries + @staticmethod + def _encode(entry: dict[str, Any]) -> str: + return json.dumps(entry, separators=(",", ":"), ensure_ascii=False) + "\n" + 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 - ) + payload = "".join(self._encode(entry) for entry in entries) temporary = self.path.with_suffix(".jsonl.tmp") - temporary.write_text(payload, encoding="utf-8") + # 0600 on the TEMP file, before the replace: `os.replace` carries the + # source's mode over, so permissioning here is what makes the queue + # private without a window where it is world-readable. + descriptor = os.open( + temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(payload) + os.chmod(temporary, 0o600) # A pre-existing temp file keeps its mode. temporary.replace(self.path) + def _append_line(self, entry: dict[str, Any]) -> None: + """Append one entry without reading or rewriting the file. + + The fallback when the queue could not be read: a single `O_APPEND` + write cannot destroy entries it cannot see, where the rewrite path + would replace all of them with this one. + """ + self._ensure_parent() + descriptor = os.open( + self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600 + ) + with os.fdopen(descriptor, "a", encoding="utf-8") as handle: + handle.write(self._encode(entry)) + def _file_lock(self): """Advisory cross-process lock, or a no-op where unavailable.""" @@ -237,7 +267,7 @@ class HomeDeliveryQueue: queue = self.path try: - queue.parent.mkdir(parents=True, exist_ok=True) + queue.parent.mkdir(parents=True, exist_ok=True, mode=0o700) except OSError: return _NoLock() @@ -248,7 +278,13 @@ class HomeDeliveryQueue: def __enter__(self): try: - self._handle = open(self._lock_path, "a+") # noqa: SIM115 + # 0600 like the queue itself: the sidecar carries no + # payload, but a world-writable lock is a way to stall + # another user's deliveries. + descriptor = os.open( + self._lock_path, os.O_RDWR | os.O_CREAT, 0o600 + ) + self._handle = os.fdopen(descriptor, "a+") fcntl.flock(self._handle, fcntl.LOCK_EX) except OSError: if self._handle is not None: @@ -272,7 +308,33 @@ class HomeDeliveryQueue: if not isinstance(frame, dict) or not frame.get("deliveryId"): return False with self._lock, self._file_lock(): - entries = self._read_lines() + try: + entries = self._read_lines() + except OSError: + # The rewrite path is off the table: it would replace every + # entry we failed to read with just this one, destroying an + # arbitrary number of unacked deliveries over a transient + # error. Append blind instead. The costs are bounded and both + # self-correct — the cap goes unenforced until the next + # successful read (a too-long queue is trimmed then), and a + # duplicate of an entry already on disk is deduped by T3 on + # `deliveryId`. + logger.warning( + "Could not read the T3 home delivery queue at %s; appending " + "without rewriting it", + self.path, + exc_info=True, + ) + try: + self._append_line(dict(frame)) + except OSError: + logger.error( + "Could not persist a T3 home delivery to %s", + self.path, + exc_info=True, + ) + return False + return True if any( entry.get("deliveryId") == frame["deliveryId"] for entry in entries ): @@ -300,9 +362,22 @@ class HomeDeliveryQueue: return True def entries(self) -> list[dict[str, Any]]: - """Every unacknowledged delivery, oldest first.""" + """Every unacknowledged delivery, oldest first. + + An unreadable queue reports empty rather than raising: the callers are + the flush loop and `__len__`, and skipping a flush cycle costs one + reconnect's delay while the entries stay on disk. + """ with self._lock: - return self._read_lines() + try: + return self._read_lines() + except OSError: + logger.warning( + "Could not read the T3 home delivery queue at %s", + self.path, + exc_info=True, + ) + return [] def purge(self, delivery_id_value: str) -> bool: """Remove one acknowledged delivery. Returns True when it was present.""" @@ -310,7 +385,20 @@ class HomeDeliveryQueue: if not target: return False with self._lock, self._file_lock(): - entries = self._read_lines() + try: + entries = self._read_lines() + except OSError: + # Purge only ever rewrites, so an unreadable queue means doing + # nothing. The entry stays and is replayed once — harmless, + # because T3 acked it and therefore dedupes the replay. + logger.warning( + "Could not read the T3 home delivery queue at %s to purge " + "%s; it will be replayed and deduped", + self.path, + target, + exc_info=True, + ) + return False remaining = [ entry for entry in entries if entry.get("deliveryId") != target ] diff --git a/integrations/hermes-t3-gateway/tests/test_adapter.py b/integrations/hermes-t3-gateway/tests/test_adapter.py index c7489e2f3d..f75c8c3bae 100644 --- a/integrations/hermes-t3-gateway/tests/test_adapter.py +++ b/integrations/hermes-t3-gateway/tests/test_adapter.py @@ -1589,6 +1589,69 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual([m["type"] for m in fallback_frames], ["item.started"]) self.assertEqual(fallback_frames[0]["threadId"], "thread-live") + async def test_a_failed_turn_start_leaves_no_phantom_turn_behind(self): + """A turn that never started must not wedge its thread forever. + + `_active_turns[thread_id]` is registered before `turn.started` goes out, + so a socket that drops in that window used to leave an entry no + completion path could ever reach — and the duplicate-turn guard then + rejected every future `turn.start` on that thread for the life of the + process. One dropped frame permanently silenced the thread. + """ + await self.adapter._handle_server_frame( + { + "type": "session.ensure", + "protocolVersion": 4, + "requestId": "ensure-wedged", + "threadId": "thread-wedged", + } + ) + session_id = self.adapter._sessions["thread-wedged"] + + original_send = self.connection.send + + async def drop_the_turn_started(message): + if message.get("type") == "turn.started": + raise ConnectionError("socket dropped mid-handshake") + await original_send(message) + + with unittest.mock.patch.object( + self.connection, "send", drop_the_turn_started + ): + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-wedged", + "threadId": "thread-wedged", + "sessionId": session_id, + "turnId": "turn-wedged", + "text": "Start", + } + ) + + # Rolled back, and the failure was reported against its own request. + self.assertEqual(self.adapter._active_turns, {}) + self.assertEqual(self.connection.messages[-1]["type"], "protocol.error") + self.assertEqual(self.connection.messages[-1]["requestId"], "start-wedged") + + # The thread is usable again on the very next attempt. + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-recovered", + "threadId": "thread-wedged", + "sessionId": session_id, + "turnId": "turn-recovered", + "text": "Try again", + } + ) + self.assertEqual( + self.adapter._active_turns["thread-wedged"].turn_id, "turn-recovered" + ) + self.assertEqual(self.adapter.messages[-1].text, "Try again") + class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): """The proactive `home.deliver` branch and its durable queue.""" @@ -1869,6 +1932,40 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): ) self.assertEqual(self.queue.entries(), []) + async def test_a_delivery_that_is_neither_queued_nor_sent_reports_failure(self): + """Success is a claim about durability, so it needs one leg to hold. + + A queue write that failed used to be ignored: an offline socket then + produced "delivered" for content held nowhere, and the cron job that + wrote it logged a success for output that will never appear. + """ + + class DeadConnection: + connected = False + + async def send(self, message): + raise ConnectionError("T3 Code gateway is offline") + + self.adapter._connection = DeadConnection() + with unittest.mock.patch.object( + self.queue, "append", return_value=False + ), self.assertLogs(adapter_module.logger, level="WARNING"): + result = await self.adapter.send(self.HOME, "Held nowhere at all") + + self.assertFalse(result.success) + self.assertIn("queued", result.error) + + async def test_a_delivery_that_reached_t3_is_honest_success_unqueued(self): + """T3 has it; the ack will simply find nothing to purge.""" + with unittest.mock.patch.object(self.queue, "append", return_value=False): + result = await self.adapter.send(self.HOME, "Sent but not queued") + + self.assertTrue(result.success) + self.assertEqual( + [frame["type"] for frame in self.connection.messages], ["home.deliver"] + ) + self.assertEqual(self.queue.entries(), []) + async def test_flush_restamps_stale_protocol_versions(self): """A frame queued under an older plugin must not wedge the reconnect. @@ -2605,6 +2702,59 @@ class MediaDeliveryTests(unittest.IsolatedAsyncioTestCase): [frame["type"] for frame in self.connection.messages], ) + async def test_media_that_is_neither_queued_nor_sent_reports_failure(self): + """An unpersisted delivery must not be reported as durable. + + Success here used to be unconditional on the queue write, so a full + disk plus a dead socket produced "delivered" for a file that exists + nowhere — and, on a notify-marked send, completed the turn on it. The + bytes are the only copy: Hermes' temp file is reaped and nothing can + replay a frame that was never written. + """ + + class DeadConnection: + connected = False + + async def send(self, message): + raise ConnectionError("T3 Code gateway is offline") + + thread = "thread-nowhere-to-go" + await self._start_turn(thread, "turn-nowhere") + self.adapter._connection = DeadConnection() + + with unittest.mock.patch.object( + self.queue, "append", return_value=False + ), self.assertLogs(adapter_module.logger, level="WARNING"): + result = await self.adapter.send_image_file( + thread, + str(self.chart), + metadata={"thread_id": thread, "notify": True}, + ) + + self.assertFalse(result.success) + self.assertIn("queued", result.error) + # The turn is NOT completed on media that went nowhere. + self.assertIn(thread, self.adapter._active_turns) + + async def test_media_that_reached_t3_is_honest_success_without_the_queue(self): + """The other branch: the live send held, so T3 has the file. + + The queue's only remaining job would be a replay T3 does not need, and + the ack simply finds nothing to purge. + """ + thread = "thread-sent-not-queued" + await self._start_turn(thread, "turn-sent-not-queued") + frames_before = len(self.connection.messages) + + with unittest.mock.patch.object(self.queue, "append", return_value=False): + result = await self.adapter.send_image_file(thread, str(self.chart)) + + self.assertTrue(result.success) + self.assertEqual( + [frame["type"] for frame in self.connection.messages[frames_before:]], + ["media.deliver"], + ) + async def test_audio_rides_the_same_media_frame_instead_of_the_fallback(self): """T3 renders audio as a download card — still strictly better than the base class's "couldn't deliver the audio attachment" notice.""" diff --git a/integrations/hermes-t3-gateway/tests/test_home.py b/integrations/hermes-t3-gateway/tests/test_home.py index b2fb6e7aaf..87cebaa040 100644 --- a/integrations/hermes-t3-gateway/tests/test_home.py +++ b/integrations/hermes-t3-gateway/tests/test_home.py @@ -2,6 +2,7 @@ from __future__ import annotations import importlib.util import json +import os import pathlib import sys import tempfile @@ -139,6 +140,74 @@ class QueueTests(unittest.TestCase): [entry["deliveryId"]], ) + def test_a_read_error_never_costs_the_entries_already_on_disk(self): + """The queue's worst failure mode, guarded. + + `append` normally rewrites the whole file to enforce the entry cap. A + read that failed used to report an empty queue, so that rewrite + replaced every unacked delivery on disk with the one being appended. + A transient EIO destroyed the outbox. The rewrite is skipped entirely + when the read fails: the cap goes briefly unenforced (recoverable on + the next successful read), the entries do not (not recoverable at all). + """ + first = make_delivery("already-queued") + second = make_delivery("also-queued") + self.queue.append(first) + self.queue.append(second) + arriving = make_delivery("arrives-during-the-outage") + + real_read_text = pathlib.Path.read_text + + def fail_reading_the_queue(path_self, *args, **kwargs): + if path_self == self.path: + raise OSError("simulated I/O error") + return real_read_text(path_self, *args, **kwargs) + + with unittest.mock.patch.object( + pathlib.Path, "read_text", fail_reading_the_queue + ), self.assertLogs(home.logger, level="WARNING"): + self.assertTrue(self.queue.append(arriving)) + + # Every pre-existing delivery survived, and the new one joined them. + self.assertEqual( + [entry["text"] for entry in self.queue.entries()], + ["already-queued", "also-queued", "arrives-during-the-outage"], + ) + + def test_a_read_error_leaves_an_acked_entry_for_a_deduped_replay(self): + """Purge only rewrites, so an unreadable queue means doing nothing.""" + entry = make_delivery("acked") + self.queue.append(entry) + + real_read_text = pathlib.Path.read_text + + def fail_reading_the_queue(path_self, *args, **kwargs): + if path_self == self.path: + raise OSError("simulated I/O error") + return real_read_text(path_self, *args, **kwargs) + + with unittest.mock.patch.object( + pathlib.Path, "read_text", fail_reading_the_queue + ), self.assertLogs(home.logger, level="WARNING"): + self.assertFalse(self.queue.purge(entry["deliveryId"])) + + self.assertEqual( + [item["deliveryId"] for item in self.queue.entries()], + [entry["deliveryId"]], + ) + + @unittest.skipIf(os.name != "posix", "POSIX file modes only") + def test_the_queue_is_readable_only_by_its_owner(self): + """Entries carry message text and base64 media — not other users' business.""" + self.queue.append(make_delivery("private")) + self.assertEqual(self.path.stat().st_mode & 0o777, 0o600) + self.assertEqual(self.path.parent.stat().st_mode & 0o777, 0o700) + + # And it stays private across the rewrite paths, not just on creation. + self.queue.append(make_delivery("still private")) + self.queue.purge(self.queue.entries()[0]["deliveryId"]) + self.assertEqual(self.path.stat().st_mode & 0o777, 0o600) + 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(