ytahdn ea8bdeeaab Feat/daemon react cli (#4380)
* feat(daemon): add shared UI transcript layer

* fix(daemon): address ui review feedback

* test(daemon): cover raw event diagnostics option

* fix(daemon): address latest ui review

* fix(daemon): cover reconnect and status edge cases

* fix(daemon): guard prompt busy cleanup

* feat(daemon): add shared UI transcript layer

* fix(daemon): address ui review feedback

* test(daemon): cover raw event diagnostics option

* fix(daemon): address latest ui review

* fix(daemon): cover reconnect and status edge cases

* fix(daemon): guard prompt busy cleanup

* fix(daemon): handle trimmed tool updates

* fix(daemon): cap transcript text blocks

* fix(daemon): dedupe trimmed tool diagnostics

* fix(daemon): harden webui transcript edge cases

* fix(daemon): preserve webui daemon events

* fix(daemon): address latest ui review comments

* feat(web-shell): add daemon-backed UI shell

* feat(web-shell): improve session routing and slash commands

* feat(daemon): add shared UI transcript layer

* fix(daemon): address ui review feedback

* test(daemon): cover raw event diagnostics option

* fix(daemon): address latest ui review

* fix(daemon): cover reconnect and status edge cases

* fix(daemon): guard prompt busy cleanup

* fix(daemon): handle trimmed tool updates

* fix(daemon): cap transcript text blocks

* fix(daemon): dedupe trimmed tool diagnostics

* fix(daemon): harden webui transcript edge cases

* fix(daemon): preserve webui daemon events

* fix(daemon): address latest ui review comments

* fix(daemon): close latest ui review nits

* fix(daemon): harden ui review edges

* fix(daemon-ui): address wenshao 2 Critical findings (#4328 review)

## Critical #1 — 401/403 reconnect storm + transcript wipe

`DaemonSessionProvider`'s reconnect loop kept retrying `createOrAttach` on
401/403 even with `autoReconnect: true`. Each cycle:
  - hit the daemon with the same bad token → 401 again
  - cleared the session handle
  - the next successful attempt (if token magically recovered) would
    receive a different sessionId, triggering the `store.reset()` branch
    at line 143 and wiping the user's transcript
  - no terminal "auth failed" state surfaced to the user

Fix: split `TERMINAL_SESSION_HTTP_STATUSES` into `AUTH_FAILURE_HTTP_STATUSES`
(401, 403) and the rest (404, 410). On auth failure, return from the
reconnect loop unconditionally regardless of the `autoReconnect` flag —
these are credential failures, not transient. The user must update
credentials; daemon spam must stop.

`extractHttpStatus` helper factored out of `isTerminalSessionHttpError` to
share between the two predicates.

## Critical #2 — rawInput / rawOutput leaking secrets to UI

`normalizer.normalizeToolUpdate` forwarded `rawInput` / `rawOutput`
verbatim onto `DaemonUiToolUpdateEvent` → `DaemonToolTranscriptBlock`. The
`details` projection was redacted via `stringifyRedactedJson` /
`redactSensitiveFields`, but the underlying `rawInput` / `rawOutput`
fields were unredacted. Any UI component that read those fields directly
(ShellToolCall, WriteToolCall, JSON debug panels) leaked the raw values
to the DOM.

Example: `{ command: 'curl', apiKey: 'sk-prod-...' }` had `apiKey`
redacted in `details` but exposed verbatim on `rawInput`.

Fix: apply `redactSensitiveFields` to both `rawInput` and `rawOutput`
ONCE at the normalizer boundary, then reuse the redacted shape for the
`details` projection. Downstream is uniformly safe; no double traversal.

## Tests (49/49 pass)

- SDK `daemonUi.test.ts` (36 tests, +1) — new test `redacts sensitive
  fields in tool.update rawInput and rawOutput at normalizer boundary`
  verifies full-event string scan finds zero secret values + structural
  keys preserved with values `'[redacted]'`.
- WebUI `DaemonSessionProvider.test.tsx` (13 tests, +2) — new tests
  `breaks out of the reconnect loop on 401 / 403 auth failures even when
  autoReconnect is true` and `still reconnects on 404 / 410
  session-not-found errors when autoReconnect is true` lock in the
  asymmetry: auth failure → 1 attempt only; session-not-found → retries
  until success.

## Out of scope (declined / deferred — see PR review reply)

- CRIT #3 `withActionTimeout` test coverage gap → behavior correct,
  test-only follow-up (avoids PR bloat)
- Suggestions #4-7 → 4 nice-to-haves, deferred to keep PR focused on
  production-correctness fixes

Generated with AI

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>

* fix(daemon-ui): redact tool details in web transcript

* feat(web-shell): align daemon UI interactions

* fix(web-shell): address daemon UI review comments

* feat(web-shell): sync independent web-shell with lib build, i18n, and daemon serve enhancements

Bring in the independently developed web-shell package with full lib
build support (vite.lib.config.ts, tsconfig.lib.json), i18n layer,
new dialogs (Help, Theme, ReleaseSession), composer hiding during
approvals, and SDK dependency restructured as peerDependency. Also
adds daemon serve routes (detach endpoint, rename persistence) and
fixes acp-bridge testUtils missing cancelImpl.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address daemon UI review comments

- Strip token from URL after caching (prevents Referer/history leak)
- Add URL scheme allowlist for markdown links/images (block javascript:)
- Add CORS restriction in vite dev server
- Handle state_resync_required event (reset store)
- Reset promptStatus on SSE disconnect
- Handle 401/403 in reconnect loop (no retry on auth failures)
- Heartbeat consecutive failure detection (3 strikes → disconnect)
- Strip <style> tags in SVG sanitization
- Replace naive diff with LCS-based buildUnifiedDiff
- Fix inputHighlight decoration ordering (sort before add)
- Add isEditableTarget guard in useDelayedGlobalKeyDown
- Fix AskUserQuestion keyboard handler (no capture phase)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address second-round review Critical issues

- Add size guard to buildUnifiedDiff (fallback when n*m > 250k)
- Strip SVG animation elements (animate, set, animateTransform, animateMotion)
- Reset promptStatus to idle on state_resync_required
- Restrict getAllowedDaemonOrigin to same port as page origin

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address remaining PR #4380 review issues

- SVG sanitizer: strip style/use/image/feImage/mpath, block external hrefs
- Markdown: split isSafeHref/isSafeImageSrc (allow data:image for img only)
- Heartbeat: fire disconnect once at 3 failures, self-heal on success
- state_resync_required: reset store and reconnect (remove dead code)
- Auth 401/403: log error, stop reconnect loop, show error state
- replaceSessionUrl: delete ?token param to prevent leak
- removeDaemonTokenFromUrl() called at module init
- Vite dev server: cors: false
- killSession: forgetSession before byId.delete (prevent lost events)
- inputHighlight: collect ranges and sort before adding to builder
- useDelayedGlobalKeyDown: isEditableTarget guard from shared utils
- buildUnifiedDiff: proper O(nm) LCS, hasDiffContent lightweight check
- detachDaemonClient: restore console.warn for observability
- App.tsx: use rAF-coalesced messageBlocks in extractPendingPermission
- extractPendingPermission: extract toolCallId from toolCall record
- vite.lib.config: wrap CSS injection in try/catch for CSP
- Add test coverage: server routes, SDK methods, transcriptAdapter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address third-round PR #4380 review issues

Critical fixes:
- ToolApproval: reset submittedRef via useEffect on request.id change
- Effect cleanup: reject pendingSessionLoadRef on dispose
- sanitizeSvg: strip style attributes with external url() values

Suggestion fixes:
- <use> elements: keep fragment-only href, strip external (+ xlink:href fallback)
- SAFE_IMAGE_DATA_URI: remove svg+xml (can load external subresources)
- extractStreamingState: accept blocks directly, remove state dependency
- coalescedState useMemo removed — rAF coalescing no longer defeated
- Auth failure log: use missingSessionId instead of already-cleared vars
- newSession(): reject pending loadSession promise
- COPY_MESSAGES: wire constants to copyFromLastAssistantMessage
- Add 39 tests for isSafeHref, isSafeImageSrc, sanitizeSvg
- Add 3 tests for toolCallId extraction fallback
- Fix test fixtures: resolved: undefined, clientReceivedAt: 1

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): delegate readWorkspaceFile to SDK client

Replaces the manual fetch() call with session.client.readWorkspaceFile()
which provides fetchWithTimeout (30s default) and error normalization.
Ensures DaemonClient baseUrl is always absolute by falling back to
window.location.origin in proxy mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address fourth-round PR #4380 review issues

- Fix suppressedOwnUserEchoCountRef not decrementing on prompt failure
- Add heartbeat status guard to prevent overwriting 'connecting' state
- Abort stale activePrompts when SSE session disconnects
- Truncate displayName to 256 chars in renameSession endpoint
- Fix DiffView counting +++ / --- header lines as additions/deletions
- Preserve existing command properties in mergeCommands
- Fix bridge cwd override by params spread order
- Validate all href attributes on SVG <use> elements
- Extend external url() check to all SVG attributes, not just style
- Unify detachDaemonClient baseUrl with DaemonClient construction
- Delegate loadMcpTools to SDK client instead of returning stub
- Add createAtCompletionSource factory with baseUrl/token fallback
- Reset AskUserQuestion state on request.id change
- Add useEffect cleanup for queue drain setTimeout
- Suppress replay_complete from reaching UI as unrecognized event

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): address fifth-round PR #4380 review issues

- Use safeWorkspaceCwd in buildWorkspaceToolsStatus for consistency
- Wire loadMcpTools to return SDK tools instead of hardcoded empty array
- Consolidate WebShellMcpToolsStatus types (remove duplicate in McpDialog)
- Abort active prompts in loadSession before switching sessions
- Pass daemon credentials to @-completion source via Editor props

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell,cli): address PR #4380 review issues and fix duplicate user message

- Remove Session#executePrompt's emitUserMessage() call to eliminate
  duplicate user_message_chunk events (bridge-echo is the single source)
- Move removeDaemonTokenFromUrl() to main.tsx entry point (S19)
- Add mount-grace, interaction guard, safe default index to ToolApproval (Critical#1)
- Fix stale credential capture in Editor @-completion (Critical#3)
- Add submittedRef guard to AskUserQuestion, remove unsafe fallback (S18/S23)
- Use .then() pattern for clipboard writeText (S17)
- Add i18n for approval dialog and rename messages (S20)
- Add session load timeout (S15)
- Distinguish MCP error types with DaemonHttpError (S12)
- Clear stale heartbeat error on success (S13)
- Fix null vs undefined clientId check in server detach (S16)
- Add daemon.test.ts for origin validation coverage

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell,cli): address PR #4380 R9 review — detach loose equality, ToolApproval stale refs, session load timeout leak

- server.ts: change `clientId == null` to `=== null` so absent header falls through to detachClient instead of hanging the request
- server.test.ts: add test for detach without X-Qwen-Client-Id header
- ToolApproval.tsx: use refs to fix stale closures in handleKeyDown, reset submittedRef on request.id change, sync selectedRef on mouse hover, remove unstable request.options from effect deps
- useDaemonSession.ts: store and clear timeout handle in PendingSessionLoad across all resolution paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-shell): add submittedRef guard to AskUserQuestion handleCancel

Prevents double-submission on rapid Escape+Enter and avoids sending
empty optionId when no reject option exists.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com>
Co-authored-by: ytahdn <ytahdn@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 10:32:17 +08:00
..
2026-05-27 10:32:17 +08:00

Daemon UI SDK — Developer Guide

The @qwen-code/sdk/daemon subpath ships shared UI primitives for daemon clients. The current adoption target is web chat and web terminal; native local TUI, channel, and IDE integrations keep their existing default paths while the daemon UI contract stabilizes. This guide covers the API surface introduced by PR #4353 (the unified follow-up to PR #4328's shared UI transcript layer).

Three-layer model

Daemon SSE wire (NDJSON envelopes)
   │
   ▼
normalizeDaemonEvent(envelope) → DaemonUiEvent[]
   │
   ▼
reduceDaemonTranscriptEvents(state, events) → DaemonTranscriptState
   │                                            { blocks, currentToolCallId,
   │                                              approvalMode, toolProgress, ... }
   ▼
daemonBlockToMarkdown(block) / ToHtml / ToPlainText  ← your renderer plugs here
  • Normalizer: takes raw daemon SSE envelopes, returns typed UI events
  • Reducer: accumulates events into a transcript state machine
  • Render helpers: project state blocks to renderable strings

Quick start

import {
  DaemonSessionClient,
  createDaemonTranscriptStore,
  normalizeDaemonEvent,
  daemonBlockToMarkdown,
  selectCurrentTool,
  selectApprovalMode,
} from '@qwen-code/sdk/daemon';

const session = await DaemonSessionClient.createOrAttach(client, {
  workspaceCwd,
});
const store = createDaemonTranscriptStore();

for await (const envelope of session.events({ signal })) {
  const events = normalizeDaemonEvent(envelope, {
    clientId: session.clientId,
    suppressOwnUserEcho: true,
  });
  store.dispatch(events);
}

// Read state from any subscriber
store.subscribe(() => {
  const state = store.getSnapshot();
  const currentTool = selectCurrentTool(state);
  const mode = selectApprovalMode(state);
  const markdown = state.blocks.map(daemonBlockToMarkdown).join('\n\n');
  myRenderer.render({ markdown, currentTool, mode });
});

Event taxonomy (28+ types)

DaemonUiEvent is a discriminated union of all UI-facing events:

Chat-stream events

Event When
user.text.delta User message chunk arrives from daemon
assistant.text.delta Assistant streaming chunk
assistant.done Prompt completion (from sendPrompt resolve)
thought.text.delta Agent reasoning chunk
tool.update Tool call lifecycle (running / completed / cancelled)
shell.output Shell tool stdout/stderr chunk
permission.request Tool needs user authorization
permission.resolved Permission decision arrived
model.changed Session model switched
status / debug / error Status / debug / error blocks

Session-meta events (PR-A)

Event When
session.metadata.changed Session title / display name updated
session.approval_mode.changed Mode toggled (plan / default / yolo / auto-edit)
session.available_commands Slash command list refreshed

Workspace events (PR-A, Wave 3-4)

Event When
workspace.memory.changed QWEN.md / memory file modified
workspace.agent.changed Sub-agent created / updated / deleted
workspace.tool.toggled Builtin tool enabled / disabled
workspace.initialized qwen init completed
workspace.mcp.budget_warning MCP child count approaching cap
workspace.mcp.child_refused MCP server refused due to budget
workspace.mcp.server_restarted Manual MCP restart succeeded
workspace.mcp.server_restart_refused Manual restart blocked

Auth device-flow events (PR-A, Wave 4 OAuth)

auth.device_flow.{started,throttled,authorized,failed,cancelled}

Each carries the daemon's deviceFlowId. Failed events carry a closed-enum errorKind (closed enum — see KNOWN_DEVICE_FLOW_ERROR_KINDS exported from @qwen-code/sdk/daemon for the canonical list, currently: expired_token / access_denied / invalid_grant / upstream_error / persist_failed / not_found_or_evicted).

Render contract (PR-D)

Three projection helpers, one preview helper. All discriminate on block.kind or preview.kind:

daemonBlockToMarkdown(block, { sanitizeUrls?, maxFieldLength?, locale? })
daemonBlockToHtml(block, { sanitizer?, ...renderOpts })
daemonBlockToPlainText(block, renderOpts)
daemonToolPreviewToMarkdown(preview, renderOpts)

Cookbook: render a transcript to markdown

const markdown = state.blocks
  .map((b) => daemonBlockToMarkdown(b, { sanitizeUrls: true }))
  .join('\n\n');

Cookbook: render to sanitized HTML for SSR

import DOMPurify from 'dompurify';
import MarkdownIt from 'markdown-it';
const md = new MarkdownIt();

const html = state.blocks
  .map((b) => {
    // Two-stage pipeline: markdown → HTML → DOMPurify
    const rawHtml = md.render(daemonBlockToMarkdown(b));
    return DOMPurify.sanitize(rawHtml);
  })
  .join('\n');

Or use the built-in conservative HTML renderer (no markdown parsing, just HTML escape):

const html = state.blocks
  .map((b) => daemonBlockToHtml(b, { sanitizer: DOMPurify.sanitize }))
  .join('\n');

Cookbook: copy-paste plain text

const plain = state.blocks.map(daemonBlockToPlainText).join('\n');
navigator.clipboard.writeText(plain);

Tool preview taxonomy (13 kinds)

Kind Surface
ask_user_question Multi-choice question with options
command Bash-style command + cwd
file_diff File edit with oldText/newText or patch
file_read Path + optional line range
web_fetch URL + HTTP method
mcp_invocation MCP server + tool + args summary
code_block Language-tagged code snippet
search Query + result count + top results
tabular Columns + rows (capped at 50, truncation flagged)
image_generation Prompt + optional thumbnail URL
subagent_delegation Agent name + task
key_value Generic label/value rows
generic Fallback summary

Each has a daemonToolPreviewToMarkdown projection. Custom renderers can dispatch on preview.kind for rich per-type display (file diff with syntax highlighting, MCP server badge, image thumbnail, etc.).

State selectors (PR-E)

selectCurrentTool(state); // → DaemonToolTranscriptBlock | undefined
selectApprovalMode(state); // → 'plan' | 'default' | 'auto-edit' | 'yolo' | undefined
selectToolProgress(state, toolCallId); // → { ratio?, step? } | undefined
selectPendingPermissionBlocks(state); // → ReadonlyArray<DaemonPermissionTranscriptBlock>
selectTranscriptBlocks(state); // → ReadonlyArray<DaemonTranscriptBlock>
selectTranscriptBlocksOrderedByEventId(state); // sorted by daemon-monotonic id

// PR-K — sub-agent nesting
selectSubagentChildBlocks(state, parentToolCallId); // direct children only
isSubagentChildBlock(block); // type guard: was this tool invoked inside a sub-agent?

currentToolCallId is automatically maintained by the reducer:

  • Set when a tool enters in-flight status (running / in_progress / pending / confirming)
  • Cleared when tool enters terminal status (completed / failed / cancelled / etc.)
  • Unknown statuses leave it untouched (forward-compat)

Cancellation propagation (PR-E)

When assistant.done.reason === 'cancelled', the reducer walks every in-flight tool block and force-sets its status to 'cancelled'. Daemon does not guarantee a terminal tool_call_update for every in-flight tool when the parent prompt is cancelled — this propagation prevents UI spinners from spinning forever.

Sub-agent children are cancelled together with their parent because cancellation iterates every in-flight tool block in toolBlockByCallId, not just the current pointer.

Sub-agent nesting (PR-K)

When the main agent delegates to a sub-agent (the Task tool, or equivalent), the daemon stamps parentToolCallId and subagentType on the child tool calls via tool_call._meta. The reducer reads both and:

  • Mirrors parentToolCallId + subagentType onto DaemonToolTranscriptBlock
  • Resolves parentBlockId (the parent's transcript block id) when the parent block is already in state; otherwise leaves it undefined and back-fills when the parent block later appears

Out-of-order arrival (child before parent) is handled transparently. A child whose parent gets trimmed by maxBlocks keeps parentToolCallId for selector queries, but parentBlockId is nulled (the dangling id would no longer resolve via blockIndexById).

import {
  selectSubagentChildBlocks,
  isSubagentChildBlock,
} from '@qwen-code/sdk/daemon';

// Render a parent tool block, then walk children:
function renderToolBlock(state, block) {
  if (block.kind !== 'tool') return renderOther(block);
  const children = selectSubagentChildBlocks(state, block.toolCallId);
  return (
    <ToolBlock block={block}>
      {children.length > 0 && (
        <Indent>
          {children.map((c) => renderToolBlock(state, c))}
        </Indent>
      )}
    </ToolBlock>
  );
}

// Or filter top-level vs. nested at render time:
const topLevel = state.blocks.filter((b) => !isSubagentChildBlock(b));

selectSubagentChildBlocks returns direct children only. Walk recursively to render nested sub-agents (a sub-agent inside a sub-agent). Daemon does not emit cycles, but renderers walking up via parentBlockId should still detect them defensively (e.g., depth cap or visited set).

Self-references (parentToolCallId === toolCallId) are dropped by the normalizer before reaching the reducer.

Time semantics (PR-B)

interface DaemonTranscriptBlockBase {
  eventId?: number; // PRIMARY sort key — daemon-monotonic
  serverTimestamp?: number; // PREFERRED display — daemon-authoritative
  clientReceivedAt: number; // FALLBACK — local clock
  createdAt: number; // @deprecated alias for clientReceivedAt
}

Always sort by eventId (use selectTranscriptBlocksOrderedByEventId) when displaying long sessions. The daemon-monotonic cursor is preserved across SSE replay-after-reconnect; client clocks are not.

Always format display timestamps from serverTimestamp (with fallback to clientReceivedAt). Multiple clients viewing the same session see the same "5 minutes ago" only when both read from the daemon clock.

import { formatBlockTimestamp } from '@qwen-code/sdk/daemon';

const label = formatBlockTimestamp(block, {
  locale: 'zh-CN',
  timeZone: 'Asia/Shanghai',
  timeStyle: 'short',
});

Adapter conformance (PR-G)

Validate your adapter projects the SDK's reference corpus to semantically equivalent output:

import { runAdapterConformanceSuite } from '@qwen-code/sdk/daemon';

it('my adapter conforms to daemon UI corpus', () => {
  const result = runAdapterConformanceSuite({
    reduce: (events) => myReducer(events),
    renderToText: (state) => myRenderer(state),
  });
  expect(result.failed).toEqual([]);
});

The fixture corpus (DAEMON_UI_CONFORMANCE_FIXTURES) covers chat, tool lifecycle, file edits, MCP, permissions, MCP budget warning, cancellation, malformed payload redaction, OAuth, command updates, and sub-agent nesting. (Count is derivable at runtime — read DAEMON_UI_CONFORMANCE_FIXTURES.length.)

Format-agnostic — your adapter can render to ANSI / HTML / markdown / JSX; the framework only checks semantic content via expectedContains and expectedAbsent.

Error categorization (PR-A)

DaemonUiErrorEvent.errorKind is a closed-enum propagated from the daemon's typed-error taxonomy (when the daemon stamps it):

import type { DaemonErrorKind } from '@qwen-code/sdk/daemon';
// 'missing_binary' | 'blocked_egress' | 'auth_env_error' | 'init_timeout'
// | 'protocol_error' | 'missing_file' | 'parse_error' | 'budget_exhausted'

Renderers should branch on errorKind for actionable affordances:

function errorAffordance(errorKind?: DaemonErrorKind): React.ReactNode {
  switch (errorKind) {
    case 'auth_env_error': return <button>Re-authenticate</button>;
    case 'missing_file':   return <button>Choose file</button>;
    case 'blocked_egress': return <span>Network blocked — check proxy</span>;
    default:               return null;
  }
}

Tool provenance dispatch (PR-A)

DaemonUiToolUpdateEvent.provenance is a closed-enum (builtin / mcp / subagent / unknown). With serverId?: string when mcp. Use it for icon dispatch and badging:

function toolIcon(event: DaemonUiToolUpdateEvent): React.ReactNode {
  switch (event.provenance) {
    case 'mcp':      return <McpIcon server={event.serverId} />;
    case 'subagent': return <SubagentIcon />;
    case 'builtin':  return <BuiltinIcon name={event.toolName} />;
    default:         return <GenericIcon />;
  }
}

The SDK has a mcp__<server>__<tool> naming heuristic fallback — even when daemon doesn't explicitly stamp provenance, MCP tools are detectable.

Forward-compat principles

Every layer in the daemon UI SDK follows the forward-compat principle: unknown values do NOT throw; they degrade gracefully.

  • Unknown daemon event types → debug event with the raw type name
  • Unknown tool status → currentToolCallId left untouched (no clear)
  • Unknown error kind → errorKind undefined (renderer falls back to text)
  • Missing serverTimestamp → falls back to clientReceivedAt
  • Unrecognized preview shape → generic kind with summary

This means SDK can ship ahead of daemon emission. PR-A's tool provenance heuristic, PR-B's three-location timestamp extraction, and PR-E's unknown-status preservation are all examples of "ready when daemon sends; safe when it doesn't."

Cross-references

  • PR #4328 — base PR with the shared UI transcript layer
  • PR #4353 — this PR (unified completeness follow-up)
  • Issue #3803 — daemon mode proposal
  • Issue #4175 — Mode B v0.16 implementation tracker