Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(chat): stream reasoning trace into the chat panel

Etienne Lescot7a35fb47a6db
diff --git a/electron/ai-edition/chat-service.toolloop.test.ts b/electron/ai-edition/chat-service.toolloop.test.ts
index 8b35a4669..543dadc1f 100644
--- a/electron/ai-edition/chat-service.toolloop.test.ts
+++ b/electron/ai-edition/chat-service.toolloop.test.ts
@@ -244,7 +244,9 @@ describe("runChat tool loop", () => {
invokeMock.mockImplementationOnce(async (args) => {
events.push({ kind: "captured", payload: args.userMessage });
args.sink.text("Hi ");
+ args.sink.thinking("pondering. ");
args.sink.text("there.");
+ args.sink.thinking("concluding.");
args.sink.toolStart("addTrim", { startSec: 1, endSec: 2 });
args.sink.toolEnd("addTrim", true, "added trim 0:01.0 – 0:02.0");
return { text: "Done.", document: args.document, mutated: true };
@@ -252,6 +254,7 @@ describe("runChat tool loop", () => {
const sink = {
text: (delta: string) => fixture.events.push({ kind: "text", payload: delta }),
+ thinking: (delta: string) => fixture.events.push({ kind: "thinking", payload: delta }),
toolStart: (name: string, args: unknown) =>
fixture.events.push({ kind: "toolStart", payload: { name, args } }),
toolEnd: (name: string, ok: boolean, summary?: string) =>
@@ -262,12 +265,22 @@ describe("runChat tool loop", () => {
const s = createSession("proj_sink");
const result = await runChat("proj_sink", s.id, "cut", stubConfig(), fixtureDocument(), sink);
expect(result.success).toBe(true);
- expect(fixture.events.map((e) => e.kind)).toEqual(["text", "text", "toolStart", "toolEnd"]);
- expect((fixture.events[0].payload as string) + (fixture.events[1].payload as string)).toBe(
+ expect(fixture.events.map((e) => e.kind)).toEqual([
+ "text",
+ "thinking",
+ "text",
+ "thinking",
+ "toolStart",
+ "toolEnd",
+ ]);
+ expect((fixture.events[0].payload as string) + (fixture.events[2].payload as string)).toBe(
"Hi there.",
);
- expect(fixture.events[2].payload).toMatchObject({ name: "addTrim" });
- expect(fixture.events[3].payload).toMatchObject({
+ expect((fixture.events[1].payload as string) + (fixture.events[3].payload as string)).toBe(
+ "pondering. concluding.",
+ );
+ expect(fixture.events[4].payload).toMatchObject({ name: "addTrim" });
+ expect(fixture.events[5].payload).toMatchObject({
name: "addTrim",
ok: true,
summary: expect.stringMatching(/added trim/),
@@ -284,6 +297,7 @@ describe("runChat tool loop", () => {
});
const sinkErr = {
text: (delta: string) => fixture.events.push({ kind: "text", payload: delta }),
+ thinking: (delta: string) => fixture.events.push({ kind: "thinking", payload: delta }),
toolStart: (name: string, args: unknown) =>
fixture.events.push({ kind: "toolStart", payload: { name, args } }),
toolEnd: (name: string, ok: boolean, summary?: string) =>
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index a2f0f7ccf..1dad3ceca 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -204,6 +204,11 @@ export function deleteSession(projectId: string, sessionId: string): boolean {
export interface ChatEventSink {
/** Streamed text delta from the model. */
text?: (delta: string) => void;
+ /** Streamed delta from the model's reasoning block (Anthropic/MiniMax
+ * thinking). Provider-agnostic — never called for providers that don't
+ * expose thinking. The chat panel streams these into a live "Thinking…"
+ * block so the reasoning phase doesn't feel like dead air. */
+ thinking?: (delta: string) => void;
/** A tool call is about to execute. */
toolStart?: (name: string, args: unknown) => void;
/** A tool call has finished. `ok=false` carries the model's error message. */
@@ -218,6 +223,7 @@ const noop = () => undefined;
/** ponytail: zero-config sink that swallows every event. */
const NOOP_SINK: Required<ChatEventSink> = {
text: noop,
+ thinking: noop,
toolStart: noop,
toolEnd: noop,
error: noop,
@@ -323,6 +329,7 @@ export async function runChat(
const agentSink = {
text: (delta: string) => emit.text(delta),
+ thinking: (delta: string) => emit.thinking(delta),
toolStart: (name: string, args: unknown) => {
emit.toolStart(name, args);
void editsAllowed;
diff --git a/electron/ai-edition/deep-agent/chat-model.test.ts b/electron/ai-edition/deep-agent/chat-model.test.ts
index cde99f6b1..477f5bece 100644
--- a/electron/ai-edition/deep-agent/chat-model.test.ts
+++ b/electron/ai-edition/deep-agent/chat-model.test.ts
@@ -9,6 +9,7 @@ import {
ANTHROPIC_API_MAX_OUTPUT_TOKENS,
createOpenScreenChatModel,
messageContentToText,
+ messageContentToThinking,
} from "./chat-model";
/** ChatOpenAI keeps the `configuration` bag it was constructed with on
@@ -104,3 +105,43 @@ describe("messageContentToText", () => {
expect(messageContentToText(42)).toBe("");
});
});
+
+describe("messageContentToThinking", () => {
+ // Anthropic/MiniMax thinking blocks land in AIMessageChunk content arrays
+ // as `{type: "thinking", thinking: "..."}` parts (see @langchain/anthropic
+ // message_outputs.js — `thinking_delta` SSE events). The extractor has to
+ // pull them out so the chat panel can stream them separately; text parts
+ // stay on the messageContentToText path.
+ it("concatenates thinking parts in array order", () => {
+ expect(
+ messageContentToThinking([
+ { type: "thinking", thinking: "step one. " },
+ { type: "text", text: "should be ignored" },
+ { type: "thinking", thinking: "step two." },
+ ]),
+ ).toBe("step one. step two.");
+ });
+
+ it("ignores redacted_thinking blocks (encrypted reasoning the provider hides)", () => {
+ // ChatAnthropic surfaces encrypted reasoning as parts of type
+ // "redacted_thinking" — we don't have a string to display, so skip.
+ expect(
+ messageContentToThinking([
+ { type: "thinking", thinking: "visible. " },
+ { type: "redacted_thinking" },
+ { type: "thinking", thinking: "more visible." },
+ ]),
+ ).toBe("visible. more visible.");
+ });
+
+ it("returns an empty string for a plain string or non-array input", () => {
+ expect(messageContentToThinking("not a list")).toBe("");
+ expect(messageContentToThinking(null)).toBe("");
+ expect(messageContentToThinking(42)).toBe("");
+ });
+
+ it("returns an empty string when there are no thinking parts", () => {
+ expect(messageContentToThinking([{ type: "text", text: "answer" }])).toBe("");
+ expect(messageContentToThinking([])).toBe("");
+ });
+});
diff --git a/electron/ai-edition/deep-agent/chat-model.ts b/electron/ai-edition/deep-agent/chat-model.ts
index 4f9917482..5845905b3 100644
--- a/electron/ai-edition/deep-agent/chat-model.ts
+++ b/electron/ai-edition/deep-agent/chat-model.ts
@@ -81,6 +81,27 @@ export function messageContentToText(content: unknown): string {
return "";
}
+// ponytail: counterpart to messageContentToText for the Anthropic/MiniMax
+// thinking blocks. ChatAnthropic with `thinking: {type: "adaptive"}` (or
+// `enabled`) emits streamed `thinking_delta` SSE events that LangChain turns
+// into content parts `{type: "thinking", thinking: "..."}`. We strip that
+// thinking text out of the final AIMessage content (where it counts against
+// max_tokens on the visible text path, but isn't user-visible text) and pipe
+// it separately to the renderer so the chat panel can show a live "Thinking…"
+// block instead of dead air. `redacted_thinking` parts (encrypted reasoning
+// the provider chose not to show us) are skipped — there's nothing to display.
+export function messageContentToThinking(content: unknown): string {
+ if (!Array.isArray(content)) return "";
+ let total = "";
+ for (const part of content) {
+ if (!part || typeof part !== "object") continue;
+ const p = part as { type?: unknown; thinking?: unknown };
+ if (p.type !== "thinking") continue;
+ if (typeof p.thinking === "string") total += p.thinking;
+ }
+ return total;
+}
+
export async function createOpenScreenChatModel(
input: OpenScreenChatModelConfig,
): Promise<BaseChatModel> {
diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts
index c8db1016c..07eb4ded4 100644
--- a/electron/ai-edition/deep-agent/service.ts
+++ b/electron/ai-edition/deep-agent/service.ts
@@ -31,11 +31,17 @@ import {
import {
createOpenScreenChatModel,
messageContentToText,
+ messageContentToThinking,
type OpenScreenChatModelConfig,
} from "./chat-model";
export interface OpenScreenAgentSink {
text: (delta: string) => void;
+ /** Streaming delta from the model's reasoning block (Anthropic/MiniMax
+ * thinking). Provider-agnostic — for providers without thinking this is
+ * never called. The chat panel uses it to surface the reasoning phase
+ * that would otherwise be invisible "dead air" while the model thinks. */
+ thinking: (delta: string) => void;
toolStart: (name: string, args: unknown) => void;
toolEnd: (name: string, ok: boolean, summary?: string) => void;
error: (message: string) => void;
@@ -233,6 +239,10 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
const chunk = data?.chunk as Record<string, unknown> | undefined;
if (chunk) chatModelChunks.push(chunk);
const content = chunk?.content;
+ const thinkingDelta = messageContentToThinking(content);
+ if (thinkingDelta) {
+ sink.thinking(thinkingDelta);
+ }
const delta = messageContentToText(content);
if (delta) {
sink.text(delta);
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 6997943dd..99cb185fb 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -189,6 +189,7 @@ function buildChatEventSink(sender: Electron.WebContents, sessionId: string): Ch
};
return {
text: (delta) => send({ kind: "text", sessionId, delta }),
+ thinking: (delta) => send({ kind: "thinking", sessionId, delta }),
toolStart: (name, args) => send({ kind: "toolStart", sessionId, name, args }),
toolEnd: (name, ok, summary) => send({ kind: "toolEnd", sessionId, name, ok, summary }),
error: (message) => send({ kind: "error", sessionId, message }),
diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsx
index 855a28e11..b8e15808c 100644
--- a/src/components/ai-edition/LeftPanel.tsx
+++ b/src/components/ai-edition/LeftPanel.tsx
@@ -8,7 +8,11 @@ import { type AxcutAsset, ensureDocument } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { nativeBridgeClient } from "@/native/client";
-import type { AiEditionLlmConfig, AiEditionToolCallSummary } from "@/native/contracts";
+import type {
+ AiEditionChatEvent,
+ AiEditionLlmConfig,
+ AiEditionToolCallSummary,
+} from "@/native/contracts";
import { formatBytes } from "@/utils/formatBytes";
import {
getReasoningEffortLabel,
@@ -341,6 +345,11 @@ interface ChatDisplayMessage {
// ponytail: axcut parity — non-null on user messages that have a
// rewind-able document snapshot, so the per-message ↩ button shows.
checkpointId?: string | null;
+ // ponytail: when an assistant message carries the model's reasoning trace
+ // (Anthropic/MiniMax thinking), the chat renders it as a collapsible block
+ // above the answer. Ephemeral — only present for the turn that streamed it;
+ // reloading a session won't show past traces.
+ thinking?: string;
}
// Quick-access model picker anchored to the composer's model pill — mirrors
@@ -639,6 +648,108 @@ function ModelQuickPopover({
);
}
+// ponytail: collapsible block that renders a model's reasoning trace (the
+// streaming text from Anthropic/MiniMax `thinking` blocks). Default state is
+// the last ~240 chars of the trace, clamped to two lines — the latest
+// reasoning the model produced. Clicking the header toggles into "solid" mode
+// (full text, scrollable). Used both while the reasoning is still streaming
+// (so the user sees the model is alive) and on the completed message (so the
+// trace is still there to revisit, collapsed by default).
+const THINKING_PREVIEW_TAIL_CHARS = 240;
+function ThinkingBlock({
+ text,
+ expanded,
+ onToggle,
+ label,
+}: {
+ text: string;
+ expanded: boolean;
+ onToggle: () => void;
+ label: string;
+}) {
+ const preview =
+ text.length > THINKING_PREVIEW_TAIL_CHARS
+ ? `…${text.slice(-THINKING_PREVIEW_TAIL_CHARS)}`
+ : text;
+ return (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={expanded}
+ style={{
+ display: "block",
+ width: "100%",
+ textAlign: "left",
+ background: "transparent",
+ border: "1px solid var(--border-soft)",
+ borderRadius: "var(--r-sm)",
+ padding: "6px 8px",
+ marginBottom: 4,
+ color: expanded ? "var(--fg-2)" : "var(--muted)",
+ font: "400 11px/1.5 var(--font-body)",
+ cursor: "pointer",
+ }}
+ >
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 4,
+ marginBottom: expanded ? 4 : 0,
+ color: "var(--muted)",
+ font: "500 10px/1 var(--font-mono)",
+ }}
+ >
+ <svg
+ width={10}
+ height={10}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ style={{
+ transform: expanded ? "rotate(90deg)" : "rotate(0deg)",
+ transition: "transform 120ms ease",
+ flex: "0 0 auto",
+ }}
+ aria-hidden="true"
+ >
+ <polyline points="9 6 15 12 9 18" />
+ </svg>
+ <span>{label}</span>
+ </div>
+ {expanded ? (
+ <div
+ style={{
+ maxHeight: 220,
+ overflow: "auto",
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ font: "400 11px/1.5 var(--font-mono)",
+ }}
+ >
+ {text}
+ </div>
+ ) : (
+ <div
+ style={{
+ display: "-webkit-box",
+ WebkitLineClamp: 2,
+ WebkitBoxOrient: "vertical",
+ overflow: "hidden",
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ }}
+ >
+ {preview}
+ </div>
+ )}
+ </button>
+ );
+}
+
function ChatStripPanel() {
const t = useScopedT("editor");
const tc = useScopedT("common");
@@ -665,6 +776,17 @@ function ChatStripPanel() {
const activeSessionIdRef = useRef<string | null>(activeSessionId);
activeSessionIdRef.current = activeSessionId;
const scrollRef = useRef<HTMLDivElement | null>(null);
+ // ponytail: live reasoning trace for the in-flight turn. Reset at send()
+ // start; deltas append through the chat-event subscription; once the run
+ // resolves we copy it onto the assistant message and clear it.
+ const [thinkingText, setThinkingText] = useState("");
+ const [thinkingExpanded, setThinkingExpanded] = useState(false);
+ // sessionId of the in-flight run — late events for prior runs (or for
+ // other windows) are ignored so a stale stream can't pollute the new turn.
+ const thinkingRunSessionRef = useRef<string | null>(null);
+ // Per-message expand state for completed turns. Using a Set keeps the
+ // default-collapsed preview lightweight and the click-to-expand obvious.
+ const [thinkingExpandedIds, setThinkingExpandedIds] = useState<Set<string>>(() => new Set());
const [reasoningOpen, setReasoningOpen] = useState(false);
const reasoningButtonRef = useRef<HTMLButtonElement | null>(null);
const [reasoningMenuRect, setReasoningMenuRect] = useState<{
@@ -715,6 +837,21 @@ function ChatStripPanel() {
void refreshLlm();
}, [refreshLlm]);
+ // ponytail: subscribe to streamed chat events so the reasoning trace (and
+ // any future streaming text deltas) lands live instead of arriving all at
+ // once when chatRun resolves. We only act on `thinking` here — text deltas
+ // are ignored in the renderer today because the chat already renders the
+ // final assistant text on chatRun resolve, and a parallel live stream
+ // would race the final message. Add `text` handling when that flow lands.
+ useEffect(() => {
+ const unsubChatEvent = window.electronAPI.onAiEditionChatEvent((event: AiEditionChatEvent) => {
+ if (event.kind !== "thinking") return;
+ if (event.sessionId !== thinkingRunSessionRef.current) return;
+ setThinkingText((prev) => prev + event.delta);
+ });
+ return unsubChatEvent;
+ }, []);
+
useEffect(() => {
if (!projectId) {
setSessions([]);
@@ -783,6 +920,12 @@ function ChatStripPanel() {
}
setInput("");
setBusy(true);
+ // ponytail: prepare the live reasoning-trace accumulator. Late events
+ // from a previous run (or from another panel/window) won't match this
+ // sessionId and are dropped by the subscription above.
+ setThinkingText("");
+ setThinkingExpanded(false);
+ thinkingRunSessionRef.current = null;
// ponytail: pre-seed the user message so the rewind ↩ button is
// available before the server confirms. Mirrors axcut's
// `before-message` checkpoint that runChat records in chat-service.
@@ -806,8 +949,11 @@ function ChatStripPanel() {
const created = await nativeBridgeClient.aiEdition.chatCreateSession(projectId);
sessionId = created.id;
setSessions((prev) => [...prev, created]);
- setActiveSessionId(created.id);
+ setActiveSessionId(sessionId);
}
+ // ponytail: start collecting the live reasoning trace for THIS run —
+ // the subscription only appends deltas whose sessionId matches.
+ thinkingRunSessionRef.current = sessionId;
// Send the current document snapshot so the agent can run edit tools
// against it (P1). Falls back to text-only chat when no doc is open.
const documentSnapshot = useProjectStore.getState().document ?? undefined;
@@ -835,6 +981,11 @@ function ChatStripPanel() {
content: assistant.content,
time: new Date().toLocaleTimeString(),
toolCalls: assistant.toolCalls,
+ // ponytail: snapshot the live reasoning trace onto the
+ // finished message so it can be revisited (collapsed by
+ // default, click-to-expand) instead of vanishing. The
+ // live accumulator is cleared in `finally`.
+ thinking: thinkingText || undefined,
},
]);
void refreshSessions(projectId);
@@ -847,6 +998,12 @@ function ChatStripPanel() {
});
} finally {
setBusy(false);
+ // ponytail: stop accepting thinking deltas and drop the in-flight
+ // preview — the snapshot was either attached to the assistant
+ // message above, or there's no message to attach it to (failure).
+ thinkingRunSessionRef.current = null;
+ setThinkingText("");
+ setThinkingExpanded(false);
}
};
@@ -1407,6 +1564,25 @@ function ChatStripPanel() {
</span>
) : null}
</div>
+ {m.thinking && m.role !== "user" ? (
+ <ThinkingBlock
+ text={m.thinking}
+ expanded={m.id !== undefined && thinkingExpandedIds.has(m.id)}
+ onToggle={() => {
+ if (!m.id) return;
+ setThinkingExpandedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(m.id!)) {
+ next.delete(m.id!);
+ } else {
+ next.add(m.id!);
+ }
+ return next;
+ });
+ }}
+ label={t("chat.thinking")}
+ />
+ ) : null}
<div className={styles.msgBubble}>{m.content}</div>
<div
style={{
@@ -1522,17 +1698,45 @@ function ChatStripPanel() {
<div className={styles.msgHead}>
<span className={styles.msgAuthor}>{t("chat.authorAssistant")}</span>
</div>
- <div
- className={styles.msgBubble}
- style={{ color: "var(--muted)", fontStyle: "italic" }}
- >
- <Loader2
- size={12}
- className="animate-spin"
- style={{ marginRight: 6, verticalAlign: "middle" }}
- />
- {t("chat.thinking")}
- </div>
+ {thinkingText ? (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "flex-start",
+ gap: 6,
+ }}
+ >
+ <Loader2
+ size={12}
+ className="animate-spin"
+ style={{
+ marginTop: 10,
+ flex: "0 0 auto",
+ color: "var(--muted)",
+ }}
+ />
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <ThinkingBlock
+ text={thinkingText}
+ expanded={thinkingExpanded}
+ onToggle={() => setThinkingExpanded((v) => !v)}
+ label={t("chat.thinking")}
+ />
+ </div>
+ </div>
+ ) : (
+ <div
+ className={styles.msgBubble}
+ style={{ color: "var(--muted)", fontStyle: "italic" }}
+ >
+ <Loader2
+ size={12}
+ className="animate-spin"
+ style={{ marginRight: 6, verticalAlign: "middle" }}
+ />
+ {t("chat.thinking")}
+ </div>
+ )}
</div>
) : null}
</>
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index c990df81c..139fa93e4 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -119,6 +119,7 @@ function createShimElectronAPI() {
sendCloseConfirmResponse: () => undefined,
onRequestCloseConfirm: () => () => undefined,
onRequestSaveBeforeClose: () => () => undefined,
+ onAiEditionChatEvent: () => () => undefined,
loadProjectFileFromPath: () => Promise.resolve({ success: false, canceled: true }),
getPathForFile: () => "",
getSources: () => Promise.resolve(SHIM_SOURCES),
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 2fca2d84d..ffe3d022e 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -729,6 +729,7 @@ export type NativeBridgeEventName =
// inline so the chat doesn't appear to "echo back my question".
export type AiEditionChatEvent =
| { kind: "text"; sessionId: string; delta: string }
+ | { kind: "thinking"; sessionId: string; delta: string }
| { kind: "toolStart"; sessionId: string; name: string; args: unknown }
| { kind: "toolEnd"; sessionId: string; name: string; ok: boolean; summary?: string }
| { kind: "error"; sessionId: string; message: string };