Skip to content
Closed
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
e16c23e
feat(serve): add pollable turn-status endpoints for daemon sessions
BenGuanRan Aug 7, 2026
f68935f
chore(serve): merge main into daemon turn-status branch
qwen-code-dev-bot Aug 7, 2026
bf111e9
Merge branch 'main' into feat/daemon-turn-status-polling
wenshao Aug 8, 2026
2e24c9a
Merge remote-tracking branch 'origin/main' into fix/pr-8682-review
BenGuanRan Aug 8, 2026
24ddb5f
test(serve): align turn status CI expectations
BenGuanRan Aug 8, 2026
83a4ebd
fix(cli): record the canonical visible turn result
BenGuanRan Aug 8, 2026
9dd8766
fix(acp-bridge): keep terminal turn status monotonic
BenGuanRan Aug 8, 2026
6153384
fix(serve): bound turn status transcript scans
BenGuanRan Aug 8, 2026
22cccee
docs(serve): define pollable turn result semantics
BenGuanRan Aug 8, 2026
91b971e
fix(serve): bound canonical turn result capture
BenGuanRan Aug 8, 2026
65d6ace
docs(serve): clarify turn result size units
BenGuanRan Aug 8, 2026
20a9dd4
Merge branch 'main' into feat/daemon-turn-status-polling
wenshao Aug 8, 2026
fa817d5
fix(daemon): resolve turn status review blockers
BenGuanRan Aug 9, 2026
f6961e7
fix(daemon): preserve long streamed turn results
BenGuanRan Aug 9, 2026
0df9510
fix(daemon): harden turn status failure handling
BenGuanRan Aug 9, 2026
4f59282
fix(cli): keep polled turn results user-visible
BenGuanRan Aug 9, 2026
1343d90
fix(cli): harden polled turn result isolation
BenGuanRan Aug 9, 2026
3493ae0
Merge origin/main into feat/daemon-turn-status-polling
BenGuanRan Aug 9, 2026
71dc1be
fix(daemon): harden turn result polling
BenGuanRan Aug 10, 2026
7862b28
fix(serve): return strict final turn result
BenGuanRan Aug 10, 2026
24847a4
fix(serve): persist deadline turn errors
BenGuanRan Aug 10, 2026
6421afb
Merge remote-tracking branch 'origin/main' into fix/pr-8682-blockers-…
BenGuanRan Aug 10, 2026
47519e9
fix(daemon): preserve pollable turn results
BenGuanRan Aug 11, 2026
497a1d2
docs(serve): align turn status contract
BenGuanRan Aug 11, 2026
c5decf9
Merge remote-tracking branch 'origin/main' into fix/pr-8682-blockers-…
BenGuanRan Aug 11, 2026
e733b25
chore(serve): merge origin/main into daemon turn-status branch
qwen-code-dev-bot Aug 12, 2026
225d93c
fix(serve): harden turn result lifecycle
BenGuanRan Aug 12, 2026
63fa50b
chore: merge origin/main into daemon turn status
BenGuanRan Aug 12, 2026
3778916
fix(daemon): harden turn result teardown and rewind
BenGuanRan Aug 12, 2026
21883e0
Merge remote-tracking branch 'origin/main' into fix/pr-8682-blockers-…
BenGuanRan Aug 12, 2026
52dc4cf
fix(daemon): persist turn results after channel crashes
BenGuanRan Aug 12, 2026
d697356
fix(serve): preserve synchronous shutdown lifecycle
BenGuanRan Aug 12, 2026
2252fcd
Merge remote-tracking branch 'origin/main' into fix/pr-8682-blockers-…
BenGuanRan Aug 12, 2026
38a63e7
fix(serve): preserve restore admission ordering
BenGuanRan Aug 12, 2026
6b44312
fix(serve): remove blocking crash persistence
BenGuanRan Aug 12, 2026
334af79
fix(serve): unblock force kill and keep dispatched results single-sou…
BenGuanRan Aug 13, 2026
f91a3cb
chore(serve): merge origin/main into turn-status polling branch
qwen-code-dev-bot Aug 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions docs/design/daemon-turn-status-endpoint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Daemon turn-status endpoint

## Goal

Provide pollable HTTP endpoints that report one turn's state for a session:
queued, running, or settled (completed with stop reason, cancelled, error),
including the agent reply text. Today the only way to observe a turn's
outcome is the SSE stream (`turn_complete` / `turn_error` keyed by
`promptId`); a client that cannot hold an SSE connection has no way to ask
"what happened to my prompt".

## Routes

Both routes are live-session-owner scoped and read-only, in the same class as
`GET /session/:id/pending-prompts`: they resolve the owning runtime via
`resolveLiveSessionRuntime`, authorize the caller via the
`X-Qwen-Client-Id` header (`parseClientIdHeader`), and never fall back to
another runtime.

- `GET /session/:id/turns/:promptId` — status of that exact prompt.
- `200` with the turn status object.
- `404 { code: 'prompt_not_found' }` when neither the live pending queue
Comment thread
wenshao marked this conversation as resolved.
Resolved
nor the persisted transcript knows that promptId.
- `GET /session/:id/turns/current` — status of the session's current turn:
the running prompt, else the queued FIFO head, else the most recent
bridge terminal or persisted outcome, else `{ state: 'idle' }`.

Shared errors: `404` unknown session (`SessionNotFoundError`), `400`
`invalid_client_id` for a client id bound to another session.

## Response shape

```json
{
"sessionId": "session-id",
"state": "completed",
"promptId": "prompt-id",
"promptText": "Summarize the build failure",
Comment thread
BenGuanRan marked this conversation as resolved.
Resolved
"startedAt": 1786152000000,
"endedAt": 1786152012000,
"stopReason": "end_turn",
"resultText": "The build failed because the route catalog assertion is stale."
}
```

Field presence: optional fields are omitted rather than defaulted. In
particular `promptTextTruncated` / `resultTruncated` are only present when
`true` — consumers must treat an absent flag as `false`. A truncated result
also carries `resultCode: "RESULT_TEXT_TRUNCATED"` so consumers can reject an
incomplete answer without interpreting free text.

`originatorClientId`, when present, identifies the trusted client that admitted
the prompt. An `error` payload may accompany `state: 'error'` and contains a
required `message` plus an optional `code`; `prompt_deadline_exceeded` identifies
the bridge deadline terminal. Error messages are capped at 4,096 UTF-16 code
units and codes at 256, with `messageTruncated` / `codeTruncated` set only when
the corresponding value was truncated.

- `queued` / `running` mirror the bridge's live `pendingPromptList`
(`queuedAt` at admission, `startedAt` at FIFO dispatch).
- `completed` / `cancelled` / `error` come from the bridge's exactly-once
formal terminal while the daemon is live. A matching persisted
`turn_result` enriches that status with recorded content but cannot
overwrite its state, stop reason, error, or terminal timestamp. After a
daemon restart, settled state comes from the persisted record alone. A
`stopReason` of `cancelled` is reported as `state: 'cancelled'`.
- `promptText` mirrors the pending-prompt extraction: first non-empty text
block, `[image]` for image-only prompts. `resultText` is the canonical
top-level assistant answer visible to the user: subagent-owned chunks,
discrete messages, and slash-command output are excluded; when message
rewrite succeeds, rewritten text replaces the corresponding raw segment.
Tool, thought, background, and status output are also excluded. When a
response block calls a tool, its visible preamble is discarded; only the
final response block after the last tool boundary is retained. Rewrite
failure or an empty rewrite falls back to the raw top-level segment. Both
fields are capped at
`TURN_RESULT_TEXT_MAX_CHARS` (32,768 UTF-16 code units) with the paired
`*Truncated` flag. A truncated `resultText` also sets
`resultCode: "RESULT_TEXT_TRUNCATED"`.
The result cap is applied after rewritten-versus-raw selection, so excluded
or replaced text does not consume the visible-answer budget.
In-flight raw/rewrite candidates are separately bounded to 65,536 UTF-16
code units and 256 segments; loss of selected content at either bound sets
`resultTruncated`.
The cap applies to both projections: the live `queued` / `running`
status caps `promptText` the same way the settled record does, so the
same promptId reports a consistent shape before and after settlement.

## Persistence and the terminal overlay

Settled outcomes survive daemon restarts by appending one
`turn_result` system record to the EXISTING session transcript JSONL
Comment thread
wenshao marked this conversation as resolved.
Resolved
(`<projectDir>/chats/<sessionId>.jsonl`) through the existing
`ChatRecordingService` append path — no new files, no new write machinery:

- `ChatRecordingService.recordTurnResult(payload)` appends a
`type: 'system'`, `subtype: 'turn_result'` record, best-effort like
`recordFileHistorySnapshot`: a recording failure must never break turn
settlement.
- `Session` accumulates the turn in flight (`#turnRecording`): the record
is created after invocation-context validation but before admission checks,
including `assertCanStartTurn()`, for prompts carrying an invocation context
(daemon-admitted prompts only — internal cron/notification turns are not
pollable). This keeps admission failures queryable by promptId. The record
accumulates canonical visible answer segments in `sendUpdate` and settles on
every exit path (early admission-cancel, pendingSend-cancel, normal
completion, thrown error).
Each `prompt()` call captures its own record reference and settles that
exact reference; the shared slot is only published once the predecessor
turn has settled and the turn's model loop starts. This keeps DAEMON-003
deadline overlaps (the bridge releases the FIFO while the agent is still
executing the old turn) from misattributing one turn's outcome to the
Comment thread
BenGuanRan marked this conversation as resolved.
Resolved
other turn's promptId.
- Durable settled results require chat recording to be enabled for the
session. Live queue state and the recent terminal overlay remain available
while the daemon session is resident even when recording is unavailable.

Reads go through the `qwen/control/session/turn_status` ext-method on the
owning ACP child: it flushes the recording service (so a just-settled turn
is visible — the flush is best-effort and a recorder in a write-failure
state still falls through to the scan), then scans the transcript backward
from the tail with
`SessionTranscriptReader` for `turn_result` records — exact `promptId`
match, or the most recent record when no promptId is given. The scan is
bounded (10 pages x 500 records x 4 MiB per page) so a pathological lookup
cannot read a huge transcript end to end. Oversized pages fail the read;
they are not converted into a successful `turnResult: null` response.

Transcript persistence is asynchronous relative to the bridge's formal
terminal event. To prevent a completed prompt from briefly regressing to
`prompt_not_found`, each live `SessionEntry` retains recent formal terminal
statuses in insertion order. The map has a fixed limit of 64 entries,
independently of `eventRingSize`; eviction only removes the transient overlay,
so persisted records remain queryable.
Comment thread
wenshao marked this conversation as resolved.
Resolved

## Bridge resolution order

`AcpSessionBridge.getSessionTurnStatus(sessionId, context?, promptId?)`:

1. Authorize the caller against the session (mirrors `/prompt`).
2. Live state wins: a prompt on `pendingPromptList` (not removed) has not
settled, so no record can exist for it. With `promptId`, exact match;
without, the running entry, then the queued FIFO head.
3. Otherwise request the persisted record and consult the bounded terminal
overlay. For the same prompt, persisted prompt/result text enriches the
bridge terminal without changing its formal outcome. For `current`, the
newer `endedAt` wins when overlay and persistence refer to different
prompts.
4. If neither source has an outcome, return `undefined` (with promptId → 404) or `{ state: 'idle' }` (current).

`PendingPromptEntry.startedAt` is stamped at FIFO dispatch (at creation
for a prompt admitted straight to running).

## Failure semantics

- Turn settlement never depends on recording: `recordTurnResult` is
best-effort, and the Session settle path swallows recording errors.
- A transcript without `turn_result` records (session never settled a
daemon turn, or recording disabled/failed) can still return recent formal
outcomes from the live daemon overlay. After restart or overlay eviction,
an outcome that was never persisted yields `idle` / `prompt_not_found`.
- Removing either a queued or running prompt immediately publishes one
authoritative `cancelled` terminal and makes it pollable. Later agent
settlement or teardown cannot replace that outcome.
- A queued deadline publishes `error` with code
`prompt_deadline_exceeded`; polling moves directly from `queued` to that
error without an intermediate unknown result.
- A bridge deadline error remains authoritative if the agent later persists
a generic cancelled record; persisted `resultText` may still enrich the
error response.
Comment thread
wenshao marked this conversation as resolved.
Resolved
- The ext-method throws for non-live sessions; the bridge routes it only to
the owning child.
7 changes: 5 additions & 2 deletions docs/developers/qwen-serve-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ registry. Clients **must** gate UI off `features`, not off `mode` (per design
'workspace_agents', 'workspace_agent_generate', 'workspace_env',
'workspace_preflight', 'session_context', 'session_context_usage',
'session_supported_commands', 'session_tasks', 'session_monitor_tool_correlation', 'session_stats',
'session_lsp', 'session_status',
'session_lsp', 'session_status', 'session_turn_status',
'session_close', 'session_metadata', 'session_organization',
'session_archive', 'mcp_guardrails',
'workspace_mcp_manage', 'mcp_guardrail_events',
Expand Down Expand Up @@ -257,6 +257,8 @@ registry. Clients **must** gate UI off `features`, not off `mode` (per design

`session_status` advertises `GET /session/:id/status`, the live bridge summary for a single session by id. In addition to `clientCount` and `hasActivePrompt`, live sessions expose `isWaitingForPermission`, `isWaitingForUserQuestion`, `pendingInteractionCount`, and a retained `turnError` after a failed turn. The error clears when the next prompt actually starts. Both the single-session status response and workspace session lists include `turnError` and `pendingInteractions`: render-ready permission actions or `ask_user_question` questions plus the `requestId` and selectable options required by the existing permission vote routes. Each user question has an `answerKey`; vote with `answers`, for example `{ "0": "Polling" }`, keyed by that value. Persisted-only sessions omit runtime state because no runtime exists. Older daemons return `404`; pre-flight this tag before polling a single session's status instead of scanning the full session list.

`session_turn_status` advertises `GET /session/:id/turns/current` and `GET /session/:id/turns/:promptId`. The current route returns the running turn, queued FIFO head, latest settled outcome, or `{ "state": "idle" }`; the prompt-specific route returns that prompt's live or persisted outcome, including `resultText` for the final main answer shown to the user when available. A result exceeding the bounded response size carries `resultTruncated: true` and `resultCode: "RESULT_TEXT_TRUNCATED"`; consumers that require a complete answer must not deliver that result. States are `idle`, `queued`, `running`, `completed`, `cancelled`, or `error`. A supported prompt-specific lookup with no matching turn returns `404 prompt_not_found`; clients must pre-flight this tag to distinguish that result from an older daemon that lacks the routes.

`session_info` advertises `GET /workspace/:id/session-info` and its `/workspaces/:workspace/session-info` twin. The response aggregates persisted active and archived session counts without hydrating list metadata. It is an explicit O(n) disk scan and must not be polled; clients should treat `truncated: true` as a lower-bound result.

`session_approval_mode_control`, `workspace_tool_toggle`, `workspace_skill_toggle`, `workspace_skill_batch_toggle`, `workspace_init`, and `workspace_mcp_restart` advertise the mutation control routes documented below. They are strict-gated by the mutation gate (a daemon configured without a bearer token rejects them with 401 `token_required`). Older daemons return `404`; pre-flight each tag before exposing the corresponding affordance.
Expand Down Expand Up @@ -1131,6 +1133,7 @@ Capability tags:
- `session_monitor_tool_correlation` → monitor entries from `GET /session/:id/tasks`
include `toolUseId` for transcript-to-task correlation
- `session_status` → `GET /session/:id/status`
- `session_turn_status` → `GET /session/:id/turns/current` and `GET /session/:id/turns/:promptId`
- `session_info` → `GET /workspace/:id/session-info` and `GET /workspaces/:workspace/session-info`
- `session_transcript` → `GET /session/:id/transcript`
- `workspace_persisted_transcript` → `GET /workspaces/:workspace/session/:id/transcript`
Expand Down Expand Up @@ -2394,7 +2397,7 @@ ACP-over-HTTP uses the same request and response bodies through vendor methods `

### Multi-workspace live-session routing

When `multi_workspace_sessions` is advertised, live-session operations identify their workspace from the `sessionId`; clients do not add a workspace selector to the URL. In addition to the existing owner-routed lifecycle operations, this applies to `PATCH /session/:id/metadata`, `POST /session/:id/recap`, `POST /session/:id/generate`, `POST /session/:id/btw`, `POST /session/:id/mid-turn-message`, `GET /session/:id/mid-turn-messages`, `DELETE /session/:id/mid-turn-messages/:messageId`, `POST /session/:id/tasks/:taskId/cancel`, `POST /session/:id/goal/clear`, `POST /session/:id/continue`, `POST /session/:id/language`, `POST /session/:id/artifacts`, and `DELETE /session/:id/artifacts/:artifactId`. The daemon routes each request to the trusted runtime that owns the live session. An untrusted non-primary owner returns `403 untrusted_workspace`, a missing live owner returns `404 session_not_found`, and an ambiguous owner fails closed with `500 ambiguous_session_owner`.
When `multi_workspace_sessions` is advertised, live-session operations identify their workspace from the `sessionId`; clients do not add a workspace selector to the URL. In addition to the existing owner-routed lifecycle operations, this applies to `PATCH /session/:id/metadata`, `POST /session/:id/recap`, `POST /session/:id/generate`, `POST /session/:id/btw`, `POST /session/:id/mid-turn-message`, `GET /session/:id/mid-turn-messages`, `DELETE /session/:id/mid-turn-messages/:messageId`, `GET /session/:id/turns/current`, `GET /session/:id/turns/:promptId`, `POST /session/:id/tasks/:taskId/cancel`, `POST /session/:id/goal/clear`, `POST /session/:id/continue`, `POST /session/:id/language`, `POST /session/:id/artifacts`, and `DELETE /session/:id/artifacts/:artifactId`. The daemon routes each request to the trusted runtime that owns the live session. An untrusted non-primary owner returns `403 untrusted_workspace`, a missing live owner returns `404 session_not_found`, and an ambiguous owner fails closed with `500 ambiguous_session_owner`.

This rule is live-session-only and does not make every workspace-less session route multi-workspace-aware. Persisted or archived operations use their documented workspace-qualified routes. `POST /session/:id/branch`, `POST /session/:id/fork`, and `POST /session/:id/cd` intentionally remain primary-only and return `non_primary_session_route_not_supported` for non-primary owners.

Expand Down
Loading
Loading