fix: complete Hermes turns on notify, never on finalize
My previous fix named the wrong culprit. `format_tool_event` is dead code at
Hermes 62e07223 — its only caller, `GatewayEventDispatcher`
(`gateway/stream_dispatch.py:108`), is referenced solely by upstream tests. The
live path is `gateway/run.py:20485+`, which builds the same progress lines and
delivers them through `adapter.send` / `adapter.edit_message` with no adapter
hook to suppress them. The override is kept as documented-contract defence with
a docstring saying so, but it never protected anything.
The turn was being closed by `finalize`. Two upstream paths set it:
- `gateway/run.py:20777-20780` — the tool-progress loop sets `finalize=True`
on every progress-bubble edit when the adapter declares
`REQUIRES_EDIT_FINALIZE`, which we did.
- `gateway/stream_consumer.py:938-940` — `finalize=(got_done or
got_segment_break)`, which fires on every mid-turn segment break
*regardless* of that flag.
So clearing `REQUIRES_EDIT_FINALIZE` alone would not have fixed it. Ignoring
`finalize` in `edit_message` is the load-bearing change; the flag is cleared
because declaring it only invites the first path. `notify=True` on `send()` is
the real completion signal — the gateway stamps it via `_mark_notify_metadata`
(`gateway/platforms/base.py:89`) only on genuine user-visible replies, and the
progress path never sets it.
Second bug, same class, found while auditing for siblings: the tool hooks'
`session_id` is `agent.session_id` (`agent/tool_executor.py:188`) — a
timestamped run id like `20260725_143012_ab12cd34`
(`gateway/session.py:2388`) — not this plugin's `build_session_key` id
(`agent:main:t3:dm:<thread>`). The namespaces never intersect, so every tool
activity item was silently dropped. `_turn_for_tool_hook` now resolves via the
raw id, then `HERMES_SESSION_KEY` from Hermes' session *contextvar* (the
concurrency-safe surface; upstream deliberately does not write the
process-global env var), then the sole active turn. With two or more concurrent
turns and no key it emits nothing rather than misattributing activity to the
wrong thread.
Also fixes the Build toggle rendering on Hermes threads. Same shape as the
`requiresWorkspace` bug: `getProviderInteractionModeToggle` is driver-kind
keyed, so it resolves `defaultInstanceIdForDriver("hermes")` — an instance id
that never exists, because Hermes ids are user-authored slugs and the registry
refuses to synthesize a default. The lookup missed and absent-means-true won.
Adds an instance-keyed helper and switches the composer to it, which fixes the
wide and compact layouts together.
Hiding the toggle is not enough on its own — plan mode stayed reachable three
other ways, all now gated: Shift+Tab, the `/plan` and `/default` menu items,
and the standalone-message parse (that last one mattered most: typing `/plan`
would otherwise swallow the message with no visible effect).
Regression tests pin both legs of the finalize bug by replaying the gateway's
own `_edit_progress_message` closure, and the interaction-mode test asserts the
kind-keyed lookup returns true while the instance-keyed one returns false on a
Hermes-shaped provider. COMPATIBILITY.md records the corrected diagnosis and
the inverted risk: if `notify` ever stops being stamped, turns would hang
instead of truncating.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
6a76a011b6
commit
3f71c601a6
7 files changed
+733
-81
No files matched your search
@@ -2383,6 +2383,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
// synthesized, so a kind-keyed lookup would never find one. Absent means
|
||||
// true, so every provider that predates the flag keeps its directory UI.
|
||||
const providerRequiresWorkspace = activeProviderStatus?.requiresWorkspace !== false;
|
||||
// Same instance-keyed resolution for the Build/Plan capability. When the
|
||||
// toggle is hidden the standalone `/plan` and `/default` messages must not be
|
||||
// intercepted either, otherwise typing one silently swallows the message with
|
||||
// no visible effect. Absent means true, matching the composer's default.
|
||||
const providerShowsInteractionModeToggle =
|
||||
activeProviderStatus?.showInteractionModeToggle !== false;
|
||||
const showComposerContextStrip = isGitRepo && activeProject !== null && providerRequiresWorkspace;
|
||||
const initialDiffPanelGitScope =
|
||||
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
|
||||
@@ -4498,6 +4504,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const standaloneSlashCommand =
|
||||
providerShowsInteractionModeToggle &&
|
||||
composerImages.length === 0 &&
|
||||
sendableComposerTerminalContexts.length === 0 &&
|
||||
composerElementContexts.length === 0 &&
|
||||
|
||||
@@ -174,8 +174,8 @@ import {
|
||||
import { proposedPlanTitle } from "../../proposedPlan";
|
||||
import {
|
||||
getProviderDisplayName,
|
||||
getProviderInstanceInteractionModeToggle,
|
||||
getProviderInstanceRequiresWorkspace,
|
||||
getProviderInteractionModeToggle,
|
||||
} from "../../providerModels";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
@@ -945,22 +945,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
// Both flags resolve per instance, not per driver kind: the composer already
|
||||
// knows the exact instance the next turn routes to, and providers whose
|
||||
// instances are always user-authored (Hermes) have no default instance for a
|
||||
// kind-keyed lookup to find.
|
||||
const composerProviderControls = useMemo(
|
||||
() => ({
|
||||
showInteractionModeToggle: getProviderInteractionModeToggle(
|
||||
showInteractionModeToggle: getProviderInstanceInteractionModeToggle(
|
||||
providerStatuses,
|
||||
selectedProvider,
|
||||
selectedInstanceId,
|
||||
),
|
||||
// Resolved per instance, not per driver kind: the composer already
|
||||
// knows the exact instance the next turn routes to, and providers
|
||||
// whose instances are always user-authored (Hermes) have no default
|
||||
// instance for a kind-keyed lookup to find.
|
||||
showRuntimeModeSelector: getProviderInstanceRequiresWorkspace(
|
||||
providerStatuses,
|
||||
selectedInstanceId,
|
||||
),
|
||||
}),
|
||||
[providerStatuses, selectedInstanceId, selectedProvider],
|
||||
[providerStatuses, selectedInstanceId],
|
||||
);
|
||||
// Only providers with no workspace get an agent button; for everyone else
|
||||
// this stays null and the Build toggle keeps the slot.
|
||||
@@ -1107,14 +1107,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}));
|
||||
}
|
||||
if (composerTrigger.kind === "slash-command") {
|
||||
const builtInSlashCommandItems = [
|
||||
{
|
||||
id: "slash:model",
|
||||
type: "slash-command",
|
||||
command: "model",
|
||||
label: "/model",
|
||||
description: "Switch response model for this thread",
|
||||
},
|
||||
const interactionModeSlashCommandItems = [
|
||||
{
|
||||
id: "slash:plan",
|
||||
type: "slash-command",
|
||||
@@ -1130,6 +1123,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
description: "Switch this thread back to normal build mode",
|
||||
},
|
||||
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
|
||||
const builtInSlashCommandItems = [
|
||||
{
|
||||
id: "slash:model",
|
||||
type: "slash-command",
|
||||
command: "model",
|
||||
label: "/model",
|
||||
description: "Switch response model for this thread",
|
||||
},
|
||||
// Hidden for providers that opt out of the Build/Plan toggle — the
|
||||
// standalone `/plan` message form is skipped for them too, so the
|
||||
// command cannot silently swallow a message with no visible effect.
|
||||
...(composerProviderControls.showInteractionModeToggle
|
||||
? interactionModeSlashCommandItems
|
||||
: []),
|
||||
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
|
||||
const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map(
|
||||
(command) => ({
|
||||
id: `provider-slash-command:${selectedProvider}:${command.name}`,
|
||||
@@ -1163,7 +1171,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]);
|
||||
}, [
|
||||
composerProviderControls.showInteractionModeToggle,
|
||||
composerTrigger,
|
||||
selectedProvider,
|
||||
selectedProviderStatus,
|
||||
workspaceEntries.entries,
|
||||
]);
|
||||
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const composerMenuSearchKey = composerTrigger
|
||||
@@ -1907,7 +1921,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => {
|
||||
if (key === "Tab" && event.shiftKey) {
|
||||
// Providers that opt out of the Build/Plan toggle must not be reachable
|
||||
// through the shortcut either; fall through to normal Tab handling.
|
||||
if (key === "Tab" && event.shiftKey && composerProviderControls.showInteractionModeToggle) {
|
||||
toggleInteractionMode();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getProviderInstanceInteractionModeToggle,
|
||||
getProviderInstanceRequiresWorkspace,
|
||||
getProviderInteractionModeToggle,
|
||||
getProviderRequiresWorkspace,
|
||||
} from "./providerModels";
|
||||
|
||||
@@ -10,6 +12,7 @@ function provider(input: {
|
||||
driver: string;
|
||||
instanceId: string;
|
||||
requiresWorkspace?: boolean;
|
||||
showInteractionModeToggle?: boolean;
|
||||
}): ServerProvider {
|
||||
return {
|
||||
instanceId: ProviderInstanceId.make(input.instanceId),
|
||||
@@ -26,6 +29,9 @@ function provider(input: {
|
||||
...(input.requiresWorkspace === undefined
|
||||
? {}
|
||||
: { requiresWorkspace: input.requiresWorkspace }),
|
||||
...(input.showInteractionModeToggle === undefined
|
||||
? {}
|
||||
: { showInteractionModeToggle: input.showInteractionModeToggle }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -129,3 +135,114 @@ describe("getProviderInstanceRequiresWorkspace", () => {
|
||||
expect(getProviderInstanceRequiresWorkspace([], hermesInstanceId)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProviderInteractionModeToggle", () => {
|
||||
it("treats an absent field as true so existing providers keep the Build/Plan toggle", () => {
|
||||
expect(
|
||||
getProviderInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex" })],
|
||||
codexKind,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("honors an explicit false on the default instance", () => {
|
||||
expect(
|
||||
getProviderInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex", showInteractionModeToggle: false })],
|
||||
codexKind,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true for an unknown driver rather than crashing", () => {
|
||||
expect(
|
||||
getProviderInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex", showInteractionModeToggle: false })],
|
||||
ProviderDriverKind.make("someForkDriver"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for an empty providers array", () => {
|
||||
expect(getProviderInteractionModeToggle([], codexKind)).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores non-default instances of the same driver kind", () => {
|
||||
expect(
|
||||
getProviderInteractionModeToggle(
|
||||
[
|
||||
provider({
|
||||
driver: "codex",
|
||||
instanceId: "codex_personal",
|
||||
showInteractionModeToggle: false,
|
||||
}),
|
||||
],
|
||||
codexKind,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProviderInstanceInteractionModeToggle", () => {
|
||||
const hermesInstanceId = ProviderInstanceId.make("hermes-work-abc123");
|
||||
|
||||
it("resolves a user-authored Hermes instance that the driver-kind lookup cannot reach", () => {
|
||||
const providers = [
|
||||
provider({
|
||||
driver: "hermes",
|
||||
instanceId: "hermes-work-abc123",
|
||||
showInteractionModeToggle: false,
|
||||
}),
|
||||
];
|
||||
|
||||
// The kind-keyed lookup resolves `defaultInstanceIdForDriver("hermes")`,
|
||||
// which never exists — the absent-means-true fallback wins and the Build
|
||||
// toggle renders even though the driver opted out. That is the bug.
|
||||
expect(getProviderInteractionModeToggle(providers, ProviderDriverKind.make("hermes"))).toBe(
|
||||
true,
|
||||
);
|
||||
// Keyed on the instance the thread is actually bound to, the driver's
|
||||
// opt-out is honored.
|
||||
expect(getProviderInstanceInteractionModeToggle(providers, hermesInstanceId)).toBe(false);
|
||||
});
|
||||
|
||||
it("treats an absent field as true", () => {
|
||||
expect(
|
||||
getProviderInstanceInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex" })],
|
||||
ProviderInstanceId.make("codex"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("honors an explicit true", () => {
|
||||
expect(
|
||||
getProviderInstanceInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex", showInteractionModeToggle: true })],
|
||||
ProviderInstanceId.make("codex"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for an unknown instance", () => {
|
||||
expect(
|
||||
getProviderInstanceInteractionModeToggle(
|
||||
[provider({ driver: "codex", instanceId: "codex", showInteractionModeToggle: false })],
|
||||
ProviderInstanceId.make("codex_missing"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for a null or undefined instance id", () => {
|
||||
const providers = [
|
||||
provider({ driver: "codex", instanceId: "codex", showInteractionModeToggle: false }),
|
||||
];
|
||||
expect(getProviderInstanceInteractionModeToggle(providers, null)).toBe(true);
|
||||
expect(getProviderInstanceInteractionModeToggle(providers, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for an empty providers array", () => {
|
||||
expect(getProviderInstanceInteractionModeToggle([], hermesInstanceId)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -46,6 +46,21 @@ export function getProviderDisplayName(
|
||||
return snapshot?.displayName?.trim() || formatProviderDriverKindLabel(provider);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this driver's default instance offers the Build/Plan interaction-mode
|
||||
* toggle.
|
||||
*
|
||||
* Absent means `true`: every provider that predates the flag is a coding
|
||||
* provider with a real plan mode.
|
||||
*
|
||||
* Driver-kind keyed, so it only ever resolves the *default* instance for the
|
||||
* kind (`defaultInstanceIdForDriver`). Drivers whose instances are always
|
||||
* user-authored — Hermes ids look like `hermes-<label>-<suffix>` and the
|
||||
* registry never synthesizes a `hermes` default — will not be found here and
|
||||
* fall through to `true`, showing a toggle the driver explicitly opted out of.
|
||||
* Prefer {@link getProviderInstanceInteractionModeToggle} whenever the caller
|
||||
* knows the instance a thread is actually bound to.
|
||||
*/
|
||||
export function getProviderInteractionModeToggle(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
provider: ProviderDriverKind,
|
||||
@@ -53,6 +68,22 @@ export function getProviderInteractionModeToggle(
|
||||
return getProviderSnapshot(providers, provider)?.showInteractionModeToggle ?? true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-instance counterpart of {@link getProviderInteractionModeToggle},
|
||||
* resolved by exact `instanceId` rather than by driver kind. Same
|
||||
* absent-means-`true` default for unknown instances.
|
||||
*/
|
||||
export function getProviderInstanceInteractionModeToggle(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
instanceId: ProviderInstanceId | null | undefined,
|
||||
): boolean {
|
||||
if (!instanceId) return true;
|
||||
return (
|
||||
providers.find((candidate) => candidate.instanceId === instanceId)?.showInteractionModeToggle ??
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether threads on this driver's default instance are rooted in a workspace
|
||||
* directory.
|
||||
|
||||
@@ -15,6 +15,19 @@ Audited surfaces, all present at that commit:
|
||||
| `resolve_gateway_approval` | `tools/approval.py:2073` |
|
||||
| `resolve_gateway_clarify` | `tools/clarify_gateway.py:160` |
|
||||
| `register_platform` (`**entry_kwargs`) | `hermes_cli/plugins.py:931` |
|
||||
| `_mark_notify_metadata` (`notify` flag) | `gateway/platforms/base.py:89` |
|
||||
| Tool-hook `session_id` (= run id) | `agent/tool_executor.py:188` |
|
||||
| Run-id generation | `gateway/session.py:2388` |
|
||||
| `HERMES_SESSION_KEY` binding | `gateway/run.py:17367` |
|
||||
| `get_session_env` accessor | `gateway/session_context.py:303` |
|
||||
| Tool-thread context propagation | `agent/tool_executor.py:715` |
|
||||
| Final-delivery `notify` stamp | `gateway/platforms/base.py:5220` |
|
||||
| Streaming final `notify` stamp | `gateway/stream_consumer.py:328` |
|
||||
| `REQUIRES_EDIT_FINALIZE` declaration | `gateway/platforms/base.py:3128` |
|
||||
| Progress-loop `finalize` injection | `gateway/run.py:20777` |
|
||||
| Segment-break `finalize` (flag-agnostic) | `gateway/stream_consumer.py:938` |
|
||||
| Live tool-chrome delivery path | `gateway/run.py:20485` |
|
||||
| `tool_progress` display resolution | `gateway/display_config.py:187` |
|
||||
| `format_tool_event` (override hook) | `gateway/platforms/base.py:2740` |
|
||||
| Tool-chrome dispatch (`None` == eat) | `gateway/stream_dispatch.py:108` |
|
||||
| `/steer` active-run handler | `gateway/run.py:11280` |
|
||||
@@ -73,13 +86,43 @@ older server/plugin pairs are rejected during the handshake.
|
||||
and raw results never cross the wire.
|
||||
- `post_tool_call` passes `result` as `Any`, not a guaranteed `str` — the
|
||||
adapter never forwards it, so the looser type is inert here.
|
||||
- **The tool hooks' `session_id` is not this plugin's session id.** Hermes
|
||||
passes `agent.session_id` (`agent/tool_executor.py:188`, `:305`, `:341`),
|
||||
which the gateway sets from `SessionEntry.session_id` — a timestamped run id
|
||||
like `20260725_143012_ab12cd34` (`gateway/session.py:2388`,
|
||||
`agent/agent_init.py:1446-1453`). This plugin's session ids come from
|
||||
`build_session_key` (`gateway/session.py:1029`) and are shaped
|
||||
`agent:main:t3:dm:<thread>`. The two namespaces never intersect, so keying
|
||||
the thread lookup on the hook's value alone matched nothing and silently
|
||||
dropped every tool activity item. This is the same class of defect as the
|
||||
`finalize` bug — keying behaviour off a Hermes-supplied value whose meaning
|
||||
was assumed rather than verified. `_turn_for_tool_hook` now resolves in three
|
||||
steps: the raw `session_id` as a routing key (free, and correct if upstream
|
||||
ever passes the gateway key here), then `HERMES_SESSION_KEY` from Hermes'
|
||||
session context (`gateway/run.py:17367` →
|
||||
`gateway/session_context.py:200`, read via `get_session_env` at `:303`),
|
||||
which IS the `build_session_key` value and is propagated into the tool worker
|
||||
threads by `propagate_context_to_thread` (`agent/tool_executor.py:715`), then
|
||||
the sole active turn when exactly one exists. With two or more concurrent
|
||||
turns and no routing key it emits nothing rather than misattributing activity
|
||||
to the wrong thread. Every step is best-effort and cannot raise: tool
|
||||
activity is decorative and must never break a turn.
|
||||
|
||||
Regression shape if upstream changes: if `HERMES_SESSION_KEY` stops being
|
||||
bound or stops propagating into tool threads, a **multi-thread** Hermes loses
|
||||
tool activity rows (single-thread still works via the sole-turn fallback).
|
||||
Turn lifecycle is unaffected either way — tool items are decorative.
|
||||
|
||||
- Approval resolution is session-FIFO in Hermes. T3 request IDs identify the UI
|
||||
prompt, then resolve the oldest matching Hermes approval for that session.
|
||||
- The public `clarify` hook is a single question. The wire protocol supports an
|
||||
array so richer structured input can be added without a protocol break.
|
||||
- Hermes session completion has no dedicated platform-adapter callback. The
|
||||
plugin uses the stream consumer's required `finalize=True` edit as the
|
||||
authoritative completion boundary.
|
||||
plugin uses `notify=True` metadata on `send` as the authoritative completion
|
||||
boundary (`_mark_notify_metadata`, `gateway/platforms/base.py:89`). It
|
||||
explicitly does **not** use `finalize=True` on `edit_message`, which upstream
|
||||
sets on every mid-turn tool-progress edit and every stream segment break —
|
||||
see "Turn completion is keyed off `notify`, never `finalize`" below.
|
||||
- Active `/steer` dispatch returns a textual Hermes control acknowledgement
|
||||
through the normal platform `send(..., notify=True)` path
|
||||
(`gateway/platforms/base.py:4926`). The plugin captures that response in the
|
||||
@@ -154,27 +197,93 @@ older server/plugin pairs are rejected during the handshake.
|
||||
- Attachments are not accepted. They are the first planned post-stability
|
||||
feature; the capability is reserved and fixed to `false` in protocol v2.
|
||||
|
||||
## Tool-progress chrome is dropped, not rendered
|
||||
## Turn completion is keyed off `notify`, never `finalize`
|
||||
|
||||
`BasePlatformAdapter.format_tool_event` renders each tool call as an emoji
|
||||
progress line ("📚 skill_view: …") and the gateway delivers it through the
|
||||
ordinary reply path. The plugin overrides it to return `None`, which
|
||||
`gateway/stream_dispatch.py:108` documents as "adapter chose to eat this event".
|
||||
**A previous revision of this document blamed `format_tool_event` for the
|
||||
early-turn-truncation bug. That diagnosis was wrong.** It is corrected here;
|
||||
the real cause and the real completion signal are documented below.
|
||||
|
||||
Two reasons, the second severe:
|
||||
### The signal that ends a turn: `notify=True` on `send`
|
||||
|
||||
1. T3 already renders tool calls as typed `item.started` / `item.completed`
|
||||
activity from the `pre_tool_call` / `post_tool_call` hooks. The text line is
|
||||
a strictly poorer duplicate of a surface T3 already has.
|
||||
2. The gateway marks user-visible replies `notify=True`
|
||||
(`_mark_notify_metadata`, `gateway/platforms/base.py:89`), and this plugin's
|
||||
`send()` treats `notify` as "this turn is finished" — it calls
|
||||
`_complete_turn`. So the **first tool call ended the T3 turn while Hermes was
|
||||
still working**: the transcript kept the progress chrome as the assistant's
|
||||
entire answer, and every subsequent send failed with "no active T3 turn"
|
||||
(visible in the gateway log as `Send failed: no active T3 turn — trying
|
||||
plain-text fallback`). The real answer never arrived.
|
||||
`_mark_notify_metadata` (`gateway/platforms/base.py:89`) stamps `notify: True`
|
||||
onto the metadata of a send, and the gateway applies it **only** for genuine
|
||||
user-visible replies:
|
||||
|
||||
If a future Hermes stops routing tool chrome through `format_tool_event`, this
|
||||
regresses silently and in exactly that shape: turns that end early, at the first
|
||||
tool call, with progress text as the answer.
|
||||
- the final response delivery (`gateway/platforms/base.py:5220`, consumed at
|
||||
`:5261`, `:5330`, `:5376`, `:5418`, `:5433`-`:5469`),
|
||||
- slash-command acknowledgements (`:4827`, `:4934`, `:4987`),
|
||||
- and, in the streaming path, `StreamConsumer._metadata_for_send(final=True)`
|
||||
(`gateway/stream_consumer.py:328-329`).
|
||||
|
||||
`send(..., metadata={"notify": True})` is therefore the plugin's completion
|
||||
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
|
||||
boundary. Two upstream paths set it mid-turn:
|
||||
|
||||
1. **The tool-progress loop.** When an adapter declares
|
||||
`REQUIRES_EDIT_FINALIZE`, `_edit_progress_message` passes `finalize=True` on
|
||||
**every** progress-bubble edit (`gateway/run.py:20777-20780`) — once per tool
|
||||
event, for the whole turn. Nothing about that edit is final.
|
||||
2. **The stream consumer's segment breaks.** `_send_or_edit` is called with
|
||||
`finalize=(got_done or got_segment_break)`
|
||||
(`gateway/stream_consumer.py:938-940`), so every mid-turn tool/segment
|
||||
boundary finalizes the current content message. This path is
|
||||
**independent of `REQUIRES_EDIT_FINALIZE`** — setting the flag to `False`
|
||||
does not suppress it.
|
||||
|
||||
This plugin previously declared `REQUIRES_EDIT_FINALIZE = True` and treated
|
||||
`finalize=True` in `edit_message` as "turn finished", calling `_complete_turn`.
|
||||
Consequently the **first tool call ended the T3 turn while Hermes was still
|
||||
working**: the transcript kept the progress chrome ("📚 Reading skill
|
||||
hermes-agent 🔍 Searching the web for …") as the assistant's entire answer, and
|
||||
every subsequent send failed with `Send failed: no active T3 turn — trying
|
||||
plain-text fallback` in the gateway log. The real answer never arrived.
|
||||
|
||||
The fix is twofold, and both halves are needed because of path (2) above:
|
||||
|
||||
- `REQUIRES_EDIT_FINALIZE = False` — declaring it only arms path (1). T3 closes
|
||||
an item on `item.completed`, which this plugin emits itself; it has no
|
||||
rich-card streaming state that needs an explicit close.
|
||||
- `edit_message` ignores `finalize` outright (`del metadata, finalize`) and
|
||||
never calls `_complete_turn` — this is what defends against path (2).
|
||||
|
||||
`test_tool_progress_bubble_edits_never_complete_the_turn` pins both legs:
|
||||
it replays the gateway's `_edit_progress_message` closure verbatim and a
|
||||
segment-break finalize, asserts the turn survives every one, then asserts a
|
||||
single `notify=True` send completes it exactly once.
|
||||
|
||||
**Regression shape if upstream changes.** If a future Hermes makes `finalize`
|
||||
genuinely mean "turn over" and removes the mid-turn uses, this plugin will
|
||||
simply never see a completion via that route — harmless, since `notify` still
|
||||
fires. The dangerous direction is the inverse: if `_mark_notify_metadata` stops
|
||||
being applied to the final delivery (or the streaming path stops calling
|
||||
`_metadata_for_send(final=True)`), turns would **never complete** — T3 threads
|
||||
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.
|
||||
|
||||
## Tool-progress chrome: the `format_tool_event` override is not the defence
|
||||
|
||||
The plugin overrides `format_tool_event` to return `None`
|
||||
(`gateway/platforms/base.py:2740`), which `gateway/stream_dispatch.py:108`
|
||||
documents as "adapter chose to eat this event". T3 already renders tool calls as
|
||||
typed `item.started` / `item.completed` activity from the `pre_tool_call` /
|
||||
`post_tool_call` hooks, so the text line is a strictly poorer duplicate.
|
||||
|
||||
**At 62e07223 this hook is dead code on the live path.** Its only caller is
|
||||
`GatewayEventDispatcher` (`gateway/stream_dispatch.py:40`, dispatch at `:108`),
|
||||
and that class is referenced nowhere in the shipped gateway — only from
|
||||
`tests/gateway/test_stream_events.py`. The path that actually runs is
|
||||
`gateway/run.py:20485+`, which builds the same emoji lines itself and delivers
|
||||
them via `adapter.send` / `adapter.edit_message`, with **no adapter hook to
|
||||
suppress them**. Chrome visibility there is governed by the platform's
|
||||
`tool_progress` display setting (`gateway/display_config.py:187`), not by this
|
||||
override.
|
||||
|
||||
The override is kept as documented-contract defence: it costs nothing and
|
||||
becomes load-bearing again if upstream routes chrome through the dispatcher. But
|
||||
it never protected the turn — ignoring `finalize` does.
|
||||
@@ -109,7 +109,12 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
|
||||
supports_code_blocks = True
|
||||
supports_status_text = True
|
||||
REQUIRES_EDIT_FINALIZE = True
|
||||
# Deliberately NOT set. It exists for rich-card surfaces that must be told
|
||||
# when to leave the streaming state; T3 closes an item on `item.completed`,
|
||||
# which this plugin emits itself. Declaring it only makes the gateway's
|
||||
# progress loop pass `finalize=True` on every progress edit
|
||||
# (`gateway/run.py:20777-20780`) — a signal we must ignore anyway.
|
||||
REQUIRES_EDIT_FINALIZE = False
|
||||
MAX_MESSAGE_LENGTH = 120_000
|
||||
_instances: weakref.WeakSet[T3PlatformAdapter] = weakref.WeakSet()
|
||||
|
||||
@@ -223,7 +228,22 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
finalize: bool = False,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SendResult:
|
||||
del metadata
|
||||
# `finalize` is deliberately ignored as a completion signal.
|
||||
#
|
||||
# It reads like "this is the final edit of the response", and that is
|
||||
# what the base class documents it as — but the gateway's tool-progress
|
||||
# loop sets it unconditionally on EVERY progress-bubble edit whenever
|
||||
# the adapter declares `REQUIRES_EDIT_FINALIZE`
|
||||
# (`gateway/run.py:20777-20780`). Treating it as "turn finished" ended
|
||||
# the turn on the first tool call; every later send then failed with
|
||||
# "no active T3 turn" and the real answer was dropped.
|
||||
#
|
||||
# `notify=True` on `send()` is the signal that actually means "the
|
||||
# user-visible reply is delivered": the gateway applies it via
|
||||
# `_mark_notify_metadata` (`gateway/platforms/base.py:89`) only on
|
||||
# final replies, and the progress path never sets it (verified across
|
||||
# every `adapter.send`/`edit_message` call in the progress loop).
|
||||
del metadata, finalize
|
||||
# `edit_message` never carries the reply anchor; its correlation
|
||||
# identifier is the id of the message being edited. Only an edit of a
|
||||
# message this adapter already reported as captured control traffic is
|
||||
@@ -236,12 +256,8 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
return SendResult(success=False, error="no active T3 turn")
|
||||
try:
|
||||
if content == _T3_HOME_CHANNEL_NOTICE:
|
||||
if finalize:
|
||||
await self._complete_turn(turn)
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
await self._emit_assistant_content(turn, content)
|
||||
if finalize:
|
||||
await self._complete_turn(turn)
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
except Exception as exc: # noqa: BLE001 - adapter edit must return SendResult
|
||||
return SendResult(success=False, error=str(exc))
|
||||
@@ -252,24 +268,22 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
def format_tool_event(
|
||||
self, event: Any, *, mode: str = "all", preview_max_len: int = 40
|
||||
) -> str | None:
|
||||
"""Drop Hermes' textual tool-progress chrome.
|
||||
"""Drop textual tool-progress chrome.
|
||||
|
||||
The base implementation renders each tool call as an emoji progress
|
||||
line ("📚 skill_view: …") and delivers it through the ordinary reply
|
||||
path. Two things go wrong when that reaches T3:
|
||||
T3 already renders tool calls as typed `item.started` / `item.completed`
|
||||
activity from the `pre_tool_call` / `post_tool_call` hooks, so a text
|
||||
line duplicating them is strictly worse than what T3 already shows.
|
||||
|
||||
1. T3 already renders tool calls as typed `item.started` /
|
||||
`item.completed` activity from the `pre_tool_call` / `post_tool_call`
|
||||
hooks, so the text is a duplicate of a richer surface.
|
||||
2. Worse, it is delivered as a *user-visible reply*, and the gateway
|
||||
marks user-visible replies `notify=True`. `send()` treats `notify`
|
||||
as "this turn is finished" and calls `_complete_turn`, so the first
|
||||
tool call ended the T3 turn while Hermes was still working. Every
|
||||
later send failed with "no active T3 turn" and the answer was lost.
|
||||
|
||||
Returning None is the documented way for an adapter that cannot render
|
||||
this chrome to drop the event, and it is what the base class's own
|
||||
docstring prescribes.
|
||||
NOTE: at Hermes 62e07223 this hook is NOT on the live delivery path —
|
||||
`GatewayEventDispatcher` (`gateway/stream_dispatch.py:108`, its only
|
||||
caller) is referenced solely by upstream tests. The path that actually
|
||||
runs is `gateway/run.py:20485+`, which builds the same lines and
|
||||
delivers them through `adapter.send` / `adapter.edit_message` with no
|
||||
adapter hook to suppress them; it is silenced by the platform's
|
||||
`tool_progress` display setting instead. This override is kept because
|
||||
it is the documented contract and costs nothing if upstream routes
|
||||
through the dispatcher again — but it is not what protects the turn.
|
||||
The turn is protected by ignoring `finalize` in `edit_message`.
|
||||
"""
|
||||
del event, mode, preview_max_len
|
||||
return None
|
||||
@@ -913,6 +927,59 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
turn.generic_activity_id = activity_id
|
||||
turn.generic_activity_detail = normalized_detail
|
||||
|
||||
def _turn_for_tool_hook(self, session_id: str) -> _TurnState | None:
|
||||
"""Resolve the active turn a tool hook belongs to.
|
||||
|
||||
The tool hooks' `session_id` is NOT this plugin's session id. Hermes
|
||||
passes `agent.session_id` (`agent/tool_executor.py:188`, `:305`,
|
||||
`:341`), which the gateway sets to `SessionEntry.session_id` — a
|
||||
timestamped run id like `20260725_143012_ab12cd34`
|
||||
(`gateway/session.py:2388`, `agent/agent_init.py:1446-1453`). This
|
||||
plugin's session ids come from `build_session_key`
|
||||
(`gateway/session.py:1029`), shaped `agent:main:t3:dm:<thread>`. The two
|
||||
never match, so `_thread_by_session` alone silently drops every tool
|
||||
activity item.
|
||||
|
||||
The gateway's stable routing key is available separately: it is bound
|
||||
onto `HERMES_SESSION_KEY` for the turn's context
|
||||
(`gateway/run.py:17367` → `gateway/session_context.py:200`) and
|
||||
propagated into the tool worker threads
|
||||
(`agent/tool_executor.py:715`, `propagate_context_to_thread`). That key
|
||||
IS `build_session_key(...)`, so it matches `_thread_by_session`.
|
||||
|
||||
Resolution order, all best-effort:
|
||||
1. `session_id` as a direct routing key (correct if a future Hermes
|
||||
passes the gateway key here, and free to check).
|
||||
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.
|
||||
Anything unresolved returns `None` and the item is simply not emitted;
|
||||
tool activity is decorative, so this must never raise or misroute.
|
||||
"""
|
||||
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 len(self._active_turns) == 1:
|
||||
return next(iter(self._active_turns.values()))
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _gateway_session_key() -> str:
|
||||
"""Read the turn's gateway routing key from Hermes' session context.
|
||||
|
||||
Returns `""` on any failure (older Hermes, no context bound, import
|
||||
error) so callers fall through to their next resolution step.
|
||||
"""
|
||||
try:
|
||||
from gateway.session_context import get_session_env
|
||||
|
||||
return str(get_session_env("HERMES_SESSION_KEY", "") or "")
|
||||
except Exception: # noqa: BLE001 - decorative activity must not raise
|
||||
return ""
|
||||
|
||||
def emit_tool_started(
|
||||
self,
|
||||
session_id: str,
|
||||
@@ -920,8 +987,7 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
args: dict[str, Any],
|
||||
tool_call_id: str = "",
|
||||
) -> None:
|
||||
thread_id = self._thread_by_session.get(str(session_id))
|
||||
turn = self._active_turns.get(thread_id or "")
|
||||
turn = self._turn_for_tool_hook(session_id)
|
||||
if turn is None:
|
||||
return
|
||||
tool_item_id = item_id()
|
||||
@@ -957,8 +1023,7 @@ class T3PlatformAdapter(BasePlatformAdapter):
|
||||
tool_call_id: str = "",
|
||||
status: str = "",
|
||||
) -> None:
|
||||
thread_id = self._thread_by_session.get(str(session_id))
|
||||
turn = self._active_turns.get(thread_id or "")
|
||||
turn = self._turn_for_tool_hook(session_id)
|
||||
if turn is None:
|
||||
return
|
||||
correlation_key = tool_call_id or tool_name
|
||||
|
||||
@@ -263,9 +263,15 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
)
|
||||
self.assertEqual(self.adapter.messages[-1].text, "Hello Hermes")
|
||||
await self.adapter.send("thread-1", "Hello", metadata={"expect_edits": True})
|
||||
# `finalize` must NOT complete the turn — the gateway's progress loop
|
||||
# sets it on every progress edit. Only a `notify=True` send does.
|
||||
await self.adapter.edit_message(
|
||||
"thread-1", "message", "Hello world", finalize=True
|
||||
)
|
||||
self.assertNotIn(
|
||||
"turn.completed", [m["type"] for m in self.connection.messages]
|
||||
)
|
||||
await self.adapter.send("thread-1", "Hello world", metadata={"notify": True})
|
||||
types_seen = [message["type"] for message in self.connection.messages]
|
||||
self.assertIn("content.delta", types_seen)
|
||||
self.assertIn("turn.completed", types_seen)
|
||||
@@ -276,6 +282,136 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
]
|
||||
self.assertEqual(deltas, ["Hello", " world"])
|
||||
|
||||
async def test_tool_progress_bubble_edits_never_complete_the_turn(self):
|
||||
"""Regression: the gateway's progress loop must not end a T3 turn.
|
||||
|
||||
This is the defect this plugin shipped with. Declaring
|
||||
``REQUIRES_EDIT_FINALIZE = True`` makes the gateway's tool-progress
|
||||
loop pass ``finalize=True`` on EVERY progress-bubble edit
|
||||
(``gateway/run.py:20777-20780`` at upstream 62e07223) — it is a
|
||||
presentation hint for rich-card surfaces, not a turn boundary.
|
||||
Treating it as "turn finished" closed the T3 turn on the first tool
|
||||
call; every later send then failed with "no active T3 turn" and the
|
||||
real answer never reached the transcript. The turn ends on exactly one
|
||||
signal: ``notify=True`` metadata on ``send``, which the gateway applies
|
||||
via ``_mark_notify_metadata`` (``gateway/platforms/base.py:89``) only
|
||||
for genuine user-visible replies.
|
||||
"""
|
||||
# Declaring the flag is what arms the gateway's finalize-on-every-edit
|
||||
# branch, so the declaration itself is part of the contract under test.
|
||||
# It is NOT sufficient on its own: the stream consumer also passes
|
||||
# finalize=True on every mid-turn segment break regardless of the flag
|
||||
# (`gateway/stream_consumer.py:938-940`), which is why `edit_message`
|
||||
# must ignore `finalize` outright — see the segment-break leg below.
|
||||
self.assertFalse(self.adapter.REQUIRES_EDIT_FINALIZE)
|
||||
|
||||
await self._start_turn("thread-progress", "turn-progress")
|
||||
turn = self.adapter._active_turns["thread-progress"]
|
||||
progress_start = len(self.connection.messages)
|
||||
|
||||
# Progress metadata is thread/routing metadata only; the progress loop
|
||||
# never marks it notify-worthy (verified: zero _mark_notify_metadata
|
||||
# calls in gateway/run.py:20700-20960).
|
||||
progress_metadata = {"thread_id": "thread-progress"}
|
||||
|
||||
async def edit_progress_message(message_id: str, content: str):
|
||||
"""Mirror of the gateway's `_edit_progress_message` closure."""
|
||||
kwargs = {
|
||||
"chat_id": "thread-progress",
|
||||
"message_id": message_id,
|
||||
"content": content,
|
||||
}
|
||||
if getattr(self.adapter, "REQUIRES_EDIT_FINALIZE", False):
|
||||
kwargs["finalize"] = True
|
||||
kwargs["metadata"] = progress_metadata
|
||||
return await self.adapter.edit_message(**kwargs)
|
||||
|
||||
# First progress bubble is a plain send, never notify-marked.
|
||||
first = await self.adapter.send(
|
||||
"thread-progress",
|
||||
"📚 Reading skill hermes-agent",
|
||||
reply_to=None,
|
||||
metadata=progress_metadata,
|
||||
)
|
||||
self.assertTrue(first.success)
|
||||
self.assertIn("thread-progress", self.adapter._active_turns)
|
||||
|
||||
# Then the loop edits that one bubble once per tool event.
|
||||
progress_lines = ["📚 Reading skill hermes-agent"]
|
||||
for line in (
|
||||
"🔍 Searching the web for hermes gateway",
|
||||
"📖 Reading file gateway/run.py",
|
||||
"🛠️ Running tests",
|
||||
):
|
||||
progress_lines.append(line)
|
||||
result = await edit_progress_message(
|
||||
first.message_id, "\n".join(progress_lines)
|
||||
)
|
||||
self.assertTrue(result.success)
|
||||
# Every single edit must leave the turn running.
|
||||
self.assertIn("thread-progress", self.adapter._active_turns)
|
||||
self.assertIs(self.adapter._active_turns["thread-progress"], turn)
|
||||
|
||||
self.assertNotIn(
|
||||
"turn.completed",
|
||||
[message["type"] for message in self.connection.messages],
|
||||
)
|
||||
|
||||
# Second, flag-independent leg: the stream consumer finalizes the
|
||||
# current content message at every tool/segment boundary
|
||||
# (`gateway/stream_consumer.py:938-940` passes
|
||||
# `finalize=(got_done or got_segment_break)`), and it does so whether
|
||||
# or not the adapter declares REQUIRES_EDIT_FINALIZE. A mid-turn
|
||||
# segment break is not a turn boundary either.
|
||||
for partial in ("Let me check the docs.", "Let me check the docs. Found it."):
|
||||
segment = await self.adapter.edit_message(
|
||||
"thread-progress",
|
||||
first.message_id,
|
||||
partial,
|
||||
finalize=True,
|
||||
metadata=progress_metadata,
|
||||
)
|
||||
self.assertTrue(segment.success)
|
||||
self.assertIn("thread-progress", self.adapter._active_turns)
|
||||
self.assertNotIn(
|
||||
"turn.completed",
|
||||
[message["type"] for message in self.connection.messages],
|
||||
)
|
||||
|
||||
# Now the real answer arrives as the gateway's notify-marked final
|
||||
# send. That — and only that — closes the turn, exactly once.
|
||||
answer = await self.adapter.send(
|
||||
"thread-progress",
|
||||
"\n".join(progress_lines) + "\nHere is the real answer.",
|
||||
metadata={"notify": True},
|
||||
)
|
||||
self.assertTrue(answer.success)
|
||||
self.assertNotIn("thread-progress", self.adapter._active_turns)
|
||||
self.assertEqual(
|
||||
[
|
||||
message["type"]
|
||||
for message in self.connection.messages[progress_start:]
|
||||
if message["type"] == "turn.completed"
|
||||
],
|
||||
["turn.completed"],
|
||||
)
|
||||
|
||||
# A late finalize edit after completion cannot resurrect or re-close
|
||||
# the turn; it fails closed with the "no active turn" result.
|
||||
late = await edit_progress_message(first.message_id, "late progress")
|
||||
self.assertFalse(late.success)
|
||||
self.assertEqual(late.error, "no active T3 turn")
|
||||
self.assertEqual(
|
||||
len(
|
||||
[
|
||||
message
|
||||
for message in self.connection.messages
|
||||
if message["type"] == "turn.completed"
|
||||
]
|
||||
),
|
||||
1,
|
||||
)
|
||||
|
||||
async def test_cumulative_edits_emit_delta_snapshot_delta_then_finalize(self):
|
||||
await self._start_turn("thread-snapshot", "turn-snapshot")
|
||||
content_start = len(self.connection.messages)
|
||||
@@ -296,6 +432,8 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
"Helpful",
|
||||
finalize=True,
|
||||
)
|
||||
# `finalize` is inert; the notify send is what closes the turn.
|
||||
await self.adapter.send("thread-snapshot", "Helpful", metadata={"notify": True})
|
||||
|
||||
content_frames = self.connection.messages[content_start:]
|
||||
self.assertEqual(
|
||||
@@ -334,6 +472,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
"",
|
||||
finalize=True,
|
||||
)
|
||||
await self.adapter.send("thread-empty", "", metadata={"notify": True})
|
||||
|
||||
content_frames = self.connection.messages[content_start:]
|
||||
self.assertEqual(
|
||||
@@ -587,6 +726,11 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
"The actual Hermes response",
|
||||
finalize=True,
|
||||
)
|
||||
await self.adapter.send(
|
||||
"thread-notice",
|
||||
"The actual Hermes response",
|
||||
metadata={"notify": True},
|
||||
)
|
||||
content_frames = self.connection.messages[content_start:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in content_frames],
|
||||
@@ -626,7 +770,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
["turn.completed", "connection.status"],
|
||||
)
|
||||
|
||||
async def test_terminal_edit_suppresses_exact_home_notice_and_completes_turn(self):
|
||||
async def test_edit_of_exact_home_notice_is_suppressed_without_completing(self):
|
||||
await self._start_turn("thread-terminal-notice-edit", "turn-terminal-notice-edit")
|
||||
content_start = len(self.connection.messages)
|
||||
notice = (
|
||||
@@ -644,14 +788,11 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
)
|
||||
|
||||
self.assertTrue(suppressed.success)
|
||||
self.assertNotIn("thread-terminal-notice-edit", self.adapter._active_turns)
|
||||
self.assertEqual(
|
||||
[
|
||||
message["type"]
|
||||
for message in self.connection.messages[content_start:]
|
||||
],
|
||||
["turn.completed", "connection.status"],
|
||||
)
|
||||
# The notice is still swallowed, but an edit — even a `finalize` one —
|
||||
# no longer ends the turn: the progress loop sets `finalize` on every
|
||||
# progress bubble, so acting on it truncated real turns.
|
||||
self.assertIn("thread-terminal-notice-edit", self.adapter._active_turns)
|
||||
self.assertEqual(self.connection.messages[content_start:], [])
|
||||
|
||||
async def test_near_match_home_channel_text_is_not_suppressed(self):
|
||||
await self._start_turn("thread-notice-near-match", "turn-notice-near-match")
|
||||
@@ -668,6 +809,9 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
),
|
||||
finalize=True,
|
||||
)
|
||||
await self.adapter.send(
|
||||
"thread-notice-near-match", "done", metadata={"notify": True}
|
||||
)
|
||||
self.assertEqual(
|
||||
[
|
||||
message["type"]
|
||||
@@ -676,6 +820,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
[
|
||||
"item.started",
|
||||
"content.delta",
|
||||
"content.snapshot",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
"connection.status",
|
||||
@@ -749,6 +894,9 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(steer_messages[0]["requestId"], "steer-2")
|
||||
self.assertIn("thread-2", self.adapter._active_turns)
|
||||
|
||||
# A post-steer edit streams the real answer. `finalize` is inert — the
|
||||
# gateway sets it on every tool-progress edit — so the turn must stay
|
||||
# open until the notify-marked final send arrives.
|
||||
await self.adapter.edit_message(
|
||||
"thread-2",
|
||||
"message",
|
||||
@@ -761,7 +909,25 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
if message["type"] == "content.delta"
|
||||
]
|
||||
self.assertEqual(deltas, ["Actual response after steering"])
|
||||
self.assertIn("thread-2", self.adapter._active_turns)
|
||||
self.assertNotIn(
|
||||
"turn.completed", [m["type"] for m in self.connection.messages]
|
||||
)
|
||||
|
||||
await self.adapter.send(
|
||||
"thread-2",
|
||||
"Actual response after steering",
|
||||
metadata={"notify": True},
|
||||
)
|
||||
self.assertNotIn("thread-2", self.adapter._active_turns)
|
||||
self.assertEqual(
|
||||
[
|
||||
message["type"]
|
||||
for message in self.connection.messages
|
||||
if message["type"] == "turn.completed"
|
||||
],
|
||||
["turn.completed"],
|
||||
)
|
||||
|
||||
async def test_assistant_output_during_a_steer_is_not_captured_as_control(self):
|
||||
session_id = await self._start_turn("thread-steer-race", "turn-steer-race")
|
||||
@@ -886,6 +1052,9 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
}
|
||||
)
|
||||
|
||||
# The core invariant: rejecting a steer reports an error and leaves the
|
||||
# running turn untouched. The rejection must emit exactly the error —
|
||||
# no turn lifecycle frame of any kind.
|
||||
steer_messages = self.connection.messages[messages_before_steer:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in steer_messages], ["protocol.error"]
|
||||
@@ -894,12 +1063,26 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(steer_messages[0]["code"], "invalid-message")
|
||||
self.assertIn("thread-rejected-steer", self.adapter._active_turns)
|
||||
|
||||
# The still-active turn keeps streaming. `finalize` on an edit is inert
|
||||
# (the gateway sets it on every progress bubble), so the turn survives.
|
||||
await self.adapter.edit_message(
|
||||
"thread-rejected-steer",
|
||||
"message",
|
||||
"Actual response after rejected steering",
|
||||
finalize=True,
|
||||
)
|
||||
self.assertEqual(self.connection.messages[-1]["type"], "content.delta")
|
||||
self.assertIn("thread-rejected-steer", self.adapter._active_turns)
|
||||
self.assertNotIn(
|
||||
"turn.completed", [m["type"] for m in self.connection.messages]
|
||||
)
|
||||
|
||||
# Only the notify-marked final send ends it.
|
||||
await self.adapter.send(
|
||||
"thread-rejected-steer",
|
||||
"Actual response after rejected steering",
|
||||
metadata={"notify": True},
|
||||
)
|
||||
self.assertEqual(self.connection.messages[-1]["type"], "connection.status")
|
||||
self.assertNotIn("thread-rejected-steer", self.adapter._active_turns)
|
||||
|
||||
@@ -1179,13 +1362,18 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
)
|
||||
|
||||
def test_tool_progress_chrome_is_dropped(self):
|
||||
"""Tool chrome must never reach T3 as a user-visible reply.
|
||||
"""Tool chrome is redundant with T3's typed activity items.
|
||||
|
||||
The gateway marks user-visible replies `notify=True`, and `send()`
|
||||
treats `notify` as "turn finished". Rendering tool chrome therefore
|
||||
ended the T3 turn on the first tool call, and everything Hermes did
|
||||
afterwards failed with "no active T3 turn". T3 already renders tool
|
||||
calls as typed activity items, so the text is redundant regardless.
|
||||
T3 already renders tool calls as typed `item.started` /
|
||||
`item.completed` activity from the `pre_tool_call` / `post_tool_call`
|
||||
hooks, so a text line duplicating them is strictly worse.
|
||||
|
||||
NOTE: this override is NOT what protects the turn. At Hermes 62e07223
|
||||
it is not even on the live path — its only caller,
|
||||
`GatewayEventDispatcher` (`gateway/stream_dispatch.py:108`), is
|
||||
referenced solely by upstream tests. The turn is protected by ignoring
|
||||
`finalize` in `edit_message`; see
|
||||
`test_tool_progress_bubble_edits_never_complete_the_turn`.
|
||||
"""
|
||||
|
||||
class _ToolCallChunk:
|
||||
@@ -1199,6 +1387,125 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.adapter.format_tool_event(_ToolCallChunk(), mode=mode)
|
||||
)
|
||||
|
||||
async def test_tool_hooks_resolve_the_turn_from_the_gateway_session_key(self):
|
||||
"""Tool hooks carry Hermes' run id, not this plugin's session id.
|
||||
|
||||
`agent.session_id` (`agent/tool_executor.py:188`) is a timestamped run
|
||||
id like `20260725_143012_ab12cd34` (`gateway/session.py:2388`), while
|
||||
this plugin's session ids come from `build_session_key`
|
||||
(`agent:main:t3:dm:<thread>`). Keying `_thread_by_session` on the hook's
|
||||
value alone therefore never matches and silently drops every tool
|
||||
activity item. The gateway's stable routing key is available from
|
||||
`HERMES_SESSION_KEY` (`gateway/run.py:17367`), which IS the
|
||||
build_session_key value.
|
||||
"""
|
||||
self.adapter._event_loop = asyncio.get_running_loop()
|
||||
session_id = await self._start_turn("thread-tools", "turn-tools")
|
||||
frames_before = len(self.connection.messages)
|
||||
|
||||
# What Hermes actually passes: an unrelated run id.
|
||||
hermes_run_id = "20260725_143012_ab12cd34"
|
||||
self.assertNotIn(hermes_run_id, self.adapter._thread_by_session)
|
||||
|
||||
with unittest.mock.patch.object(
|
||||
adapter_module.T3PlatformAdapter,
|
||||
"_gateway_session_key",
|
||||
staticmethod(lambda: session_id),
|
||||
):
|
||||
self.adapter.emit_tool_started(
|
||||
hermes_run_id, "web_search", {"query": "hermes"}, "call-1"
|
||||
)
|
||||
self.adapter.emit_tool_completed(
|
||||
hermes_run_id, "web_search", "result", 42, "call-1"
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
tool_frames = self.connection.messages[frames_before:]
|
||||
self.assertEqual(
|
||||
[message["type"] for message in tool_frames],
|
||||
["item.started", "item.completed"],
|
||||
)
|
||||
# Both halves must correlate onto ONE activity item, or T3 renders a
|
||||
# started row that never resolves plus an orphan completion.
|
||||
self.assertEqual(tool_frames[0]["itemId"], tool_frames[1]["itemId"])
|
||||
self.assertEqual(tool_frames[0]["title"], "web_search")
|
||||
self.assertEqual(tool_frames[1]["status"], "completed")
|
||||
self.assertEqual(tool_frames[0]["threadId"], "thread-tools")
|
||||
self.assertEqual(tool_frames[0]["sessionId"], session_id)
|
||||
|
||||
async def test_tool_hooks_fall_back_to_the_sole_active_turn(self):
|
||||
"""With exactly one active turn there is no ambiguity to resolve."""
|
||||
self.adapter._event_loop = asyncio.get_running_loop()
|
||||
await self._start_turn("thread-only", "turn-only")
|
||||
frames_before = len(self.connection.messages)
|
||||
|
||||
with unittest.mock.patch.object(
|
||||
adapter_module.T3PlatformAdapter,
|
||||
"_gateway_session_key",
|
||||
staticmethod(lambda: ""),
|
||||
):
|
||||
self.adapter.emit_tool_started(
|
||||
"20260725_143012_ab12cd34", "read_file", {"path": "a.py"}, "call-2"
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
tool_frames = self.connection.messages[frames_before:]
|
||||
self.assertEqual([m["type"] for m in tool_frames], ["item.started"])
|
||||
self.assertEqual(tool_frames[0]["threadId"], "thread-only")
|
||||
|
||||
async def test_tool_hooks_drop_when_the_turn_is_ambiguous(self):
|
||||
"""Two concurrent turns and no routing key: emit nothing.
|
||||
|
||||
Guessing would attach one thread's tool activity to another's
|
||||
transcript. Tool activity is decorative, so dropping is correct.
|
||||
"""
|
||||
self.adapter._event_loop = asyncio.get_running_loop()
|
||||
await self._start_turn("thread-a", "turn-a")
|
||||
await self._start_turn("thread-b", "turn-b")
|
||||
frames_before = len(self.connection.messages)
|
||||
|
||||
with unittest.mock.patch.object(
|
||||
adapter_module.T3PlatformAdapter,
|
||||
"_gateway_session_key",
|
||||
staticmethod(lambda: ""),
|
||||
):
|
||||
self.adapter.emit_tool_started(
|
||||
"20260725_143012_ab12cd34", "read_file", {"path": "a.py"}, "call-3"
|
||||
)
|
||||
self.adapter.emit_tool_completed(
|
||||
"20260725_143012_ab12cd34", "read_file", "ok", 5, "call-3"
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
self.assertEqual(self.connection.messages[frames_before:], [])
|
||||
|
||||
async def test_tool_hook_session_key_lookup_never_raises(self):
|
||||
"""An unavailable Hermes session context must degrade, not raise."""
|
||||
self.adapter._event_loop = asyncio.get_running_loop()
|
||||
await self._start_turn("thread-ctx-a", "turn-ctx-a")
|
||||
await self._start_turn("thread-ctx-b", "turn-ctx-b")
|
||||
frames_before = len(self.connection.messages)
|
||||
|
||||
def _boom():
|
||||
raise RuntimeError("no session context bound")
|
||||
|
||||
with unittest.mock.patch.object(
|
||||
adapter_module.T3PlatformAdapter,
|
||||
"_gateway_session_key",
|
||||
staticmethod(_boom),
|
||||
):
|
||||
with self.assertRaises(RuntimeError):
|
||||
adapter_module.T3PlatformAdapter._gateway_session_key()
|
||||
|
||||
# The real accessor swallows its own failures rather than propagating.
|
||||
with unittest.mock.patch.dict(sys.modules, {"gateway.session_context": None}):
|
||||
self.assertEqual(self.adapter._gateway_session_key(), "")
|
||||
self.adapter.emit_tool_started(
|
||||
"20260725_143012_ab12cd34", "read_file", {"path": "a.py"}, "call-4"
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
self.assertEqual(self.connection.messages[frames_before:], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user