diff --git a/.changeset/mcp-auth-approval-precedence.md b/.changeset/mcp-auth-approval-precedence.md
new file mode 100644
index 0000000000..6d1911da91
--- /dev/null
+++ b/.changeset/mcp-auth-approval-precedence.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge-assistant-ui-runtime': patch
+'@truefoundry/trueforge-ui': patch
+---
+
+Prefer tool-approval chrome over MCP auth when both are pending, keep Connect/ask-user/custom prompts usable while siblings run without inventing paused turnState on later content, dismiss Continue without a blank Working gap, and show Cancelling feedback on the composer stop button.
diff --git a/docs/api/overview-v2.mdx b/docs/api/overview-v2.mdx
new file mode 100644
index 0000000000..1b2c026dde
--- /dev/null
+++ b/docs/api/overview-v2.mdx
@@ -0,0 +1,234 @@
+---
+title: 'SDK Concepts'
+sidebarTitle: 'Concepts (v2)'
+description: 'The mental model behind the SDK — Agent, Session, Turn, Event, and Delta — with one worked example.'
+---
+
+Already running? Jump to the [SDK Quickstart](/api/quickstart) to install and stream your first turn. This page is the mental model behind that code: how an [agent](#agent), a [session](#session), a [turn](#turn), an [event](#event), and a [delta](#delta) fit together. Once it clicks, [Use an agent](/api/use-agent-v2) is the runnable cookbook, and the **API Reference** tab has the raw HTTP schemas.
+
+## Core concepts
+
+Talking to an agent follows one hierarchy: **one Agent → many Sessions → many Turns → many Events → some Deltas**. The sections below walk through each layer with one running example: a customer support agent named **`support-bot`**.
+
+
+
+
+
+### Agent
+
+An **agent** is a definition, not a running process. You define it once (the model, instructions, tools, and config), and any number of conversations can use it. `support-bot` is a support assistant that looks up orders and processes refunds through an MCP server. Its [AgentSpec](/create-agent/overview#create-an-agent-via-the-api) looks like this:
+
+```json support-bot AgentSpec wrap
+{
+ "model": {
+ "name": "anthropic/claude-sonnet-4-6",
+ "params": { "max_tokens": 4096 }
+ },
+ "instructions": "You help customers with orders. Look up order details before taking action. Always confirm before processing refunds.",
+ "mcp_servers": [
+ {
+ "name": "orders-api",
+ "enable_tools": ["get_order", "process_refund"],
+ "require_approval_for_tools": ["process_refund"]
+ }
+ ],
+ "config": { "iteration_limit": 25 }
+}
+```
+
+Save this spec as a named agent and reference it by name in every session, or pass it inline when you create a session. The [agent spec reference](/create-agent/overview#create-an-agent-via-the-api) lists every field.
+
+### Session
+
+A **session** is one issue worked through with the agent. It holds the conversation context: every turn on that issue chains together, and the agent remembers what happened earlier in the same session. Each new issue gets its own session, whether it comes from the same customer or a different one.
+
+| Session | Issue | How it starts |
+| --------------- | -------------------------------- | ------------------------------------------ |
+| `sess-7f2a9c1b` | Jane, refund for order ORD-2031 | _"What's the status of order ORD-2031?"_ |
+| `sess-9d4e2a88` | Bob, shipping question | A different customer starts their own chat |
+
+Jane's follow-ups about the refund stay in `sess-7f2a9c1b`. Bob's question runs in a separate session, so the two conversations never share context.
+
+```json Session for Jane's refund issue wrap
+{
+ "id": "sess-7f2a9c1b",
+ "agent": { "type": "reference", "id": "agt_01jc...", "name": "support-bot" },
+ "title": "Refund for ORD-2031",
+ "created_by_subject": {
+ "subject_type": "user",
+ "subject_id": "trueforge-default",
+ "subject_display_name": "trueforge-default"
+ },
+ "created_at": "2026-06-24T10:00:00Z",
+ "updated_at": "2026-06-24T10:00:00Z"
+}
+```
+
+Persist the session `id` so Jane can come back tomorrow and pick up where she left off. Only one turn is active in a session at a time; sending a new message cancels a turn that is still running or waiting.
+
+Every session you run this way is also recorded in the [Sessions](/sessions) view, where you can inspect its turns, tool calls, subagents, and timing.
+
+### Turn
+
+A **turn** is one request in the conversation: Jane sends a message, and the agent works until it has an answer. Each time Jane sends a message, you create a new turn. Turns in a session **chain automatically** (`previous_turn_id` defaults to `"auto"`), so the agent sees every earlier turn without you resending history.
+
+Sometimes the agent needs something from Jane before it can finish: an approval for a gated tool, an answer to a question, or a sign-in to an MCP server. The turn then **pauses** and waits. Your app sends the answer to that same turn, and the agent picks up where it stopped.
+
+```mermaid
+flowchart LR
+ T1["Turn 1
Jane: status of ORD-2031?"]
+ T2["Turn 2
Jane: issue full refund"]
+ P["Turn 2 pauses
waiting for approval"]
+ T1 -->|"agent replies, Jane follows up"| T2
+ T2 --> P
+ P -->|"Jane approves, same turn continues"| T2
+```
+
+| Turn | Who sends it | Input | What happens |
+| ---------- | ------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| **Turn 1** | Jane (via your app) | `"What's the status of order ORD-2031?"` | Agent looks up the order and replies with shipping status. |
+| **Turn 2** | Jane | `"Please issue a full refund for that order."` | Agent prepares a refund and **pauses** for approval. Jane (or a support rep) approves; the agent runs the refund and confirms. |
+
+
+ A turn can also pause when the agent asks a clarifying question ([`tool.response_required`](/api/use-agent-v2#tool-response-required))
+ or needs MCP OAuth ([`mcp.auth_required`](/mcp-servers#in-chat-authentication)). You answer on the same turn, just like
+ the approval in Turn 2 above. See [Handle pauses](/api/use-agent-v2#handle-pauses).
+
+
+### Event
+
+While a turn runs, the agent emits **events** on the SDK stream, one JSON object at a time. Each event tells your app what the agent is doing: calling a tool, getting a result, writing a reply, waiting for you, or finishing.
+
+**Events during Turn 1** (Jane asks for order status):
+
+| Order | Event type | What your app learns |
+| ----- | --------------------- | ------------------------------------------------ |
+| 1 | `turn.created` | Turn started; carries `turn_id` |
+| 2 | `mcp.initialize` | Agent connected to `orders-api` |
+| 3 | `model.message` | Agent decided to call `get_order` |
+| 4 | `tool.response` | Order data: shipped, $1,240.00 |
+| 5 | `model.message` | Agent starts composing the reply (empty shell) |
+| 6–8 | `model.message.delta` | Reply text arriving in chunks (see [Delta](#delta)) |
+| 9 | `turn.done` | Turn finished; final reply in `state.output` |
+
+Sample payload:
+
+```json turn.done wrap
+{
+ "type": "turn.done",
+ "id": "01jc...",
+ "thread_id": null,
+ "created_at": "2026-06-24T10:00:09Z",
+ "state": {
+ "status": "done",
+ "output": {
+ "type": "model.message",
+ "content": "Your order ORD-2031 shipped on June 12. Total: $1,240.00."
+ },
+ "completed_at": "2026-06-24T10:00:09Z"
+ }
+}
+```
+
+**Events during Turn 2** (Jane asks for a refund, then approves it):
+
+| Order | Event type | What your app learns |
+| ----- | ------------------------ | ------------------------------------------------------------- |
+| 1 | `turn.created` | Turn started |
+| 2 | `model.message` | Agent decided to call `process_refund` |
+| 3 | `tool.approval_required` | That call needs approval; carries the tool call `id` |
+| 4 | `turn.update` | `status: "paused"`: the turn is waiting for Jane |
+| 5 | `user.tool_approval` | Jane's approval, which your app sent to the turn |
+| 6 | `turn.update` | `status: "running"`: the agent is working again |
+| 7 | `tool.response` | Refund result: RF-9914, completed |
+| 8 | `model.message` + deltas | The confirmation reply |
+| 9 | `turn.done` | Turn finished; confirmation in `state.output` |
+
+Every event carries an `id`. Most also carry a `thread_id` (`"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events). `user.tool_approval_policy` and `user.mcp_auth_continue` omit `thread_id`. The `id` is also how you [resume after a disconnect](/api/use-agent-v2#resume-a-stream): reconnect from the last event you saw. A new turn's stream opens with `turn.created` and closes with `turn.done`, and stays open while the turn is paused. Field-level schemas for every event type are in the [turn events reference](/api/use-agent-v2#turn-events-reference).
+
+### Delta
+
+Most events arrive as a complete payload. Model output is the exception: the LLM streams token by token, so the harness sends a base `model.message` event first, then a series of `model.message.delta` fragments that you merge into it. All deltas share the base event's `id`.
+
+The agent's full reply in Turn 1 is _"Your order ORD-2031 shipped on June 12. Total: $1,240.00."_ Your client receives:
+
+```json Base event (empty shell) wrap
+{ "type": "model.message", "id": "msg-a1", "thread_id": "main", "content": "" }
+```
+
+```json Deltas (merge into msg-a1 as they arrive) wrap
+{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": "Your order ORD-2031" }
+{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": " shipped on June 12." }
+{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": " Total: $1,240.00.", "finish_reason": "stop" }
+```
+
+Append each delta's `content` to the event with the matching `id` and re-render on every chunk. That's how the chat UI shows the reply word by word:
+
+```text wrap
+Your order ORD-2031
+Your order ORD-2031 shipped on June 12.
+Your order ORD-2031 shipped on June 12. Total: $1,240.00.
+```
+
+In the SDK, use TypeScript `isEventDelta` / `mergeEventDelta` or Python `is_event_delta` / `merge_event_delta` from `trueforge_sdk.events`. See [Create and stream a turn](/api/use-agent-v2#create-and-stream-a-turn).
+
+Deltas only exist on the live stream. When you list a turn's events afterwards (`GET .../events`), each `model.message` is already merged, so you use it directly.
+
+
+ A **thread** is a related idea: an execution context inside a turn. The root agent runs on `thread_id: "main"`, and
+ [subagents](/key-features/subagents) get their own thread ids, announced by `thread.created` / `thread.done`
+ events. Events carry `thread_id` so you can separate a single turn stream when subagents run in parallel.
+
+
+## The two turns, end to end
+
+Here is Jane's whole refund session: your app opens a session, runs turns, reads the streamed events, and answers the approval.
+
+```mermaid
+sequenceDiagram
+ actor App as Your app
+ participant TF as TrueForge · support-bot · main thread
+
+ Note over App,TF: Turn 1 — order status
+ App->>TF: sessions.create (agent: support-bot)
+ TF-->>App: { "id": "sess-7f2a9c1b" }
+ App->>TF: createTurnStream (user.message: "status of ORD-2031?")
+ TF-->>App: turn.created { turn_id: "turn-001", previous_turn_id: null }
+ TF-->>App: mcp.initialize { mcp_servers: [orders-api] }
+ TF-->>App: model.message — tool call get_order({ order_id: "ORD-2031" })
+ TF-->>App: tool.response { status: shipped, total: 1240.00 }
+ TF-->>App: model.message (id: msg-a1) + deltas: "Your order ORD-2031 shipped on June 12..."
+ TF-->>App: turn.done { output: reply }
+
+ Note over App,TF: Turn 2 — refund request, paused for approval
+ App->>TF: createTurnStream (user.message: "issue a full refund")
+ TF-->>App: turn.created { turn_id: "turn-002", previous_turn_id: "turn-001" }
+ TF-->>App: model.message (id: msg-b2) — tool call process_refund({ order_id, amount })
+ TF-->>App: tool.approval_required { tool_calls: [{ id: "call-refund-01" }] }
+ TF-->>App: turn.update { status: paused }
+
+ Note over App,TF: Jane approves — same turn, same stream
+ App->>TF: createTurnEvents (turn-002, user.tool_approval: allow call-refund-01)
+ TF-->>App: user.tool_approval { tool_call_id: "call-refund-01" }
+ TF-->>App: turn.update { status: running }
+ TF-->>App: tool.response { refund_id: "RF-9914", status: completed }
+ TF-->>App: model.message (id: msg-c3) + deltas: "Refund RF-9914 has been processed..."
+ TF-->>App: turn.done { output: confirmation }
+```
+
+| Turn | Jane's action | Ends with | What your app does next |
+| ---- | --------------------- | ------------------------ | -------------------------------------------------------------- |
+| 1 | Asks for order status | Reply in `output` | Show reply, wait for the next message |
+| 2 | Requests refund | Pauses for approval | Show approval UI, send Jane's decision to the same turn |
+| 2 | Approves refund | Confirmation in `output` | Show confirmation, issue closed |
+
+A separate issue (Bob's shipping question, or Jane's next problem) runs in its own session, where Turn 1 starts fresh with no refund history.
+
+## Next steps
+
+- [SDK Quickstart](/api/quickstart) installs the SDK, connects with a token, and streams your first turn.
+- [Use an agent](/api/use-agent-v2) is the full cookbook: streaming, approvals, questions, threads, and reconnects.
+- The **API Reference** tab has the raw HTTP endpoints and OpenAPI schemas.
diff --git a/docs/api/use-agent-v2.mdx b/docs/api/use-agent-v2.mdx
new file mode 100644
index 0000000000..0dde672e11
--- /dev/null
+++ b/docs/api/use-agent-v2.mdx
@@ -0,0 +1,1993 @@
+---
+title: 'Use an agent'
+sidebarTitle: 'Use an agent (v2)'
+description: 'Run a saved agent with the TypeScript or Python SDK: a Quick Start, then recipes for streaming, approvals, questions, threads, and reconnects.'
+---
+
+The recipe book for running an agent with [`@truefoundry/trueforge-sdk`](https://www.npmjs.com/package/@truefoundry/trueforge-sdk) or [`trueforge-sdk`](https://pypi.org/project/trueforge-sdk/). New here? Install and stream your first turn in the [SDK Quickstart](/api/quickstart) first. For the mental model (Agent → Session → Turn → Event → Delta), see [Concepts](/api/overview-v2); for every event field, see the [turn events reference](#turn-events-reference) at the bottom of this page.
+
+
+Prerequisite: a named agent in the registry, or an inline [agent spec](/create-agent/overview#create-an-agent-via-the-api) you pass when creating the session. The examples below run the **`web-research-brief`** agent from the [Quickstart](/quickstart); build it there first, or swap in your own agent name / inline spec.
+
+
+Every snippet is self-contained and runnable. They all use the `client` from [Install and connect](#install-and-connect).
+
+## Install and connect
+
+
+```bash TypeScript wrap
+npm i @truefoundry/trueforge-sdk
+```
+
+```bash Python wrap
+pip install trueforge-sdk
+```
+
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600, // raise for long-running SSE turns (default 60s)
+ // token: process.env.TRUEFORGE_TOKEN, // ID token when OIDC login is enabled
+});
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600, # raise for long-running SSE turns (default 60s)
+ # ID token when OIDC login is enabled.
+ # token=os.environ.get("TRUEFORGE_TOKEN"),
+)
+```
+
+
+Point `baseUrl` / `base_url` at your running TrueForge server; `http://localhost:8790` is the Quickstart default. When [OIDC login](/authentication/overview) is enabled, pass `token` (an ID token from your IdP; see [Get a token and connect](/api/quickstart#get-a-token-and-connect)). When login is off, omit it. TypeScript fields are camelCase; Python fields match the wire format (`snake_case`).
+
+## Quick Start
+
+The [Concepts](/api/overview-v2) page explains the model with a conceptual `support-bot`; here is a real agent you can run. In the [Quickstart](/quickstart) you built **`web-research-brief`**, an agent with Exa web search and the web-artifacts-builder skill. Here it is from the SDK: open a session on that agent, stream one research turn, and print the brief as it arrives. It fans out to [subagents](/key-features/subagents), so you'll see their threads in the same stream. It has no approval gate, so it runs end to end without waiting on you; for approvals and questions, see [Handle pauses](#handle-pauses).
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+
+// The agent you saved in the Quickstart.
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content:
+ 'Compare Qdrant, Weaviate, and Milvus on performance, features, '
+ + 'and licensing, then write a one-page brief with sources.',
+ },
+ ],
+});
+
+for await (const event of stream) {
+ if (event.type === 'thread.created')
+ console.log(`\n↳ subagent: ${event.title}`);
+ if (event.type === 'model.message.delta' && event.threadId === 'main') {
+ // The root agent's reply, streaming in.
+ process.stdout.write(event.content ?? '');
+ }
+ if (event.type === 'turn.done' && event.state.status === 'done') {
+ console.log('\n\n--- brief ---\n', event.state.output?.content ?? '');
+ }
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+
+# The agent you saved in the Quickstart.
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": (
+ "Compare Qdrant, Weaviate, and Milvus on performance, "
+ "features, and licensing, then write a one-page brief "
+ "with sources."
+ ),
+ },
+ ],
+) as stream:
+ for event in stream:
+ if event.type == "thread.created":
+ print(f"\n↳ subagent: {event.title}")
+ if event.type == "model.message.delta" and event.thread_id == "main":
+ print(event.content or "", end="", flush=True)
+ if event.type == "turn.done" and event.state.status == "done":
+ output = event.state.output
+ print(
+ "\n\n--- brief ---\n",
+ None if output is None else output.content,
+ )
+```
+
+
+That's the core loop: open a session, stream a turn, print the reply as it arrives, and read the final `turn.done`. This version writes each delta straight to stdout. The [next section](#create-and-stream-a-turn) keeps an id-keyed event index, the pattern the pause recipes build on. The rest of the page is a reference for each piece, plus the pauses (approvals, questions, MCP auth) a real agent runs into.
+
+## Sessions
+
+A **session** is the conversation context for one issue; it persists across turns. Persist `session.id` to resume later.
+
+```mermaid
+stateDiagram-v2
+ [*] --> active: sessions.create()
+ active --> active: createTurnStream() (many turns)
+ active --> cancelled: sessions.cancel()
+ cancelled --> [*]
+```
+
+### Open a session
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+});
+
+// By saved agent name:
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+// …or with an inline spec (no saved agent needed):
+const { data: inlineSession } = await client.sessions.create({
+ agent: {
+ spec: {
+ model: { name: 'anthropic/claude-sonnet-4-6' },
+ instructions: 'You are a concise research assistant.',
+ },
+ },
+});
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790")
+)
+
+# By saved agent name:
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+# …or with an inline spec (no saved agent needed):
+inline_session = client.sessions.create(
+ agent={
+ "spec": {
+ "model": {"name": "anthropic/claude-sonnet-4-6"},
+ "instructions": "You are a concise research assistant.",
+ },
+ },
+)
+```
+
+
+### List sessions
+
+Newest-first; filter with `agentId` / `agent_id`. TypeScript returns a `Page` async iterable; Python returns a `SyncPager`. Both auto-paginate.
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+});
+
+for await (const session of await client.sessions.list()) {
+ console.log(session.id, session.createdAt);
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790")
+)
+
+for session in client.sessions.list():
+ print(session.id, session.created_at)
+```
+
+
+## Turns
+
+A **turn** is one request/response cycle: you send a message, and the agent works until it has an answer. If it needs something from you along the way (an approval, an answer, or an MCP sign-in), the turn **pauses** and waits. You answer on the same turn and it carries on. Turns chain automatically (`previousTurnId` defaults to `"auto"`), so you never resend history.
+
+```mermaid
+stateDiagram-v2
+ [*] --> running: createTurnStream()
+ running --> paused: agent needs your input
+ paused --> running: you answer with createTurnEvents()
+ running --> done
+ running --> error
+ running --> cancelled: sessions.cancel() or a new message
+ paused --> cancelled: sessions.cancel() or a new message
+ done --> [*]
+ error --> [*]
+ cancelled --> [*]
+```
+
+
+Only one turn is active in a session at a time. Sending a new message cancels a turn that is still running or waiting for an answer, and the new turn picks up from there.
+
+
+### Create and stream a turn
+
+`createTurnStream` / `create_turn_stream` returns a stream of [turn events](#turn-events-reference). The stream opens with `turn.created` and closes with `turn.done`; read the final result from `turn.done.state`. If the turn pauses, stop reading there and continue with [Handle pauses](#handle-pauses): subscribe, send your answer, then read.
+
+Keep an **`id`-keyed event index**. Model output streams as an empty `model.message` base followed by `model.message.delta` fragments that share the base's `id`. Store each non-delta event under its `id` and merge each delta into the base with TypeScript `isEventDelta` / `mergeEventDelta` or Python `is_event_delta` / `merge_event_delta` (`from trueforge_sdk.events import …`). (Deltas appear only while streaming; [`listTurnEvents`](#replay-a-turn) / `list_turn_events` returns them already merged.) Pause handlers and the per-thread index below reuse this pattern.
+
+Also keep the turn id (from `turn.created`) and the `id` of the last event you received. You need the turn id to answer a paused turn, and the last event id to [resume the stream](#resume-a-stream) if the connection drops.
+
+
+```typescript TypeScript wrap
+import {
+ TrueForge,
+ TrueForgeApi,
+ isEventDelta,
+ mergeEventDelta,
+} from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const events = new Map();
+let turnId: string | undefined;
+let lastEventId: string | undefined;
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: 'Summarize the current state of open-source vector databases.',
+ },
+ ],
+});
+for await (const event of stream) {
+ lastEventId = event.id;
+ if (event.type === 'turn.created') turnId = event.turnId;
+ if (isEventDelta(event)) {
+ const base = events.get(event.id);
+ if (base) mergeEventDelta(base, event);
+ } else {
+ events.set(event.id, event);
+ }
+ if (event.type === 'turn.done') console.log('status:', event.state.status);
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+from trueforge_sdk.events import is_event_delta, merge_event_delta
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+events = {}
+turn_id = None
+last_event_id = None
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": (
+ "Summarize the current state of open-source vector databases."
+ ),
+ }
+ ],
+) as stream:
+ for event in stream:
+ last_event_id = event.id
+ if event.type == "turn.created":
+ turn_id = event.turn_id
+ if is_event_delta(event):
+ base = events.get(event.id)
+ if base is not None:
+ merge_event_delta(base, event)
+ else:
+ events[event.id] = event
+ if event.type == "turn.done":
+ print("status:", event.state.status)
+```
+
+
+A turn's `input` is one or more `user.message` items. `content` is a non-empty string, or an array of `text` / `file` parts (files as data URIs). Approvals, answers, and MCP sign-ins are not part of `input`; you send them to the paused turn, as shown in [Handle pauses](#handle-pauses).
+
+### Non-streaming turn
+
+If you don't need live events, TypeScript `sessions.createTurn` (`stream: false`) and Python `sessions.create_turn` return immediately with `state.status: "running"` and run in the background. Poll `getTurn` / `get_turn` while the status is `running`. When it stops, the turn has either finished (`done`, `cancelled`, `error`) or is `paused` and waiting for you; see [Answer later](#answer-later) for how to find out what it needs.
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const { data: created } = await client.sessions.createTurn(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: 'Give me a one-paragraph summary of the Qdrant licensing model.',
+ },
+ ],
+});
+
+let turn = created;
+while (turn.state.status === 'running') {
+ await new Promise(resolve => setTimeout(resolve, 500));
+ ({ data: turn } = await client.sessions.getTurn(session.id, created.id));
+}
+// done → output; paused → waiting for you; else reason / message
+console.log(turn.state);
+```
+
+```python Python wrap
+import os
+import time
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790")
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+created = client.sessions.create_turn(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": (
+ "Give me a one-paragraph summary of the Qdrant licensing model."
+ ),
+ }
+ ],
+)
+
+turn = created.data
+while turn.state.status == "running":
+ time.sleep(0.5)
+ turn = client.sessions.get_turn(
+ session_id=session.data.id, turn_id=created.data.id
+ ).data
+print(
+ turn.state
+) # done → output; paused → waiting for you; else reason / message
+```
+
+
+### List turns
+
+Oldest-first; each turn exposes its `input` and `state`.
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+});
+
+for await (const turn of await client.sessions.listTurns('sess-abc123')) {
+ console.log(turn.id, turn.state.status);
+ if (turn.state.status === 'done' && turn.state.output != null) {
+ console.log(turn.state.output.content);
+ }
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790")
+)
+
+for turn in client.sessions.list_turns(session_id="sess-abc123"):
+ print(turn.id, turn.state.status)
+ if turn.state.status == "done" and turn.state.output is not None:
+ print(turn.state.output.content)
+```
+
+
+### Attach images or files
+
+A `user.message`'s `content` can be an array of parts: text plus one or more files as [data URIs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) (`data:;base64,`).
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+import { readFileSync } from 'node:fs';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const toDataUri = (path: string, mime: string) =>
+ `data:${mime};base64,${readFileSync(path).toString('base64')}`;
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: [
+ { type: 'text', text: 'Use this chart in the brief.' },
+ {
+ type: 'file',
+ name: 'benchmarks.png',
+ data: toDataUri('benchmarks.png', 'image/png'),
+ },
+ ],
+ },
+ ],
+});
+for await (const event of stream) console.log(event.type);
+```
+
+```python Python wrap
+import base64
+import os
+from pathlib import Path
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+
+def to_data_uri(path: str, mime: str) -> str:
+ payload = base64.b64encode(Path(path).read_bytes()).decode("ascii")
+ return f"data:{mime};base64,{payload}"
+
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": [
+ {"type": "text", "text": "Use this chart in the brief."},
+ {
+ "type": "file",
+ "name": "benchmarks.png",
+ "data": to_data_uri("benchmarks.png", "image/png"),
+ },
+ ],
+ },
+ ],
+) as stream:
+ for event in stream:
+ print(event.type)
+```
+
+
+
+Whether a file is understood depends on the agent's model, so send images only to a vision-capable model. Non-image files (e.g. PDFs) need the [sandbox](/sandbox) enabled on the agent; the harness uses it to process the document.
+
+
+### Cancel a turn
+
+`sessions.cancel(sessionId)` / `sessions.cancel(session_id=…)` stops the session's active turn, whether it is running or paused waiting for you. It aborts the in-flight model request, waits for running MCP tool calls to finish, and force-stops any sandbox the turn provisioned. It's idempotent, and the backend closes the SSE stream gracefully (a terminal `turn.done`, then it ends, so don't `break`). Continue by creating a new turn, which chains on the cancelled turn's history.
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: 'Run a deep comparison across a dozen vector databases.',
+ },
+ ],
+});
+let i = 0;
+for await (const event of stream) {
+ // The stream ends itself after the terminal turn.done.
+ if (i++ === 5) await client.sessions.cancel(session.id);
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": "Run a deep comparison across a dozen vector databases.",
+ }
+ ],
+) as stream:
+ i = 0
+ for event in stream:
+ if i == 5:
+ # The stream ends itself after the terminal turn.done.
+ client.sessions.cancel(session_id=session.data.id)
+ i += 1
+```
+
+
+## Handle pauses
+
+A turn **pauses** when the agent needs something from you. You'll first see an event saying what it needs, then a [`turn.update`](#turn-update) with `state.status: "paused"`. The turn isn't over. Read until that point and keep the id of the last event, then:
+
+1. Open `subscribeToTurn` / `subscribe_to_turn` from that event id.
+2. Send your answers to the same turn with `createTurnEvents` / `create_turn_events`.
+3. Read the subscription. It carries everything your answer produces, through to `turn.done` or the next pause.
+
+Subscribe before you send, so the events the answer produces arrive on a stream you're about to read. A turn can pause more than once; each time, subscribe, send, then read.
+
+| The agent emits | It's waiting for | You send |
+| --- | --- | --- |
+| [`tool.approval_required`](#tool-approval-required) | A decision on a gated tool call | `user.tool_approval` (allow or deny) for each call |
+| [`tool.response_required`](#tool-response-required) | An answer to a question, or a client-side tool result | `user.tool_response` for each call |
+| [`mcp.auth_required`](#mcp-auth-required) | The user to sign in to an MCP server | `user.mcp_auth_continue` once they have |
+
+A turn can wait on several things at once (e.g. parallel subagents each hit a gate), so collect every prompt. The turn continues once everything it was waiting for is answered. You can send all the answers in one call, or a few at a time.
+
+For approvals and questions, each pending call in `tool_calls` has an `id` (the tool call you answer, as `tool_call_id`) and a `source_event_id` pointing at the [`model.message`](#model-message) that made the call. Look it up in the [event index](#create-and-stream-a-turn) to read the tool's name and arguments.
+
+The answers you send also show up on the stream as events (`user.tool_approval`, `user.tool_response`, `user.tool_approval_policy`, `user.mcp_auth_continue`). So the stream always tells you what is still open: a call is waiting until a matching answer with its `tool_call_id` appears or a [session approval](#approve-a-tool-for-the-rest-of-the-session) covers its tool, and an MCP sign-in is waiting until a `user.mcp_auth_continue` follows it. [Answer later](#answer-later) shows how to work this out from the turn's events.
+
+
+`web-research-brief` won't pause on its own; it has no gated tool or clarifying-question step. The snippets below are **illustrative**: point them at an agent that has a `require_approval_for_tools` tool, uses `ask_user_question`, or connects to an MCP server needing OAuth.
+
+
+### Tool approvals
+
+A gated tool ([human approval](/create-agent/overview#what’s-in-an-agent)) emits [`tool.approval_required`](#tool-approval-required). Read until the turn pauses and collect the pending calls. Then subscribe from the last event, send one `user.tool_approval` per call (allow, or deny with a reason), and read that subscription.
+
+
+```typescript TypeScript wrap
+import {
+ TrueForge,
+ TrueForgeApi,
+ isEventDelta,
+ mergeEventDelta,
+} from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'ops-bot' },
+});
+
+const events = new Map();
+const pendingApprovals: TrueForgeApi.ToolApprovalRequiredEvent[] = [];
+let turnId: string | undefined;
+let lastEventId: string | undefined;
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [{ type: 'user.message', content: 'Restart the billing service.' }],
+});
+for await (const event of stream) {
+ lastEventId = event.id;
+ if (isEventDelta(event)) {
+ const base = events.get(event.id);
+ if (base) mergeEventDelta(base, event);
+ } else {
+ events.set(event.id, event);
+ }
+ if (event.type === 'turn.created') turnId = event.turnId;
+ if (event.type === 'tool.approval_required') pendingApprovals.push(event);
+ if (event.type === 'turn.update' && event.state.status === 'paused') break;
+}
+
+const approvals: TrueForgeApi.TurnUserEventMessage[] = [];
+for (const pending of pendingApprovals) {
+ for (const ref of pending.toolCalls) {
+ const msg = events.get(ref.sourceEventId);
+ if (msg?.type !== 'model.message') continue;
+ const call = msg.toolCalls?.find(tc => tc.id === ref.id);
+ if (!call) continue;
+ console.log(
+ `approve ${call.toolInfo.name}? args: ${call.function.arguments}`,
+ );
+ approvals.push({
+ type: 'user.tool_approval',
+ threadId: pending.threadId,
+ toolCallId: ref.id,
+ // or { status: 'deny', reason: 'denied by user' }
+ approval: { status: 'allow' },
+ });
+ }
+}
+
+// Subscribe first, then send, then read what the answer produces.
+const resume = await client.sessions.subscribeToTurn(
+ session.id,
+ turnId!,
+ { afterEventId: lastEventId },
+ { timeoutInSeconds: 600 },
+);
+await client.sessions.createTurnEvents(session.id, turnId!, {
+ events: approvals,
+});
+for await (const event of resume) {
+ if (event.type === 'turn.done') console.log('status:', event.state.status);
+ // Handle other event types.
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+from trueforge_sdk.events import is_event_delta, merge_event_delta
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "ops-bot"})
+
+events = {}
+pending_approvals = []
+turn_id = None
+last_event_id = None
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[{"type": "user.message", "content": "Restart the billing service."}],
+) as stream:
+ for event in stream:
+ last_event_id = event.id
+ if is_event_delta(event):
+ base = events.get(event.id)
+ if base is not None:
+ merge_event_delta(base, event)
+ else:
+ events[event.id] = event
+ if event.type == "turn.created":
+ turn_id = event.turn_id
+ if event.type == "tool.approval_required":
+ pending_approvals.append(event)
+ if event.type == "turn.update" and event.state.status == "paused":
+ break
+
+approvals = []
+for pending in pending_approvals:
+ for ref in pending.tool_calls:
+ msg = events.get(ref.source_event_id)
+ if msg is None or msg.type != "model.message":
+ continue
+ call = next(
+ (tc for tc in (msg.tool_calls or []) if tc.id == ref.id), None
+ )
+ if call is None:
+ continue
+ print(f"approve {call.tool_info.name}? args: {call.function.arguments}")
+ approvals.append(
+ {
+ "type": "user.tool_approval",
+ "thread_id": pending.thread_id,
+ "tool_call_id": ref.id,
+ "approval": {
+ "status": "allow"
+ }, # or {"status": "deny", "reason": "denied by user"}
+ }
+ )
+
+with client.sessions.subscribe_to_turn(
+ session_id=session.data.id,
+ turn_id=turn_id,
+ after_event_id=last_event_id,
+ request_options={"timeout": 600},
+) as resume:
+ client.sessions.create_turn_events(
+ session_id=session.data.id, turn_id=turn_id, events=approvals
+ )
+ for event in resume:
+ if event.type == "turn.done":
+ print("status:", event.state.status)
+ # Handle other event types.
+```
+
+
+#### Approve a tool for the rest of the session
+
+For a tool on an MCP server, you can approve every call to it for the rest of the session instead of one call at a time. Send a `user.tool_approval_policy` with the MCP server name and the tool name. It also approves calls to that tool that are already waiting, so send it **instead of** a `user.tool_approval` for those calls. Add `expireAt` / `expire_at` (an ISO 8601 time) to make the approval expire.
+
+Where you read the server and tool name depends on how the agent loads tools:
+
+- **Preloaded tools** arrive as the tool itself. `toolInfo` / `tool_info` has `type: "mcp"` with `serverName` / `server_name` and `name`.
+- **Deferred tools** (the default, see [Deferred tool loading](/key-features/deferred-tool-loading)) arrive as a `call_tool` call whose `toolInfo` / `tool_info` is `type: "truefoundry-system"`. The real server and tool are in its arguments as `mcp_server` and `tool_name`.
+
+In the recipe above, replace the `user.tool_approval` push with the following. A call that isn't an MCP tool falls back to a normal one-off approval.
+
+
+```typescript TypeScript wrap
+// Server and tool behind a call, or undefined if it isn't an MCP tool.
+function mcpTarget(call: TrueForgeApi.ToolCall) {
+ if (call.toolInfo.type === 'mcp') {
+ return { server: call.toolInfo.serverName, tool: call.toolInfo.name };
+ }
+ if (call.toolInfo.name !== 'call_tool') return undefined;
+ const args = JSON.parse(call.function.arguments || '{}') as {
+ mcp_server?: string;
+ tool_name?: string;
+ };
+ if (!args.mcp_server || !args.tool_name) return undefined;
+ return { server: args.mcp_server, tool: args.tool_name };
+}
+
+const target = mcpTarget(call);
+if (target) {
+ approvals.push({
+ type: 'user.tool_approval_policy',
+ policies: [
+ {
+ serverName: target.server,
+ name: target.tool,
+ // Add expireAt: '2026-06-24T18:00:00Z' to expire.
+ policy: { type: 'allow_session' },
+ },
+ ],
+ });
+} else {
+ approvals.push({
+ type: 'user.tool_approval',
+ threadId: pending.threadId,
+ toolCallId: ref.id,
+ approval: { status: 'allow' },
+ });
+}
+```
+
+```python Python wrap
+import json
+
+
+def mcp_target(call):
+ """Server and tool behind a call, or None if it isn't an MCP tool."""
+ if call.tool_info.type == "mcp":
+ return call.tool_info.server_name, call.tool_info.name
+ if call.tool_info.name != "call_tool":
+ return None
+ args = json.loads(call.function.arguments or "{}")
+ if "mcp_server" not in args or "tool_name" not in args:
+ return None
+ return args["mcp_server"], args["tool_name"]
+
+
+target = mcp_target(call)
+if target is None:
+ approvals.append(
+ {
+ "type": "user.tool_approval",
+ "thread_id": pending.thread_id,
+ "tool_call_id": ref.id,
+ "approval": {"status": "allow"},
+ }
+ )
+else:
+ server_name, tool_name = target
+ approvals.append(
+ {
+ "type": "user.tool_approval_policy",
+ "policies": [
+ {
+ "server_name": server_name,
+ "name": tool_name,
+ "policy": {
+ "type": "allow_session"
+ }, # add "expire_at": "2026-06-24T18:00:00Z" to expire
+ }
+ ],
+ }
+ )
+```
+
+
+### Agent questions
+
+When the agent uses the built-in [`ask_user_question`](/create-agent/overview#what’s-in-an-agent) tool, it emits [`tool.response_required`](#tool-response-required); the pending call's `arguments` carry the `question` and `options`. Read until the turn pauses, then subscribe, send one `user.tool_response` per pending call, and read on.
+
+
+```typescript TypeScript wrap
+import {
+ TrueForge,
+ TrueForgeApi,
+ isEventDelta,
+ mergeEventDelta,
+} from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'ops-bot' },
+});
+
+const events = new Map();
+const pendingQuestions: TrueForgeApi.ToolResponseRequiredEvent[] = [];
+let turnId: string | undefined;
+let lastEventId: string | undefined;
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: 'Create a new environment called testing-1.',
+ },
+ ],
+});
+for await (const event of stream) {
+ lastEventId = event.id;
+ if (isEventDelta(event)) {
+ const base = events.get(event.id);
+ if (base) mergeEventDelta(base, event);
+ } else {
+ events.set(event.id, event);
+ }
+ if (event.type === 'turn.created') turnId = event.turnId;
+ if (event.type === 'tool.response_required') pendingQuestions.push(event);
+ if (event.type === 'turn.update' && event.state.status === 'paused') break;
+}
+
+const responses: TrueForgeApi.TurnUserEventMessage[] = [];
+for (const pending of pendingQuestions) {
+ for (const ref of pending.toolCalls) {
+ const msg = events.get(ref.sourceEventId);
+ if (msg?.type !== 'model.message') continue;
+ const call = msg.toolCalls?.find(tc => tc.id === ref.id);
+ // tool.response_required covers any client-side tool.
+ // Handle ask_user_question here.
+ if (
+ call?.toolInfo.type !== 'truefoundry-system' ||
+ call.toolInfo.name !== 'ask_user_question'
+ )
+ continue;
+ const { question, options } = JSON.parse(
+ call.function.arguments || '{}',
+ ) as { question?: string; options?: string[] };
+ console.log(question, options);
+ responses.push({
+ type: 'user.tool_response',
+ threadId: pending.threadId,
+ toolCallId: ref.id,
+ content: 'the chosen option, or any text', // free-form answer
+ });
+ }
+}
+
+const resume = await client.sessions.subscribeToTurn(
+ session.id,
+ turnId!,
+ { afterEventId: lastEventId },
+ { timeoutInSeconds: 600 },
+);
+await client.sessions.createTurnEvents(session.id, turnId!, {
+ events: responses,
+});
+for await (const event of resume) {
+ if (event.type === 'turn.done') console.log('status:', event.state.status);
+ // Handle other event types.
+}
+```
+
+```python Python wrap
+import json
+import os
+from trueforge_sdk import TrueForge
+from trueforge_sdk.events import is_event_delta, merge_event_delta
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "ops-bot"})
+
+events = {}
+pending_questions = []
+turn_id = None
+last_event_id = None
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": "Create a new environment called testing-1.",
+ }
+ ],
+) as stream:
+ for event in stream:
+ last_event_id = event.id
+ if is_event_delta(event):
+ base = events.get(event.id)
+ if base is not None:
+ merge_event_delta(base, event)
+ else:
+ events[event.id] = event
+ if event.type == "turn.created":
+ turn_id = event.turn_id
+ if event.type == "tool.response_required":
+ pending_questions.append(event)
+ if event.type == "turn.update" and event.state.status == "paused":
+ break
+
+responses = []
+for pending in pending_questions:
+ for ref in pending.tool_calls:
+ msg = events.get(ref.source_event_id)
+ if msg is None or msg.type != "model.message":
+ continue
+ call = next(
+ (tc for tc in (msg.tool_calls or []) if tc.id == ref.id), None
+ )
+ if call is None:
+ continue
+ # tool.response_required covers any client-side tool.
+ # Handle ask_user_question here.
+ if (
+ call.tool_info.type != "truefoundry-system"
+ or call.tool_info.name != "ask_user_question"
+ ):
+ continue
+ payload = json.loads(call.function.arguments or "{}")
+ print(payload.get("question"), payload.get("options"))
+ responses.append(
+ {
+ "type": "user.tool_response",
+ "thread_id": pending.thread_id,
+ "tool_call_id": ref.id,
+ "content": "the chosen option, or any text",
+ }
+ )
+
+with client.sessions.subscribe_to_turn(
+ session_id=session.data.id,
+ turn_id=turn_id,
+ after_event_id=last_event_id,
+ request_options={"timeout": 600},
+) as resume:
+ client.sessions.create_turn_events(
+ session_id=session.data.id, turn_id=turn_id, events=responses
+ )
+ for event in resume:
+ if event.type == "turn.done":
+ print("status:", event.state.status)
+ # Handle other event types.
+```
+
+
+### MCP outbound auth
+
+When a tool needs a server's OAuth, the agent emits [`mcp.auth_required`](#mcp-auth-required), listing each server and its `authUrl`, and the turn pauses. Send the user there. Once they've signed in, subscribe, send `user.mcp_auth_continue`, and read on. The agent picks up the interrupted work. See [In-chat authentication](/mcp-servers#in-chat-authentication).
+
+
+```typescript TypeScript wrap
+import { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'github-bot' },
+});
+
+let turnId: string | undefined;
+let lastEventId: string | undefined;
+let pendingAuth: TrueForgeApi.McpAuthRequiredEvent | undefined;
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ { type: 'user.message', content: 'Summarize my latest GitHub issues.' },
+ ],
+});
+for await (const event of stream) {
+ lastEventId = event.id;
+ if (event.type === 'turn.created') turnId = event.turnId;
+ if (event.type === 'mcp.auth_required') pendingAuth = event;
+ if (event.type === 'turn.update' && event.state.status === 'paused') break;
+}
+
+if (pendingAuth != null) {
+ for (const server of pendingAuth.mcpServers) {
+ console.log(`Authorize ${server.name}: ${server.authUrl}`);
+ }
+ // …wait for the user to authorize the server(s)…
+}
+
+const resume = await client.sessions.subscribeToTurn(
+ session.id,
+ turnId!,
+ { afterEventId: lastEventId },
+ { timeoutInSeconds: 600 },
+);
+await client.sessions.createTurnEvents(session.id, turnId!, {
+ events: [{ type: 'user.mcp_auth_continue' }],
+});
+for await (const event of resume) {
+ if (event.type === 'turn.done') console.log('status:', event.state.status);
+ // Handle other event types.
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "github-bot"})
+
+turn_id = None
+last_event_id = None
+pending_auth = None
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": "Summarize my latest GitHub issues.",
+ }
+ ],
+) as stream:
+ for event in stream:
+ last_event_id = event.id
+ if event.type == "turn.created":
+ turn_id = event.turn_id
+ if event.type == "mcp.auth_required":
+ pending_auth = event
+ if event.type == "turn.update" and event.state.status == "paused":
+ break
+
+if pending_auth is not None:
+ for server in pending_auth.mcp_servers:
+ print(f"Authorize {server.name}: {server.auth_url}")
+ # …wait for the user to authorize the server(s)…
+
+with client.sessions.subscribe_to_turn(
+ session_id=session.data.id,
+ turn_id=turn_id,
+ after_event_id=last_event_id,
+ request_options={"timeout": 600},
+) as resume:
+ client.sessions.create_turn_events(
+ session_id=session.data.id,
+ turn_id=turn_id,
+ events=[{"type": "user.mcp_auth_continue"}],
+ )
+ for event in resume:
+ if event.type == "turn.done":
+ print("status:", event.state.status)
+ # Handle other event types.
+```
+
+
+### Answer later
+
+The answer doesn't have to come while you hold the stream open. If a person needs time to review, stop reading, save the session id and turn id, and come back later, even from a different process. A paused turn keeps waiting until you answer it, [cancel](#cancel-a-turn) it, or send a new message. Time spent waiting doesn't count toward the turn's execution time limit.
+
+When you come back, [list the turn's events](#replay-a-turn) and work out what it is still waiting on:
+
+- **Approvals and questions**: every call in a `tool.approval_required` or `tool.response_required` that has no matching `user.tool_approval` or `user.tool_response` yet.
+- **Session approvals**: a `user.tool_approval_policy` also settles the waiting calls to its tools, without a separate `user.tool_approval` for each. Match each waiting call's server and tool (see [Approve a tool for the rest of the session](#approve-a-tool-for-the-rest-of-the-session)) against the policies. An approval that had already expired when it was sent settles nothing.
+- **MCP sign-in**: an `mcp.auth_required` with no `user.mcp_auth_continue` after it.
+
+Then [subscribe](#resume-a-stream) from the last event, send the answers, and read that subscription. Don't answer anything that is already settled: the request fails with `400` and none of its answers are applied.
+
+
+```typescript TypeScript wrap
+import { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const sessionId = 'sess-abc123'; // saved earlier
+const turnId = 'turn-abc123'; // saved earlier
+
+// Server and tool behind a call, or undefined if it isn't an MCP tool.
+function mcpTarget(call: TrueForgeApi.ToolCall) {
+ if (call.toolInfo.type === 'mcp') {
+ return { server: call.toolInfo.serverName, tool: call.toolInfo.name };
+ }
+ if (call.toolInfo.name !== 'call_tool') return undefined;
+ const args = JSON.parse(call.function.arguments || '{}') as {
+ mcp_server?: string;
+ tool_name?: string;
+ };
+ if (!args.mcp_server || !args.tool_name) return undefined;
+ return { server: args.mcp_server, tool: args.tool_name };
+}
+
+const { data: turn } = await client.sessions.getTurn(sessionId, turnId);
+if (turn.state.status === 'paused') {
+ const calls = new Map(); // by tool call id
+ const approvals = new Map(); // toolCallId → threadId
+ const questions = new Map(); // toolCallId → threadId
+ let signIn: TrueForgeApi.McpAuthRequiredEvent | undefined;
+ let lastEventId: string | undefined;
+
+ for await (const event of await client.sessions.listTurnEvents(
+ sessionId,
+ turnId,
+ )) {
+ lastEventId = event.id;
+ switch (event.type) {
+ case 'model.message':
+ for (const call of event.toolCalls ?? []) calls.set(call.id, call);
+ break;
+ case 'tool.approval_required':
+ for (const ref of event.toolCalls) approvals.set(ref.id, event.threadId);
+ break;
+ case 'tool.response_required':
+ for (const ref of event.toolCalls) questions.set(ref.id, event.threadId);
+ break;
+ case 'user.tool_approval':
+ approvals.delete(event.toolCallId);
+ break;
+ case 'user.tool_response':
+ questions.delete(event.toolCallId);
+ break;
+ case 'user.tool_approval_policy':
+ for (const toolCallId of approvals.keys()) {
+ const call = calls.get(toolCallId);
+ const target = call && mcpTarget(call);
+ const covered = event.policies.some(
+ p =>
+ p.serverName === target?.server &&
+ p.name === target.tool &&
+ (p.policy.expireAt == null ||
+ Date.parse(p.policy.expireAt) > Date.parse(event.createdAt)),
+ );
+ if (covered) approvals.delete(toolCallId);
+ }
+ break;
+ case 'mcp.auth_required':
+ signIn = event;
+ break;
+ case 'user.mcp_auth_continue':
+ signIn = undefined;
+ break;
+ }
+ }
+
+ const answers: TrueForgeApi.TurnUserEventMessage[] = [];
+ for (const [toolCallId, threadId] of approvals) {
+ answers.push({
+ type: 'user.tool_approval',
+ threadId,
+ toolCallId,
+ // or { status: 'deny', reason: 'denied by user' }
+ approval: { status: 'allow' },
+ });
+ }
+ for (const [toolCallId, threadId] of questions) {
+ answers.push({
+ type: 'user.tool_response',
+ threadId,
+ toolCallId,
+ content: 'the user’s answer',
+ });
+ }
+ if (signIn) {
+ // Send only once the user has signed in at each server's authUrl.
+ answers.push({ type: 'user.mcp_auth_continue' });
+ }
+
+ // Subscribe first, then send, then read what the answer produces.
+ const rest = await client.sessions.subscribeToTurn(
+ sessionId,
+ turnId,
+ { afterEventId: lastEventId },
+ { timeoutInSeconds: 600 },
+ );
+ await client.sessions.createTurnEvents(sessionId, turnId, {
+ events: answers,
+ });
+ for await (const event of rest) console.log(event.type);
+}
+```
+
+```python Python wrap
+import json
+import os
+from datetime import datetime
+
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session_id = "sess-abc123" # saved earlier
+turn_id = "turn-abc123" # saved earlier
+
+
+def mcp_target(call):
+ """Server and tool behind a call, or None if it isn't an MCP tool."""
+ if call.tool_info.type == "mcp":
+ return call.tool_info.server_name, call.tool_info.name
+ if call.tool_info.name != "call_tool":
+ return None
+ args = json.loads(call.function.arguments or "{}")
+ if "mcp_server" not in args or "tool_name" not in args:
+ return None
+ return args["mcp_server"], args["tool_name"]
+
+
+def parse_time(value):
+ # Python 3.10 rejects a trailing "Z"; a time without an offset is local.
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone()
+
+
+def covers(policy, target, sent_at):
+ """Whether a session-approval policy settles a call to target."""
+ if target != (policy.server_name, policy.name):
+ return False
+ expire_at = policy.policy.expire_at
+ return expire_at is None or parse_time(expire_at) > parse_time(sent_at)
+
+
+turn = client.sessions.get_turn(session_id=session_id, turn_id=turn_id).data
+if turn.state.status == "paused":
+ calls = {} # by tool call id
+ approvals = {} # tool_call_id → thread_id
+ questions = {} # tool_call_id → thread_id
+ sign_in = None
+ last_event_id = None
+
+ for event in client.sessions.list_turn_events(
+ session_id=session_id, turn_id=turn_id
+ ):
+ last_event_id = event.id
+ if event.type == "model.message":
+ for call in event.tool_calls or []:
+ calls[call.id] = call
+ elif event.type == "tool.approval_required":
+ for ref in event.tool_calls:
+ approvals[ref.id] = event.thread_id
+ elif event.type == "tool.response_required":
+ for ref in event.tool_calls:
+ questions[ref.id] = event.thread_id
+ elif event.type == "user.tool_approval":
+ approvals.pop(event.tool_call_id, None)
+ elif event.type == "user.tool_response":
+ questions.pop(event.tool_call_id, None)
+ elif event.type == "user.tool_approval_policy":
+ for tool_call_id in list(approvals):
+ call = calls.get(tool_call_id)
+ target = mcp_target(call) if call is not None else None
+ if any(covers(p, target, event.created_at) for p in event.policies):
+ del approvals[tool_call_id]
+ elif event.type == "mcp.auth_required":
+ sign_in = event
+ elif event.type == "user.mcp_auth_continue":
+ sign_in = None
+
+ answers = []
+ for tool_call_id, thread_id in approvals.items():
+ answers.append(
+ {
+ "type": "user.tool_approval",
+ "thread_id": thread_id,
+ "tool_call_id": tool_call_id,
+ "approval": {
+ "status": "allow"
+ }, # or {"status": "deny", "reason": "denied by user"}
+ }
+ )
+ for tool_call_id, thread_id in questions.items():
+ answers.append(
+ {
+ "type": "user.tool_response",
+ "thread_id": thread_id,
+ "tool_call_id": tool_call_id,
+ "content": "the user's answer",
+ }
+ )
+ if sign_in is not None:
+ # Send only once the user has signed in at each server's auth_url.
+ answers.append({"type": "user.mcp_auth_continue"})
+
+ # Subscribe first, then send, then read what the answer produces.
+ with client.sessions.subscribe_to_turn(
+ session_id=session_id,
+ turn_id=turn_id,
+ after_event_id=last_event_id,
+ request_options={"timeout": 600},
+ ) as rest:
+ client.sessions.create_turn_events(
+ session_id=session_id, turn_id=turn_id, events=answers
+ )
+ for event in rest:
+ print(event.type)
+```
+
+
+
+An answer is checked against what the turn is waiting for. If it names a call that isn't waiting (already answered, or a wrong `thread_id`), the request fails with `400` and none of the events in it are applied. Answering a turn that has already ended, for example because a new message cancelled it, fails with `409`.
+
+
+## Resilience and threads
+
+### Resume a stream
+
+If you lose the `createTurnStream` / `create_turn_stream` connection (e.g. a process restart), persist `session.id`, `turnId` / `turn_id`, and the `id` of the last event you received. To resume, call `getTurn` / `get_turn`:
+
+- **Running or paused:** reconnect with `subscribeToTurn` / `subscribe_to_turn` and `fromEventId` / `from_event_id` set to the last event id. The replay starts at that event, so if you dropped in the middle of a reply, the `model.message` base arrives again and your [event index](#create-and-stream-a-turn) rebuilds it from its deltas. Use `afterEventId` / `after_event_id` instead when you only want what comes after it.
+- **Finished:** rebuild from `listTurnEvents` / `list_turn_events`.
+
+
+```typescript TypeScript wrap
+import {
+ TrueForge,
+ TrueForgeApi,
+ isEventDelta,
+ mergeEventDelta,
+} from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const events = new Map();
+let turnId: string | undefined;
+let lastEventId: string | undefined;
+
+const index = (event: TrueForgeApi.TurnStreamingEvent) => {
+ lastEventId = event.id;
+ if (isEventDelta(event)) {
+ const base = events.get(event.id);
+ if (base) mergeEventDelta(base, event);
+ } else {
+ events.set(event.id, event);
+ }
+};
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ { type: 'user.message', content: 'Compare Qdrant, Weaviate, and Milvus.' },
+ ],
+});
+for await (const event of stream) {
+ if (event.type === 'turn.created') turnId = event.turnId;
+ index(event);
+}
+
+// …after a disconnect, with session.id / turnId / lastEventId restored:
+const { data: turn } = await client.sessions.getTurn(session.id, turnId!);
+if (turn.state.status === 'running' || turn.state.status === 'paused') {
+ const resume = await client.sessions.subscribeToTurn(
+ session.id,
+ turnId!,
+ { fromEventId: lastEventId },
+ { timeoutInSeconds: 600 },
+ );
+ for await (const event of resume) index(event);
+} else {
+ // Already finished: rebuild from the stored log (deltas already merged).
+ for await (const event of await client.sessions.listTurnEvents(
+ session.id,
+ turnId!,
+ )) {
+ events.set(event.id, event);
+ }
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+from trueforge_sdk.events import is_event_delta, merge_event_delta
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+events = {}
+turn_id = None
+last_event_id = None
+
+
+def index(event):
+ global last_event_id
+ last_event_id = event.id
+ if is_event_delta(event):
+ base = events.get(event.id)
+ if base is not None:
+ merge_event_delta(base, event)
+ else:
+ events[event.id] = event
+
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": "Compare Qdrant, Weaviate, and Milvus.",
+ }
+ ],
+) as stream:
+ for event in stream:
+ if event.type == "turn.created":
+ turn_id = event.turn_id
+ index(event)
+
+# …after a disconnect, with session.id / turn_id / last_event_id restored:
+turn = client.sessions.get_turn(
+ session_id=session.data.id, turn_id=turn_id
+).data
+if turn.state.status in ("running", "paused"):
+ with client.sessions.subscribe_to_turn(
+ session_id=session.data.id,
+ turn_id=turn_id,
+ from_event_id=last_event_id,
+ request_options={"timeout": 600},
+ ) as resume:
+ for event in resume:
+ index(event)
+else:
+ # Already finished: rebuild from the stored log (deltas already merged).
+ for event in client.sessions.list_turn_events(
+ session_id=session.data.id, turn_id=turn_id
+ ):
+ events[event.id] = event
+```
+
+
+
+`subscribeToTurn` / `subscribe_to_turn` doesn't reconnect on its own. A subscription can also end before `turn.done`, for example after a long wait on a paused turn. Whenever it ends without `turn.done`, subscribe again from the last event id you saw.
+
+
+### Subagent threads
+
+A turn stream interleaves the root agent and any parallel [subagents](/key-features/subagents), exactly what the [Quick Start](#quick-start) above does. Every event carries a `threadId` / `thread_id`:
+
+- `"main"`: the root agent.
+- A unique id: a subagent thread. [`thread.created`](#thread-created) and [`thread.done`](#thread-done) bracket its lifecycle.
+- `null`: a turn-level event, such as [`turn.created`](#turn-created), [`turn.update`](#turn-update), [`turn.done`](#turn-done), [`sandbox.created`](#sandbox-created), and [`mcp.auth_required`](#mcp-auth-required).
+
+Keep a **per-thread** index (`Map>` in TypeScript; nested dicts in Python) and apply the same [event-index](#create-and-stream-a-turn) merge inside each thread's bucket.
+
+A subagent can need your approval or answer too. Its prompt carries the subagent's `thread_id`; send that same `thread_id` back with your answer. Other subagents may keep working while one waits, so a prompt can arrive while the turn is still running; the turn shows `paused` only once nothing else can move forward. Answer it the same way as any other pause: subscribe from the last event you saw, send, then read.
+
+```mermaid
+sequenceDiagram
+ actor Client
+ box Session
+ participant Main as main thread
+ participant Research as research thread
+ end
+
+ Note over Client,Research: Turn 1 — user message
+ Client->>Main: user.message
+ Main-->>Client: model.message + deltas
+ Main->>Research: spawn sub-agent
+ Main-->>Client: thread.created
+ Research-->>Client: model.message + deltas
+ Research->>Main: sub-agent completes
+ Main-->>Client: thread.done
+ Main-->>Client: model.message + deltas
+```
+
+
+```typescript TypeScript wrap
+import {
+ TrueForge,
+ TrueForgeApi,
+ isEventDelta,
+ mergeEventDelta,
+} from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+ timeoutInSeconds: 600,
+});
+const { data: session } = await client.sessions.create({
+ agent: { name: 'web-research-brief' },
+});
+
+const threads = new Map>();
+
+const stream = await client.sessions.createTurnStream(session.id, {
+ input: [
+ {
+ type: 'user.message',
+ content: 'Compare Qdrant, Weaviate, and Milvus in parallel.',
+ },
+ ],
+});
+for await (const event of stream) {
+ // These two answer events omit threadId.
+ if (!('threadId' in event) || event.threadId == null) {
+ console.log('turn-level event:', event.type);
+ continue;
+ }
+ let bucket = threads.get(event.threadId);
+ if (!bucket) threads.set(event.threadId, (bucket = new Map()));
+
+ if (isEventDelta(event)) {
+ const base = bucket.get(event.id);
+ if (base) mergeEventDelta(base, event);
+ } else {
+ bucket.set(event.id, event);
+ }
+ if (event.type === 'thread.done') {
+ console.log(
+ `${event.threadId} done: ${event.title} (${bucket.size} events)`,
+ );
+ threads.delete(event.threadId);
+ }
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+from trueforge_sdk.events import is_event_delta, merge_event_delta
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790"),
+ timeout=600,
+)
+session = client.sessions.create(agent={"name": "web-research-brief"})
+
+threads = {}
+
+with client.sessions.create_turn_stream(
+ session_id=session.data.id,
+ input=[
+ {
+ "type": "user.message",
+ "content": "Compare Qdrant, Weaviate, and Milvus in parallel.",
+ }
+ ],
+) as stream:
+ for event in stream:
+ # These two answer events omit thread_id.
+ thread_id = getattr(event, "thread_id", None)
+ if thread_id is None:
+ print("turn-level event:", event.type)
+ continue
+ bucket = threads.setdefault(thread_id, {})
+ if is_event_delta(event):
+ base = bucket.get(event.id)
+ if base is not None:
+ merge_event_delta(base, event)
+ else:
+ bucket[event.id] = event
+ if event.type == "thread.done":
+ print(f"{thread_id} done: {event.title} ({len(bucket)} events)")
+ del threads[thread_id]
+```
+
+
+### Replay a turn
+
+`sessions.listTurnEvents()` / `list_turn_events()` yields a turn's [events](#turn-events-reference) in order (auto-paginates; `order: "asc"` default, or `"desc"`). Events are **already merged**, so you can use each one directly. It works for finished and paused turns, including the answers you sent.
+
+
+While a turn is running, the reply it is writing right now is not in the list yet. To watch a running turn, stream it with `createTurnStream` / `create_turn_stream` or `subscribeToTurn` / `subscribe_to_turn` instead.
+
+
+
+```typescript TypeScript wrap
+import { TrueForge } from '@truefoundry/trueforge-sdk';
+
+const client = new TrueForge({
+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',
+});
+
+for await (const turn of await client.sessions.listTurns('sess-abc123')) {
+ if (turn.state.status === 'running') continue;
+ for await (const event of await client.sessions.listTurnEvents(
+ 'sess-abc123',
+ turn.id,
+ { order: 'asc' },
+ )) {
+ console.log(event.type);
+ }
+}
+```
+
+```python Python wrap
+import os
+from trueforge_sdk import TrueForge
+
+client = TrueForge(
+ base_url=os.environ.get("TRUEFORGE_BASE_URL", "http://localhost:8790")
+)
+
+for turn in client.sessions.list_turns(session_id="sess-abc123"):
+ if turn.state.status == "running":
+ continue
+ for event in client.sessions.list_turn_events(
+ session_id="sess-abc123", turn_id=turn.id, order="asc"
+ ):
+ print(event.type)
+```
+
+
+## Schedules
+
+A **schedule** runs a saved agent on a recurring cadence, unattended. Each run sends the schedule's `task` to the agent and is recorded as a [session](/sessions). Manage them through `client.schedules`; the [Schedules guide](/schedules) covers the same feature in the UI.
+
+### Create a schedule
+
+
+```typescript TypeScript
+const { data: schedule } = await client.schedules.create({
+ agentName: 'web-research-brief',
+ name: 'morning-brief',
+ manifest: {
+ task:
+ 'Summarize the most important AI news from the last 24 hours '
+ + 'and list the top five items with links.',
+ cron: '0 9 * * *', // 09:00 every day, evaluated in `timezone`
+ timezone: 'Asia/Kolkata', // IANA time zone
+ status: 'active', // or 'paused'
+ },
+});
+```
+
+```python Python
+schedule = client.schedules.create(
+ agent_name="web-research-brief",
+ name="morning-brief",
+ manifest={
+ "task": (
+ "Summarize the most important AI news from the last 24 hours "
+ "and list the top five items with links."
+ ),
+ "cron": "0 9 * * *", # 09:00 every day, evaluated in `timezone`
+ "timezone": "Asia/Kolkata", # IANA time zone
+ "status": "active", # or "paused"
+ },
+)
+```
+
+
+The `cron` is a standard 5-field expression evaluated in `timezone`. The shortest interval is one hour.
+
+### List, get, update, and delete
+
+Update replaces the whole manifest, so pass every field you want to keep.
+
+
+```typescript TypeScript
+for await (const schedule of await client.schedules.list()) {
+ console.log(schedule.name, schedule.manifest.cron);
+}
+
+const { data: schedule } = await client.schedules.get('sched-abc123');
+
+await client.schedules.update('sched-abc123', {
+ name: 'morning-brief',
+ manifest: {
+ task:
+ 'Summarize the most important AI news from the last 24 hours '
+ + 'and list the top five items with links.',
+ cron: '0 8 * * 1-5', // now weekdays at 08:00
+ timezone: 'Asia/Kolkata',
+ status: 'paused',
+ },
+});
+
+await client.schedules.delete('sched-abc123');
+```
+
+```python Python
+for schedule in client.schedules.list():
+ print(schedule.name, schedule.manifest.cron)
+
+schedule = client.schedules.get(schedule_id="sched-abc123").data
+
+client.schedules.update(
+ schedule_id="sched-abc123",
+ name="morning-brief",
+ manifest={
+ "task": (
+ "Summarize the most important AI news from the last 24 hours "
+ "and list the top five items with links."
+ ),
+ "cron": "0 8 * * 1-5", # now weekdays at 08:00
+ "timezone": "Asia/Kolkata",
+ "status": "paused",
+ },
+)
+
+client.schedules.delete(schedule_id="sched-abc123")
+```
+
+
+### Runs
+
+
+```typescript TypeScript
+// Trigger a run now, without waiting for the next scheduled time.
+await client.schedules.createRun({ scheduleId: 'sched-abc123' });
+
+// Review recent runs.
+for await (const run of await client.schedules.listRuns('sched-abc123')) {
+ // 'scheduled' | 'triggered' | 'failed'
+ console.log(run.scheduledFor, run.status);
+}
+```
+
+```python Python
+# Trigger a run now, without waiting for the next scheduled time.
+client.schedules.create_run(schedule_id="sched-abc123")
+
+# Review recent runs.
+for run in client.schedules.list_runs(schedule_id="sched-abc123"):
+ print(run.scheduled_for, run.status) # "scheduled" | "triggered" | "failed"
+```
+
+
+Each run executes as a [session](/sessions), so open it there or through the session APIs above to read the transcript.
+
+## Turn events reference
+
+Field-level schemas for every event streamed while a turn runs. The recipes above link here for the exact shape of each event they handle.
+
+
+ Field names in this reference use the HTTP/JSON wire format (snake_case, e.g. `turn_id`, `source_event_id`). The Python SDK uses those same names. The TypeScript SDK returns the same fields camelCased (`turnId`, `sourceEventId`).
+
+
+Events carry:
+
+| Field | Description |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `type` | The event type — one of the types below. |
+| `id` | Unique event id (monotonic ULID — sortable by creation order). Pass it as `from_event_id` / `after_event_id` to [resume a stream](#resume-a-stream). |
+| `created_at` | ISO 8601 timestamp. Some `model.message.delta` fragments omit it. |
+| `thread_id` | Which execution thread emitted it: `"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events (`turn.*`, `sandbox.created`, `mcp.auth_required`). `user.tool_approval_policy` and `user.mcp_auth_continue` omit this field. |
+
+A new turn's stream opens with `turn.created` and closes with `turn.done`. A [resumed stream](#resume-a-stream) starts at the event id you pass. When you list persisted session events afterwards, you get the same events with deltas pre-merged into their `model.message`.
+
+### Lifecycle events
+
+#### `turn.created`
+
+First event on a new turn's stream. A resumed stream starts at the cursor you pass.
+
+| Field | Description |
+| ------------------ | --------------------------------------------------------- |
+| `turn_id` | Id of this turn. |
+| `previous_turn_id` | The turn this one chains from, or `null` for a root turn. |
+| `input` | The turn's input items, echoed back. |
+| `state` | `{ "status": "running" }` |
+
+#### `turn.update`
+
+The turn paused or started running again. `state.status` is one of:
+
+- **`paused`** — the agent is waiting for you. The events just before it say what it needs (see [Handle pauses](#handle-pauses)). Carries optional `metrics` (tokens and cost) for the turn so far.
+- **`running`** — your answers were applied and the agent is working again.
+
+```json turn.update — paused for approval wrap
+{
+ "type": "turn.update",
+ "id": "01jc...",
+ "thread_id": null,
+ "created_at": "2026-06-24T10:01:12Z",
+ "state": {
+ "status": "paused",
+ "metrics": { "total_tokens": 2451, "total_cost_in_usd": 0.011 }
+ }
+}
+```
+
+#### `turn.done`
+
+Last event on every stream. `state.status` is one of:
+
+- **`done`** — carries `output` (the final `model.message`, or `null` when the turn ended without one), `completed_at`, and optional `metrics`.
+- **`cancelled`** — carries a `reason`: `client-cancelled`, `server-execution-timeout`, `cancelled-for-next-turn`, or `abandoned`.
+- **`error`** — carries a `message`.
+
+`metrics`, when present, aggregates the whole turn: `total_input_tokens`, `total_output_tokens`, `total_tokens`, `total_cache_read_tokens`, `total_cache_write_tokens`, `total_reasoning_tokens`, and `total_cost_in_usd`. A cancelled turn keeps the metrics for the work it did.
+
+```json turn.done wrap
+{
+ "type": "turn.done",
+ "id": "01jc...",
+ "thread_id": null,
+ "created_at": "2026-06-24T10:02:40Z",
+ "state": {
+ "status": "done",
+ "output": {
+ "type": "model.message",
+ "content": "Refund RF-9914 has been processed."
+ },
+ "completed_at": "2026-06-24T10:02:40Z",
+ "metrics": { "total_tokens": 3920, "total_cost_in_usd": 0.018 }
+ }
+}
+```
+
+### Model output
+
+#### `model.message`
+
+An assistant message — text content and/or tool calls. On a live stream the base event arrives first and fills in via deltas; the merged event carries:
+
+| Field | Description |
+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `content` | Assistant text (may be empty when the message is only tool calls). |
+| `tool_calls` | Tool invocations, each with an `id`, `function` (`name`, `arguments`), and `tool_info` (`{ type: "mcp", server_name, name }` or `{ type: "truefoundry-system", name }`). |
+| `finish_reason` | Why generation stopped (`stop`, `tool_calls`, ...), `null` mid-stream. |
+| `usage` | Token usage for this model call: `input_tokens`, `output_tokens`, optional cache counters, and `input_tokens_breakdown` (`harness`, `skills`, `instructions`, `tool_definitions`, `messages`). |
+
+#### `model.message.delta`
+
+An incremental fragment of a `model.message` — text and/or tool-call chunks. All deltas share the base event's `id`; append `content` chunks and merge tool-call fragments by index (`isEventDelta` / `mergeEventDelta` in TypeScript; `is_event_delta` / `merge_event_delta` from `trueforge_sdk.events` in Python). The most frequent event on a live stream. Not present when listing persisted events.
+
+### Tool activity
+
+#### `tool.response`
+
+The result of a tool the harness executed, linked to its call by `tool_call_id`:
+
+```json wrap
+{
+ "type": "tool.response",
+ "id": "01jc...",
+ "thread_id": "main",
+ "tool_call_id": "call-get-order-01",
+ "content": "{\"order_id\":\"ORD-2031\",\"status\":\"shipped\",\"total\":1240.0}",
+ "created_at": "2026-06-24T10:00:04Z"
+}
+```
+
+#### `tool.approval_required`
+
+One or more tool calls need [human approval](/create-agent/overview#what’s-in-an-agent) before they can run. The turn waits for a `user.tool_approval` for each call (or a [session approval](#approve-a-tool-for-the-rest-of-the-session) for the tool).
+
+| Field | Description |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `tool_calls` | Pending calls: each `{ id, source_event_id }`, where `source_event_id` points at the `model.message` that contains the call's name and arguments. |
+
+```json wrap
+{
+ "type": "tool.approval_required",
+ "id": "01jc...",
+ "thread_id": "main",
+ "created_at": "2026-06-24T10:01:11Z",
+ "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]
+}
+```
+
+#### `tool.response_required`
+
+A client-side tool (e.g. [`ask_user_question`](/create-agent/overview#what’s-in-an-agent)) needs a result from your app. Same shape as `tool.approval_required`; the turn waits for a `user.tool_response` for each call.
+
+### Subagent thread events
+
+#### `thread.created`
+
+A [subagent](/key-features/subagents) started. Subsequent events with this `thread_id` belong to it.
+
+| Field | Description |
+| ------------ | -------------------------------------------------------------------------------------- |
+| `thread_id` | The new thread's id. |
+| `title` | Human-readable subagent name. |
+| `parent` | `{ thread_id, tool_call_id }` — the spawning thread and tool call. |
+| `agent_info` | `{ type: "dynamic", name, input }` — the generated instructions the subagent received. |
+
+#### `thread.done`
+
+The subagent finished. `state` is `{ status: "done", output: }` or `{ status: "error", error, output? }`. Does not close the turn stream — the root agent continues.
+
+### Environment events
+
+#### `mcp.initialize`
+
+MCP server connections were initialized for a thread. `mcp_servers` lists each server: `{ id, name, session_id?, transport_type? }` (`streamable-http` or `sse`).
+
+#### `mcp.auth_required`
+
+One or more MCP servers need [OAuth authorization](/mcp-servers#in-chat-authentication) before the agent can proceed. `mcp_servers` lists `{ id, name, auth_url }`. Send the user to `auth_url`; the turn waits for a `user.mcp_auth_continue`.
+
+#### `sandbox.created`
+
+A [sandbox](/sandbox) was provisioned, carrying its `sandbox_id`. Emitted once per session — subsequent turns reuse the same sandbox and emit no new event.
+
+### User events
+
+`user.message` is what you send when you create a turn:
+
+| Type | Fields | Purpose |
+| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
+| `user.message` | `content` — non-empty string, or array of `{ type: "text", text }` / `{ type: "file", name, data }` parts (files as `data:;base64,...` URIs) | A user message. |
+
+The rest are answers you send to a paused turn with `createTurnEvents` / `create_turn_events`. Once applied, each one also appears on the turn's stream and in its event list, with its own `id` and `created_at`:
+
+| Type | Fields | Purpose |
+| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
+| `user.tool_approval` | `thread_id`, `tool_call_id`, `approval` — `{ status: "allow" }` or `{ status: "deny", reason? }` | Decision for a pending tool call. |
+| `user.tool_response` | `thread_id`, `tool_call_id`, `content` (non-empty) | Answer for a pending client-side tool call. |
+| `user.tool_approval_policy` | `policies` — each `{ server_name, name, policy: { type: "allow_session", expire_at? } }` | Approve an MCP tool for the rest of the session. |
+| `user.mcp_auth_continue` | none | The user finished signing in; continue the paused work. |
diff --git a/docs/api/use-agent.mdx b/docs/api/use-agent.mdx
index 6bc2e3e18b..7719d90b35 100644
--- a/docs/api/use-agent.mdx
+++ b/docs/api/use-agent.mdx
@@ -536,7 +536,10 @@ for (const pending of pendingApprovals) {
}
const resume = await client.sessions.createTurnStream(session.id, { input: approvals });
-for await (const { data: event } of resume.withMetadata()) console.log(event.type);
+for await (const { data: event } of resume.withMetadata()) {
+ console.log(event.type);
+ // Handle other event types.
+}
```
```python Python wrap
@@ -589,6 +592,7 @@ for pending in pending_approvals:
resume = client.sessions.create_turn_stream(session_id=session.data.id, input=approvals)
for event in resume:
print(event.type)
+ # Handle other event types.
```
@@ -642,7 +646,10 @@ for (const pending of pendingQuestions) {
}
const resume = await client.sessions.createTurnStream(session.id, { input: responses });
-for await (const { data: event } of resume.withMetadata()) console.log(event.type);
+for await (const { data: event } of resume.withMetadata()) {
+ console.log(event.type);
+ // Handle other event types.
+}
```
```python Python wrap
@@ -700,6 +707,7 @@ for pending in pending_questions:
resume = client.sessions.create_turn_stream(session_id=session.data.id, input=responses)
for event in resume:
print(event.type)
+ # Handle other event types.
```
@@ -738,7 +746,10 @@ if (pendingAuth != null) {
// Resume with empty input; the agent continues the interrupted work.
const resume = await client.sessions.createTurnStream(session.id, {});
-for await (const { data: event } of resume.withMetadata()) console.log(event.type);
+for await (const { data: event } of resume.withMetadata()) {
+ console.log(event.type);
+ // Handle other event types.
+}
```
```python Python wrap
@@ -769,6 +780,7 @@ if pending_auth is not None:
resume = client.sessions.create_turn_stream(session_id=session.data.id)
for event in resume:
print(event.type)
+ # Handle other event types.
```
diff --git a/packages/assistant-ui-runtime/src/convertTurnMessages.ts b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
index d039dcb273..48b9c4bdc3 100644
--- a/packages/assistant-ui-runtime/src/convertTurnMessages.ts
+++ b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
@@ -498,9 +498,9 @@ function ingestSessionEventsIntoSnapshot(
} else if (event.type === EVENT_TYPE.TURN_UPDATE) {
// Lifecycle updates describe the open turn but do not belong in a thread
// bucket. resolveSessionTip reads the latest update below.
- if (event.state.status === TURN_STATUS.RUNNING) {
- snapshot.pendingMcpAuth = undefined;
- }
+ // Do not clear pendingMcpAuth on running: approving one sub-agent makes the
+ // turn running while another thread can still need MCP auth. Only
+ // user.mcp_auth_continue / turn.done clear it.
continue;
} else {
if (currentTurnId != null) {
@@ -1157,6 +1157,27 @@ function buildTurnUpdateFromFold(
}
try {
const { parts: content, parallelToolGroups } = buildRootAssistantFoldForIds(foldState, rootModelMessageIds);
+ const approvalThreadId = findFirstPendingApprovalThreadId(foldState);
+ const responseThreadId = findFirstPendingResponseThreadId(foldState);
+ // Approvals / ask-user before MCP auth when both are open on the same pause.
+ // Keep pendingMcpAuth on metadata (no Connect text yet) so the composer can
+ // switch to Connect as soon as the last approval clears — without waiting
+ // for the next SSE pause.
+ if (approvalThreadId != null || responseThreadId != null) {
+ const custom = {
+ ...(approvalThreadId != null ? toolApprovalMessageCustom(approvalThreadId) : {}),
+ ...(responseThreadId != null ? toolResponseMessageCustom(responseThreadId) : {}),
+ ...(turn.pendingMcpAuth != null ? mcpAuthMessageCustom(turn.pendingMcpAuth.mcpServers) : {}),
+ };
+ return withParallelToolGroups(
+ {
+ content,
+ status: approvalThreadId != null ? toolApprovalStatus() : toolResponseStatus(),
+ metadata: { custom },
+ },
+ parallelToolGroups,
+ );
+ }
if (turn.pendingMcpAuth != null) {
return withParallelToolGroups(
{
@@ -1170,23 +1191,7 @@ function buildTurnUpdateFromFold(
let update: TurnStreamUpdate = { content };
update = appendMcpAuthToTurnContent(update.content, turn);
update = appendToolApprovalToTurnContent(update, turn);
- if (turn.state.status === TURN_STATUS.PAUSED && update.status == null) {
- const approvalThreadId = findFirstPendingApprovalThreadId(foldState);
- const responseThreadId = findFirstPendingResponseThreadId(foldState);
- // Answered but not yet resumed: leave status unset so it does not look blocked.
- if (approvalThreadId == null && responseThreadId == null) {
- return update;
- }
- const custom = {
- ...(approvalThreadId != null ? toolApprovalMessageCustom(approvalThreadId) : {}),
- ...(responseThreadId != null ? toolResponseMessageCustom(responseThreadId) : {}),
- };
- update = {
- content,
- status: approvalThreadId != null ? toolApprovalStatus() : toolResponseStatus(),
- metadata: { custom },
- };
- }
+ // Paused with every prompt answered (not yet resumed): leave status unset.
return withParallelToolGroups(update, parallelToolGroups);
} finally {
foldState.parentTerminalStatus = previousParentTerminal;
@@ -1965,23 +1970,33 @@ export async function* streamTurnEvents(
};
const buildRequiredActionUpdate = (): TurnStreamUpdate => {
- if (pendingMcpAuth != null) {
- return buildMcpAuthUpdate(pendingMcpAuth, foldState, groupRootBaseline);
- }
-
const approvalThreadId = findFirstPendingApprovalThreadId(foldState);
const responseThreadId = findFirstPendingResponseThreadId(foldState);
- const custom: Record = {};
- if (approvalThreadId != null) {
- Object.assign(custom, toolApprovalMessageCustom(approvalThreadId));
+ // Prefer tool approval / ask-user over MCP auth when both are pending so the
+ // composer shows "N tools need your input" first; Connect waits until those clear.
+ // Stash MCP metadata anyway so approving the last tool can reveal Connect
+ // immediately (optimistic overlay) instead of after the next running/pause SSE.
+ if (approvalThreadId != null || responseThreadId != null) {
+ const custom: Record = {
+ ...(pendingMcpAuth != null ? mcpAuthMessageCustom(pendingMcpAuth.mcpServers) : {}),
+ };
+ if (approvalThreadId != null) {
+ Object.assign(custom, toolApprovalMessageCustom(approvalThreadId));
+ }
+ if (responseThreadId != null) {
+ Object.assign(custom, toolResponseMessageCustom(responseThreadId));
+ }
+ return buildRootContentUpdate(foldState, groupRootBaseline, {
+ status: approvalThreadId != null ? toolApprovalStatus() : toolResponseStatus(),
+ metadata: { custom },
+ });
}
- if (responseThreadId != null) {
- Object.assign(custom, toolResponseMessageCustom(responseThreadId));
+
+ if (pendingMcpAuth != null) {
+ return buildMcpAuthUpdate(pendingMcpAuth, foldState, groupRootBaseline);
}
- return buildRootContentUpdate(foldState, groupRootBaseline, {
- status: approvalThreadId != null ? toolApprovalStatus() : toolResponseStatus(),
- metadata: { custom },
- });
+
+ return buildRootContentUpdate(foldState, groupRootBaseline);
};
/** Partial approvals: BE may echo user.tool_approval without another turn.update. */
@@ -1990,6 +2005,14 @@ export async function* streamTurnEvents(
findFirstPendingApprovalThreadId(foldState) != null ||
findFirstPendingResponseThreadId(foldState) != null;
+ // Authoritative turn.update status. Content events must not invent paused just
+ // because a sibling prompt is still open after the orchestrator resumed.
+ let lastTurnLifecycleStatus: typeof TURN_STATUS.RUNNING | typeof TURN_STATUS.PAUSED | undefined;
+
+ const requiredActionTurnState = (): { status: typeof TURN_STATUS.RUNNING | typeof TURN_STATUS.PAUSED } => ({
+ status: lastTurnLifecycleStatus ?? TURN_STATUS.PAUSED,
+ });
+
const withSequence = (update: TurnStreamUpdate, sequenceNumber: number | undefined): TurnStreamUpdate =>
sequenceNumber === undefined ? update : { ...update, sequenceNumber };
@@ -1998,7 +2021,7 @@ export async function* streamTurnEvents(
return withSequence(
{
...buildRequiredActionUpdate(),
- turnState: { status: TURN_STATUS.PAUSED },
+ turnState: requiredActionTurnState(),
},
sequenceNumber,
);
@@ -2019,10 +2042,9 @@ export async function* streamTurnEvents(
activeTurnId = event.turnId;
}
if ('id' in event && typeof event.id === 'string') {
- const endsMcpAuthPrompt =
- event.type === EVENT_TYPE.USER_MCP_AUTH_CONTINUE ||
- event.type === EVENT_TYPE.TURN_DONE ||
- (event.type === EVENT_TYPE.TURN_UPDATE && event.state.status === TURN_STATUS.RUNNING);
+ // Running alone does not answer MCP auth: another sub-agent can resume
+ // while this thread still needs Connect. Only continue / done end it.
+ const endsMcpAuthPrompt = event.type === EVENT_TYPE.USER_MCP_AUTH_CONTINUE || event.type === EVENT_TYPE.TURN_DONE;
// Resume replays from mcp.auth_required until the prompt is answered. A later
// paused update must not move the cursor past it: a fresh fold would lose the prompt.
if (pendingMcpAuth == null || event.type === EVENT_TYPE.MCP_AUTH_REQUIRED || endsMcpAuthPrompt) {
@@ -2053,19 +2075,34 @@ export async function* streamTurnEvents(
if (event.type === EVENT_TYPE.TURN_UPDATE) {
if (event.state.status === TURN_STATUS.RUNNING) {
- pendingMcpAuth = undefined;
- yield withSandbox(
- withSequence(
- buildRootContentUpdate(foldState, groupRootBaseline, {
- status: runningAssistantStatus(),
- turnState: { status: TURN_STATUS.RUNNING },
- }),
- data.sequenceNumber,
- ),
- );
+ lastTurnLifecycleStatus = TURN_STATUS.RUNNING;
+ // Approving one sub-agent resumes the turn while a sibling may still need
+ // MCP auth (or another approval). Keep required-action chrome until continue.
+ if (foldStillNeedsUserInput()) {
+ yield withSandbox(
+ withSequence(
+ {
+ ...buildRequiredActionUpdate(),
+ turnState: { status: TURN_STATUS.RUNNING },
+ },
+ data.sequenceNumber,
+ ),
+ );
+ } else {
+ yield withSandbox(
+ withSequence(
+ buildRootContentUpdate(foldState, groupRootBaseline, {
+ status: runningAssistantStatus(),
+ turnState: { status: TURN_STATUS.RUNNING },
+ }),
+ data.sequenceNumber,
+ ),
+ );
+ }
continue;
}
+ lastTurnLifecycleStatus = TURN_STATUS.PAUSED;
// Pause is in-stream: the same SSE continues through apply-only echoes,
// turn.update running, and turn.done. Do not detach the consumer.
yield withSandbox(
@@ -2136,7 +2173,7 @@ export async function* streamTurnEvents(
yield withSandbox({
...buildRequiredActionUpdate(),
...(lastSequenceNumber != null ? { sequenceNumber: lastSequenceNumber } : {}),
- turnState: { status: TURN_STATUS.PAUSED },
+ turnState: requiredActionTurnState(),
});
}
return;
diff --git a/packages/assistant-ui-runtime/src/mcpAuth.ts b/packages/assistant-ui-runtime/src/mcpAuth.ts
index ff524f023f..f59e90eb6d 100644
--- a/packages/assistant-ui-runtime/src/mcpAuth.ts
+++ b/packages/assistant-ui-runtime/src/mcpAuth.ts
@@ -1,21 +1,23 @@
import type { MessageStatus } from '@assistant-ui/core';
import type { McpAuthRequiredEvent, TurnStateDone } from './server/index.js';
-import { EVENT_TYPE } from './server/index.js';
+import { EVENT_TYPE, TURN_STATUS } from './server/index.js';
-import { interruptRequiredAssistantStatus } from './assistantMessageStatus.js';
+import { interruptRequiredAssistantStatus, runningAssistantStatus } from './assistantMessageStatus.js';
import { MESSAGE_CUSTOM_KEY, type McpAuthMessageCustomMetadata } from './messageCustomMetadata.js';
import type { AssistantContentPart } from './modelMessageContent.js';
+import { replaceSessionSnapshot, STREAM_SEGMENT_STATUS, type SessionSnapshot } from './sessionSnapshot.js';
type McpServerAuthInfo = McpAuthRequiredEvent['mcpServers'][number];
+const MCP_AUTH_HINT_TEXT = [
+ 'This agent needs access to external services before it can continue.',
+ '',
+ 'Click the **Connect** button(s) to authorize the Connectors, then press **Continue**.',
+].join('\n');
+
export function buildMcpAuthTextParts(servers?: readonly McpServerAuthInfo[]): AssistantContentPart[] {
void servers;
- const text = [
- 'This agent needs access to external services before it can continue.',
- '',
- 'Click the **Connect** button(s) to authorize the Connectors, then press **Continue**.',
- ].join('\n');
- return [{ type: 'text', text }];
+ return [{ type: 'text', text: MCP_AUTH_HINT_TEXT }];
}
export function findMcpAuthRequired(
@@ -36,3 +38,86 @@ export function mcpAuthMessageCustom(servers: readonly McpServerAuthInfo[]): Mcp
[MESSAGE_CUSTOM_KEY.MCP_SERVERS]: [...servers],
};
}
+
+function omitMcpAuthMessageCustom(custom: Record): Record {
+ return Object.fromEntries(
+ Object.entries(custom).filter(
+ ([key]) => key !== MESSAGE_CUSTOM_KEY.PENDING_MCP_AUTH && key !== MESSAGE_CUSTOM_KEY.MCP_SERVERS,
+ ),
+ );
+}
+
+function omitMcpAuthHintText(content: readonly AssistantContentPart[]): AssistantContentPart[] {
+ return content.filter(part => !(part.type === 'text' && part.text === MCP_AUTH_HINT_TEXT));
+}
+
+/**
+ * Clears Connect chrome after the continue request has returned success, so
+ * Working... can show before the stream reports running. A failed request does
+ * not call this, and the prompt stays. Stream updates can put Connect back if
+ * auth is still required.
+ */
+export function withOptimisticMcpAuthContinue(snapshot: SessionSnapshot): SessionSnapshot {
+ const active = snapshot.activeStream;
+ if (active == null) {
+ return replaceSessionSnapshot(snapshot, { pendingMcpAuth: undefined });
+ }
+
+ const priorCustom = active.update.metadata?.custom;
+ const hadOnlyMcpAuth =
+ priorCustom?.[MESSAGE_CUSTOM_KEY.PENDING_MCP_AUTH] === true &&
+ priorCustom[MESSAGE_CUSTOM_KEY.TOOL_APPROVAL_THREAD_ID] == null &&
+ priorCustom[MESSAGE_CUSTOM_KEY.TOOL_RESPONSE_THREAD_ID] == null;
+ const custom = priorCustom == null ? undefined : omitMcpAuthMessageCustom(priorCustom);
+
+ if (!hadOnlyMcpAuth) {
+ return replaceSessionSnapshot(snapshot, {
+ pendingMcpAuth: undefined,
+ activeStream: {
+ ...active,
+ update: {
+ ...active.update,
+ ...(custom == null
+ ? {}
+ : {
+ metadata: {
+ ...active.update.metadata,
+ custom,
+ },
+ }),
+ },
+ },
+ });
+ }
+
+ const runningTurn =
+ snapshot.runningTurn == null
+ ? undefined
+ : {
+ ...snapshot.runningTurn,
+ state: { status: TURN_STATUS.RUNNING },
+ };
+
+ return replaceSessionSnapshot(snapshot, {
+ pendingMcpAuth: undefined,
+ ...(runningTurn != null ? { runningTurn } : {}),
+ activeStream: {
+ ...active,
+ segmentStatus: STREAM_SEGMENT_STATUS.OPEN,
+ update: {
+ ...active.update,
+ content: omitMcpAuthHintText(active.update.content),
+ status: runningAssistantStatus(),
+ turnState: { status: TURN_STATUS.RUNNING },
+ ...(custom == null
+ ? {}
+ : {
+ metadata: {
+ ...active.update.metadata,
+ custom,
+ },
+ }),
+ },
+ },
+ });
+}
diff --git a/packages/assistant-ui-runtime/src/turnStreamUpdate.ts b/packages/assistant-ui-runtime/src/turnStreamUpdate.ts
index 572e82abb8..4ded084b50 100644
--- a/packages/assistant-ui-runtime/src/turnStreamUpdate.ts
+++ b/packages/assistant-ui-runtime/src/turnStreamUpdate.ts
@@ -31,13 +31,11 @@ export function subscribeCursorForEvent(
return { afterEventId: event.id };
}
-function isRunningState(state: unknown): boolean {
- return typeof state === 'object' && state !== null && 'status' in state && state.status === 'running';
-}
-
/**
* Newest event first. A pending `mcp.auth_required` stays the cursor even when a
* later paused `turn.update` is the last stored row: the prompt is only on that event.
+ * Sibling-thread `turn.update` running also must not end it — another agent can
+ * resume while this thread still needs Connect.
*/
export function cursorFromTurnEvents(
eventsNewestFirst: readonly { type: string; id: string; state?: unknown }[],
@@ -48,10 +46,7 @@ export function cursorFromTurnEvents(
if (event.type === EVENT_TYPE.MCP_AUTH_REQUIRED) {
return { fromEventId: event.id };
}
- const promptEnded =
- event.type === EVENT_TYPE.USER_MCP_AUTH_CONTINUE ||
- event.type === EVENT_TYPE.TURN_DONE ||
- (event.type === EVENT_TYPE.TURN_UPDATE && isRunningState(event.state));
+ const promptEnded = event.type === EVENT_TYPE.USER_MCP_AUTH_CONTINUE || event.type === EVENT_TYPE.TURN_DONE;
if (promptEnded) {
return newest;
}
diff --git a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
index 19b1a558cb..bb4b857d4c 100644
--- a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
+++ b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
@@ -35,6 +35,7 @@ import {
resolveToolApprovalPolicyTarget,
} from './foldPeerThreads.js';
import { loadSessionSnapshot } from './loadSessionSnapshot.js';
+import { withOptimisticMcpAuthContinue } from './mcpAuth.js';
import { isMcpServerAuthInfoList, MESSAGE_CUSTOM_KEY } from './messageCustomMetadata.js';
import type { AssistantContentPart } from './modelMessageContent.js';
import { findPausedAssistantMessage } from './requiredActionInputs.js';
@@ -537,6 +538,7 @@ export function useTrueForgeAgentMessages({
const sendEpochRef = useRef(0);
const streamReconnectPendingRef = useRef(false);
const cancelRequestedRef = useRef(false);
+ const cancelInFlightRef = useRef | null>(null);
const lazilyCreatedSessionIdRef = useRef(undefined);
const initialLoadStartedForRef = useRef(undefined);
const skipInitialPromotionLoadForRef = useRef(undefined);
@@ -1250,43 +1252,59 @@ export function useTrueForgeAgentMessages({
);
const cancel = useCallback(async () => {
- // A turn can start before the thread list publishes `remoteId`, and that
- // run still has a backend session to stop.
- const activeSessionId = sessionId ?? lazilyCreatedSessionIdRef.current;
- if (activeSessionId == null) {
- abortControllerRef.current?.abort();
+ if (cancelInFlightRef.current != null) {
+ await cancelInFlightRef.current;
return;
}
- const conversationSessionId = await resolveActiveSessionId(
- activeSessionId,
- resolveConversationSessionIdRef.current,
- );
- const runningTurn = snapshotRef.current.runningTurn;
- if (runningTurn?.state.status === TURN_STATUS.PAUSED) {
- await ensureTurnSubscription({ conversationSessionId, turnId: runningTurn.id });
- }
- cancelRequestedRef.current = true;
- // Drain a healthy live SSE for the cancelled turn.done. Abort a pending
- // reconnect so cancel cannot start or keep a new subscribe after the live
- // stream dropped.
- if (streamReconnectPendingRef.current) {
- abortControllerRef.current?.abort();
- }
+
+ const run = (async () => {
+ // A turn can start before the thread list publishes `remoteId`, and that
+ // run still has a backend session to stop.
+ const activeSessionId = sessionId ?? lazilyCreatedSessionIdRef.current;
+ if (activeSessionId == null) {
+ abortControllerRef.current?.abort();
+ return;
+ }
+ const conversationSessionId = await resolveActiveSessionId(
+ activeSessionId,
+ resolveConversationSessionIdRef.current,
+ );
+ const runningTurn = snapshotRef.current.runningTurn;
+ if (runningTurn?.state.status === TURN_STATUS.PAUSED) {
+ await ensureTurnSubscription({ conversationSessionId, turnId: runningTurn.id });
+ }
+ cancelRequestedRef.current = true;
+ // Drain a healthy live SSE for the cancelled turn.done. Abort a pending
+ // reconnect so cancel cannot start or keep a new subscribe after the live
+ // stream dropped.
+ if (streamReconnectPendingRef.current) {
+ abortControllerRef.current?.abort();
+ }
+ try {
+ // Cancellation remains server-authoritative. The attached subscription
+ // delivers the cancelled turn.done for both running and paused turns.
+ await server.cancelSession({ sessionId: conversationSessionId });
+ } catch (error) {
+ onErrorRef.current?.(error);
+ throw error;
+ }
+ await activeRunRef.current?.promise.catch(() => undefined);
+ // No attached stream delivered turn.done (resumeUnavailable / detached
+ // reconnect). Finalize locally so the tip is not left status:running —
+ // clearing resumeUnavailable would otherwise bring the activity loader back.
+ updateSnapshot(finalizeLocallyCancelledTurn);
+ markResumeUnavailable(false);
+ setIsRunning(false);
+ })();
+
+ cancelInFlightRef.current = run;
try {
- // Cancellation remains server-authoritative. The attached subscription
- // delivers the cancelled turn.done for both running and paused turns.
- await server.cancelSession({ sessionId: conversationSessionId });
- } catch (error) {
- onErrorRef.current?.(error);
- throw error;
+ await run;
+ } finally {
+ if (cancelInFlightRef.current === run) {
+ cancelInFlightRef.current = null;
+ }
}
- await activeRunRef.current?.promise.catch(() => undefined);
- // No attached stream delivered turn.done (resumeUnavailable / detached
- // reconnect). Finalize locally so the tip is not left status:running —
- // clearing resumeUnavailable would otherwise bring the activity loader back.
- updateSnapshot(finalizeLocallyCancelledTurn);
- markResumeUnavailable(false);
- setIsRunning(false);
}, [ensureTurnSubscription, markResumeUnavailable, server, sessionId, updateSnapshot]);
const submitTurnEvents = useCallback(
@@ -1298,9 +1316,9 @@ export function useTrueForgeAgentMessages({
events: TurnInboundEventItem[];
submissionId: string;
optimisticSnapshot: SessionSnapshot;
- }): Promise => {
+ }): Promise => {
if (actionSubmissionsRef.current.has(submissionId)) {
- return;
+ return false;
}
const activeSessionId = sessionId ?? lazilyCreatedSessionIdRef.current;
const active = snapshotRef.current.activeStream;
@@ -1338,6 +1356,7 @@ export function useTrueForgeAgentMessages({
// authoritative point where every resolved overlay can be cleared.
return replaceSessionSnapshot(previous, {});
});
+ return true;
} catch (error) {
updateSnapshot(previous => {
const approvals = new Map(previous.requiredActions.approvals);
@@ -1456,12 +1475,22 @@ export function useTrueForgeAgentMessages({
const continueMcpAuth = useCallback(async (): Promise => {
const event: UserMcpAuthContinueInputEvent = { type: EVENT_TYPE.USER_MCP_AUTH_CONTINUE };
- await submitTurnEvents({
+ // Leave Connect up until the request succeeds. A duplicate click while this
+ // submission is in flight returns false and must not clear the prompt.
+ const accepted = await submitTurnEvents({
events: [event],
submissionId: 'mcp-auth-continue',
optimisticSnapshot: snapshotRef.current,
});
- }, [submitTurnEvents]);
+ if (!accepted) {
+ return;
+ }
+ const next = updateSnapshot(withOptimisticMcpAuthContinue);
+ // Working... needs thread isRunning as well as message status:running.
+ if (next.runningTurn?.state.status === TURN_STATUS.RUNNING) {
+ setIsRunning(true);
+ }
+ }, [submitTurnEvents, updateSnapshot]);
const resumeRun = useCallback(async () => {
const turn = runningTurnRef.current;
diff --git a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
index 3bfcb7d816..2c33601968 100644
--- a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
+++ b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
@@ -2271,10 +2271,119 @@ describe('convertTurnMessages', () => {
),
).toHaveLength(1);
+ // turn.update running can arrive while a sibling approval is still open
+ // (same bug class as concurrent MCP auth). Keep requires-action chrome.
expect(updates.at(-1)).toMatchObject({
- status: { type: 'running' },
+ status: { type: 'requires-action', reason: 'tool-calls' },
turnState: { status: 'running' },
});
+ const runningContent = updates.at(-1)?.content ?? [];
+ expect(
+ runningContent.filter(
+ part => part.type === 'tool-call' && part.approval != null && part.approval.approved === undefined,
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('keeps turnState running across later content while a sibling prompt is still open', async () => {
+ const foldState = new PeerThreadFoldState();
+ const updates = await collectStream(
+ streamTurnEvents(
+ streamFrom([
+ modelMessage({
+ id: 'm-root',
+ threadId: ROOT_THREAD_ID,
+ content: 'spawn',
+ toolCalls: [
+ {
+ id: 'spawn-a',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ {
+ id: 'spawn-b',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ threadCreated({
+ id: 't-a',
+ threadId: 'child-a',
+ title: 'a',
+ agentInfo: { type: 'dynamic', name: 'a', input: 'a' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-a' },
+ }),
+ threadCreated({
+ id: 't-b',
+ threadId: 'child-b',
+ title: 'b',
+ agentInfo: { type: 'dynamic', name: 'b', input: 'b' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-b' },
+ }),
+ modelMessage({
+ id: 'm-a',
+ threadId: 'child-a',
+ content: 'need approval',
+ toolCalls: [
+ {
+ id: 'approval-a',
+ type: 'function',
+ function: { name: 'bash', arguments: '{}' },
+ },
+ ],
+ }),
+ approvalRequired({
+ id: 'approval-event',
+ threadId: 'child-a',
+ toolCalls: [{ id: 'approval-a', sourceEventId: 'm-a' }],
+ }),
+ {
+ type: 'mcp.auth_required',
+ id: 'mcp-auth',
+ createdAt,
+ threadId: 'child-b',
+ mcpServers: [{ id: 'pylon', name: 'pylon', authUrl: 'https://example.com/pylon' }],
+ },
+ {
+ type: 'turn.update',
+ id: 'pause-1',
+ createdAt,
+ threadId: null,
+ state: { status: 'paused' },
+ },
+ {
+ type: 'user.tool_approval',
+ id: 'user-approve',
+ createdAt,
+ threadId: 'child-a',
+ toolCallId: 'approval-a',
+ approval: { status: 'allow' },
+ },
+ {
+ type: 'turn.update',
+ id: 'run-1',
+ createdAt,
+ threadId: null,
+ state: { status: 'running' },
+ },
+ // Sibling resume content must not invent paused over the running turn.
+ modelMessage({
+ id: 'm-a-2',
+ threadId: 'child-a',
+ content: 'approved agent continues',
+ }),
+ ]),
+ foldState,
+ ),
+ );
+
+ const afterContent = updates.at(-1);
+ expect(afterContent?.turnState).toEqual({ status: 'running' });
+ expect(afterContent?.status).toEqual({ type: 'requires-action', reason: 'interrupt' });
+ expect(afterContent?.metadata?.custom?.['pendingMcpAuth']).toBe(true);
});
it('folds a later approval_required after pause without another turn.update paused', async () => {
@@ -2387,7 +2496,7 @@ describe('convertTurnMessages', () => {
});
});
- it('keeps the resume cursor on mcp.auth_required until a running update answers it', async () => {
+ it('keeps the resume cursor on mcp.auth_required until user.mcp_auth_continue answers it', async () => {
const cursors: TurnSubscribeCursor[] = [];
const mcpAuth = {
type: 'mcp.auth_required' as const,
@@ -2400,6 +2509,9 @@ describe('convertTurnMessages', () => {
streamFrom([
mcpAuth,
{ type: 'turn.update', id: 'pause-mcp', createdAt, threadId: null, state: { status: 'paused' } },
+ // Sibling-thread resume must not advance past auth — only continue does.
+ { type: 'turn.update', id: 'run-sibling', createdAt, threadId: null, state: { status: 'running' } },
+ { type: 'user.mcp_auth_continue', id: 'continue-mcp', createdAt },
{ type: 'turn.update', id: 'run-mcp', createdAt, threadId: null, state: { status: 'running' } },
{ type: 'turn.done', id: 'done-mcp', createdAt, state: { status: 'done', completedAt: createdAt } },
]),
@@ -2411,7 +2523,138 @@ describe('convertTurnMessages', () => {
),
);
- expect(cursors).toEqual([{ fromEventId: 'mcp-auth' }, { afterEventId: 'run-mcp' }, { afterEventId: 'done-mcp' }]);
+ expect(cursors).toEqual([
+ { fromEventId: 'mcp-auth' },
+ { afterEventId: 'continue-mcp' },
+ { afterEventId: 'run-mcp' },
+ { afterEventId: 'done-mcp' },
+ ]);
+ });
+
+ it('prefers tool-approval chrome over MCP auth when both are pending, then shows MCP after approve', async () => {
+ const foldState = new PeerThreadFoldState();
+ const mcpServers = [{ id: 'pylon', name: 'pylon', authUrl: 'https://example.com/pylon' }];
+ const updates = await collectStream(
+ streamTurnEvents(
+ streamFrom([
+ modelMessage({
+ id: 'm-root',
+ threadId: ROOT_THREAD_ID,
+ content: 'spawn agents',
+ toolCalls: [
+ {
+ id: 'spawn-approve',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ {
+ id: 'spawn-auth',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ threadCreated({
+ id: 't-approve',
+ threadId: 'child-approve',
+ title: 'approver',
+ agentInfo: { type: 'dynamic', name: 'approver', input: 'comment' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-approve' },
+ }),
+ threadCreated({
+ id: 't-auth',
+ threadId: 'child-auth',
+ title: 'auther',
+ agentInfo: { type: 'dynamic', name: 'auther', input: 'events' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-auth' },
+ }),
+ modelMessage({
+ id: 'm-approve',
+ threadId: 'child-approve',
+ content: 'need approval',
+ toolCalls: [
+ {
+ id: 'approval-1',
+ type: 'function',
+ function: { name: 'save_comment', arguments: '{"body":"Test"}' },
+ toolInfo: {
+ type: 'mcp',
+ name: 'save_comment',
+ serverId: 'linear',
+ serverName: 'linear',
+ },
+ },
+ ],
+ }),
+ approvalRequired({
+ id: 'approval-event',
+ threadId: 'child-approve',
+ toolCalls: [{ id: 'approval-1', sourceEventId: 'm-approve' }],
+ }),
+ {
+ type: 'mcp.auth_required',
+ id: 'mcp-auth',
+ createdAt,
+ threadId: 'child-auth',
+ mcpServers,
+ },
+ {
+ type: 'turn.update',
+ id: 'pause-both',
+ createdAt,
+ threadId: null,
+ state: { status: 'paused' },
+ },
+ {
+ type: 'user.tool_approval',
+ id: 'user-approve',
+ createdAt,
+ threadId: 'child-approve',
+ toolCallId: 'approval-1',
+ approval: { status: 'allow' },
+ },
+ {
+ type: 'turn.update',
+ id: 'run-after-approve',
+ createdAt,
+ threadId: null,
+ state: { status: 'running' },
+ },
+ {
+ type: 'turn.update',
+ id: 'pause-auth-only',
+ createdAt,
+ threadId: null,
+ state: { status: 'paused' },
+ },
+ ]),
+ foldState,
+ ),
+ );
+
+ // While both are open: approval status wins, but MCP metadata stays for an
+ // instant Connect handoff once the last approval is answered.
+ const bothPaused = updates.find(
+ update =>
+ update.turnState?.status === 'paused' &&
+ update.status?.type === 'requires-action' &&
+ update.status.reason === 'tool-calls' &&
+ update.metadata?.custom?.['pendingMcpAuth'] === true,
+ );
+ expect(bothPaused?.metadata?.custom?.['mcpServers']).toEqual(mcpServers);
+
+ const afterApproveRunning = updates.find(update => update.turnState?.status === 'running');
+ expect(afterApproveRunning?.metadata?.custom?.['pendingMcpAuth']).toBe(true);
+ expect(afterApproveRunning?.metadata?.custom?.['mcpServers']).toEqual(mcpServers);
+ expect(afterApproveRunning?.status).toEqual({ type: 'requires-action', reason: 'interrupt' });
+
+ const final = updates.at(-1);
+ expect(final?.turnState?.status).toBe('paused');
+ expect(final?.metadata?.custom?.['pendingMcpAuth']).toBe(true);
+ expect(final?.metadata?.custom?.['mcpServers']).toEqual(mcpServers);
+ expect(final?.status).toEqual({ type: 'requires-action', reason: 'interrupt' });
});
it('stamps sandboxId onto every content yield after sandbox.created is seen', async () => {
diff --git a/packages/assistant-ui-runtime/test/mcpAuth.test.ts b/packages/assistant-ui-runtime/test/mcpAuth.test.ts
new file mode 100644
index 0000000000..d3893f696d
--- /dev/null
+++ b/packages/assistant-ui-runtime/test/mcpAuth.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import { buildMcpAuthTextParts, withOptimisticMcpAuthContinue } from '../src/mcpAuth.js';
+import { createEmptySessionSnapshot, replaceSessionSnapshot, STREAM_SEGMENT_STATUS } from '../src/sessionSnapshot.js';
+
+const createdAt = new Date().toISOString();
+const mcpServers = [{ id: 'pylon', name: 'pylon', authUrl: 'https://example.com/pylon' }];
+
+describe('withOptimisticMcpAuthContinue', () => {
+ it('wakes a paused MCP-only tip so Working can show immediately', () => {
+ const snapshot = replaceSessionSnapshot(createEmptySessionSnapshot(), {
+ pendingMcpAuth: {
+ type: 'mcp.auth_required',
+ id: 'mcp-1',
+ createdAt,
+ threadId: null,
+ mcpServers,
+ },
+ runningTurn: {
+ id: 'turn-1',
+ sessionId: 'session-1',
+ createdAt,
+ state: { status: 'paused' },
+ },
+ activeStream: {
+ turnId: 'turn-1',
+ segmentStatus: STREAM_SEGMENT_STATUS.PAUSED,
+ update: {
+ content: [{ type: 'text', text: 'Need auth' }, ...buildMcpAuthTextParts()],
+ status: { type: 'requires-action', reason: 'interrupt' },
+ turnState: { status: 'paused' },
+ metadata: {
+ custom: { pendingMcpAuth: true, mcpServers },
+ },
+ },
+ },
+ });
+
+ const next = withOptimisticMcpAuthContinue(snapshot);
+
+ expect(next.pendingMcpAuth).toBeUndefined();
+ expect(next.runningTurn?.state).toEqual({ status: 'running' });
+ expect(next.activeStream?.segmentStatus).toBe(STREAM_SEGMENT_STATUS.OPEN);
+ expect(next.activeStream?.update.status).toEqual({ type: 'running' });
+ expect(next.activeStream?.update.turnState).toEqual({ status: 'running' });
+ expect(next.activeStream?.update.metadata?.custom?.['pendingMcpAuth']).toBeUndefined();
+ expect(next.activeStream?.update.content).toEqual([{ type: 'text', text: 'Need auth' }]);
+ });
+});
diff --git a/packages/assistant-ui-runtime/test/streamTurn.test.ts b/packages/assistant-ui-runtime/test/streamTurn.test.ts
index 13806d2f36..825ae25536 100644
--- a/packages/assistant-ui-runtime/test/streamTurn.test.ts
+++ b/packages/assistant-ui-runtime/test/streamTurn.test.ts
@@ -402,8 +402,9 @@ describe('streamTurn', () => {
},
},
{
+ // Sibling/orchestrator running does not clear pending approval chrome.
sequenceNumber: 5,
- status: { type: 'running' },
+ status: { type: 'requires-action', reason: 'tool-calls' },
turnState: { status: 'running' },
},
{
diff --git a/packages/assistant-ui-runtime/test/turnStreamUpdate.test.ts b/packages/assistant-ui-runtime/test/turnStreamUpdate.test.ts
index d2c05017cd..eb6f5f1b3f 100644
--- a/packages/assistant-ui-runtime/test/turnStreamUpdate.test.ts
+++ b/packages/assistant-ui-runtime/test/turnStreamUpdate.test.ts
@@ -47,6 +47,25 @@ describe('cursorFromTurnEvents', () => {
]),
).toEqual({ afterEventId: 'done' });
});
+
+ it('keeps mcp auth when a sibling turn.update running is newest', () => {
+ expect(
+ cursorFromTurnEvents([
+ { type: 'turn.update', id: 'running', state: { status: 'running' } },
+ { type: 'mcp.auth_required', id: 'auth' },
+ ]),
+ ).toEqual({ fromEventId: 'auth' });
+ });
+
+ it('ends mcp auth on user.mcp_auth_continue even if running follows', () => {
+ expect(
+ cursorFromTurnEvents([
+ { type: 'turn.update', id: 'running', state: { status: 'running' } },
+ { type: 'user.mcp_auth_continue', id: 'continue' },
+ { type: 'mcp.auth_required', id: 'auth' },
+ ]),
+ ).toEqual({ afterEventId: 'running' });
+ });
});
describe('createSubscribeReplayProgress', () => {
diff --git a/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx b/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
index a4623eda89..8c83e10a2e 100644
--- a/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
+++ b/packages/assistant-ui-runtime/test/useTrueForgeAgentMessages.test.tsx
@@ -1924,7 +1924,14 @@ describe('useTrueForgeAgentMessages', () => {
});
});
- it('submits MCP auth continuation on the paused turn', async () => {
+ it('submits MCP auth continuation and clears Connect only after the request succeeds', async () => {
+ let resolveSend: (() => void) | undefined;
+ vi.mocked(mockServer.sendTurnEvents).mockImplementation(
+ () =>
+ new Promise(resolve => {
+ resolveSend = () => resolve([]);
+ }),
+ );
vi.mocked(loadSessionSnapshot).mockResolvedValue(
snapshotWithAssistantMessage({
id: 'turn-1-assistant',
@@ -1949,15 +1956,25 @@ describe('useTrueForgeAgentMessages', () => {
const { result } = renderHook(() => useTrueForgeAgentMessages({ server: mockServer, sessionId: 'session-1' }));
await waitFor(() => expect(result.current.messages).toHaveLength(1));
- await act(async () => {
- await result.current.continueMcpAuth();
+ let continued: Promise | undefined;
+ act(() => {
+ continued = result.current.continueMcpAuth();
});
-
+ await waitFor(() => expect(mockServer.sendTurnEvents).toHaveBeenCalledTimes(1));
expect(mockServer.sendTurnEvents).toHaveBeenCalledWith({
sessionId: 'session-1',
turnId: 'turn-1',
events: [{ type: 'user.mcp_auth_continue' }],
});
+ expect(result.current.messages[0]?.metadata.custom?.['pendingMcpAuth']).toBe(true);
+
+ await act(async () => {
+ resolveSend?.();
+ await continued;
+ });
+
+ expect(result.current.messages[0]?.metadata.custom?.['pendingMcpAuth']).toBeUndefined();
+ expect(result.current.messages[0]?.status).toEqual({ type: 'running' });
});
it('uses the stored event-id cursor when subscribing before an action', async () => {
diff --git a/packages/trueforge-ui/src/atoms/ComposerSections.tsx b/packages/trueforge-ui/src/atoms/ComposerSections.tsx
index d3e937cc3d..162a2a183a 100644
--- a/packages/trueforge-ui/src/atoms/ComposerSections.tsx
+++ b/packages/trueforge-ui/src/atoms/ComposerSections.tsx
@@ -22,6 +22,8 @@ export type ComposerSendButtonProps = {
disabled: boolean;
canSubmit: boolean;
isRunning: boolean;
+ /** True while a cancel request is in flight. */
+ isCancelling?: boolean;
/** True when the composer has trimmed text or attachments. */
hasContent: boolean;
onSubmit: () => void;
@@ -52,14 +54,28 @@ export function ComposerRightSection(_: ComposerRightSectionProps): ReactNode {
return null;
}
-export function ComposerSendButton({ canSubmit, isRunning, hasContent, onSubmit, onCancel }: ComposerSendButtonProps) {
+export function ComposerSendButton({
+ canSubmit,
+ isRunning,
+ isCancelling = false,
+ hasContent,
+ onSubmit,
+ onCancel,
+}: ComposerSendButtonProps) {
// Cancel only while busy with an empty composer. Content (even when Send is
- // blocked by a missing model) keeps the Send affordance.
- if (isRunning && !hasContent) {
+ // blocked by a missing model) keeps the Send affordance. Keep the control
+ // visible while cancel is in flight even if the thread already looks idle.
+ if ((isRunning || isCancelling) && !hasContent) {
return (
-
+
- Cancel
+ {isCancelling ? 'Cancelling...' : 'Cancel'}
);
}
diff --git a/packages/trueforge-ui/src/atoms/ComposerShell.tsx b/packages/trueforge-ui/src/atoms/ComposerShell.tsx
index cc7e6bf513..c0dbec8443 100644
--- a/packages/trueforge-ui/src/atoms/ComposerShell.tsx
+++ b/packages/trueforge-ui/src/atoms/ComposerShell.tsx
@@ -11,6 +11,8 @@ export type ComposerShellProps = {
disabled: boolean;
canSubmit: boolean;
isRunning?: boolean;
+ /** True while a cancel request is in flight. */
+ isCancelling?: boolean;
/** True when the composer has trimmed text or attachments. */
hasContent?: boolean;
attachments?: ReactNode;
@@ -28,6 +30,7 @@ export function ComposerShell({
disabled,
canSubmit,
isRunning = false,
+ isCancelling = false,
hasContent = false,
attachments,
modelLabel,
@@ -76,6 +79,7 @@ export function ComposerShell({
disabled={disabled}
canSubmit={canSubmit}
isRunning={isRunning}
+ isCancelling={isCancelling}
hasContent={hasContent}
onSubmit={onSubmit}
onCancel={onCancel}
diff --git a/packages/trueforge-ui/src/containers/AskUserContainer.tsx b/packages/trueforge-ui/src/containers/AskUserContainer.tsx
index b0d20b2d82..740b64502f 100644
--- a/packages/trueforge-ui/src/containers/AskUserContainer.tsx
+++ b/packages/trueforge-ui/src/containers/AskUserContainer.tsx
@@ -1,6 +1,5 @@
'use client';
-import { useThreadIsRunning } from '@assistant-ui/core/react';
import { useTrueForgeToolResponses } from '@truefoundry/trueforge-assistant-ui-runtime';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
@@ -19,7 +18,6 @@ export function AskUserContainer({ disabled = false }: { disabled?: boolean }) {
const AskUserPrompt = useSlot('AskUserPrompt');
const { pending, respond } = useTrueForgeToolResponses();
const track = useTrackAnalytics();
- const isRunning = useThreadIsRunning();
const item = pending[0];
const questions = useMemo(
@@ -59,7 +57,9 @@ export function AskUserContainer({ disabled = false }: { disabled?: boolean }) {
);
const selectedResponse =
currentAnswer.radioValue === ASK_USER_CUSTOM_OPTION ? currentAnswer.custom.trim() : currentAnswer.radioValue.trim();
- const isSubmitDisabled = isRunning || disabled || currentQuestion == null || selectedResponse.length === 0;
+ // Do not gate on thread isRunning: a sibling sub-agent can keep the turn
+ // running while this ask-user prompt is still waiting for an answer.
+ const isSubmitDisabled = disabled || currentQuestion == null || selectedResponse.length === 0;
const isSubmitAllDisabled = isSubmitDisabled || !allQuestionsAnswered;
const onCurrentAnswerChange = useCallback((questionId: string, update: Partial) => {
@@ -90,7 +90,7 @@ export function AskUserContainer({ disabled = false }: { disabled?: boolean }) {
return (
(null);
+ const [isCancelling, setIsCancelling] = useState(false);
+ const cancellingRef = useRef(false);
// Running/pause no longer lock the input — only session permissions do.
const disabled = !canManageSession;
const canSubmit = canSubmitComposer({ disabled, hasText, hasAttachments, requiresModel, hasModel });
@@ -179,13 +181,22 @@ function ComposerBody({
canSubmit={canSubmit}
hasContent={hasContent}
isRunning={isBusy}
+ isCancelling={isCancelling}
onSubmit={submit}
onCancel={
canManageSession
? () => {
+ if (cancellingRef.current) return;
+ cancellingRef.current = true;
+ setIsCancelling(true);
track(AnalyticsEvents.Message.CANCELLED, withSessionProps(undefined, { sessionId, ...shellAgent }));
resetBusy();
- void cancel();
+ void cancel()
+ .catch(() => undefined)
+ .finally(() => {
+ cancellingRef.current = false;
+ setIsCancelling(false);
+ });
}
: undefined
}
diff --git a/packages/trueforge-ui/src/containers/CustomActionContainer.tsx b/packages/trueforge-ui/src/containers/CustomActionContainer.tsx
index d06f146898..e2cefb7383 100644
--- a/packages/trueforge-ui/src/containers/CustomActionContainer.tsx
+++ b/packages/trueforge-ui/src/containers/CustomActionContainer.tsx
@@ -1,6 +1,5 @@
'use client';
-import { useThreadIsRunning } from '@assistant-ui/core/react';
import { useTrueForgeToolResponses } from '@truefoundry/trueforge-assistant-ui-runtime';
import { useCallback } from 'react';
@@ -10,7 +9,6 @@ import { useOptionalCustomActionRenderers } from '../server/CustomActionRenderer
export function CustomActionContainer({ disabled = false }: { disabled?: boolean }) {
const renderers = useOptionalCustomActionRenderers();
const { pending, respond } = useTrueForgeToolResponses();
- const isRunning = useThreadIsRunning();
const item = pending[0];
const onSubmit = useCallback(
@@ -27,5 +25,7 @@ export function CustomActionContainer({ disabled = false }: { disabled?: boolean
const Renderer = renderers?.[item.toolName];
if (Renderer == null) return null;
- return ;
+ // Do not gate on thread isRunning: a sibling sub-agent can keep the turn
+ // running while this custom action is still waiting for input.
+ return ;
}
diff --git a/packages/trueforge-ui/src/containers/McpAuthContainer.tsx b/packages/trueforge-ui/src/containers/McpAuthContainer.tsx
index c2027d2eec..2bdb3878aa 100644
--- a/packages/trueforge-ui/src/containers/McpAuthContainer.tsx
+++ b/packages/trueforge-ui/src/containers/McpAuthContainer.tsx
@@ -1,6 +1,5 @@
'use client';
-import { useThreadIsRunning } from '@assistant-ui/core/react';
import { useTrueForgeMcpAuth } from '@truefoundry/trueforge-assistant-ui-runtime';
import { useEffect, useRef, useState } from 'react';
@@ -22,6 +21,7 @@ function CatalogMcpAuthPrompt({ servers, onContinue, readOnly }: McpAuthPromptPr
const [connectedServerIds, setConnectedServerIds] = useState>(() => new Set());
const connectedServerIdsRef = useRef(connectedServerIds);
const [isResuming, setIsResuming] = useState(false);
+ const [continueAccepted, setContinueAccepted] = useState(false);
const resumedRef = useRef(false);
const promptGenerationRef = useRef(0);
@@ -33,13 +33,16 @@ function CatalogMcpAuthPrompt({ servers, onContinue, readOnly }: McpAuthPromptPr
);
const startResume = () => {
- if (readOnly || resumedRef.current) return;
+ if (readOnly || resumedRef.current || continueAccepted) return;
resumedRef.current = true;
setIsResuming(true);
- // Always clear the in-flight lock when the call settles. A 2xx ack does not
- // mean the turn woke (BE may stub the inbox or fail to resume); if this
- // prompt is still mounted the user must be able to retry Continue.
+ // On success, hide as soon as loading ends so Continue cannot be clicked
+ // again while the turn catches up. Failures keep the prompt for retry;
+ // runtime/stream can also bring Connect back if auth is still required.
void onContinue()
+ .then(() => {
+ setContinueAccepted(true);
+ })
.catch(() => undefined)
.finally(() => {
resumedRef.current = false;
@@ -59,6 +62,8 @@ function CatalogMcpAuthPrompt({ servers, onContinue, readOnly }: McpAuthPromptPr
});
};
+ if (continueAccepted) return null;
+
return (
{
+ if (readOnly || resumedRef.current || continueAccepted) return;
+ resumedRef.current = true;
+ setIsResuming(true);
+ void onContinue()
+ .then(() => {
+ setContinueAccepted(true);
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ resumedRef.current = false;
+ setIsResuming(false);
+ });
+ };
+
+ if (continueAccepted) return null;
+
+ const handleConnect = (serverId: string) => {
+ const server = servers.find(s => s.id === serverId);
+ if (server?.authUrl) {
+ window.open(server.authUrl, '_blank', 'noopener,noreferrer');
+ }
+ };
+
+ return (
+
+ );
+}
+
+export function McpAuthContainer({ disabled = false }: { disabled?: boolean }) {
const { pending, continue: continueMcpAuth } = useTrueForgeMcpAuth();
- const isRunning = useThreadIsRunning();
const catalog = useOptionalCatalogServer();
if (!pending) return null;
+ // Do not gate on thread isRunning: a sibling sub-agent can keep the turn
+ // running while this prompt is still the path to finish MCP auth.
+ const readOnly = disabled;
+ const pendingServerKey = JSON.stringify(pending.mcpServers.map(server => server.id));
+
if (catalog) {
- const pendingServerKey = JSON.stringify(pending.mcpServers.map(server => server.id));
return (
);
}
- const handleConnect = (serverId: string) => {
- const server = pending.mcpServers.find(s => s.id === serverId);
- if (server?.authUrl) {
- window.open(server.authUrl, '_blank', 'noopener,noreferrer');
- }
- };
-
return (
- {
- if (!disabled) void continueMcpAuth();
- }}
- readOnly={isRunning || disabled}
+ onContinue={continueMcpAuth}
+ readOnly={readOnly}
/>
);
}
diff --git a/packages/trueforge-ui/src/hooks/useComposerPauseView.ts b/packages/trueforge-ui/src/hooks/useComposerPauseView.ts
index 2651cd739b..1a7aad0cdd 100644
--- a/packages/trueforge-ui/src/hooks/useComposerPauseView.ts
+++ b/packages/trueforge-ui/src/hooks/useComposerPauseView.ts
@@ -38,10 +38,8 @@ export function useComposerPauseView(): ComposerPauseView {
const { pending: approvalsPending } = useTrueForgeApprovals();
const customActionRenderers = useOptionalCustomActionRenderers();
- if (mcpPending) {
- return { kind: 'mcp' };
- }
-
+ // Tool input (ask-user / approval) before MCP auth: when both are open,
+ // show "N tools need your input" first; Connect appears after those clear.
const firstPending = toolResponsesPending[0];
if (firstPending != null) {
const toolName = firstPending.toolName;
@@ -55,5 +53,9 @@ export function useComposerPauseView(): ComposerPauseView {
return { kind: 'approval' };
}
+ if (mcpPending) {
+ return { kind: 'mcp' };
+ }
+
return { kind: 'compose' };
}
diff --git a/packages/trueforge-ui/test/containers/AskUserContainer.test.tsx b/packages/trueforge-ui/test/containers/AskUserContainer.test.tsx
index 186860f689..462f1ff0fb 100644
--- a/packages/trueforge-ui/test/containers/AskUserContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/AskUserContainer.test.tsx
@@ -7,16 +7,11 @@ import { AskUserContainer } from '@/containers/AskUserContainer.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
const useToolResponses = vi.hoisted(() => vi.fn());
-const useThreadRunning = vi.hoisted(() => vi.fn());
vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({
useTrueForgeToolResponses: () => useToolResponses(),
}));
-vi.mock('@assistant-ui/core/react', () => ({
- useThreadIsRunning: () => useThreadRunning(),
-}));
-
function AskUserPromptProbe({
currentQuestion,
currentAnswer,
@@ -81,7 +76,6 @@ describe('AskUserContainer', () => {
beforeEach(() => {
vi.clearAllMocks();
- useThreadRunning.mockReturnValue(false);
useToolResponses.mockReturnValue({ pending: [], respond });
});
@@ -143,17 +137,20 @@ describe('AskUserContainer', () => {
expect(screen.getByRole('button', { name: 'Submit response' })).toBeDisabled();
});
- it('maps a running thread to read-only pending state', () => {
- useThreadRunning.mockReturnValue(true);
+ it('honors the disabled prop for session permissions', () => {
useToolResponses.mockReturnValue({
pending: [{ toolCallId: 'question-1', question: 'Continue?', options: ['Proceed'] }],
respond,
});
- renderSubject();
+ render(
+
+
+ ,
+ );
expect(screen.getByTestId('ask-user-probe')).toHaveAttribute('data-read-only', 'true');
expect(screen.getByRole('button', { name: 'Choose Proceed' })).toBeDisabled();
- expect(screen.getByRole('textbox', { name: 'Custom response' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'Submit response' })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: 'Choose Proceed' }));
+ expect(respond).not.toHaveBeenCalled();
});
});
diff --git a/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx b/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx
index 759b2a5cf9..e3e18a3d4f 100644
--- a/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx
@@ -107,6 +107,7 @@ describe('ComposerContainer', () => {
toolResponsesState.respond = vi.fn();
approvalsState.pending = [];
cancelMock.mockReset();
+ cancelMock.mockResolvedValue(undefined);
});
it('wraps the composer in an attachment dropzone by default', () => {
renderComposer();
@@ -381,6 +382,32 @@ describe('ComposerContainer', () => {
expect(screen.queryByRole('button', { name: 'Send message' })).not.toBeInTheDocument();
});
+ it('disables Cancel and shows Cancelling while cancel is in flight', async () => {
+ let resolveCancel: (() => void) | undefined;
+ cancelMock.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ resolveCancel = resolve;
+ }),
+ );
+
+ render(
+
+
+
+
+ ,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Cancelling' })).toBeDisabled());
+ fireEvent.click(screen.getByRole('button', { name: 'Cancelling' }));
+ expect(cancelMock).toHaveBeenCalledTimes(1);
+
+ resolveCancel?.();
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Cancelling' })).not.toBeInTheDocument());
+ });
+
it('sends while running without calling cancel', async () => {
const onNew = vi.fn(async () => {});
render(
diff --git a/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx b/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx
index 604c30f988..eab9e57e8a 100644
--- a/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx
@@ -9,16 +9,11 @@ import {
} from '@/server/CustomActionRenderersContext.js';
const useToolResponses = vi.hoisted(() => vi.fn());
-const useThreadRunning = vi.hoisted(() => vi.fn());
vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({
useTrueForgeToolResponses: () => useToolResponses(),
}));
-vi.mock('@assistant-ui/core/react', () => ({
- useThreadIsRunning: () => useThreadRunning(),
-}));
-
function SecretSelectProbe({ args, disabled, onSubmit }: CustomActionRendererProps) {
const secrets = Array.isArray(args.secrets)
? args.secrets.filter((value): value is string => typeof value === 'string')
@@ -49,7 +44,6 @@ describe('CustomActionContainer', () => {
beforeEach(() => {
vi.clearAllMocks();
- useThreadRunning.mockReturnValue(false);
useToolResponses.mockReturnValue({ pending: [], respond });
});
@@ -90,15 +84,19 @@ describe('CustomActionContainer', () => {
expect(respond).toHaveBeenCalledWith({ toolCallId: 'tc-secret', content: 'prod-db' });
});
- it('disables the host component while the thread is running', () => {
- useThreadRunning.mockReturnValue(true);
+ it('honors the disabled prop for session permissions', () => {
useToolResponses.mockReturnValue({
pending: [{ toolCallId: 'tc-secret', toolName: 'secret_select', args: {} }],
respond,
});
- renderSubject();
+ render(
+
+
+ ,
+ );
expect(screen.getByTestId('secret-select-probe')).toHaveAttribute('data-disabled', 'true');
- expect(screen.getByRole('button', { name: 'Choose prod-db' })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: 'Choose prod-db' }));
+ expect(respond).not.toHaveBeenCalled();
});
});
diff --git a/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx b/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx
index 611e855ecd..0e6bc39fd5 100644
--- a/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx
@@ -102,9 +102,13 @@ describe('McpAuthContainer', () => {
expect(continueMcpAuth).toHaveBeenCalledTimes(1);
});
- it('disables Continue while the thread is running', () => {
- render();
- expect(screen.getByRole('button', { name: /continue/i })).toBeDisabled();
+ it('keeps Continue enabled while the thread is running with pending MCP auth', () => {
+ const continueMcpAuth = vi.fn().mockResolvedValue(undefined);
+ render();
+ const continueButton = screen.getByRole('button', { name: /continue/i });
+ expect(continueButton).toBeEnabled();
+ fireEvent.click(continueButton);
+ expect(continueMcpAuth).toHaveBeenCalledTimes(1);
});
it('shows each successful catalog connection and resumes once all servers are connected', async () => {
@@ -153,8 +157,9 @@ describe('McpAuthContainer', () => {
await act(async () => {
resolveResume?.();
});
- // Ack without clearing pending MCP auth must allow another Continue click.
- await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled());
+ // Successful Continue hides the prompt immediately so it cannot be clicked twice
+ // while the turn wakes; a later mcp.auth_required can bring Connect back.
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Continue' })).not.toBeInTheDocument());
});
it('keeps a failed catalog connection available without resuming', async () => {
@@ -285,9 +290,10 @@ describe('McpAuthContainer', () => {
fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
await waitFor(() => expect(getMcpConnector).toHaveBeenCalledWith({ connectorId: GITHUB_SERVER.id }));
- await waitFor(() => expect(screen.getByText('Connected')).toBeInTheDocument());
+ await waitFor(() => expect(continueMcpAuth).toHaveBeenCalledTimes(1));
+ // Auto-Continue after the only server connects hides the card on success.
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Continue' })).not.toBeInTheDocument());
expect(getConnector).not.toHaveBeenCalled();
- expect(continueMcpAuth).toHaveBeenCalledTimes(1);
});
it('does not resume a paused turn after the prompt unmounts mid-authorize', async () => {
diff --git a/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsx b/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsx
index f2a918180c..c1152afbe1 100644
--- a/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsx
+++ b/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsx
@@ -128,7 +128,7 @@ describe('useComposerPauseView', () => {
expect(result.current).toEqual({ kind: 'ask-user' });
});
- it('gives MCP authorization precedence over pending tool responses', () => {
+ it('gives pending tool responses precedence over MCP authorization', () => {
useAuiState.mockReturnValue(true);
useToolResponses.mockReturnValue({
pending: [{ toolCallId: 'question-1', toolName: 'secret_select' }],
@@ -138,7 +138,18 @@ describe('useComposerPauseView', () => {
wrapper: withRenderers({ secret_select: () => null }),
});
- expect(result.current).toEqual({ kind: 'mcp' });
+ expect(result.current).toEqual({ kind: 'custom', toolName: 'secret_select' });
+ });
+
+ it('gives pending tool approvals precedence over MCP authorization', () => {
+ useAuiState.mockReturnValue(true);
+ useApprovals.mockReturnValue({
+ pending: [{ approvalId: 'appr-1', threadId: 'root', toolName: 'call_tool', args: {}, argsText: '{}' }],
+ });
+
+ const { result } = renderHook(() => useComposerPauseView());
+
+ expect(result.current).toEqual({ kind: 'approval' });
});
it('gives custom renderers precedence over ask-user for the same pending tool', () => {