Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
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
2 changes: 1 addition & 1 deletion backend/app/services/device/local_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ async def list_devices(
else "offline"
),
"is_default": spec.get("isDefault", False),
"device_type": spec.get("deviceType", DeviceType.LOCAL.value),
"device_type": DeviceType.LOCAL.value,
"connection_mode": spec.get(
"connectionMode", DeviceConnectionMode.WEBSOCKET.value
),
Expand Down
41 changes: 41 additions & 0 deletions backend/tests/api/ws/test_device_capabilities_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,47 @@ async def fake_get_session(sid):
assert payload["block"]["tool_name"] == "shell"


@pytest.mark.asyncio
async def test_local_task_streaming_tool_arguments_emit_generating_block(monkeypatch):
namespace = device_namespace.DeviceNamespace()
sio = SimpleNamespace(emit=AsyncMock())

async def fake_get_session(sid):
return {"user_id": 7, "device_id": "device-1"}

monkeypatch.setattr(namespace, "get_session", fake_get_session)
monkeypatch.setattr(local_task_responses, "get_sio", lambda: sio, raising=False)

result = await namespace._handle_responses_api_event(
"sid-1",
"response.output_item.added",
{
"subtask_id": 202,
"local_task_id": "claude-1",
"runtime": "claude_code",
"data": {
"item": {
"type": "function_call",
"call_id": "call-1",
"name": "Bash",
"arguments": "{}",
},
"argument_status": "streaming",
},
},
)

assert result == {"success": True}
sio.emit.assert_awaited_once()
event_name, payload = sio.emit.await_args.args[:2]
assert event_name == device_namespace.ServerEvents.CHAT_BLOCK_CREATED
assert payload["device_id"] == "device-1"
assert payload["local_task_id"] == "claude-1"
assert payload["block"]["type"] == "tool"
assert payload["block"]["tool_name"] == "Bash"
assert payload["block"]["status"] == "generating_arguments"


@pytest.mark.asyncio
async def test_local_task_im_source_forwards_stream_event_to_channel_callbacks(
monkeypatch,
Expand Down
64 changes: 64 additions & 0 deletions backend/tests/services/test_local_device_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# SPDX-FileCopyrightText: 2026 Weibo, Inc.
#
# SPDX-License-Identifier: Apache-2.0

"""Tests for local device provider response normalization."""

import pytest

from app.models.kind import Kind
from app.schemas.device import DeviceInfo
from app.services.device.local_provider import LocalDeviceProvider


def _local_device(device_id: str, device_type: str) -> Kind:
return Kind(
user_id=7,
kind="Device",
name=device_id,
namespace="default",
is_active=True,
json={
"apiVersion": "agent.wecode.io/v1",
"kind": "Device",
"metadata": {
"name": device_id,
"namespace": "default",
},
"spec": {
"deviceId": device_id,
"deviceType": device_type,
"connectionMode": "websocket",
"bindShell": "claudecode",
"displayName": device_id,
"isDefault": False,
},
},
)


@pytest.mark.asyncio
async def test_list_devices_normalizes_legacy_remote_device_type(
test_db,
monkeypatch,
):
"""Legacy remote devices are local devices in the current API contract."""
test_db.add(_local_device("legacy-remote", "remote"))
test_db.commit()

async def fake_mget(keys):
return {}

async def fake_latest_version():
return "1.0.0"

monkeypatch.setattr("app.core.cache.cache_manager.mget", fake_mget)
monkeypatch.setattr(
"app.services.device.local_provider.executor_version_service.get_latest_version",
fake_latest_version,
)

devices = await LocalDeviceProvider().list_devices(test_db, user_id=7)

assert devices[0]["device_type"] == "local"
DeviceInfo(**devices[0])
Comment on lines +63 to +64

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard against empty results before indexing devices[0].

This test currently fails with IndexError if filtering/regression returns no devices, which hides the actual contract failure. Add an explicit non-empty assertion first.

Suggested patch
     devices = await LocalDeviceProvider().list_devices(test_db, user_id=7)
 
+    assert len(devices) == 1
     assert devices[0]["device_type"] == "local"
     DeviceInfo(**devices[0])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/tests/services/test_local_device_provider.py` around lines 63 - 64,
The test code accesses devices[0] without first verifying that the devices list
contains any elements, which can result in an IndexError that masks the actual
contract failure being tested. Before the assertions that access
devices[0]["device_type"] and the DeviceInfo(**devices[0]) call, add an explicit
assertion to ensure the devices list is not empty, such as checking that its
length is greater than zero or that it is truthy.

206 changes: 184 additions & 22 deletions executor/agents/claude_code/response_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
[], Union[Dict[str, Any], Awaitable[Dict[str, Any]]]
]

CLAUDE_STREAM_TOOL_STATE_ATTR = "_claude_stream_tool_state"
CLAUDE_STREAM_TOOL_STARTED_ATTR = "_claude_stream_tool_started"
CLAUDE_STREAM_TOOL_FINALIZED_ATTR = "_claude_stream_tool_finalized"


# Maximum retry count for API errors per session
MAX_API_ERROR_RETRIES = 3
Expand Down Expand Up @@ -504,6 +508,7 @@ async def _handle_user_message(
message_details["message"]["content"].append(tool_detail)

logger.info(f"UserMessage ToolUseBlock: tool = {block.name}")
await _emit_tool_use_start(block, emitter)

elif isinstance(block, TextBlock):
# Check if this is SDK interruption text block
Expand Down Expand Up @@ -727,23 +732,7 @@ async def _handle_assistant_message(
block.id,
)

# Always emit tool_start from the finalized ToolUseBlock. Raw stream
# events do not contain complete arguments and may not correlate with
# the later ToolResultBlock in Claude Code SDK output.
try:
# Flush any buffered text_delta events before sending tool_start
# This ensures text content is sent before tool events
await emitter.flush()

arguments = block.input if isinstance(block.input, dict) else {}
await emitter.tool_start(
call_id=block.id,
name=block.name,
arguments=arguments,
)
logger.info(f"Sent tool_start event for tool {block.name}")
except Exception as e:
logger.warning(f"Failed to send tool_start event: {e}")
await _emit_tool_use_start(block, emitter)

elif isinstance(block, TextBlock):
# Text content details in target format
Expand Down Expand Up @@ -850,11 +839,27 @@ async def _handle_stream_event(
state_manager.update_workbench_summary(text, append=True)

elif delta_type == "input_json_delta":
# Tool input streaming - could be used for showing tool arguments being built
partial_json = delta.get("partial_json", "")
logger.debug(
f"StreamEvent: input_json_delta with {len(partial_json)} chars"
)
if partial_json:
tool_state = _stream_tool_for_index(emitter, event.get("index"))
if tool_state is not None:
tool_state["partial_json"] = (
str(tool_state.get("partial_json") or "") + partial_json
)
arguments_summary = _parse_tool_arguments_summary(
tool_state.get("partial_json")
)
try:
await emitter.tool_argument_delta(
call_id=tool_state["call_id"],
arguments_delta=partial_json,
arguments_summary=arguments_summary,
)
except Exception as e:
logger.warning(f"Failed to send stream input_json_delta: {e}")

elif delta_type == "thinking_delta":
thinking = delta.get("thinking", "")
Expand All @@ -874,10 +879,31 @@ async def _handle_stream_event(
logger.debug(f"StreamEvent: content_block_start, type={block_type}")

if block_type == "tool_use":
# Do not emit tool_start from raw stream start. The finalized
# AssistantMessage ToolUseBlock carries complete input and is the
# stable source for the tool_use_id used by ToolResultBlock.
logger.debug("StreamEvent: defer tool_start until ToolUseBlock")
call_id = content_block.get("id")
name = content_block.get("name")
if call_id and name:
arguments_summary = (
content_block.get("input")
if isinstance(content_block.get("input"), dict)
else {}
)
try:
await emitter.tool_argument_start(
call_id=call_id,
name=name,
arguments_summary=arguments_summary,
)
_remember_stream_tool(
emitter,
event.get("index"),
str(call_id),
str(name),
arguments_summary,
)
except Exception as e:
logger.warning(f"Failed to send stream tool_start: {e}")
else:
logger.debug("StreamEvent: tool_use start missing id or name")

elif block_type == "text":
# A start event carries no text; only text_delta proves content
Expand All @@ -887,6 +913,26 @@ async def _handle_stream_event(
elif event_type == "content_block_stop":
# A content block has finished
logger.debug(f"StreamEvent: content_block_stop, index={event.get('index', -1)}")
tool_state = _pop_stream_tool_for_index(emitter, event.get("index"))
if tool_state is not None:
arguments_summary = _parse_tool_arguments_summary(
tool_state.get("partial_json")
)
if arguments_summary is None:
arguments_summary = tool_state.get("arguments_summary")
if not isinstance(arguments_summary, dict):
arguments_summary = {}
try:
await emitter.tool_argument_done(
call_id=tool_state["call_id"],
arguments=arguments_summary,
arguments_summary=arguments_summary,
)
_mark_stream_tool_finalized(
emitter, tool_state["call_id"], arguments_summary
)
except Exception as e:
logger.warning(f"Failed to send stream tool_argument_done: {e}")

elif event_type == "message_start":
# Message is starting
Expand All @@ -910,6 +956,122 @@ async def _handle_stream_event(
return sent_content


async def _emit_tool_use_start(
block: ToolUseBlock,
emitter: ResponsesAPIEmitter,
) -> None:
try:
arguments = block.input if isinstance(block.input, dict) else {}
if _stream_tool_was_started(emitter, block.id):
if _stream_tool_needs_final_arguments(emitter, block.id, arguments):
await emitter.tool_argument_done(
call_id=block.id,
arguments=arguments,
arguments_summary=arguments,
)
_mark_stream_tool_finalized(emitter, block.id, arguments)
logger.info(f"Finalized streamed tool arguments for tool {block.name}")
return

# Flush any buffered text_delta events before sending tool_start.
# This ensures text content is sent before tool events.
await emitter.flush()

await emitter.tool_start(
call_id=block.id,
name=block.name,
arguments=arguments,
)
logger.info(f"Sent tool_start event for tool {block.name}")
except Exception as e:
logger.warning(f"Failed to send tool_start event: {e}")
Comment on lines +986 to +987

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Resolve the Ruff BLE001 violation.

If suppressing all emitter failures is intentional, add an explicit noqa rationale; otherwise narrow the exception type.

🔧 Proposed fix when broad suppression is intentional
-    except Exception as e:
+    except Exception as e:  # noqa: BLE001 - event forwarding failures must not abort response processing.
         logger.warning(f"Failed to send tool_start event: {e}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
except Exception as e:
logger.warning(f"Failed to send tool_start event: {e}")
except Exception as e: # noqa: BLE001 - event forwarding failures must not abort response processing.
logger.warning(f"Failed to send tool_start event: {e}")
🧰 Tools
🪛 Ruff (0.15.18)

[warning] 986-986: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@executor/agents/claude_code/response_processor.py` around lines 986 - 987,
The bare except Exception clause in the response_processor.py file's tool_start
event handler violates Ruff's BLE001 rule against catching overly broad
exceptions. Either narrow the exception type being caught to be more specific
(like EventEmitterError or a more targeted exception), or if catching all
exceptions for this logging case is intentional, add an explicit `# noqa:
BLE001` comment with a rationale explaining why broad exception suppression is
necessary for the tool_start event emission failure handling in that location.

Source: Linters/SAST tools



def _stream_tool_state(emitter: ResponsesAPIEmitter) -> dict[str, dict[str, Any]]:
state = getattr(emitter, "__dict__", {}).get(CLAUDE_STREAM_TOOL_STATE_ATTR)
if isinstance(state, dict):
return state
state = {}
setattr(emitter, CLAUDE_STREAM_TOOL_STATE_ATTR, state)
return state


def _stream_tool_started(emitter: ResponsesAPIEmitter) -> set[str]:
started = getattr(emitter, "__dict__", {}).get(CLAUDE_STREAM_TOOL_STARTED_ATTR)
if isinstance(started, set):
return started
started = set()
setattr(emitter, CLAUDE_STREAM_TOOL_STARTED_ATTR, started)
return started


def _stream_tool_finalized(emitter: ResponsesAPIEmitter) -> dict[str, dict[str, Any]]:
finalized = getattr(emitter, "__dict__", {}).get(CLAUDE_STREAM_TOOL_FINALIZED_ATTR)
if isinstance(finalized, dict):
return finalized
finalized = {}
setattr(emitter, CLAUDE_STREAM_TOOL_FINALIZED_ATTR, finalized)
return finalized


def _stream_index_key(index: Any) -> str:
return str(index)


def _remember_stream_tool(
emitter: ResponsesAPIEmitter,
index: Any,
call_id: str,
name: str,
arguments_summary: dict[str, Any],
) -> None:
_stream_tool_state(emitter)[_stream_index_key(index)] = {
"call_id": call_id,
"name": name,
"arguments_summary": arguments_summary,
"partial_json": "",
}
_stream_tool_started(emitter).add(call_id)


def _stream_tool_for_index(
emitter: ResponsesAPIEmitter, index: Any
) -> Optional[dict[str, Any]]:
return _stream_tool_state(emitter).get(_stream_index_key(index))


def _pop_stream_tool_for_index(
emitter: ResponsesAPIEmitter, index: Any
) -> Optional[dict[str, Any]]:
return _stream_tool_state(emitter).pop(_stream_index_key(index), None)


def _stream_tool_was_started(emitter: ResponsesAPIEmitter, call_id: str) -> bool:
return call_id in _stream_tool_started(emitter)


def _mark_stream_tool_finalized(
emitter: ResponsesAPIEmitter, call_id: str, arguments_summary: dict[str, Any]
) -> None:
_stream_tool_finalized(emitter)[call_id] = arguments_summary


def _stream_tool_needs_final_arguments(
emitter: ResponsesAPIEmitter, call_id: str, arguments: dict[str, Any]
) -> bool:
return _stream_tool_finalized(emitter).get(call_id) != arguments


def _parse_tool_arguments_summary(value: Any) -> Optional[dict[str, Any]]:
if not isinstance(value, str) or not value:
return None
try:
parsed = json.loads(value)
except (json.JSONDecodeError, TypeError):
return None
return parsed if isinstance(parsed, dict) else None


def _handle_legacy_message(msg: Dict[str, Any], thinking_manager=None):
msg_type = msg.get("type", "unknown")

Expand Down
Loading
Loading