Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(chat): show output-token truncation warnings

Seraph-x84de669cf7d7
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
index 27fb46792..9703b0403 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
@@ -1,4 +1,5 @@
import { memo } from "react";
+import { useTranslation } from "react-i18next";
import type { AgentActivity, UiMessage } from "@pi-desktop/shared";
import type { AssistantTurnPart } from "../../../lib/assistant-turns";
import type { SubagentOutcome, SubagentTiming } from "../../../lib/subagent-topology";
@@ -18,6 +19,7 @@ const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streami
message: UiMessage;
streaming: boolean;
}) {
+ const { t } = useTranslation();
const smoothStreaming = useAppStore((s) => s.settings?.smoothStreaming !== false);
// Opt-in feature: an absent setting keeps cards out of the transcript.
const inlineVisualizations = useAppStore((s) => s.settings?.inlineVisualizations === true);
@@ -39,6 +41,9 @@ const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streami
>
{genUi.content ? <TranscriptProse source={genUi.content} streaming={streaming} /> : null}
<GenUiCards references={genUi.references} sessionId={sessionId} remote={remote} />
+ {message.outputTruncated ? (
+ <p className="message-output-notice" role="status">{t("chat.outputTruncated")}</p>
+ ) : null}
{message.error ? <AssistantErrorMessage message={message} /> : null}
</div>
);
diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.css
index 87dd4442d..fd211b865 100644
--- a/apps/desktop/src/styles/messages.css
+++ b/apps/desktop/src/styles/messages.css
@@ -2125,6 +2125,13 @@
`--ds-tile` card belongs only to `.tool-activity-group.has-subagents`
(D319) and the nested `.subagent-run`. */
+.message-output-notice {
+ margin: 12px 0 0;
+ color: var(--ds-warning);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+}
+
.message-error {
/* The message column owns the dynamic chat width; do not add a second cap. */
width: 100%;
diff --git a/apps/desktop/test/empty-assistant-persistence.test.mjs b/apps/desktop/test/empty-assistant-persistence.test.mjs
index b1671e71c..f147e29ce 100644
--- a/apps/desktop/test/empty-assistant-persistence.test.mjs
+++ b/apps/desktop/test/empty-assistant-persistence.test.mjs
@@ -156,6 +156,14 @@ test("an empty assistant message with an error payload stays durable", () => {
assert.equal(f.enqueued.length, 1);
});
+test("an output-limited answer keeps its text and truncation metadata in the outbox", () => {
+ const f = fixture();
+ f.persistAssistant({ id: "truncated", content: "Partial answer", status: "complete", outputTruncated: true });
+ assert.equal(f.enqueued.length, 1);
+ assert.equal(f.enqueued[0].message.content, "Partial answer");
+ assert.equal(f.enqueued[0].message.outputTruncated, true);
+});
+
test("an empty assistant message reserved for steering is persisted", () => {
const f = fixture();
f.steeringReplies.add("m5");
diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rs
index 833b1e845..854dc433a 100644
--- a/crates/host-core/src/plugin_sessions.rs
+++ b/crates/host-core/src/plugin_sessions.rs
@@ -276,6 +276,7 @@ fn parse_message(
};
Ok(UiMessage {
+ output_truncated: None,
id: Uuid::new_v4().to_string(),
role: role.to_string(),
content: input.content.clone(),
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 174391ab5..aea494626 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -241,6 +241,9 @@ pub struct UiMessage {
pub thinking: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
+ /// Additive transcript metadata; older records have no truncation marker.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub output_truncated: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -456,6 +459,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<String
if let Some(status) = &message.status {
meta_obj.insert("status".into(), json!(status));
}
+ if let Some(truncated) = message.output_truncated {
+ meta_obj.insert("outputTruncated".into(), json!(truncated));
+ }
if let Some(model_id) = &message.model_id {
meta_obj.insert("modelId".into(), json!(model_id));
}
@@ -658,6 +664,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
let error = meta.get("error").cloned();
let response_duration_ms = meta.get("responseDurationMs").and_then(|v| v.as_i64());
let response_output_tokens = meta.get("responseOutputTokens").and_then(|v| v.as_i64());
+ let output_truncated = meta.get("outputTruncated").and_then(Value::as_bool);
let response_model_id = meta
.get("responseModelId")
.and_then(|v| v.as_str())
@@ -749,6 +756,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
session_message,
voice_origin: voice_origin.clone(),
attachments: None,
+ output_truncated,
steering,
created_at: record.created_at,
thinking,
@@ -806,6 +814,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
session_message,
voice_origin,
attachments,
+ output_truncated,
steering,
created_at: record.created_at,
thinking,
@@ -4533,6 +4542,7 @@ mod tests {
fn user_msg(id: &str, content: &str, ts: &str) -> UiMessage {
UiMessage {
+ output_truncated: None,
id: id.into(),
role: "user".into(),
content: content.into(),
@@ -5499,6 +5509,7 @@ mod tests {
)
.unwrap();
let tool = UiMessage {
+ output_truncated: None,
id: "m2".into(),
role: "tool".into(),
content: "ok".into(),
@@ -6291,11 +6302,50 @@ mod tests {
}
}
+ #[test]
+ fn output_truncation_survives_host_restart_and_legacy_rows() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ let session_id = {
+ let db = Database::open(&path).unwrap();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ for (id, truncated) in [
+ ("truncated", Some(true)),
+ ("legacy", None),
+ ("normal", Some(false)),
+ ] {
+ let mut wire = json!({
+ "id": id, "role": "assistant", "content": "Original answer",
+ "status": "complete", "createdAt": "2026-11-12T00:00:00Z"
+ });
+ if let Some(value) = truncated {
+ wire["outputTruncated"] = json!(value);
+ }
+ let message: UiMessage = serde_json::from_value(wire).unwrap();
+ append_message(&db, &session.id, &message, None).unwrap();
+ }
+ session.id
+ };
+ let db = Database::open(&path).unwrap();
+ let detail = get_session(&db, &session_id).unwrap().unwrap();
+ assert_eq!(detail.messages.len(), 3);
+ let messages = serde_json::to_value(&detail.messages).unwrap();
+ assert_eq!(messages[0]["outputTruncated"], json!(true));
+ assert!(messages[1].get("outputTruncated").is_none());
+ assert_eq!(messages[2]["outputTruncated"], json!(false));
+ for message in &detail.messages {
+ assert_eq!(message.content, "Original answer");
+ assert_eq!(message.status.as_deref(), Some("complete"));
+ assert!(message.error.is_none());
+ }
+ }
+
#[test]
fn assistant_thinking_roundtrips_as_canonical_blocks() {
let db = test_db();
let session = create_session(&db, None, None, None, None, None).unwrap();
let assistant = UiMessage {
+ output_truncated: None,
id: "assistant-1".into(),
role: "assistant".into(),
content: "final answer".into(),
@@ -6450,6 +6500,7 @@ mod tests {
let db = test_db();
let session = create_session(&db, None, None, None, None, None).unwrap();
let assistant = UiMessage {
+ output_truncated: None,
id: "assistant-search-1".into(),
role: "assistant".into(),
content: "answer with sources".into(),
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 7c8847596..f8d903b63 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -145,6 +145,19 @@ title therefore win concurrent updates. Host-core owns the title source in
schema v23; this state survives renderer restart and does not expose a general
transcript-read API. The core runs no title completion of its own.
+### 4.2 Output-token truncation (#2277)
+
+A visible text answer ending with `stopReason: "length"` and no tool calls
+retains its original content and records `UiMessage.outputTruncated: true`.
+Host-core round-trips the optional flag through transcript record metadata;
+legacy messages without the flag remain unchanged. No database migration is needed.
+The transcript renders a localized output-token-limit warning below that answer,
+including after history restoration. This annotation is not a terminal error,
+does not enter model context, and does not automatically retry or continue the
+answer. Subsequent prompts remain available. Normal replies, aborts, context
+overflow recovery, empty-response recovery, and Pi's rejection/recovery of
+truncated tool calls retain their existing behavior.
+
## 5. Prompt flow
1. load the durable session and reject a missing session
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5ee166e85..260a4176d 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1,5 +1,21 @@
# 04. E2E Test Plan
+### E2E-CHAT-output-token-truncation (#2277)
+
+Use the real Desktop runtime and Pi loop with a controlled provider stream
+ending in `length` after text output. Preserve the answer, emit truncation
+metadata exactly once, make no extra provider request, and accept a follow-up.
+Normal stops and aborts have no truncation annotation; a truncated tool call
+is rejected and recovered by Pi without an additional answer warning.
+Coverage: `output-truncation.test.ts`. The production persistence test in
+`empty-assistant-persistence.test.mjs` retains the text and metadata in the
+outbox. `e2e-transcript-render.mjs` renders production AssistantTurn in Electron,
+checks the visible localized warning for live and JSON-restored snapshots, and
+checks its absence on normal replies. No paid provider is used.
+The Host test `output_truncation_survives_host_restart_and_legacy_rows`
+deserializes the wire message, appends it to a real transcript, reopens the
+database, and checks that true/false flags and absent legacy flags survive.
+
### E2E-FILE-INDEX-git-deadline
Drive `getWorkspaceFileIndex` and `searchWorkspaceFiles` against real fixture
diff --git a/packages/agent-runtime/src/output-truncation.test.ts b/packages/agent-runtime/src/output-truncation.test.ts
new file mode 100644
index 000000000..3d0b25b44
--- /dev/null
+++ b/packages/agent-runtime/src/output-truncation.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from "vitest";
+import { createAssistantMessageEventStream, type AssistantMessage } from "@earendil-works/pi-ai";
+import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
+import { DesktopAgentRuntime } from "./runtime.js";
+
+const PARTIAL = "The answer ends in the middle of";
+
+function reply(stopReason: AssistantMessage["stopReason"], withTool = false): AssistantMessage {
+ return {
+ role: "assistant", api: "openai-completions", provider: "fixture", model: "fixture",
+ stopReason, timestamp: 1,
+ content: [
+ { type: "text", text: PARTIAL },
+ ...(withTool ? [{ type: "toolCall" as const, id: "truncated-call", name: "plugin_demo_probe", arguments: {} }] : []),
+ ],
+ usage: { input: 10, output: 200, cacheRead: 0, cacheWrite: 0, totalTokens: 210,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ };
+}
+
+function fixture(first: AssistantMessage) {
+ const events: AgentEventEnvelope["event"][] = [];
+ const host = { call: vi.fn(async (_method: string) => ({})) };
+ const runtime = new DesktopAgentRuntime({
+ host: host as never, sessionId: "output-truncation", mode: "agent", thinkingLevel: "off",
+ provider: { id: "fixture", name: "Fixture", modelId: "fixture", apiKey: "fixture",
+ baseUrl: "http://localhost/v1", supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ pluginTools: [{ name: "plugin_demo_probe", description: "Probe", parameters: {} }],
+ onEvent: ({ event }) => events.push(event),
+ });
+ const stream = vi.spyOn(runtime["models"], "streamSimple").mockImplementation(() => {
+ const message = stream.mock.calls.length === 1 ? first : reply("stop");
+ const result = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ result.push({ type: "start", partial: message });
+ if (message.stopReason === "aborted") result.push({ type: "error", reason: "aborted", error: message });
+ else result.push({ type: "done", reason: message.stopReason as "length" | "stop", message });
+ result.end(message);
+ });
+ return result;
+ });
+ const messages = () => events.flatMap((event): UiMessage[] =>
+ event.type === "message_end" && event.message.role === "assistant" ? [event.message] : []);
+ return { runtime, host, stream, events, messages };
+}
+
+describe("main-chat output truncation", () => {
+ it("marks a length-limited answer without changing its text or retrying, and accepts a follow-up", async () => {
+ const f = fixture(reply("length"));
+ try {
+ await f.runtime.prompt("Write a long answer.");
+ expect(f.messages()).toHaveLength(1);
+ expect(f.messages()[0]).toMatchObject({ content: PARTIAL, status: "complete", outputTruncated: true });
+ expect(f.stream).toHaveBeenCalledTimes(1);
+ expect(f.events.some((event) => event.type === "error")).toBe(false);
+ expect(f.runtime.getStatus().isRunning).toBe(false);
+ await f.runtime.prompt("Continue.");
+ expect(f.stream).toHaveBeenCalledTimes(2);
+ expect(f.messages()[1].outputTruncated).not.toBe(true);
+ } finally { await f.runtime.dispose(); }
+ });
+
+ it.each(["stop", "aborted"] as const)("does not mark a %s response as output-limited", async (reason) => {
+ const f = fixture(reply(reason));
+ try {
+ await f.runtime.prompt("Reply.");
+ expect(f.messages()).toHaveLength(1);
+ expect(f.messages()[0].outputTruncated).not.toBe(true);
+ expect(f.stream).toHaveBeenCalledTimes(1);
+ } finally { await f.runtime.dispose(); }
+ });
+
+ it("keeps Pi's truncated-tool rejection and recovery without adding an answer warning", async () => {
+ const f = fixture(reply("length", true));
+ try {
+ await f.runtime.prompt("Run the probe.");
+ expect(f.stream).toHaveBeenCalledTimes(2);
+ expect(f.host.call.mock.calls.some(([method]) => method === "tools.execute")).toBe(false);
+ expect(f.events).toContainEqual(expect.objectContaining({ type: "tool_end", isError: true }));
+ expect(f.messages().some((message) => message.outputTruncated)).toBe(false);
+ } finally { await f.runtime.dispose(); }
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 67e782e78..3abd8c72e 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -8932,6 +8932,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
modelId: this.provider.modelId,
providerId: this.provider.id,
responseModelId: concreteResponseModel(event.message, this.provider.modelId),
+ // Tool-call truncation is recovered by Pi; annotate only a visible
+ // text answer, without turning the settled run into an error.
+ outputTruncated: !failed && !aborted && stopReason === "length" &&
+ Boolean(responseText.trim()) && !messageRequestsTools(event.message) || undefined,
...(usage ? { usage } : {}),
...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 01457ff12..52fac8034 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -454,6 +454,7 @@ export const de = {
"diagramTooLarge": "Dieses Diagramm ist zu groß, um sicher gerendert zu werden. Stattdessen wird die Quelle angezeigt.",
"responseError": "Diese Antwort konnte nicht fertiggestellt werden.",
"responseFailed": "Der Assistent konnte diese Antwort nicht fertigstellen.",
+ "outputTruncated": "Diese Antwort wurde abgeschnitten, weil das Modell sein Ausgabe-Token-Limit erreicht hat. Der Inhalt ist möglicherweise unvollständig.",
"showErrorDetails": "Details anzeigen",
"hideErrorDetails": "Details ausblenden",
"dismissError": "Fehlermeldung schließen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 30b8aa6d8..7a01eef55 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -466,6 +466,7 @@ export const en = {
diagramTooLarge: "This diagram is too large to render safely. Showing source instead.",
responseError: "Couldn't finish this reply",
responseFailed: "The assistant couldn't complete this reply.",
+ outputTruncated: "This reply was truncated because the model reached its output token limit. The content may be incomplete.",
showErrorDetails: "Show details",
hideErrorDetails: "Hide details",
dismissError: "Dismiss error message",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 70adf3ccb..1d9224899 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -454,6 +454,7 @@ export const es = {
"diagramTooLarge": "Este diagrama es demasiado grande para representarlo de forma segura. Mostrando la fuente en su lugar.",
"responseError": "No se pudo finalizar esta respuesta",
"responseFailed": "El asistente no pudo completar esta respuesta.",
+ "outputTruncated": "Esta respuesta se ha truncado porque el modelo alcanzó su límite de tokens de salida. El contenido puede estar incompleto.",
"showErrorDetails": "Mostrar detalles",
"hideErrorDetails": "Ocultar detalles",
"dismissError": "Cerrar mensaje de error",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index b035967e7..00341ff32 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -454,6 +454,7 @@ export const fr = {
"diagramTooLarge": "Ce diagramme est trop grand pour être rendu en toute sécurité. Afficher la source à la place.",
"responseError": "Impossible de terminer cette réponse",
"responseFailed": "L'assistant n'a pas pu terminer cette réponse.",
+ "outputTruncated": "Cette réponse a été tronquée car le modèle a atteint sa limite de tokens de sortie. Le contenu peut être incomplet.",
"showErrorDetails": "Afficher les détails",
"hideErrorDetails": "Masquer les détails",
"dismissError": "Fermer le message d’erreur",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 8c2a49cbe..9f300ee74 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -466,6 +466,7 @@ export const ko = {
diagramTooLarge: "이 다이어그램은 안전하게 렌더링하기에 너무 큽니다. 대신 소스를 표시합니다.",
responseError: "이 답변을 완료할 수 없습니다",
responseFailed: "어시스턴트가 이 답변을 완료하지 못했습니다.",
+ outputTruncated: "모델이 출력 토큰 한도에 도달하여 답변이 잘렸습니다. 내용이 완전하지 않을 수 있습니다.",
showErrorDetails: "세부 정보 표시",
hideErrorDetails: "세부 정보 숨기기",
dismissError: "오류 메시지 닫기",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index dfaf41c1d..1f6ffc31f 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -453,6 +453,7 @@ export const ptBR = {
diagramTooLarge: "Este diagrama é grande demais para ser renderizado com segurança. Exibindo o código-fonte.",
responseError: "Não foi possível concluir esta resposta",
responseFailed: "O assistente não conseguiu concluir esta resposta.",
+ outputTruncated: "Esta resposta foi truncada porque o modelo atingiu o limite de tokens de saída. O conteúdo pode estar incompleto.",
showErrorDetails: "Mostrar detalhes",
hideErrorDetails: "Ocultar detalhes",
dismissError: "Dispensar mensagem de erro",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index f8c2e437a..b486d0ba9 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -466,6 +466,7 @@ export const tr = {
diagramTooLarge: "Bu diyagram güvenle oluşturulmak için çok büyük. Bunun yerine kaynak gösteriliyor.",
responseError: "Bu yanıt tamamlanamadı",
responseFailed: "Asistan bu yanıtı tamamlayamadı.",
+ outputTruncated: "Model çıktı token sınırına ulaştığı için bu yanıt kesildi. İçerik eksik olabilir.",
showErrorDetails: "Ayrıntıları göster",
hideErrorDetails: "Ayrıntıları gizle",
dismissError: "Hata mesajını kapat",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 96faddf06..c8982aae1 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -459,6 +459,7 @@ export const zhCN = {
diagramTooLarge: "此图表过大,无法安全渲染,已改为显示源码。",
responseError: "这次回复未能完成",
responseFailed: "助手没能完成这次回复。",
+ outputTruncated: "回复因达到模型输出 token 上限而被截断,内容可能不完整。",
showErrorDetails: "显示详情",
hideErrorDetails: "隐藏详情",
dismissError: "关闭错误消息",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 5d6a7688e..a16ee6191 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -459,6 +459,7 @@ export const zhTW = {
diagramTooLarge: "此圖表過大,無法安全渲染,已改為顯示原始碼。",
responseError: "這次回覆未能完成",
responseFailed: "助手沒能完成這次回覆。",
+ outputTruncated: "回覆因達到模型輸出 token 上限而被截斷,內容可能不完整。",
showErrorDetails: "顯示詳情",
hideErrorDetails: "隱藏詳情",
dismissError: "關閉錯誤訊息",
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index f163fd2f6..bd585ae68 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -133,6 +133,8 @@ export type UiMessage = {
thinking?: string;
createdAt: string;
status?: "streaming" | "complete" | "error" | "aborted";
+ /** The provider cut off this text response at its output-token limit. */
+ outputTruncated?: boolean;
/** Provider/model that produced this assistant turn, when known. */
modelId?: string;
providerId?: string;
diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsx
index ee27c6745..1c0d220ae 100644
--- a/scripts/e2e/transcript-render.tsx
+++ b/scripts/e2e/transcript-render.tsx
@@ -702,6 +702,24 @@ globalThis.transcriptRenderProbe = async () => {
}
}
+ // The saved snapshot must show the same warning after session restoration.
+ flushSync(() => useAppStore.setState({ settings: {
+ ...useAppStore.getState().settings!, smoothStreaming: false, inlineVisualizations: false,
+ } }));
+ const truncatedAnswer = message("truncated-answer", "assistant", "An incomplete answer", {
+ status: "complete", outputTruncated: true,
+ });
+ for (const snapshot of [truncatedAnswer, JSON.parse(JSON.stringify(truncatedAnswer))]) {
+ render([message("truncated-user", "user", "Write a long answer"), snapshot]);
+ assert(container.textContent?.includes("An incomplete answer"), "truncation hid the answer");
+ assert(container.querySelector('[role="status"]')?.textContent === i18n.t("chat.outputTruncated"),
+ "output-token warning missing from live or restored answer");
+ assert(container.querySelector('.message-output-notice')?.getBoundingClientRect().height,
+ "output-token warning is not visible");
+ }
+ render([message("normal-user", "user", "Reply"), message("normal-answer", "assistant", "Complete answer")]);
+ assert(!container.querySelector('.message-output-notice'), "normal answer has a truncation warning");
+
const statusLifecycle = await transcriptStatusProbe();
const markdownLinks = await markdownLinkInteractionProbe(i18n);
const contextMenuSubmenu = await contextMenuSubmenuInteractionProbe();
@@ -718,6 +736,7 @@ globalThis.transcriptRenderProbe = async () => {
changedToolRenders: 1,
taskLifecycleUpdated: true,
taskTimingUpdated: true,
+ outputTruncationVisible: true,
turnProcess,
autoCollapse,
messageEditing: await transcriptEditProbe(),