The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): name the tool call being written, ask the router's query vector once
purpleff212961b5ba
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d0dfbd13..4c04a9d4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,11 @@ cloud catalogue.a request of its own. It now keeps a plan in Plan mode, when you ask for aplan, or while a plan is still open. The plan panel, the approval bar and thefile explorer are dark instead of blue.+- **The run says which tool the model is writing.** A model writing a long+ file sends the call in pieces for many seconds, and the run said only+ "Working" the whole time. It now shows the tool's name and how much of the+ call has arrived, for example "Preparing file_write 3 kB", as soon as the+ first piece is in.- **Code conversations stay in the Code tab.** After a restart the last Codeconversation opened in the Chat tab, where the agent was off and a"continue" ran without tools. The app now starts on an empty chat, and thediff --git a/src/api/__tests__/a-call-being-written-names-itself.test.ts b/src/api/__tests__/a-call-being-written-names-itself.test.tsnew file mode 100644index 00000000..da5fbda4--- /dev/null+++ b/src/api/__tests__/a-call-being-written-names-itself.test.ts@@ -0,0 +1,82 @@+/**+ * Realtime pass 01.10.2026 (R1). A model that answers with a tool call streams+ * the call's arguments for seconds: a 4 kB file_write on Mistral Small took+ * ~11 s from the first argument byte to the end (measured live against+ * DeepInfra). The providers kept the pieces to themselves until the done+ * chunk, and the run showed "Working" with an "Analyzing..." placeholder the+ * whole time. They now report the call while it is being written.+ *+ * Run: npx vitest run src/api/__tests__/a-call-being-written-names-itself.test.ts+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { OpenAIProvider } from '../providers/openai-provider'+import { AnthropicProvider } from '../providers/anthropic-provider'+import type { ChatStreamChunk, ToolCallProgress } from '../providers/types'+import { streamProviderTurn } from '../../lib/provider-stream'++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {+ const out: ChatStreamChunk[] = []+ for await (const c of gen) out.push(c)+ return out+}++const openaiSse = [+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"file_write","arguments":""}}]}}]}',+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"path\\":\\"a.html\\","}}]}}]}',+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"content\\":\\"hi\\"}"}}]}}]}',+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}',+ 'data: [DONE]',+ '',+].join('\n\n')++function openai(): OpenAIProvider {+ return new OpenAIProvider({ id: 'openai', name: 'T', enabled: true, baseUrl: 'https://api.test.com/v1', apiKey: 'k', isLocal: false })+}++describe('a tool call names itself while it is written', () => {+ it('OpenAI-compatible stream: progress with the name and the growing size, before the done chunk', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(openaiSse, { status: 200 }))+ const chunks = await drain(openai().chatStream('m', [{ role: 'user', content: 'x' }]))+ const done = chunks.findIndex((c) => c.done)+ const progress = chunks.slice(0, done).flatMap((c) => (c.toolProgress ? [c.toolProgress] : []))+ expect(progress.map((p) => p.name)).toEqual(['file_write', 'file_write', 'file_write'])+ expect(progress.map((p) => p.argsChars)).toEqual([0, 17, 32])+ // The finished call still arrives once, on the done chunk.+ expect(chunks[done].toolCalls?.[0].function.name).toBe('file_write')+ })++ it('Anthropic stream: progress from the block start and every JSON piece', async () => {+ const events = [+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":1,"output_tokens":0}}}\n\n',+ 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"file_write"}}\n\n',+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":"}}\n\n',+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"\\"a\\"}"}}\n\n',+ 'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}\n\n',+ 'event: message_stop\ndata: {"type":"message_stop"}\n\n',+ ]+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(events.join(''), { status: 200, headers: { 'Content-Type': 'text/event-stream' } })))+ const chunks = await drain(new AnthropicProvider({ id: 'anthropic', name: 'A', enabled: true, baseUrl: 'https://api.anthropic.com', apiKey: 'sk-ant-test', isLocal: false })+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'x' }]))+ const progress = chunks.flatMap((c) => (c.toolProgress ? [c.toolProgress] : []))+ expect(progress).toEqual([+ { name: 'file_write', argsChars: 0 },+ { name: 'file_write', argsChars: 8 },+ { name: 'file_write', argsChars: 12 },+ ])+ })++ it('streamProviderTurn hands the progress to the run, and the turn result is unchanged', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(openaiSse, { status: 200 }))+ const seen: ToolCallProgress[] = []+ const turn = await streamProviderTurn(openai(), 'm', [{ role: 'user', content: 'x' }], {}, undefined, undefined, (p) => seen.push(p))+ expect(seen.at(-1)).toEqual({ name: 'file_write', argsChars: 32 })+ expect(turn.toolCalls).toHaveLength(1)+ expect(turn.toolCalls[0].function.arguments).toEqual({ path: 'a.html', content: 'hi' })+ expect(turn.content).toBe('')+ })+})diff --git a/src/api/agents/__tests__/embedding-router.test.ts b/src/api/agents/__tests__/embedding-router.test.tsindex fe435a47..9b8e0fff 100644--- a/src/api/agents/__tests__/embedding-router.test.ts+++ b/src/api/agents/__tests__/embedding-router.test.ts@@ -185,3 +185,34 @@ describe('embedding-router — hashDescription', () => {expect(__internal.hashDescription('a')).not.toBe(__internal.hashDescription('b'))})})++// Realtime pass 01.10.2026 (R3): the agent loop routes every step of a run on+// the same user instruction and asked the embedding server for its vector+// before every model call.+describe('embedding-router: the query vector is asked for once per query', () => {+ beforeEach(() => clearEmbeddingCache())++ it('a second step with the same instruction does not call the embedding server', async () => {+ const tools = [{ name: 'a', description: 'apple' }, { name: 'b', description: 'banana' }]+ const embed = vi.fn(fakeEmbed)+ await selectToolsByEmbedding('make an apple pie', tools, embed, { topN: 1 })+ const afterFirst = embed.mock.calls.length+ await selectToolsByEmbedding('make an apple pie', tools, embed, { topN: 1 })+ expect(afterFirst).toBe(2) // the tool descriptions, then the query+ expect(embed.mock.calls.length).toBe(afterFirst)+ // A new instruction is embedded, of course.+ await selectToolsByEmbedding('peel a banana', tools, embed, { topN: 1 })+ expect(embed.mock.calls.length).toBe(afterFirst + 1)+ })++ it('a query cached under another embedding backend is asked for again, not compared across spaces', async () => {+ const tools = [{ name: 'a', description: 'apple' }]+ await selectToolsByEmbedding('apple', tools, fakeEmbed, { topN: 1 })+ // Backend switch: the tools are re-embedded in the new 4-dim space.+ __internal.CACHE.clear()+ const smallEmbed = vi.fn(async (texts: string[]) => texts.map(() => [1, 0, 0, 0]))+ const out = await selectToolsByEmbedding('apple', tools, smallEmbed, { topN: 1 })+ expect(out).toEqual(['a'])+ expect(smallEmbed.mock.calls.some((c) => c[0][0] === 'apple' && c[0].length === 1)).toBe(true)+ })+})diff --git a/src/api/agents/embedding-router.ts b/src/api/agents/embedding-router.tsindex 1fc2d613..bbebabcc 100644--- a/src/api/agents/embedding-router.ts+++ b/src/api/agents/embedding-router.ts@@ -43,8 +43,28 @@ function hashDescription(s: string): string {return (h >>> 0).toString(16)}+/**+ * The query's own vector, by query text. The agent loop routes on the user's+ * instruction, which stays the same for every step of a run, and asked the+ * embedding server for that same vector again before every model call+ * (realtime pass 01.10.2026, R3). A few entries cover the runs in flight.+ */+const QUERY_CACHE = new Map<string, number[]>()+const QUERY_CACHE_MAX = 8++async function queryVector(query: string, embed: EmbeddingFn): Promise<number[] | undefined> {+ const hit = QUERY_CACHE.get(query)+ if (hit) return hit+ const [vec] = await embed([query])+ if (!vec) return undefined+ QUERY_CACHE.set(query, vec)+ if (QUERY_CACHE.size > QUERY_CACHE_MAX) QUERY_CACHE.delete(QUERY_CACHE.keys().next().value as string)+ return vec+}+export function clearEmbeddingCache(): void {CACHE.clear()+ QUERY_CACHE.clear()}/**@@ -105,7 +125,14 @@ export async function rankToolsByEmbedding(opts: { topN?: number } = {}): Promise<Array<{ tool: ToolLike; score: number }>> {const topN = opts.topN ?? 10- const [queryVec] = await embed([query])+ let queryVec = await queryVector(query, embed)+ // A cached vector from an embedding backend that has since changed (the+ // built-in engine and Ollama differ in length) is asked for once more.+ const sample = tools.map((t) => CACHE.get(t.name)).find(Boolean)+ if (queryVec && sample && sample.vector.length !== queryVec.length) {+ QUERY_CACHE.delete(query)+ queryVec = await queryVector(query, embed)+ }if (!queryVec) return []const scored: Array<{ tool: ToolLike; score: number }> = []diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.tsindex 4a05783e..fdb0646c 100644--- a/src/api/providers/anthropic-provider.ts+++ b/src/api/providers/anthropic-provider.ts@@ -434,6 +434,7 @@ export class AnthropicProvider implements ProviderClient {name: data.content_block.name || '',input: '',})+ if (data.content_block.name) yield { content: '', toolProgress: { name: data.content_block.name, argsChars: 0 }, done: false }}break}@@ -452,7 +453,10 @@ export class AnthropicProvider implements ProviderClient {// gefuellt wird — dieselbe Regel wie oben, dieselbe Funktion.const key = data.index ?? keyForUnindexedBlock(toolUseBlocks)const block = toolUseBlocks.get(key)- if (block) block.input += delta.partial_json+ if (block) {+ block.input += delta.partial_json+ if (block.name) yield { content: '', toolProgress: { name: block.name, argsChars: block.input.length }, done: false }+ }}break}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 77380384..a2827ae4 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -988,6 +988,8 @@ export class OpenAIProvider implements ProviderClient {args: tc.function?.arguments || '',})}+ const call = toolCallAccum.get(key)+ if (call?.name) yield { content: '', toolProgress: { name: call.name, argsChars: call.args.length }, done: false }}}diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex 712e28db..adce2a0f 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -228,10 +228,21 @@ export interface ChatOptions {// ── Streaming Chunk (unified output) ──────────────────────────+export interface ToolCallProgress {+ name: string+ argsChars: number+}+export interface ChatStreamChunk {content: stringthinking?: string // Model reasoning (Ollama thinking field, <think> tags)toolCalls?: ToolCall[]+ // A tool call the model is still writing: its name and how much of its+ // arguments has arrived. The finished calls still come only on the done+ // chunk; this is what the run shows in the meantime instead of "Working"+ // (a 4 kB file_write streams for ~11 s on Mistral Small, measured+ // 01.10.2026).+ toolProgress?: ToolCallProgressdone: boolean// Why generation ended, on the final done:true chunk. 'stop' | 'length'// (token budget exhausted, e.g. the whole budget went into reasoning) |diff --git a/src/components/chat/WorkingAnchor.tsx b/src/components/chat/WorkingAnchor.tsxindex 9cad32ee..3ddff550 100644--- a/src/components/chat/WorkingAnchor.tsx+++ b/src/components/chat/WorkingAnchor.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react'import { formatElapsed } from '../../lib/format-elapsed'import { useGenerationStore } from '../../stores/generationStore'+import { useRunActivityStore } from '../../stores/runActivityStore'interface Props {isRunning: boolean@@ -27,6 +28,9 @@ interface Props {export function WorkingAnchor({ isRunning, label, conversationId }: Props) {const [elapsed, setElapsed] = useState(0)const bookedAt = useGenerationStore((s) => (conversationId ? s.runs[conversationId]?.bookedAt : undefined))+ // What the run reports it is doing (a tool call being written). An explicit+ // label from the surface still wins: an approval wait is the more urgent fact.+ const activity = useRunActivityStore((s) => (conversationId ? s.activity[conversationId] : undefined))// The clock resets in the render where `isRunning` flips, not in an effect// afterwards. Two things were wrong with the effect version: `useRef(Date.now())`@@ -93,7 +97,12 @@ export function WorkingAnchor({ isRunning, label, conversationId }: Props) {aria-hidden="true"className="lu-band-dot w-1.5 h-1.5 rounded-full bg-lu-accent-edge dark:bg-lu-accent shrink-0"/>- <span className="lu-tool-shimmer t-control">{label ?? 'Working'}</span>+ <span className="lu-tool-shimmer t-control">{label ?? activity?.label ?? 'Working'}</span>+ {!label && activity?.detail && (+ <span aria-hidden="true" className="lu-hud-num t-micro text-gray-500 dark:text-gray-500">+ {activity.detail}+ </span>+ )}{elapsed >= 1 && (<span aria-hidden="true" className="lu-hud-num t-micro text-gray-500 dark:text-gray-500">{formatElapsed(elapsed)}diff --git a/src/components/chat/__tests__/the-anchor-names-the-call-being-written.test.ts b/src/components/chat/__tests__/the-anchor-names-the-call-being-written.test.tsnew file mode 100644index 00000000..2e0e8231--- /dev/null+++ b/src/components/chat/__tests__/the-anchor-names-the-call-being-written.test.ts@@ -0,0 +1,59 @@+/**+ * @vitest-environment jsdom+ *+ * Realtime pass 01.10.2026 (R1): the run anchor says which call the model is+ * writing instead of "Working", with the size that has arrived. An explicit+ * label from the surface (an approval wait) still wins, and a run without+ * activity still reads "Working".+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { createElement } from 'react'+import { render, screen, act, cleanup } from '@testing-library/react'+import { WorkingAnchor } from '../WorkingAnchor'+import { useRunActivityStore, toolProgressActivity } from '../../../stores/runActivityStore'++beforeEach(() => {+ useRunActivityStore.setState({ activity: {} })+})+afterEach(() => cleanup())++const anchor = () => screen.getByTestId('working-anchor').textContent ?? ''++describe('the run anchor while a call is written', () => {+ it('reads Working until the run reports a call, then names it with its size', () => {+ render(createElement(WorkingAnchor, { isRunning: true, conversationId: 'c1' }))+ expect(anchor()).toContain('Working')++ act(() => useRunActivityStore.getState().setActivity('c1', toolProgressActivity({ name: 'file_write', argsChars: 300 })))+ expect(anchor()).toContain('Preparing file_write')+ expect(anchor()).not.toContain('kB')++ act(() => useRunActivityStore.getState().setActivity('c1', toolProgressActivity({ name: 'file_write', argsChars: 2300 })))+ expect(anchor()).toContain('Preparing file_write')+ expect(anchor()).toContain('2 kB')++ act(() => useRunActivityStore.getState().setActivity('c1', null))+ expect(anchor()).toContain('Working')+ })++ it('an explicit label wins, and another conversation does not leak in', () => {+ useRunActivityStore.getState().setActivity('c1', toolProgressActivity({ name: 'shell_execute', argsChars: 10 }))+ useRunActivityStore.getState().setActivity('c2', toolProgressActivity({ name: 'file_write', argsChars: 10 }))+ render(createElement(WorkingAnchor, { isRunning: true, conversationId: 'c1', label: 'Waiting for your approval' }))+ expect(anchor()).toContain('Waiting for your approval')+ expect(anchor()).not.toContain('Preparing')+ cleanup()+ render(createElement(WorkingAnchor, { isRunning: true, conversationId: 'c3' }))+ expect(anchor()).toContain('Working')+ })++ it('the store ignores a write that changes nothing, so a stream of deltas within one kB does not re-render', () => {+ let writes = 0+ const off = useRunActivityStore.subscribe(() => { writes++ })+ for (let chars = 1024; chars < 2048; chars += 37) {+ useRunActivityStore.getState().setActivity('c1', toolProgressActivity({ name: 'file_write', argsChars: chars }))+ }+ off()+ expect(writes).toBe(1)+ })+})diff --git a/src/hooks/__tests__/the-run-names-the-call-it-is-writing.test.ts b/src/hooks/__tests__/the-run-names-the-call-it-is-writing.test.tsnew file mode 100644index 00000000..faf89e96--- /dev/null+++ b/src/hooks/__tests__/the-run-names-the-call-it-is-writing.test.ts@@ -0,0 +1,115 @@+/**+ * @vitest-environment jsdom+ *+ * Realtime pass 01.10.2026 (R1), end to end through the Agent loop: while the+ * model's tool call is still streaming, the run anchor's store names the call+ * and the "Analyzing..." placeholder is gone; once the step is over the label+ * is cleared, so the anchor goes back to "Working" for the tool run and the+ * next step.+ *+ * Run: npx vitest run src/hooks/__tests__/the-run-names-the-call-it-is-writing.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act, waitFor } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({+ getAccessToken: async () => 'session-token-abc',+}))+vi.mock('../../api/rag', () => ({+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),+ generateEmbeddings: async () => [[0.1, 0.2]],+}))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))++import { useAgentChat } from '../useAgentChat'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useAgentModeStore } from '../../stores/agentModeStore'+import { useAgentTaskStore } from '../../stores/agentTaskStore'+import { useAgentLoopStore } from '../../stores/agentLoopStore'+import { useGenerationStore } from '../../stores/generationStore'+import { useTodoStore } from '../../stores/todoStore'+import { useToolAuditStore } from '../../stores/toolAuditStore'+import { useRunActivityStore } from '../../stores/runActivityStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'+import { __resetRunStopsForTests } from '../../lib/run-stop'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'++const MODEL = 'lu-cloud::zai-org/GLM-5.3'+const enc = new TextEncoder()+const line = (payload: object) => enc.encode(`data: ${JSON.stringify(payload)}\n\n`)++beforeEach(() => {+ registerBuiltinTools(toolRegistry)+ __resetRunStopsForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useAgentTaskStore.setState({ byConv: {} })+ useAgentLoopStore.setState({ loops: {} })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useAgentModeStore.setState({ agentModeActive: {} })+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+ useToolAuditStore.setState({ entries: {} })+ useRunActivityStore.setState({ activity: {} })+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off' } })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },+ }))+ useModelStore.setState({ models: [], activeModel: MODEL })+})+afterEach(() => vi.restoreAllMocks())++describe('the run names the call it is writing', () => {+ it('label while the arguments stream, placeholder gone, cleared after the step', async () => {+ let push!: (b: Uint8Array) => void+ let end!: () => void+ let calls = 0+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })+ calls+++ if (calls === 1) {+ const body = new ReadableStream<Uint8Array>({+ start(c) {+ push = (b) => c.enqueue(b)+ end = () => c.close()+ },+ })+ return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } })+ }+ return new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: 'Done.' } }] })}\n\ndata: [DONE]\n\n`, {+ status: 200, headers: { 'content-type': 'text/event-stream' },+ })+ })++ const { result } = renderHook(() => useAgentChat())+ const convId = useChatStore.getState().createConversation(MODEL, '')+ useChatStore.getState().setActiveConversation(convId)+ useAgentModeStore.getState().setAgentModeActive(convId, true)++ let run!: Promise<void>+ act(() => { run = result.current.sendAgentMessage('note a todo: buy milk') })+ await waitFor(() => expect(calls).toBe(1))+ await waitFor(() => expect(push).toBeTypeOf('function'))++ push(line({ choices: [{ delta: { tool_calls: [{ index: 0, id: 'c1', function: { name: 'todo_write', arguments: '' } }] } }] }))+ await waitFor(() => expect(useRunActivityStore.getState().activity[convId]?.label).toBe('Preparing todo_write'))+ const blocks = useChatStore.getState().conversations.find((c) => c.id === convId)!+ .messages.at(-1)!.agentBlocks ?? []+ expect(blocks.some((b) => b.phase === 'thinking' && b.content === 'Analyzing...')).toBe(false)++ push(line({ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '{"todos":[{"content":"buy milk","status":"pending"}]}' } }] } }] }))+ push(line({ choices: [{ delta: {}, finish_reason: 'tool_calls' }] }))+ push(enc.encode('data: [DONE]\n\n'))+ end()+ await act(async () => { await run })++ expect(calls).toBeGreaterThanOrEqual(2)+ expect(useRunActivityStore.getState().activity[convId]).toBeUndefined()+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 0129abdc..aeb0e06a 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -1,5 +1,6 @@import { useRef, useState, useCallback, useEffect } from 'react'import { frameFlush } from '../lib/frame-flush'+import { useRunActivityStore, toolProgressActivity } from '../stores/runActivityStore'import { markCannotThink } from '../lib/model-compatibility'import {type ApprovalEntry,@@ -86,7 +87,7 @@ import { toolFailureNote } from '../lib/tool-failure-note'import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'import { AgentLoopGuard } from '../lib/agent-loop-guard'import { budgetFromSettings } from '../api/agents/budget'-import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'+import type { ChatMessage, ToolCall, ToolCallProgress, ToolDefinition } from '../api/providers/types'import type { WorkflowEngineCallbacks } from '../types/agent-workflows'import { renderWorkflowStepList, workflowProgressHeader, type WorkflowStepView } from '../lib/workflow-progress-view'import { executeParallel, applyResultToToolCall, resultFailed, type ExecutionRequest } from '../api/agents/tool-executor'@@ -1147,6 +1148,8 @@ export function useAgentChat() {// Bind the generating flag to THIS conversation so the typing indicator// shows only in the chat whose turn is in flight (David 2026-06-12).useGenerationStore.getState().setGenerating(convId, true)+ // A run that threw mid-call left its label behind; this run starts clean.+ useRunActivityStore.getState().setActivity(convId, null)// Register so deleting/closing this chat stops the agent loop (Bug C).// requestGenerationCancel too, so a ComfyUI gen the agent kicked off is// interrupted when the chat is deleted mid-generation (gated to a no-op when@@ -1751,13 +1754,21 @@ export function useAgentChat() {scheduleUIUpdate()}}+ // A call still being written names itself on the run anchor+ // (stores/runActivityStore, realtime pass R1).+ const onToolProgress = (p: ToolCallProgress) => {+ // The call is the first output of the step: the "Analyzing..."+ // placeholder goes, as it does on the first token.+ dropThinkingBlock()+ useRunActivityStore.getState().setActivity(convId, toolProgressActivity(p))+ }const streamOpts = { ...chatOptions, tools }// Dasselbe wie im Ollama-Zweig, aus demselben Grund.let providerTurn!: Awaited<ReturnType<typeof streamProviderTurn>>let connRetries = 0for (;;) {try {- providerTurn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, onLiveContent, onLiveThinking)+ providerTurn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, onLiveContent, onLiveThinking, onToolProgress)break} catch (thinkErr) {// G22 parity with the Ollama branch: heal a wrong vision@@ -1776,7 +1787,7 @@ export function useAgentChat() {// number used to be in useChat.ts only, so this branch ended// the whole run where plain chat just retried.if (shouldDowngradeThinking(streamOpts.thinking, thinkErr)) {- providerTurn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {})+ providerTurn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {}, onToolProgress)break}const transient = asString(prop(thinkErr, 'name')) !== 'AbortError' && !isTerminalModelError(thinkErr)@@ -1792,6 +1803,7 @@ export function useAgentChat() {}}dropThinkingBlock()+ useRunActivityStore.getState().setActivity(convId, null)turn = providerTurn// Und jeder andere Transport nennt ihn `finish_reason`.turnFinishReason = providerTurn.finishReasondiff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 644fc7ba..f26a84fb 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -55,7 +55,8 @@ import { useStagedChangesStore, flushStagedPersist } from '../stores/stagedChangimport { log } from '../lib/logger'import type { AgentToolCall } from '../types/agent-mode'import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'-import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'+import type { ChatMessage, ToolCall, ToolCallProgress, ToolDefinition } from '../api/providers/types'+import { useRunActivityStore, toolProgressActivity } from '../stores/runActivityStore'import { executeParallel, applyResultToToolCall, resultFailed, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'import { useToolAuditStore } from '../stores/toolAuditStore'import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'@@ -970,6 +971,8 @@ export function useCodex() {// realtime counter show only in the coding chat that's actually running,// not in every chat the user switches to (David 2026-06-12). Cleared below.useGenerationStore.getState().setGenerating(convId, true)+ // A run that threw mid-call left its label behind; this run starts clean.+ useRunActivityStore.getState().setActivity(convId, null)// Register the abort in the STORE, not just in hook refs (audit A2). The// Code view unmounts on a tab switch and the remounted hook starts with// empty refs — before this, a run that survived the switch had no working@@ -1564,16 +1567,22 @@ export function useCodex() {useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, combined)}}+ // A call still being written names itself on the run anchor+ // (stores/runActivityStore, realtime pass R1).+ const onToolProgress = (p: ToolCallProgress) => {+ useRunActivityStore.getState().setActivity(convId, toolProgressActivity(p))+ }try {- turn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, liveContent, liveThinking)+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, liveContent, liveThinking, onToolProgress)} catch (thinkErr) {if (shouldDowngradeThinking(streamOpts.thinking, thinkErr)) {- turn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {}, onToolProgress)} else {throw thinkErr}}settleLivePaint()+ useRunActivityStore.getState().setActivity(convId, null)toolCalls = turn.toolCallsturnContent = turn.content || ''turnFinishReason = turn.finishReasondiff --git a/src/lib/provider-stream.ts b/src/lib/provider-stream.tsindex ce46a415..8636471c 100644--- a/src/lib/provider-stream.ts+++ b/src/lib/provider-stream.ts@@ -11,7 +11,8 @@** Callbacks receive the CUMULATIVE text first (what the existing UI paths* paint directly) and the raw delta second (what the Hermes display filter- * feeds on).+ * feeds on). `onToolProgress` hears about a call while its arguments are still+ * arriving, so the run can name it before the done chunk.*/import type {@@ -19,6 +20,7 @@ import type {ChatOptions,ProviderClient,ToolCall,+ ToolCallProgress,} from '../api/providers/types'export interface StreamedProviderTurn {@@ -48,6 +50,7 @@ export async function streamProviderTurn(options: ChatOptions,onContent?: (full: string, delta: string) => void,onThinking?: (full: string, delta: string) => void,+ onToolProgress?: (progress: ToolCallProgress) => void,): Promise<StreamedProviderTurn> {let content = ''let thinking = ''@@ -61,6 +64,7 @@ export async function streamProviderTurn(thinking += chunk.thinkingonThinking?.(thinking, chunk.thinking)}+ if (chunk.toolProgress) onToolProgress?.(chunk.toolProgress)if (chunk.done) {if (chunk.toolCalls?.length) turn.toolCalls = chunk.toolCallsturn.promptEvalCount = chunk.promptEvalCountdiff --git a/src/lib/release-notes.ts b/src/lib/release-notes.tsindex 8ce682ed..70ac2185 100644--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@ -170,6 +170,10 @@ export const RELEASE_NOTES: ReleaseNote[] = [title: 'Fixes in Chat and Create.',detail: 'An error message is no longer overwritten by the last frame of the answer, and Regenerate no longer deletes your question when nothing can be sent. Cancel on a render a GPU already took says it will finish and be charged, and a submit whose answer got lost no longer leaves a paid job you never see.',},+ {+ title: 'The run says which tool the model is writing.',+ detail: 'A model writing a long file sends the call in pieces for many seconds, and the run said only "Working" the whole time. It now shows the tool\'s name and how much of the call has arrived as soon as the first piece is in.',+ },{title: 'Code conversations stay in the Code tab.',detail: 'After a restart the last Code conversation opened in the Chat tab, where the agent was off and a "continue" ran without tools. The app now starts on an empty chat, and the Code button takes you back to the Code conversation you worked on last, also while a run is going.',diff --git a/src/stores/runActivityStore.ts b/src/stores/runActivityStore.tsnew file mode 100644index 00000000..31ae4305--- /dev/null+++ b/src/stores/runActivityStore.ts@@ -0,0 +1,47 @@+import { create } from 'zustand'+import type { ToolCallProgress } from '../api/providers/types'++/**+ * What a running turn is doing right now, when the run knows more than+ * "Working". Read by WorkingAnchor; an explicit label there (an approval wait,+ * a model load) still wins.+ *+ * Realtime pass 01.10.2026 (R1): while a model writes a tool call, the+ * arguments stream in for seconds (a 4 kB file_write took ~11 s on Mistral+ * Small, measured live) and the run said only "Working". The provider knows+ * the call's name from the first delta, so the anchor says it.+ *+ * Not persisted: a label from a crashed run must not survive a restart.+ */+export interface RunActivity {+ /** Announced to screen readers when it changes. */+ label: string+ /** A count that grows while the label stands (the call's size); shown, not announced. */+ detail?: string+}++interface RunActivityState {+ activity: Record<string, RunActivity>+ setActivity: (conversationId: string | null | undefined, activity: RunActivity | null) => void+}++export const useRunActivityStore = create<RunActivityState>((set) => ({+ activity: {},+ setActivity: (conversationId, activity) => {+ if (!conversationId) return+ set((state) => {+ const now = state.activity[conversationId]+ if (now?.label === activity?.label && now?.detail === activity?.detail) return state+ const next = { ...state.activity }+ if (activity) next[conversationId] = activity+ else delete next[conversationId]+ return { activity: next }+ })+ },+}))++/** "Preparing file_write", plus the size once a kilobyte has arrived. Whole kB, so the store changes at most once per kB. */+export function toolProgressActivity(progress: ToolCallProgress): RunActivity {+ const kb = Math.floor(progress.argsChars / 1024)+ return kb > 0 ? { label: `Preparing ${progress.name}`, detail: `${kb} kB` } : { label: `Preparing ${progress.name}` }+}