* feat(web-shell): add /delete command with batch delete support
Add a /delete slash command to the web-shell that allows users to
permanently delete session data files. Supports both single-session
and multi-select batch deletion with proper error handling.
Changes:
- Add POST /sessions/delete batch endpoint to daemon server
- Add deleteSessionsData() to SDK DaemonClient
- Add DeleteSessionDialog with multi-select (Space to toggle, Enter
to confirm) and search/filter support
- Add deleteSession/deleteSessions workspace actions and hooks
- Distinguish errors vs notFound in single-delete action (throw on
real errors, return false only for notFound)
- Surface failure reasons in batch delete (allFailed / partialFail
messages include first error detail)
- Normalize Error objects to string messages in server JSON response
- Add tests for server route, SDK client, and workspace provider
* fix(web-shell,cli): address PR review issues for batch delete
- Pass clientId to deleteSessionsData for ownership validation
- Add sessionIds max length (100) and deduplication
- Parallelize bridge.closeSession via Promise.allSettled
- Add server-side logging for close failures
- Reconcile selectedIds with search filter before delete
- Prune selectedIds when search query changes
- Fix notFound counting: only errors are failures
- Fix partial failure double toast: single error message
- Fix empty-state: show error message when load fails
- Fix hardcoded English "matches" → i18n key
- Remove dead targetSession parameter
- Align checkbox for current session ([-] instead of spaces)
- Add happy path test for batch delete
- Reload session list on notFound-only response
* fix(web-shell,cli): remove clientId ownership check for batch delete and improve UX
- Remove clientId validation from batch delete endpoint since workspace-level
access is sufficient authorization. The per-tab clientId check prevented
cross-tab deletion of active sessions without real security benefit (user
can bypass by resuming the session first).
- Wrap filtered sessions list in useMemo to stabilize reference and prevent
unnecessary keydown listener teardown/re-register on each render.
- Include notFound sessions in onDeleted callback so the toast correctly
reports the total count of cleaned-up sessions.
Generated with AI
* fix(web-shell,cli): address round-2 review — logging, dead code, tests
- Add comment documenting intentional no-clientId in batch delete
- Log removeSessions filesystem errors to stderr for debuggability
- Count notFound as success in deleteSession for proper UI reload
- Remove dead if (!deleteSessions) / if (!deleteSession) guards
- Fix partial-failure double-wrapped toast message
- Reset selectedIdx when exiting search mode via Enter
- Add 5 batch tests: mixed outcomes, max-100 cap, non-string
validation, dedup, and file preservation on error
Generated with AI
* fix(web-shell,cli): fix partial-failure toast and add 500 catch block test
- Revert partial-failure handler to use delete.partialFail i18n key
through onError only, removing contradictory onDeleted call
- Add test for removeSessions unexpected throw (500 catch block)
* refactor(cli): use static import for SessionService in batch delete test
---------
Co-authored-by: ytahdn <ytahdn@gmail.com>
* feat(web-shell,webui,sdk,cli): context-usage API + dialog UX improvements
- Add GET /session/:id/context-usage endpoint (SDK types, acp-bridge,
cli route, acpAgent handler with tests)
- Refactor webui daemon providers into session/ and workspace/ modules
with daemon-react-sdk subpath export
- Web-shell dialog UX: replace left back icon with right-side ESC close
button, fix keyboard scope so dialogs properly capture keys when input
is focused, blur editor when dialog opens
- Remove /stats subcommands and model dialog custom model (c key) feature
- Remove slash completion auto-submit behavior (align with CLI)
* fix(web-shell,webui,cli): address PR #4573 review issues + parallel agents display
Security fixes:
- Mermaid securityLevel reverted to 'strict', strip foreignObject/style from SVG sanitizer
- Shift+Tab no longer silently sets yolo mode (only approves current request)
- clientLifecycle uses sessionStorage for per-tab client ID isolation
Bug fixes:
- cancel() finally block guards setPromptStatus with session-ID check
- lastRecapBlockCountRef resets on session switch
- collectContextData wrapped in try/catch with field stripping
- useDaemonResource: request sequence counter prevents stale response overwrite
- ResumeDialog: shows error state when session list fails to load
- detachDaemonClient: adds keepalive:true for tab-close reliability
- server.test.ts: adds session_context_usage to EXPECTED_STAGE1_FEATURES
Performance:
- useSyncExternalStore selector hoisted via useCallback
Feature:
- Parallel agents merged display (ParallelAgentsGroup component)
Tests:
- clientLifecycle.test.ts (9 tests): sessionStorage, keepalive, detach behavior
- useDaemonResource.test.tsx (5 tests): stale response race condition coverage
- Markdown.test.ts: updated foreignObject/style assertions to expect stripping
* fix(web-shell): improve ask user question flow
Fix AskUserQuestion answer submission and rendering by forwarding answers through acp-bridge permission metadata while keeping arbitrary response fields filtered.
Improve the web-shell AskUserQuestion dialog: keep the submit tab in order, preserve custom input values, align cursor position with existing selections when switching tabs, and show selected/custom answers with a consistent underline state.
Show ask_user_question tool results without truncating the answer payload.
* fix(web-shell,webui,cli): address PR #4573 critical and suggestion review issues
Critical fixes:
- releaseSession: close session before detaching client to avoid orphaned sessions
- ParallelAgentsGroup: forward pendingApproval/onConfirm props so approvals render inside grouped agents
- fmtCategoryRow: guard against zero contextWindowSize division
Suggestion fixes:
- MemoryDialog: await reloadMemory() before showing success message
- useInputHistory: keep storageKeyRef in sync with prop changes
- App: reset lastRecapBlockCountRef on session switch to prevent auto-recap from silently failing
- App: log auto-recap errors instead of silently swallowing them
- acpAgent: log collectContextData failures instead of silent catch
* feat(web-shell): add daemon followup suggestions
* fix(web-shell): validate context-usage payload and restore question-text answer keys
- parseContextUsageMessage: add runtime check for usage.totalTokens before casting, prevent white-screen on malformed daemon payload
- AskUserQuestion buildResult: use q.question as answer key instead of numeric index, matching downstream consumers that match answers by question text
* fix(web-shell,webui): address remaining PR #4573 review issues
- sanitizeSvg: keep <style> (sanitize @import/external url()) and <foreignObject>
so mermaid diagrams render with correct theming and visible text labels
- mermaid: skip redundant mermaid.initialize() when theme unchanged
- newSession: abort in-flight prompts before resetting store
- ParallelAgentsGroup: i18n for hardcoded English strings
- vite.config: restore rollupTypes: true for NodeNext compatibility
- AskUserQuestion: restore q.question as answer key
* fix(web-shell,webui): fix mermaid error rendering, add detach logging, deduplicate session switch, and add tests
- Add suppressErrorRendering to mermaid.initialize() to prevent error SVGs from being injected into the DOM on render failure
- Replace silent catch on detachDaemonClient with console.warn for debuggability
- Extract startSessionSwitch() helper to deduplicate loadSession/resumeSession
- Update sanitizeSvg tests to match current behavior (foreignObject/style preserved)
- Add groupParallelAgents unit tests covering grouping, splitting, and edge cases
* fix(webui): resolve rebase conflicts with upstream daemon_mode_b_main
- Fix useDaemonFollowupSuggestion import path after DaemonSessionProvider move to session/
- Merge daemon/index.ts exports (keep followup suggestion + add SDK type re-exports)
- Restore lastEventId/setLastEventId in test MockSession interface
- Remove non-existent DaemonWorkspaceSkillDetail re-export
* fix(acp-bridge): validate answer value types in permission response metadata
Reject non-string values in the answers payload to prevent malformed
data from being forwarded through the permission mediator to the agent.
* fix(web-shell,webui): fix shell command output display, loading state, and detach timeout
- transcriptToMessages: create standalone tool_group for shell output
when previous message is not a tool_group (fixes silent drop of ! command output)
- actions: register sendShellCommand in activePromptsRef and manage
promptStatus lifecycle (fixes stuck loading after shell command)
- actions: wrap detachDaemonClient with withActionTimeout in releaseSession
to prevent indefinite hang when daemon is unresponsive
- ToolGroup: auto-expand bash/shell/execute_command tool output by default
- Add shell output tests for transcriptToMessages
* fix(webui): fix state_resync_required handling and catchingUp flag
- Differentiate state_resync_required by reason: epoch_reset resets store
and replays on same stream; ring_evicted preserves awaitingResync and
continues on same stream; other reasons keep original break+reconnect
- Clear awaitingResync on replay_complete so post-replay events flow
- Set catchingUp when activeSession.lastEventId is present, not only on
same-session reconnect (fixes resume catchingUp indicator)
* fix(web-shell,webui): add getTasks action and fix broken reference after rebase
- Add getTasks() to DaemonSessionActions interface and implement in actions.ts
- Fix App.tsx: actions.getTasks → sessionActions.getTasks (variable renamed
during refactor but this callsite was missed during rebase merge)
* fix(webui): fix releaseSession to use closeSession instead of detach
releaseSession was incorrectly calling detachDaemonClient with the
current client's ID, which only decremented attachCount without
actually closing the target session. Replace with
session.client.closeSession() (DELETE /session/:id) to properly
terminate the session. Also fix sendShellCommand to use a distinct
shellKey to avoid colliding with prompt AbortControllers.
* feat(webui): add non-blocking prompt settlement and passive turn event handling
- Add settleActivePromptFromTurnEvent to resolve/reject active prompts
from turn_complete/turn_error SSE events in the Provider event loop
- Add isPromptLifecycleTurnEvent filter to prevent turn events from being
dispatched to the transcript store as unrecognized debug events
- Add waitForAcceptedPromptCompletion in actions.ts to bridge the gap
between 202-accepted prompts and their eventual turn completion
- Extend ActivePrompt type with promptId, resolve/reject callbacks, and
pendingResult/pendingError for deferred settlement
- Add passive observer handling for turn_complete/turn_error so non-sender
tabs correctly end the streaming state
- Add tests for non-blocking prompt acceptance and early turn completion
---------
Co-authored-by: ytahdn <ytahdn@gmail.com>
* 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>