Skip to content

fix(codex): emit app-server final chat events - #71293

Merged
steipete merged 2 commits into
mainfrom
fix/chat-resync-final-after-agent-run
Apr 25, 2026
Merged

steipete merged 2 commits into
mainfrom
fix/chat-resync-final-after-agent-run

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Summary

Replaces #70815 with the root fix instead of a message-less chat.final fallback.

Codex app-server runs now emit the same terminal agent-event shape the gateway chat stream already understands:

  • lifecycle start after the Codex turn is accepted
  • final assistant text after transcript mirroring
  • lifecycle end or error exactly once
  • global agent-event bus emission for Codex app-server projected item/tool/plan events

This lets Control UI/WebChat receive the normal final signal and leave the spinner without relying on a transcript reload fallback.

Closes #71183.

Validation

  • pnpm test extensions/codex/src/app-server/run-attempt.test.ts
  • pnpm test extensions/codex/src/app-server/event-projector.test.ts
  • pnpm test src/gateway/server-methods/chat.directive-tags.test.ts
  • pnpm exec oxfmt --check --threads=1 CHANGELOG.md extensions/codex/src/app-server/event-projector.test.ts extensions/codex/src/app-server/event-projector.ts extensions/codex/src/app-server/run-attempt.test.ts extensions/codex/src/app-server/run-attempt.ts src/gateway/server-methods/chat.directive-tags.test.ts src/gateway/server-methods/chat.ts src/plugin-sdk/agent-harness-runtime.ts
  • pnpm check:changed passes typecheck/lint/changed tests; fails only in unrelated Slack shard extensions/slack/src/monitor.tool-result.test.ts with existing app.use is not a function / Slack message handler not registered failures.
  • reran pnpm test extensions/slack/src/monitor.tool-result.test.ts; same unrelated Slack failure.

Co-authored-by: Lēsa [email protected]

@aisle-research-bot

aisle-research-bot Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 4 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Global agent event emission may broadcast Codex run events without session scoping (cross-session information disclosure)
2 🟠 High Untrusted plugins can spoof/broadcast agent events via exported emitAgentEvent
3 🟡 Medium Unsanitized terminal assistant text emitted to clients bypassing transcript hooks
4 🟡 Medium Potential sensitive information disclosure via logging raw Error objects in debug logs
1. 🟠 Global agent event emission may broadcast Codex run events without session scoping (cross-session information disclosure)
Property Value
Severity High
CWE CWE-200
Location extensions/codex/src/app-server/run-attempt.ts:89-101

Description

runCodexAppServerAttempt now forwards all per-run onAgentEvent data into the process-wide emitAgentEvent bus. When params.sessionKey is missing, the emitted event has no sessionKey, and the gateway’s global agent-event subscription (createAgentEventHandler) will still broadcast("agent", …) the payload to all connected clients.

Key points:

  • Source: Codex app-server emits global events for each agent event, but only attaches sessionKey when params.sessionKey is truthy.
  • Sink: src/infra/agent-events.ts notifies all registered listeners; the gateway listener (createAgentEventHandler) broadcasts events to all websocket clients even when sessionKey is undefined.
  • Impact: If a Codex run is started without a sessionKey (or if session-key resolution fails), assistant/tool/lifecycle payloads can be delivered to unrelated UI clients, leaking potentially sensitive content across sessions.

Vulnerable code (emits global event with optional sessionKey):

emitGlobalAgentEvent({
  runId: params.runId,
  stream: event.stream,
  data: event.data,
  ...(params.sessionKey ? { sessionKey: params.sessionKey } : {}),
});

Recommendation

Ensure global agent events are always scoped to an authorized session (or never broadcast to the gateway when scoping is unknown).

Recommended fixes (pick one, depending on desired behavior):

  1. Require sessionKey for global emission (drop/skip otherwise):
if (params.sessionKey) {
  emitGlobalAgentEvent({
    runId: params.runId,
    sessionKey: params.sessionKey,
    stream: event.stream,
    data: event.data,
  });
}
  1. Register run context before emitting so emitAgentEvent can reliably infer sessionKey:
registerAgentRunContext(params.runId, { sessionKey: params.sessionKey });
emitGlobalAgentEvent({ runId: params.runId, stream: event.stream, data: event.data });
  1. Harden the gateway handler to avoid broadcasting unscoped events:
  • If sessionKey cannot be resolved, do not broadcast to all clients; only deliver to explicitly run-scoped recipients.

Any approach should guarantee that events cannot be delivered cross-session when sessionKey is absent or ambiguous.

2. 🟠 Untrusted plugins can spoof/broadcast agent events via exported emitAgentEvent
Property Value
Severity High
CWE CWE-285
Location src/infra/agent-events.ts:201-220

Description

emitAgentEvent is exported through the plugin SDK, allowing plugin code to emit arbitrary agent events into the global agent-event bus.

Because emitAgentEvent accepts a caller-supplied runId, stream, data, and optional sessionKey, a plugin can:

  • Spoof assistant or lifecycle events (e.g., fake completion/errors, inject arbitrary assistant text)
  • Inject events into other sessions by setting sessionKey to a target session (or by guessing/observing a runId) because emitAgentEvent does not verify that the caller is authorized for that runId/sessionKey
  • Cause downstream components (e.g., gateway/websocket broadcasting) to treat those events as authoritative

Vulnerable code paths:

  • Plugin surface exports emitAgentEvent directly
  • emitAgentEvent enriches and forwards events to all listeners without any authentication/authorization or run/session ownership validation

Vulnerable code:

export { emitAgentEvent } from "../infra/agent-events.js";

export function emitAgentEvent(event: Omit<AgentEventPayload, "seq" | "ts">) {
  ​// ...
  notifyListeners(state.listeners, enriched);
}

Recommendation

Do not expose low-level global event emitters to plugins, or enforce strict authorization at the emission boundary.

Recommended fixes (choose one):

  1. Remove from plugin SDK and expose a narrower, capability-scoped API instead (e.g., emitAgentEventForCurrentRun(...)), where the runtime injects the runId and sessionKey and the plugin cannot override them.

  2. Validate run/session ownership inside emitAgentEvent by requiring a non-forgeable capability token or emitter handle created when the run context is registered.

Example (capability-based handle):

​// when starting a run
const emitter = createAgentEventEmitter({ runId, sessionKey });

​// plugin only receives emitter, not global emitAgentEvent
emitter.emit({ stream: "assistant", data: { text: "..." } });

​// implementation
export function createAgentEventEmitter(bound: { runId: string; sessionKey?: string }) {
  return {
    emit(evt: { stream: AgentEventStream; data: Record<string, unknown> }) {
      emitAgentEvent({ runId: bound.runId, sessionKey: bound.sessionKey, ...evt });
    },
  };
}

Additionally, consider rejecting caller-supplied sessionKey entirely in the low-level emitter and always deriving it from the registered run context to prevent cross-session injection.

3. 🟡 Unsanitized terminal assistant text emitted to clients bypassing transcript hooks
Property Value
Severity Medium
CWE CWE-201
Location extensions/codex/src/app-server/run-attempt.ts:670-675

Description

runCodexAppServerAttempt now emits a terminal stream: "assistant" event containing result.assistantTexts joined into a single string.

This introduces a sensitive-data/content exposure risk because:

  • result.assistantTexts is raw assistant output collected by the projector.
  • Transcript persistence goes through mirrorCodexAppServerTranscript() which applies runAgentHarnessBeforeMessageWriteHook(...) (plugin hooks can block or rewrite messages before they are saved).
  • The new event emission happens before/outside that hook-based sanitization pipeline, so any content that a before_message_write hook would redact (e.g., secrets, directive tags, internal markers) can still be broadcast to event consumers/clients.

Vulnerable code:

const terminalAssistantText = collectTerminalAssistantText(result);
if (terminalAssistantText && !finalAborted && !finalPromptError) {
  emitCodexAppServerEvent(params, {
    stream: "assistant",
    data: { text: terminalAssistantText },
  });
}

Impact depends on deployments/plugins, but in systems relying on before_message_write for redaction this can leak sensitive text to UIs/log streams even if it would not be persisted.

Recommendation

Apply the same sanitization/redaction policy to emitted terminal assistant text that you apply before persistence.

Options:

  1. Run the same before_message_write hook on an assistant message before emitting:
import { runAgentHarnessBeforeMessageWriteHook } from "openclaw/plugin-sdk/agent-harness-runtime";

const terminalAssistantText = collectTerminalAssistantText(result);
if (terminalAssistantText && !finalAborted && !finalPromptError) {
  const sanitized = runAgentHarnessBeforeMessageWriteHook({
    message: { role: "assistant", content: terminalAssistantText, timestamp: Date.now() },
    agentId: sessionAgentId,
    sessionKey: sandboxSessionKey,
  });
  if (sanitized && typeof sanitized.content === "string" && sanitized.content.trim()) {
    emitCodexAppServerEvent(params, { stream: "assistant", data: { text: sanitized.content } });
  }
}
  1. Alternatively, remove this terminal emission and require clients to rely on the already-sanitized transcript update stream.

Also consider clearly separating UI-safe text from internal/debug streams to prevent accidental client display.

4. 🟡 Potential sensitive information disclosure via logging raw Error objects in debug logs
Property Value
Severity Medium
CWE CWE-532
Location extensions/codex/src/app-server/event-projector.ts:725-746

Description

embeddedAgentLog.debug(..., { error }) logs the full thrown/rejected error object coming from downstream event handlers / global event emit.

Because createSubsystemLogger() forwards meta directly into the underlying tslog file/console transports without redaction, the serialized error can include:

  • error messages containing user content, prompts, tool output, API responses
  • stack traces with internal file paths and environment details
  • nested properties attached to custom errors (may include tokens/credentials)

Affected code paths were introduced/expanded in this change:

  • emitGlobalAgentEvent(...) failure handler
  • params.onAgentEvent rejection/throw handlers

Vulnerable code (examples):

embeddedAgentLog.debug("codex app-server agent event handler rejected", { error });
embeddedAgentLog.debug("codex app-server agent event handler threw", { error });

Recommendation

Avoid logging raw error objects from untrusted/extension callbacks. Log a sanitized string instead (and optionally a truncated stack) with redaction.

Example fix:

import { formatErrorMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
import { redactSensitiveText } from "../../../src/logging/redact"; // or expose a helper

} catch (err) {
  const msg = redactSensitiveText(formatErrorMessage(err));
  embeddedAgentLog.debug("codex app-server agent event handler threw", { error: msg });
}

Additionally, consider updating the logger transport to redact sensitive strings in structured metadata (including error.stack / error.message) before writing file logs.


Analyzed PR: #71293 at commit d17d2a9

Last updated on: 2026-04-25T00:12:02Z

@cursor

cursor Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

PR Summary

Medium Risk
Touches Codex app-server run lifecycle/event emission that drives Control UI/WebChat completion, so ordering/duplication mistakes could cause stuck spinners or noisy event streams; changes are scoped and covered by updated tests.

Overview
Codex app-server runs now emit a gateway-compatible terminal agent-event sequence: lifecycle start once the turn is accepted, a final assistant text event after transcript mirroring, and exactly-one lifecycle end/error terminal event.

Projected Codex app-server item/plan/compaction/etc events are also forwarded onto the global agent-event bus (with guarded error handling so consumer failures don’t break projection), and tests were updated to reset/verify global event state and ensure the gateway no longer relies on a message-less chat.final broadcast fallback.

Reviewed by Cursor Bugbot for commit 9e39e28. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes Codex app-server runs so they emit the same native agent-event lifecycle/assistant events the gateway chat stream already understands, letting the Control UI/WebChat spinner resolve without needing a transcript-reload fallback. The implementation is well-structured: emitLifecycleStart is called once after the projector is created, emitLifecycleTerminal is called after await completion with the correct phase (end/error), and a safety-net emitLifecycleTerminal in the finally block covers any unexpected exception path. Test coverage verifies event ordering and global bus emission shape.

Confidence Score: 5/5

Safe to merge — no P0/P1 issues; logic is correct and test coverage is thorough.

All findings are P2 or lower. The emitLifecycleTerminal/lifecycleStarted guard logic is correct, the dual-try-catch pattern in both run-attempt.ts and event-projector.ts is defensive, and the finally safety net properly uses the idempotency guard to avoid double-emission.

No files require special attention.

Reviews (1): Last reviewed commit: "fix(codex): emit app-server final chat e..." | Re-trigger Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 07e138312a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +94 to +98
emitGlobalAgentEvent({
runId: params.runId,
stream: event.stream,
data: event.data,
...(params.sessionKey ? { sessionKey: params.sessionKey } : {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop double-emitting codex_app_server events

emitCodexAppServerEvent now publishes every event to the global bus, but the upstream onAgentEvent callbacks in src/auto-reply/reply/agent-runner-execution.ts:1142, src/auto-reply/reply/followup-runner.ts:338, and src/agents/agent-command.ts:921 still re-emit codex_app_server.* events. For Codex runs, each codex_app_server lifecycle/tool/item/hook event is therefore broadcast twice (with different seq values), which can duplicate operator/UI updates and inflate event-driven counters.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the fix/chat-resync-final-after-agent-run branch from 07e1383 to b31beb5 Compare April 24, 2026 23:57

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b31beb5f4e145faecf292423d52317ab2083ea9d. Configure here.

@steipete
steipete force-pushed the fix/chat-resync-final-after-agent-run branch from b31beb5 to a34b935 Compare April 25, 2026 00:01
@openclaw-barnacle openclaw-barnacle Bot added the channel: slack Channel integration: slack label Apr 25, 2026
lesaai and others added 2 commits April 25, 2026 01:05
…ut terminal lifecycle

Some harnesses (e.g. native Codex app-server path for codex/gpt-5.x) record the final assistant answer and update the transcript, but do not emit a terminal assistant event + lifecycle:end onto the gateway chat event bus. chat.send then waits forever for a finalization path that never arrives, leaving the TUI spinning on 'hobnobbing...' until the user exits and reopens (at which point the already-stored answer is visible).

This adds a conservative fallback in chat.send: after the user transcript update for an agent run, emit a message-less chat.final broadcast as a UI resync point. The transcript already contains the assistant message; the client reloads history and goes idle instead of spinning.

Regression coverage: chat.directive-tags.test.ts now asserts the message-less final event fires on the agent-run path.

Authored primarily by OpenAI Codex CLI (gpt-5.5) during a live debugging session with Parker. Verified end-to-end: Lēsa now streams cleanly on codex/gpt-5.5 in the TUI.

Co-Authored-By: Parker Todd Brooks <[email protected]>

Co-Authored-By: Lēsa <[email protected]>

Co-Authored-By: OpenAI Codex CLI (GPT-5.5) <[email protected]>

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@steipete
steipete force-pushed the fix/chat-resync-final-after-agent-run branch from d17d2a9 to 9e39e28 Compare April 25, 2026 00:06
@openclaw-barnacle openclaw-barnacle Bot removed the channel: slack Channel integration: slack label Apr 25, 2026
@steipete
steipete merged commit db95846 into main Apr 25, 2026
67 checks passed
@steipete
steipete deleted the fix/chat-resync-final-after-agent-run branch April 25, 2026 00:09
@steipete

Copy link
Copy Markdown
Contributor Author

Landed via squash merge onto main.

  • Source head: 9e39e28
  • Merge commit: db95846
  • Gate: GitHub CI + parity gate passed on head; local focused regression tests passed before final rebase, and final CI covered the rebased SHA. Cursor Bugbot remained pending only.

Thanks @lesaai!

Angfr95 pushed a commit to Angfr95/openclaw that referenced this pull request Apr 25, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
Fix live webchat finalization for Codex app-server runs by emitting standard assistant and lifecycle completion events on the global agent event bus, instead of relying on a message-less chat.final fallback.

Replaces openclaw#70815. Closes openclaw#71183.

Co-authored-by: Lēsa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex gateway Gateway runtime maintainer Maintainer-authored PR size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Control UI does not render final assistant event for Codex-provider runs (page refresh required to see reply) — separate from #67422

2 participants