Skip to content

The agent that grows with you

fix: show transform_llm_output rewrites in the TUI and desktop app

Tekniumf973257cab30
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index f5f125c8999..eda70cbb2fa 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -78,6 +78,10 @@ def completion_payload(row, settled, response, captured):
complete['response_previewed'] = True
if captured_result.get('response_transformed'):
complete['response_transformed'] = True
+ # The stream carried the raw reply and the turn counts as delivered (``response`` is
+ # None): this frame is the only carrier of the rewrite the session stored.
+ if not response and (final := captured_result.get('final_response')):
+ complete['text'] = complete['content'] = final
if isinstance(captured_result.get('warning'), str) and captured_result['warning']:
complete['warning'] = captured_result['warning']
if isinstance(captured_result.get('billing_block'), dict):
diff --git a/tests/gateway/test_local_viewer_transformed_final.py b/tests/gateway/test_local_viewer_transformed_final.py
new file mode 100644
index 00000000000..1823bf178c8
--- /dev/null
+++ b/tests/gateway/test_local_viewer_transformed_final.py
@@ -0,0 +1,65 @@
+"""A ``transform_llm_output`` rewrite reaches a local viewer (Ink TUI, Desktop) on ``message.complete``.
+
+The viewer painted the raw reply from ``message.delta`` frames; the transform ran after the stream.
+A streamed local turn is delivered by the event stream itself, so ``_handle_message`` answers
+``None`` and the completion frame was the only carrier left, with ``text: null``: the raw reply
+stayed on screen while the session stored (and replays) the rewrite.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+from gateway.run_turn_runner import TurnRunner
+from gateway.session import SessionSource
+from gateway.session_results import execution_result
+from gateway.session_settlement_recovery import completion_payload
+from gateway.turn_context import TurnContext
+from tests.gateway.test_local_viewer_events_submit import _gateway_runner, _RecordingAgent
+
+RAW = "Your api key is SECRET-123."
+REWRITE = "Your api key is [REDACTED]."
+
+
+class _StreamedAgent(_RecordingAgent):
+ transformed = True
+
+ def run_conversation(self, message, **kwargs):
+ if self.transformed:
+ return {"final_response": REWRITE, "messages": [], "response_transformed": True,
+ "pre_transform_response": RAW}
+ return {"final_response": RAW, "messages": []}
+
+
+def _settle(platform, transformed):
+ _StreamedAgent.transformed = transformed
+ ctx = TurnContext(
+ source=SessionSource(platform=platform, chat_id="sid", user_id="u"),
+ message="show me the config", history=[], session_id="sid", session_key="key", user_config={},
+ AIAgent=_StreamedAgent, resolve_display_setting=lambda *_a: False,
+ _run_still_current=lambda: True, _hooks_ref=SimpleNamespace(loaded_hooks=False))
+ captured = {}
+ token = execution_result.set(captured)
+ try:
+ turn = TurnRunner(_gateway_runner(), ctx)
+ turn._approval_owner = (SimpleNamespace(sessions={"sid": SimpleNamespace(tool_progress_mode=None)},
+ profile_id="p", adopt_agent=lambda *a: None), "sid", 1)
+ turn.run_sync()
+ finally:
+ execution_result.reset(token)
+ # The streamed turn was delivered by the event stream: the handler's reply is None.
+ return completion_payload({"admission_id": "a1", "request_id": "r1"}, {"outcome": "completed"}, None, captured)
+
+
+def test_a_streamed_local_turn_completes_with_the_transformed_final():
+ from tui_gateway.contracts.registry import EVENTS
+ complete = _settle(Platform.LOCAL, transformed=True)
+ assert complete["text"] == REWRITE and complete["response_transformed"] is True
+ EVENTS["message.complete"].payload.model_validate(
+ {k: v for k, v in complete.items() if k not in ("content", "admission_id", "outcome")})
+
+
[email protected]("platform, transformed", [(Platform.LOCAL, False), (Platform.TELEGRAM, True)])
+def test_the_stream_stays_the_delivery_without_a_local_rewrite(platform, transformed):
+ # An unrewritten streamed reply is already on screen; a messaging turn's chat holds its own copy.
+ assert _settle(platform, transformed)["text"] is None
diff --git a/ui-tui/src/__tests__/transformedFinal.test.ts b/ui-tui/src/__tests__/transformedFinal.test.ts
new file mode 100644
index 00000000000..dca17611c8b
--- /dev/null
+++ b/ui-tui/src/__tests__/transformedFinal.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'
+import { resetOverlayState } from '../app/overlayStore.js'
+import { turnController } from '../app/turnController.js'
+import { resetTurnState } from '../app/turnStore.js'
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import type { Msg } from '../types.js'
+
+// A transform_llm_output plugin rewrites the final after the raw reply streamed: the completion
+// carries the rewrite (response_transformed) and the transcript must show only that.
+const RAW = 'Your api key is SECRET-123 and the backup is SECRET-456.'
+const REWRITE = 'Your api key is [REDACTED] and the backup is [REDACTED].'
+
+const ref = <T>(current: T) => ({ current })
+
+const buildCtx = (appended: Msg[]) =>
+ ({
+ composer: { dequeue: () => undefined, queueEditRef: ref<null | number>(null), sendQueued: vi.fn(), setInput: vi.fn() },
+ gateway: { gw: { request: vi.fn(async () => null) }, rpc: vi.fn(async () => null) },
+ session: {
+ STARTUP_RESUME_ID: '',
+ colsRef: ref(80),
+ newSession: vi.fn(),
+ resetSession: vi.fn(),
+ resumeById: vi.fn(),
+ setCatalog: vi.fn()
+ },
+ submission: { submitRef: { current: vi.fn() } },
+ system: { bellOnComplete: false, sys: vi.fn() },
+ transcript: { appendMessage: (msg: Msg) => appended.push(msg), panel: vi.fn(), setHistoryItems: vi.fn() },
+ voice: { setProcessing: vi.fn(), setRecording: vi.fn(), setVoiceEnabled: vi.fn() }
+ }) as any
+
+const streamThenComplete = (complete: Record<string, unknown>) => {
+ const appended: Msg[] = []
+ const onEvent = createGatewayEventHandler(buildCtx(appended))
+
+ onEvent({ payload: {}, type: 'message.start' } as any)
+
+ for (const word of RAW.split(' ')) {
+ onEvent({ payload: { text: `${word} ` }, type: 'message.delta' } as any)
+ }
+
+ onEvent({ payload: complete, type: 'message.complete' } as any)
+
+ return appended.filter(m => m.role === 'assistant' && m.text).map(m => m.text)
+}
+
+describe('transformed final settlement', () => {
+ beforeEach(() => {
+ resetOverlayState()
+ resetUiState()
+ resetTurnState()
+ turnController.fullReset()
+ patchUiState({ showReasoning: true })
+ })
+
+ it('replaces the streamed raw reply with the rewrite', () => {
+ expect(streamThenComplete({ response_transformed: true, status: 'complete', text: REWRITE })).toEqual([REWRITE])
+ })
+
+ it('keeps a streamed tail the final does not carry when nothing was rewritten', () => {
+ expect(streamThenComplete({ status: 'complete', text: 'A different closing line.' })).toEqual([
+ `${RAW} `,
+ 'A different closing line.'
+ ])
+ })
+})
diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.ts
index 99cc437ecb5..2ffef5ff13d 100644
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@ -125,6 +125,13 @@ const finalTail = (finalText: string, segments: Msg[]) => {
return tail
}
+// Whether the streamed tail is a segment of its own: only when the gateway's final text does not
+// already carry it — otherwise the tail IS the answer and flushing would move the tool shelf/trail
+// under it. Never without a final text (`rawText` is then the buffer, #16391), nor when a
+// transform_llm_output plugin rewrote the reply: the tail is the raw text the rewrite replaces.
+const keepsStreamedTail = (tail: string, completionText: null | string | undefined, transformed?: boolean | null) =>
+ Boolean(tail && completionText != null && !transformed && !completionText.includes(tail))
+
const interruptedText = (partial: string) => (partial ? `${partial}\n\n*[interrupted]*` : '*[interrupted]*')
// What interruptTurn sealed into the transcript: `text` is the bubble it
@@ -683,13 +690,8 @@ class TurnController {
const rawText = (completionText ?? this.bufRef).trimStart()
// Text still in `this.bufRef` streamed after the last segment flush; `idle()`
- // below would wipe it (#61520). Flush it as a segment only when the
- // gateway's final text does not already carry it — otherwise the tail IS
- // the answer and flushing would move the tool shelf/trail under it. Skipped
- // when `completionText` is absent: `rawText` is then the buffer (#16391).
- const tail = this.bufRef.trim()
-
- if (tail && completionText != null && !completionText.includes(tail)) {
+ // below would wipe it (#61520).
+ if (keepsStreamedTail(this.bufRef.trim(), completionText, payload.response_transformed)) {
this.flushStreamingSegment()
}
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index 71209c03370..becb4b3807c 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -1776,7 +1776,10 @@ def my_callback(
When CLI streaming is enabled, an append-only transform is printed after the
streamed body. A transform that replaces the response is printed in full after
the streamed body, labeled as a post-stream transformation, so replacement
-content is never silently lost.
+content is never silently lost. In the TUI, the desktop app and messaging chats
+that edit a streamed message in place, the streamed reply is replaced by the
+rewrite when the turn completes. The hook runs on the finished text, so the
+unrewritten reply is visible while it streams.
```python
import os, re