diff --git a/.env b/.env index e3b46c7de24baac234e6a91af57836720564e10b..16e472914d7fb57e5340737413f14177c73a7080 100644 --- a/.env +++ b/.env @@ -2,6 +2,11 @@ OPENAI_API_KEY=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 OPENAI_BASE_URL=https://openrouter.ai/api/v1 OPENAI_MODEL=deepseek/deepseek-v4-flash +CONVERSATION_MEMORY_ENABLED=true +LLM_GOAL_RESOLUTION_ENABLED=true +STRUCTURED_GOAL_CHECK_ENABLED=true +MAX_REPLANS=3 +LLM_STRUCTURED_OUTPUTS_ENABLED=auto # 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 # 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 của tôi # Default model diff --git a/.history/.env_20260704103453 b/.history/.env_20260704103453 new file mode 100644 index 0000000000000000000000000000000000000000..e13f8fb88cc57c8caaea6f2f74c0e92b6719cd6c --- /dev/null +++ b/.history/.env_20260704103453 @@ -0,0 +1,22 @@ +# Choose one or both providers +OPENAI_API_KEY=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 +OPENAI_BASE_URL=https://openrouter.ai/api/v1 +OPENAI_MODEL=deepseek/deepseek-v4-flash +CONVERSATION_MEMORY_ENABLED=true +LLM_GOAL_RESOLUTION_ENABLED=true +STRUCTURED_GOAL_CHECK_ENABLED=true +MAX_REPLANS=3 +LLM_STRUCTURED_OUTPUTS_ENABLED=auto +# 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 +# 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 của tôi +# Default model +DEFAULT_MODEL=claude-sonnet-4-20250514 +# DEFAULT_MODEL=gpt-4o + +# Logging +LOG_LEVEL=INFO + +# AI Hook Logging (set by instructor) +AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest +AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47 +AI_LOG_DIR=.ai-log diff --git a/.history/note_20260704093813.md b/.history/note_20260704093813.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.history/note_20260704093816.md b/.history/note_20260704093816.md new file mode 100644 index 0000000000000000000000000000000000000000..f8c5d8094807e983f624a27ea88aa0a0d5255822 --- /dev/null +++ b/.history/note_20260704093816.md @@ -0,0 +1,34 @@ +> Gửi yêu cầu: "cho quả lê lên lon chip" +> Tôi đang suy nghĩ cách thực hiện... +> Tôi đang phân tích yêu cầu... +> I will pick up the tennis ball, soup can, chips can and pear and move to the table. +> Tôi đang kiểm tra mức độ an toàn của kế hoạch... +> Kế hoạch an toàn và hợp lệ. +> Tôi bắt đầu thực hiện các bước... +> Tôi đang gắp quả bóng tennis lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp lon súp lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp lon snack lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp quả lê lên... +> Thực thi lỗi tại bước 10 'pick_up': pick_up('pear') did not secure the object (gripper missed) +> [MONITOR] Phát hiện lỗi. Đang khôi phục cánh tay robot và lập kế hoạch lại (thử lần 1)... +> [MONITOR] Re-plan attempt 1/3 due to: Step 10 'pick_up' failed: pick_up('pear') did not secure the object (gripper missed) +> Tôi đang suy nghĩ cách thực hiện... +> I will pick up the chips can, banana, soup can, chips can and pear and move to the table. +> Tôi đang kiểm tra mức độ an toàn của kế hoạch... +> Phát hiện 1 rủi ro tiềm ẩn. +> - step 12: pick_up target 'pear' is OUT OF REACH +> Tôi bắt đầu thực hiện các bước... +> Tôi đang gắp lon snack lên... +> Thực thi lỗi tại bước 1 'pick_up': pick_up('chips_can') did not secure the object (gripper missed) +> [MONITOR] Phát hiện lỗi. Đang khôi phục cánh tay robot và lập kế hoạch lại (thử lần 2)... +> [MONITOR] Re-plan attempt 2/3 due to: Step 1 'pick_up' failed: pick_up('chips_can') did not secure the object (gripper missed) +> Tôi đang suy nghĩ cách thực hiện... +> Tôi chưa có đủ thông tin để tạo kế hoạch an toàn. Bạn muốn thao tác với vật nào và đặt nó ở đâu? +> Robot phản hồi: Tôi chưa có đủ thông tin để tạo kế hoạch an toàn. Bạn muốn thao tác với vật nào và đặt nó ở đâu? + diff --git a/.pytest_cache/v/cache/lastfailed b/.pytest_cache/v/cache/lastfailed index e6b602c425d257f3e21bdafc758e6371e1124a1f..74956539b5afc98b57224ff983616dda0cba4076 100644 --- a/.pytest_cache/v/cache/lastfailed +++ b/.pytest_cache/v/cache/lastfailed @@ -1,15 +1,6 @@ { - "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true, - "tests/test_pipeline.py::test_grasp_survives_fast_translation": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_g\\u1eafp bim bim b\\u1ecf v\\xe0o khay]": true, "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t v\\xe0o khay]": true, "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]": true, "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_8_g\\u1eafp v\\u1eadt n\\u1eb1m b\\xean tr\\xe1i qu\\u1ea3 chu\\u1ed1i \\u0111\\u1eb7t v\\xe0o khay]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]": true, - "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_10_g\\u1eafp lon s\\xfap]": true, - "tests/test_multi_angle.py::test_side_grasp_pose_is_tilted": true + "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]": true } \ No newline at end of file diff --git a/.pytest_cache/v/cache/nodeids b/.pytest_cache/v/cache/nodeids index a039a9c6f5a9ffad5e91b6b6611f565d65f69e68..dbb926a5d33b9e7250c4d33cd9b38776fab08e04 100644 --- a/.pytest_cache/v/cache/nodeids +++ b/.pytest_cache/v/cache/nodeids @@ -5,26 +5,43 @@ "tests/test_conversation_memory.py::test_clear_removes_pending_and_recent_turns", "tests/test_conversation_memory.py::test_complete_new_command_replaces_pending_request", "tests/test_conversation_memory.py::test_default_replan_limit_is_finite", + "tests/test_conversation_memory.py::test_directional_relation_to_surface_is_not_silently_rewritten", + "tests/test_conversation_memory.py::test_explicit_relation_without_reference_still_requires_clarification", "tests/test_conversation_memory.py::test_feature_flag_can_restore_stateless_behavior", + "tests/test_conversation_memory.py::test_follow_up_cannot_overwrite_manipulated_object_slot", "tests/test_conversation_memory.py::test_follow_up_completes_rule_based_plan_without_extra_api_call", "tests/test_conversation_memory.py::test_follow_up_marks_changed_scene_and_uses_fresh_state", "tests/test_conversation_memory.py::test_follow_up_uses_exactly_one_planner_call_per_user_turn", + "tests/test_conversation_memory.py::test_former_location_infers_anchor_surface_from_scene", "tests/test_conversation_memory.py::test_goal_check_falls_back_to_live_geometry_for_on_top_relation", "tests/test_conversation_memory.py::test_goal_resolution_parser_accepts_structured_clarification", "tests/test_conversation_memory.py::test_goal_resolution_parser_rejects_ready_without_canonical_goal", + "tests/test_conversation_memory.py::test_goal_resolution_repairs_empty_provider_response_without_losing_context", + "tests/test_conversation_memory.py::test_intermediate_execution_is_excluded_from_resolved_goal", + "tests/test_conversation_memory.py::test_intermediate_task_needs_no_user_selected_destination_or_relation", "tests/test_conversation_memory.py::test_invalid_clarification_choice_keeps_original_request_pending", "tests/test_conversation_memory.py::test_invalid_physical_action_is_converted_to_clarification", + "tests/test_conversation_memory.py::test_llm_semantically_replaces_pending_without_fixed_verb_list", "tests/test_conversation_memory.py::test_one_shot_command_is_not_rewritten", "tests/test_conversation_memory.py::test_pending_clarification_expires", "tests/test_conversation_memory.py::test_pipeline_agent_setter_keeps_monitor_agent_in_sync", "tests/test_conversation_memory.py::test_ready_goal_is_canonicalized_before_planning", "tests/test_conversation_memory.py::test_remote_parser_accepts_structured_plan_wrapper", + "tests/test_conversation_memory.py::test_replacement_follow_up_preserves_all_ordered_tasks", + "tests/test_conversation_memory.py::test_replacement_plan_missing_second_task_is_rejected", "tests/test_conversation_memory.py::test_replan_can_skip_goal_resolution_gate", "tests/test_conversation_memory.py::test_rule_based_move_request_tracks_missing_destination", + "tests/test_conversation_memory.py::test_self_referential_spatial_goal_is_blocked_before_planner", "tests/test_conversation_memory.py::test_sessions_do_not_share_pending_clarification", + "tests/test_conversation_memory.py::test_standalone_compound_intent_normalizes_every_task_adaptively", "tests/test_conversation_memory.py::test_structured_clarification_metadata_is_preserved", "tests/test_conversation_memory.py::test_structured_goal_check_uses_resolved_goal_not_raw_follow_up", "tests/test_conversation_memory.py::test_structured_output_falls_back_once_when_provider_rejects", + "tests/test_conversation_memory.py::test_surface_reference_is_normalized_to_surface_destination", + "tests/test_conversation_memory.py::test_surface_reference_normalization_applies_to_every_sequence_task", + "tests/test_conversation_memory.py::test_swap_former_locations_are_anchored_from_initial_scene", + "tests/test_conversation_memory.py::test_swap_goal_compiles_position_predicates_not_surface_only", + "tests/test_conversation_memory.py::test_unconstrained_dangling_relation_is_removed_after_destination_reply", "tests/test_cost_map.py::test_astar_finds_straight_path_on_empty_workspace", "tests/test_cost_map.py::test_astar_routes_around_tall_obstacle", "tests/test_cost_map.py::test_clearance_scales_with_carried_height", @@ -37,6 +54,11 @@ "tests/test_cost_map.py::test_tall_obstacle_is_a_cost_wall", "tests/test_cost_map.py::test_tray_obstacle_routes_within_workspace", "tests/test_cost_map.py::test_workspace_covers_table_and_tray", + "tests/test_environment_semantics.py::test_adaptive_prompt_uses_only_active_environment_catalog", + "tests/test_environment_semantics.py::test_entity_grounding_uses_unique_aliases_from_active_catalog", + "tests/test_environment_semantics.py::test_env1_references_catalog_covering_every_configured_object", + "tests/test_environment_semantics.py::test_env_builder_loads_referenced_catalog_into_scene", + "tests/test_environment_semantics.py::test_remote_core_prompt_no_longer_contains_env1_object_catalog", "tests/test_geofik.py::test_clamp_acos_input", "tests/test_geofik.py::test_franka_geometry", "tests/test_geofik.py::test_rotations", @@ -69,9 +91,12 @@ "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]", "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_8_g\\u1eafp v\\u1eadt n\\u1eb1m b\\xean tr\\xe1i qu\\u1ea3 chu\\u1ed1i \\u0111\\u1eb7t v\\xe0o khay]", "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]", + "tests/test_monitor.py::test_controller_cancellation_stops_inside_cartesian_motion", "tests/test_monitor.py::test_monitor_aborts_when_replan_repeats_failing_plan", "tests/test_monitor.py::test_monitor_replans_until_attempts_exhausted", "tests/test_monitor.py::test_monitor_stops_on_success", + "tests/test_monitor.py::test_pipeline_interrupts_between_steps_without_recovery", + "tests/test_monitor.py::test_position_near_goal_requires_actual_swap_coordinate", "tests/test_monitor.py::test_recover_returns_arm_to_safe_height", "tests/test_monitor.py::test_verify_step_flags_failed_grasp", "tests/test_monitor.py::test_verify_step_flags_joint_stuck", @@ -100,6 +125,7 @@ "tests/test_occupancy.py::test_on_top_detection_accepts_small_physics_interpenetration", "tests/test_occupancy.py::test_on_top_detection_rejects_object_floating_too_high", "tests/test_occupancy.py::test_on_top_detection_rejects_side_contact_with_tiny_overlap", + "tests/test_occupancy.py::test_preferred_position_biases_free_placement_to_swap_anchor", "tests/test_occupancy.py::test_reachable_filter_is_applied", "tests/test_occupancy.py::test_relation_left_of_places_on_correct_side", "tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table", @@ -131,5 +157,32 @@ "tests/test_pipeline.py::test_relation_word_inside_object_alias_does_not_trigger", "tests/test_pipeline.py::test_rule_based_planner_two_step_pick_place", "tests/test_task_nullspace.py::test_box_manifold_jacobian", - "tests/test_task_nullspace.py::test_cylinder_manifold_jacobian" + "tests/test_task_nullspace.py::test_cylinder_manifold_jacobian", + "tests/test_web_command_button.py::test_clarification_result_is_not_recorded_as_failed_execution", + "tests/test_web_command_button.py::test_click_stops_but_enter_submits_replacement_command", + "tests/test_web_command_button.py::test_command_input_stays_enabled_while_execution_is_active", + "tests/test_web_command_button.py::test_execution_button_has_spinner_and_stop_square", + "tests/test_web_command_button.py::test_html_cache_busts_live_command_assets", + "tests/test_web_drag_drop.py::test_catalog_rows_spawn_real_runtime_objects", + "tests/test_web_drag_drop.py::test_delete_ui_and_incremental_object_events_exist", + "tests/test_web_drag_drop.py::test_disconnect_cleans_up_physics_constraint", + "tests/test_web_drag_drop.py::test_environment_dropdown_excludes_semantic_catalogs", + "tests/test_web_drag_drop.py::test_environment_listing_keeps_valid_empty_scene_templates", + "tests/test_web_drag_drop.py::test_frontend_uses_complete_pointer_lifecycle_and_drag_ids", + "tests/test_web_drag_drop.py::test_manual_target_is_clamped_to_workspace_and_surface", + "tests/test_web_drag_drop.py::test_manual_target_rejects_non_finite_coordinates", + "tests/test_web_drag_drop.py::test_objects_are_selected_for_deletion_not_manually_dragged", + "tests/test_web_drag_drop.py::test_robot_and_object_drag_have_separate_backend_paths", + "tests/test_web_drag_drop.py::test_runtime_visual_metadata_uses_mesh_matching_material", + "tests/test_web_runtime.py::test_cancel_all_interrupts_active_and_discards_pending_command", + "tests/test_web_runtime.py::test_cancellation_token_raises_only_after_request", + "tests/test_web_runtime.py::test_event_journal_is_bounded_and_replayable", + "tests/test_web_runtime.py::test_explicit_reset_clears_ui_history_but_keeps_monotonic_sequence", + "tests/test_web_runtime.py::test_new_command_cancels_active_and_latest_pending_wins", + "tests/test_web_runtime.py::test_reload_snapshot_preserves_runtime_state_and_event_history", + "tests/test_web_runtime.py::test_runtime_conversation_survives_client_disconnect", + "tests/test_web_runtime.py::test_scene_reset_clears_cli_conversation_memory", + "tests/test_web_runtime.py::test_stale_result_is_journaled_but_does_not_replace_latest_result", + "tests/test_web_runtime.py::test_web_pipeline_keeps_resolved_goal_across_replans_and_goal_check", + "tests/test_web_runtime.py::test_web_replan_limit_uses_environment_configuration" ] \ No newline at end of file diff --git a/__pycache__/main.cpython-310.pyc b/__pycache__/main.cpython-310.pyc index e2a3ee534afaac29d7194694082bd61077e14eba..791dd556ca88541861953c0bcd5db67d01f9ee32 100644 Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ diff --git a/development_logs/2026-07-04_10-13-19_semantic-conversation-boundary-and-generalization-audit.md b/development_logs/2026-07-04_10-13-19_semantic-conversation-boundary-and-generalization-audit.md new file mode 100644 index 0000000000000000000000000000000000000000..bc60f47acfdc88b4db6950c197be5dd0bca46621 --- /dev/null +++ b/development_logs/2026-07-04_10-13-19_semantic-conversation-boundary-and-generalization-audit.md @@ -0,0 +1,64 @@ +# Semantic conversation boundary và generalization audit + +## Yêu cầu + +- Cho Remote LLM tự reasoning lệnh mới/follow-up thay vì dựa trên danh sách động từ + cố định. +- Kiểm kê toàn bộ phần hard-code khiến dự án chỉ tối ưu cho một số object, hành vi + hoặc môi trường. + +## Phạm vi và giả định + +- Thay đổi runtime chỉ ở conversation boundary của luồng Remote LLM. +- Giữ lexical heuristic cho RuleBasedPlanner/offline fallback để không phá tính năng. +- Chưa tự động thay toàn bộ action/location/robot architecture vì đây là thay đổi + nhiều phase và ảnh hưởng tương thích. +- Tạo tài liệu audit và lộ trình chi tiết cho phần còn lại. + +## File sửa/thêm + +- Sửa `llm_panda/conversation/manager.py`. +- Sửa `llm_panda/llm_agent.py`. +- Sửa `tests/test_conversation_memory.py`. +- Thêm `docs/GENERALIZATION_AUDIT.md`. +- Thêm development log này. + +## Hành vi trước + +- Khi có pending clarification, `_ACTION_WORDS` + `_OBJECT_WORDS` quyết định câu mới. +- `cho quả lê lên lon chip` không có động từ trong list nên bị ghép với pending cũ. +- Plan output lỗi bị báo sai thành “người dùng chưa cung cấp đủ thông tin”. + +## Hành vi sau + +- Khi planner có Goal Resolver, `ConversationManager` luôn cung cấp pending context + và không tự phân loại bằng lexical list. +- Goal Resolver trả `conversation_mode=standalone|follow_up`. +- `standalone` đóng pending cũ; `follow_up` tiếp tục bổ sung intent. +- Prompt nêu rõ phải reasoning semantic, kể cả wording chưa có trong examples. +- Plan rỗng/sai schema được báo là lỗi model output, không đổ lỗi cho người dùng. +- Rule-based/offline vẫn giữ heuristic cũ làm fallback. + +## Kiểm tra + +- Test đang có pending `đặt vào khay`, sau đó nhập + `cho quả lê lên lon chip`. +- Xác nhận LLM resolver nhận cả context, quyết định `standalone`. +- Xác nhận planner chỉ nhận canonical goal + `đặt pear on_top_of chips_can trên table`. +- Xác nhận pending cũ bị đóng và plan ba bước được giữ nguyên. +- Regression liên quan: **64 passed**. +- Python compile và `git diff --check` chạy ở bước xác minh cuối. + +## Bảo toàn + +- Không sửa `.env`, secret, robot speed, motion executor hoặc physics. +- Không xóa RuleBasedPlanner. +- API `LLMAgent.plan()` và action list hiện tại vẫn tương thích. + +## Vấn đề còn lại + +- Core action/location/relation ontology, prompt object catalog, grasp classes, + table/tray world model, motion planner, monitor, UI và scoring vẫn có hard-code. +- Toàn bộ danh sách và lộ trình loại bỏ được ghi tại + `docs/GENERALIZATION_AUDIT.md`. diff --git a/development_logs/2026-07-04_10-28-46_implement-adaptive-environment-prompts.md b/development_logs/2026-07-04_10-28-46_implement-adaptive-environment-prompts.md new file mode 100644 index 0000000000000000000000000000000000000000..1d2b43ffb70b5ed98f86f2535da7871ef2a22f40 --- /dev/null +++ b/development_logs/2026-07-04_10-28-46_implement-adaptive-environment-prompts.md @@ -0,0 +1,75 @@ +# Triển khai adaptive environment prompts + +## Yêu cầu + +- Giữ nguyên Panda model, A* 2D/U-trajectory, Goal Predicate và scoring vì thuộc + scope bài toán. +- Tổng quát hóa semantic information theo từng môi trường. +- Mỗi environment lưu thông tin trong file riêng và prompt phải tự thay đổi khi đổi + environment. + +## Phạm vi và giả định + +- Thực hiện Phase G1 của generalization audit. +- Không thay robot/controller, motion planning, predicates hoặc scoring. +- Giữ RuleBasedPlanner hard-code làm offline fallback. +- Remote Goal Resolver, Planner và fallback Goal Check dùng adaptive catalog. + +## File thêm/sửa + +- Sửa `envs/env1.json`. +- Sửa `envs/default_desk.json`. +- Sửa `envs/scenarios/scenario_1.json`. +- Thêm `envs/env1.semantics.json`. +- Thêm `envs/default_desk.semantics.json`. +- Sửa `llm_panda/core/env_builder.py`. +- Sửa `llm_panda/scene_manager.py`. +- Sửa `llm_panda/llm_agent.py`. +- Thêm `tests/test_environment_semantics.py`. +- Sửa `docs/GENERALIZATION_AUDIT.md`. +- Thêm `docs/ENVIRONMENT_SEMANTIC_CATALOG.md`. +- Thêm development log này. + +## Hành vi trước + +- Object properties và synonym của sáu object nằm trực tiếp trong Remote LLM prompt. +- Đổi object/environment không tự đổi semantic prompt. +- Environment JSON chỉ chứa geometry/asset; scene state không mang semantic metadata. +- Fallback Goal Check lặp lại object facts hard-code. + +## Hành vi sau + +- Environment tham chiếu semantic catalog bằng relative path. +- Catalog lưu display name, aliases, categories, attributes và affordances. +- EnvBuilder kiểm tra mọi configured object và table/tray đều được mô tả. +- Scene state chứa environment metadata và semantic data của object hiện có. +- Prompt được tạo động theo environment/objects của scene hiện tại. +- Core Remote prompt không còn catalog/synonym/examples riêng của `env1`. +- Fallback Goal Check dùng cùng adaptive context. + +## Kiểm tra + +- Xác minh catalog `env1` bao phủ toàn bộ configured objects. +- Xác minh EnvBuilder nạp đúng catalog referenced. +- Dùng hai scene giả lập `orchard` và `workshop`; prompt chứa đúng object/surface của + từng scene và không rò catalog scene kia. +- Xác minh core Remote prompt không chứa ID riêng `soup_can`, `chips_can`, + `tennis_ball`. +- Regression liên quan: **68 passed**. +- Python compile và `git diff --check` chạy ở bước xác minh cuối. + +## Bảo toàn + +- Không sửa `.env`, secrets, `.history` hoặc thay đổi local ngoài phạm vi. +- Không sửa Panda model/controller. +- Không sửa A* 2D/U-trajectory. +- Không sửa Goal Predicate. +- Không sửa scoring. +- API plan/action hiện tại giữ nguyên. + +## Vấn đề còn lại + +- UI/server vẫn có map tên hiển thị của sáu object; Phase G1 tiếp theo nên đọc display + name từ scene catalog. +- RuleBasedPlanner vẫn dùng synonym hard-code theo chủ đích offline fallback. +- Action/location/relation schema vẫn thuộc scope pick-and-place hiện tại. diff --git a/development_logs/2026-07-04_10-41-41_fix-follow-up-slot-grounding.md b/development_logs/2026-07-04_10-41-41_fix-follow-up-slot-grounding.md new file mode 100644 index 0000000000000000000000000000000000000000..45e39700150b6b22dd7e0410c0568336ac1aa528 --- /dev/null +++ b/development_logs/2026-07-04_10-41-41_fix-follow-up-slot-grounding.md @@ -0,0 +1,69 @@ +# Sửa follow-up ghi đè object và tạo self-reference + +## Yêu cầu + +Sửa ca hội thoại: + +1. `cho kẹp lên trên lon`; +2. robot hỏi chọn lon súp hay lon chips; +3. người dùng chọn lon súp; +4. hệ thống lại lập plan `soup_can on_top_of soup_can`. + +## Nguyên nhân + +- Prompt chưa định nghĩa rõ vai trò từng slot. +- `object_id` bị dùng đồng thời cho vật cần thao tác và object tham chiếu. +- `destination` đôi khi bị dùng cho reference object dù nó phải là surface. +- Follow-up có thể ghi đè `object_id=clamp` đã biết bằng câu trả lời + `object_id=soup_can`. +- Không có guard ngăn `object_id == relative_to`. +- Không có kiểm tra plan sinh ra có khớp resolved intent hay không. + +## Phạm vi + +- Siết Goal Resolution schema semantics và deterministic intent merge. +- Không thay đổi Panda, A* 2D/U-trajectory, Goal Predicate hoặc scoring. +- Không thay đổi chuyển động/grasp/placement. + +## File sửa + +- `llm_panda/llm_agent.py` +- `tests/test_conversation_memory.py` +- `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md` +- Thêm development log này. + +## Hành vi sau + +- Slot có nghĩa duy nhất: + - `object_id`: vật robot thao tác; + - `destination`: surface table/tray; + - `relation`: quan hệ không gian; + - `relative_to`: object tham chiếu. +- Follow-up chỉ được điền field đang thiếu. +- Slot đã biết từ pending intent được bảo vệ khỏi model overwrite. +- Metadata cũ dùng object làm `destination` được migrate sang `relative_to`. +- Canonical instruction được dựng deterministic từ merged intent. +- Object/reference không tồn tại và self-reference bị clarify trước planner. +- Plan không khớp resolved intent bị reject trước executor. + +## Kiểm tra + +- Tái hiện pending intent `object_id=clamp`, `relation=on_top_of`. +- Cho resolver cố trả sai `soup_can on_top_of soup_can`. +- Xác nhận planner thực tế nhận + `place clamp on_top_of soup_can on table`. +- Xác nhận self-reference bị chặn và planner không được gọi. +- Regression liên quan: **70 passed**. +- Python compile và `git diff --check` chạy ở bước xác minh cuối. + +## Bảo toàn + +- Không sửa `.env`, secrets, `.history` hoặc robot speed. +- Không sửa motion planner, Goal Predicate và scoring. +- API plan/action hiện tại giữ nguyên. + +## Vấn đề còn lại + +- Live OpenRouter vẫn cần kiểm thử sau khi restart ứng dụng. +- Nếu bổ sung action phức hợp ngoài pick-and-place, typed intent cần được version hóa + thay vì mở rộng một dict không schema. diff --git a/development_logs/2026-07-04_10-54-16_fix-composite-replacement-memory.md b/development_logs/2026-07-04_10-54-16_fix-composite-replacement-memory.md new file mode 100644 index 0000000000000000000000000000000000000000..5f67fddf700d294ff08427a712af180c9156afbe --- /dev/null +++ b/development_logs/2026-07-04_10-54-16_fix-composite-replacement-memory.md @@ -0,0 +1,73 @@ +# Sửa composite replacement bị mất task sau clarification + +## Yêu cầu + +Sửa lỗi robot chỉ dời chiếc kẹp nhưng không thực hiện phần “thế chỗ cái kẹp bằng +quả bóng”. + +## Phân tích log + +Goal Resolver ban đầu hiểu đúng hai hiệu ứng: + +1. lấy kẹp khỏi trên lon súp và đặt kẹp sang nơi khác; +2. đặt bóng tennis lên trên lon súp. + +Vì chưa biết vị trí mới của kẹp, robot hỏi lại. Khi người dùng trả lời “để trên +bàn”, resolved intent phẳng chỉ giữ task dời kẹp. Planner vì vậy sinh đúng ba bước +cho kẹp nhưng làm mất task đặt bóng. + +## Nguyên nhân + +- Intent model trước đây chỉ có một `object_id/destination/relation/relative_to`. +- Không có representation cho ordered multi-object task. +- Follow-up merge chỉ bảo vệ slot của một task. +- Plan/goal guard chỉ kiểm tra một hiệu ứng cuối. + +## Phạm vi + +- Mở rộng resolved intent trong scope pick-and-place hiện tại. +- Không thay Panda, A* 2D/U-trajectory, Goal Predicate hoặc scoring. +- Không thay executor action primitives. + +## File sửa + +- `llm_panda/llm_agent.py` +- `tests/test_conversation_memory.py` +- `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md` +- Thêm development log này. + +## Hành vi sau + +- Compound/swap/replacement dùng: + `{"action":"sequence","tasks":[...]}`. +- Replacement lưu hai task: + - relocate displaced object; + - place replacement object vào semantic position/relation cũ. +- Follow-up chỉ điền field còn thiếu của task tương ứng. +- Các task hoàn chỉnh còn lại luôn được giữ. +- Canonical instruction nối ordered tasks bằng `; then`. +- Plan guard xác minh mọi task xuất hiện đúng thứ tự; thiếu bất kỳ task nào thì + reject trước execution. +- Goal compiler hiện có tự tạo predicate cho mọi move/place trong sequence. + +## Kiểm tra + +- Pending replacement có task dời clamp và task đặt tennis ball trên soup can. +- Resolver follow-up cố tình chỉ trả task clamp. +- Xác nhận canonical goal vẫn chứa đủ hai task. +- Xác nhận plan sáu bước được chấp nhận. +- Xác nhận plan ba bước chỉ dời clamp bị `plan_goal_mismatch`. +- Regression liên quan: **72 passed**. +- Python compile và `git diff --check` chạy ở bước xác minh cuối. + +## Bảo toàn + +- Không sửa `.env`, secrets, `.history` hoặc tốc độ robot. +- Không sửa motion planner, Goal Predicate và scoring. +- Action schema pick/move/place giữ nguyên. + +## Vấn đề còn lại + +- Cần restart và thử live OpenRouter để xác nhận model tuân thủ `tasks` ngay từ lượt + clarification đầu tiên. +- Composite task hiện tuần tự; chưa hỗ trợ parallel/conditional/loop. diff --git a/development_logs/2026-07-04_11-07-56_improve-adaptive-dialogue-grounding.md b/development_logs/2026-07-04_11-07-56_improve-adaptive-dialogue-grounding.md new file mode 100644 index 0000000000000000000000000000000000000000..d91bb43afb295e5409e867b6bb1b3afebf7ad133 --- /dev/null +++ b/development_logs/2026-07-04_11-07-56_improve-adaptive-dialogue-grounding.md @@ -0,0 +1,71 @@ +# Cải thiện adaptive dialogue grounding và schema repair + +## Yêu cầu + +Sửa hội thoại: + +1. người dùng yêu cầu đổi vị trí quả bóng và quả chuối; +2. robot hỏi xác nhận quả bóng tennis; +3. người dùng trả lời `Tennis và quả chuối`; +4. hệ thống lại trả câu hỏi chung vì không parse được Goal Resolution. + +Mục tiêu là kết hợp chính xác lịch sử hội thoại theo cách adaptive. + +## Nguyên nhân + +- Goal Resolver chưa được nhắc rõ rằng alias chỉ khớp một object thì không mơ hồ. +- Semantic catalog thiếu alias ngắn `tennis`. +- Alias catalog chưa được tiền xử lý thành grounding hints cho model. +- Khi provider trả `content=None` hoặc JSON lệch schema, parser trả `None` và hệ + thống lập tức dùng generic clarification. +- Không có repair turn giữ nguyên pending partial intent và ordered tasks. + +## Phạm vi + +- Cải thiện Goal Resolution và conversation grounding. +- Không thay Panda, A* 2D/U-trajectory, Goal Predicate hoặc scoring. +- Không thay executor action primitives. + +## File sửa + +- `envs/env1.semantics.json` +- `llm_panda/llm_agent.py` +- `tests/test_environment_semantics.py` +- `tests/test_conversation_memory.py` +- `docs/CONVERSATION_MEMORY_PLAN.md` +- Thêm development log này. + +## Hành vi sau + +- `tennis` là alias data-driven của `tennis_ball`. +- Trước Goal Resolution, hệ thống quét alias/display names trong active semantic + catalog và gửi canonical grounding hints. +- Một mention chỉ khớp một current object được coi là resolved, không hỏi xác nhận. +- Prompt yêu cầu follow-up fragment điền missing slots và không bắt người dùng nhắc + lại action/destination/relation đã biết. +- Swap/replace/compound follow-up phải trả toàn bộ ordered tasks. +- Parser chấp nhận wrapper phổ biến, alias conversation mode, missing field dạng + string và ready response có structured partial intent. +- Response rỗng/sai schema kích hoạt đúng một repair turn với nguyên conversation + context; chỉ sau khi repair vẫn lỗi mới dùng fallback clarification. + +## Kiểm tra + +- `Tennis và quả chuối` ground thành `tennis_ball` và `banana`, không match `pear`. +- Fake provider trả `content=None` ở lượt đầu và valid follow-up JSON ở repair turn. +- Xác nhận repair giữ `conversation_mode=follow_up` cùng ordered tasks. +- Regression liên quan: **74 passed**. +- Python compile và `git diff --check` chạy ở bước xác minh cuối. + +## Bảo toàn + +- Không sửa `.env`, secrets, `.history` hoặc tốc độ robot. +- Không sửa motion planner, Goal Predicate và scoring. +- Adaptive prompt vẫn chỉ dùng metadata của active environment. + +## Vấn đề còn lại + +- Exact geometric swap vẫn bị giới hạn bởi action/location primitives hiện tại; thay + đổi đó nằm ngoài scope của bản sửa conversation grounding này. +- Không mô hình LLM nào bảo đảm 100% semantic output; schema repair và deterministic + grounding giảm failure nhưng vẫn cần guardrails. diff --git a/development_logs/2026-07-04_11-18-47_normalize-intent-object-surface-namespaces.md b/development_logs/2026-07-04_11-18-47_normalize-intent-object-surface-namespaces.md new file mode 100644 index 0000000000000000000000000000000000000000..34ef1d2b0a440ec7f659cfedc789cb7449662458 --- /dev/null +++ b/development_logs/2026-07-04_11-18-47_normalize-intent-object-surface-namespaces.md @@ -0,0 +1,66 @@ +# Chuẩn hóa namespace object/surface trong intent + +## Yêu cầu của người dùng + +Sửa triệt để lỗi hệ thống coi `table` là vật tham chiếu, đồng thời chuẩn hóa +intent theo hướng tổng quát. + +## Phạm vi và giả định + +- Chỉ thay đổi semantic boundary giữa Goal Resolution và planner. +- `destination` chỉ nhận ID của surface trong scene. +- `relative_to` chỉ nhận ID của manipulable object trong scene. +- `on_top_of + surface` có cùng ý nghĩa với đặt trực tiếp lên surface nên có + thể chuẩn hóa xác định, không cần hỏi lại. +- Quan hệ định hướng với surface như `left_of(table)` không có reference frame + đủ rõ nên phải fail-closed và yêu cầu người dùng chọn vật tham chiếu. +- Không thay đổi model Panda, A* 2D, U-trajectory, goal predicate, scoring, + executor hoặc cấu hình tốc độ. + +## File đã sửa + +- `llm_panda/llm_agent.py` +- `tests/test_conversation_memory.py` + +Không thêm, xóa hoặc đổi tên tính năng hiện có. + +## Hành vi trước và sau + +### Trước + +Intent `on_top_of(table)` giữ `table` trong `relative_to`. Validator chỉ tìm +`relative_to` trong danh sách object nên báo không tìm thấy vật tham chiếu dù +`table` tồn tại trong danh sách surface. + +### Sau + +- `on_top_of(table|surface khác)` được chuẩn hóa thành + `destination=` và loại bỏ `relation/relative_to` thừa. +- Quy tắc áp dụng cho intent đơn và từng task trong compound/sequence intent. +- `relative_to=` với quan hệ định hướng không được âm thầm chuyển đổi; + validator trả câu hỏi làm rõ đúng kiểu dữ liệu. +- `relative_to` có object nhưng thiếu relation cũng được phát hiện trước planner. +- Danh sách surface được lấy từ scene hiện hành, không gắn riêng với `env1`. + +## Kiểm tra và kết quả + +- `python -m py_compile llm_panda\llm_agent.py` + - Thành công. +- `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py -q` + - `40 passed`. +- `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q` + - `77 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF đã tồn tại trong working tree. + +## Bảo toàn hành vi hiện có + +- Không sửa `.env`, scene geometry, semantic catalog, frontend hay executor. +- Không đụng tới các thay đổi local không liên quan. +- Quan hệ object-to-object như `pear on_top_of chips_can` giữ nguyên. +- Destination surface hợp lệ như `table` và `tray` giữ nguyên. + +## Vấn đề còn lại + +- Lệnh hoán đổi “đúng tọa độ cũ” vẫn phụ thuộc primitive biểu diễn vị trí hiện + có. Thay đổi này chỉ bảo đảm intent không nhầm namespace và không bị chặn sai. diff --git a/development_logs/2026-07-04_11-35-55_separate-user-constraints-from-intermediate-planning.md b/development_logs/2026-07-04_11-35-55_separate-user-constraints-from-intermediate-planning.md new file mode 100644 index 0000000000000000000000000000000000000000..f7ee7d4ad8fd2ffa58b8d08562cb30c9dc0b1f57 --- /dev/null +++ b/development_logs/2026-07-04_11-35-55_separate-user-constraints-from-intermediate-planning.md @@ -0,0 +1,81 @@ +# Tách ràng buộc người dùng khỏi bước lập kế hoạch trung gian + +## Yêu cầu của người dùng + +Chỉ xét quan hệ không gian khi người dùng thực sự yêu cầu. Với task dài, các +giai đoạn trung gian không có ràng buộc phải được hệ thống tự lập kế hoạch an +toàn, không hỏi người dùng những chi tiết không cần thiết. + +## Phạm vi và giả định + +- Giữ nguyên model Panda, A* 2D, U-trajectory, goal predicate, scoring và + execution primitive hiện tại. +- Không thay đổi `.env`, scene geometry hoặc semantic catalog. +- Thay đổi nằm ở prompt, intent normalization, plan/intent matching và bước + biên dịch resolved goal. +- Bảo toàn tương thích với intent cũ chưa có provenance. + +## File đã sửa + +- `llm_panda/llm_agent.py` +- `tests/test_conversation_memory.py` +- `docs/CONVERSATION_MEMORY_PLAN.md` + +Không xóa hoặc đổi tên file/tính năng. + +## Hành vi trước và sau + +### Trước + +- Relation rời như `relation=on_top_of, relative_to=null` bị coi là constraint + bắt buộc và hệ thống hỏi vật tham chiếu dù người dùng chỉ chọn khay. +- Mọi bước trong execution plan có thể được biên dịch thành Goal Predicate, + kể cả bước dời tạm. +- Một bước trung gian thiếu destination có thể gây clarification không cần thiết. + +### Sau + +- `relation`/`relative_to` là cặp nguyên tử và có provenance + `constraint_sources`. +- Relation rời không có nguồn từ người dùng/context được loại bỏ. +- Relation được người dùng yêu cầu nhưng thiếu reference vẫn fail-closed và hỏi + đúng thông tin. +- Task `purpose=intermediate` tự dùng `placement_policy=auto_safe`; planner chọn + vị trí an toàn từ scene. +- Intent/plan matcher chấp nhận bất kỳ destination hợp lệ cho bước auto-safe. +- Goal Check chỉ nhận predicate từ task mục tiêu; intermediate task không trở + thành điều kiện hoàn thành. +- Prompt cấm LLM tự thêm quan hệ cho lệnh chỉ nêu surface. + +## Kiểm tra và kết quả + +- `python -m py_compile llm_panda\llm_agent.py` + - Thành công. +- `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py -q` + - `44 passed`. +- `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q` + - `81 passed`. +- Hồi quy mở rộng ban đầu: + - `106 passed`, `1 failed`. + - Lỗi duy nhất tại `tests/test_pipeline.py::test_grasp_survives_fast_translation`: + fixture `PandaApp` không có thuộc tính `grasp_planner`. + - Lỗi không đi qua code intent vừa sửa và thuộc thay đổi local có sẵn trong + `main.py`; không tự ý sửa ngoài phạm vi. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Object-to-object relation hợp lệ vẫn giữ nguyên. +- Surface destination không relation vẫn giữ nguyên. +- Explicit relation thiếu reference vẫn yêu cầu làm rõ. +- Blocker clearing, safety guardrail và executor vẫn hoạt động theo luồng cũ. +- Không ghi đè hoặc hoàn tác thay đổi local khác. + +## Vấn đề còn lại + +- Primitive hiện tại biểu diễn “vị trí cũ” ở mức semantic surface/support, chưa + có predicate tọa độ riêng. Việc mở rộng exact-pose goal sẽ thay đổi scope goal + predicate nên chưa thực hiện. +- Test pipeline nêu trên cần được xử lý riêng nếu người dùng yêu cầu sửa fixture + hoặc khôi phục API `PandaApp.grasp_planner`. diff --git a/development_logs/2026-07-04_11-59-33_implement-swap-former-location-anchors.md b/development_logs/2026-07-04_11-59-33_implement-swap-former-location-anchors.md new file mode 100644 index 0000000000000000000000000000000000000000..f702f1e25faeadd0a6e8ce97643049421f8f01db --- /dev/null +++ b/development_logs/2026-07-04_11-59-33_implement-swap-former-location-anchors.md @@ -0,0 +1,77 @@ +# Triển khai former-location anchor cho thao tác hoán đổi + +## Yêu cầu của người dùng + +Sửa thao tác hoán đổi để hai vật được đặt vào vị trí ban đầu của nhau trên +surface, thay vì chỉ đặt cả hai vào một vị trí bất kỳ trên bàn. + +## Phạm vi và giả định + +- LLM chỉ xác định semantic intent: vật nào phải đến vị trí cũ của vật nào. +- Tọa độ không do LLM sinh; hệ thống snapshot từ scene state ban đầu. +- Giữ nguyên Panda, A*, U-trajectory và scoring hiện có. Chỉ bổ sung preferred + position vào scoring free-space. +- Mở rộng Goal Predicate theo hướng tương thích ngược bằng `position_near`; + các predicate cũ không đổi. +- Nếu anchor chính xác không còn an toàn/khả dụng, optimiser chọn điểm hợp lệ + gần nhất thay vì bỏ qua collision/reachability. + +## File đã sửa + +- `llm_panda/llm_agent.py` +- `llm_panda/conversation/models.py` +- `llm_panda/execution/pipeline.py` +- `llm_panda/execution/monitor.py` +- `llm_panda/scene_manager.py` +- `tests/test_conversation_memory.py` +- `tests/test_monitor.py` +- `tests/test_occupancy.py` +- `docs/CONVERSATION_MEMORY_PLAN.md` + +Không xóa hoặc đổi tên file/tính năng. + +## Hành vi trước và sau + +### Trước + +- Swap được hạ xuống hai goal `location_is(table)`. +- Executor chọn hai free spot thông thường trên bàn. +- Goal Check báo thành công chỉ vì cả hai vật vẫn ở `table`. + +### Sau + +- Goal Resolution được hướng dẫn biểu diễn swap bằng: + - một task tạm `auto_safe`; + - hai task `former_location` neo vào hai object ban đầu. +- Intent layer lấy position của anchor từ initial scene snapshot. +- Matching `move_to` nhận `target_position` và `placement_anchor` nội bộ. +- Surface được suy ra từ vị trí ban đầu của anchor nếu LLM không lặp lại. +- Placement optimiser ưu tiên free/reachable spot gần anchor nhất. +- Goal Check tạo hai predicate `position_near`, mặc định tolerance 4 cm. +- Output cũ dùng free-text `details="... original/former location ..."` được + migrate best-effort sang schema mới. + +## Kiểm tra và kết quả + +- `python -m py_compile llm_panda\llm_agent.py llm_panda\conversation\models.py llm_panda\execution\monitor.py llm_panda\execution\pipeline.py llm_panda\scene_manager.py` + - Thành công. +- `python -m pytest tests\test_conversation_memory.py tests\test_monitor.py tests\test_occupancy.py -q` + - `63 passed` sau khi bổ sung test cuối. +- `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q` + - `86 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Placement không có anchor vẫn dùng scoring cũ. +- Relation object-to-object, table/tray placement và blocker clearing giữ nguyên. +- A* và U-trajectory vẫn nhận target cuối theo luồng cũ. +- Không thay đổi `.env`, semantic catalog hoặc thay đổi local ngoài phạm vi. + +## Vấn đề còn lại + +- Tolerance hiện là 4 cm để hấp thụ sai số raster/physics. Có thể cấu hình hóa + sau nếu benchmark cho thấy cần độ chính xác khác. +- Test pipeline cũ `test_grasp_survives_fast_translation` vẫn có lỗi ngoài phạm + vi do `PandaApp` không có `grasp_planner`; không tự ý sửa trong thay đổi này. diff --git a/development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md b/development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md new file mode 100644 index 0000000000000000000000000000000000000000..356c8cb446b06cf5270adb8b227a927f5d93b78a --- /dev/null +++ b/development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md @@ -0,0 +1,96 @@ +# Triển khai reload persistence và live interrupt/re-plan + +## Yêu cầu của người dùng + +- Reload trang web không reset trạng thái; giữ mọi thứ đang diễn ra. +- Cho phép gửi prompt trong lúc robot thực thi; robot dừng ngay theo cơ chế an + toàn, giữ live state rồi lập kế hoạch mới từ state đó. +- Thực hiện đầy đủ các phase đã lập kế hoạch. + +## Phạm vi và giả định + +- Persistence áp dụng cho browser reload/WebSocket reconnect trong cùng process + server, không phải restart backend. +- Giữ một shared simulation như kiến trúc `current_sim` hiện tại. +- Cooperative cancellation, không kill thread. +- Không thay đổi Panda model, A*, U-trajectory, cost scoring, environment semantic + catalog hoặc tốc độ robot. +- Các thay đổi local có sẵn được bảo toàn. + +## File đã thêm + +- `frontend/web_runtime.py` +- `llm_panda/execution/cancellation.py` +- `tests/test_web_runtime.py` +- `docs/WEB_RUNTIME_INTERRUPTION_PLAN.md` +- `development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md` + +## File đã sửa + +- `frontend/interactive_server.py` +- `frontend/app.js` +- `llm_panda/execution/pipeline.py` +- `llm_panda/robot_controller.py` +- `tests/test_monitor.py` + +Không xóa hoặc đổi tên file. + +## Hành vi trước và sau + +### Trước + +- Mỗi WebSocket mới reset object và đưa robot về home. +- ConversationManager thuộc connection và bị xóa khi disconnect. +- Pipeline gửi thẳng vào socket cũ nên reload mất log/plan/result. +- Frontend khóa input khi robot chạy. +- Không có cancellation token; nhiều run có thể cạnh tranh simulation. + +### Sau + +- Server-owned runtime sống qua reconnect và broadcast đến subscriber hiện tại. +- Reconnect không reset scene; nhận init cache, latest physical state và runtime + snapshot. +- Conversation, event journal, plan, result và task lifecycle được giữ. +- Input luôn nhận prompt; prompt mới interrupt task cũ và dùng latest-wins. +- Một command worker duy nhất serialize quyền điều khiển robot. +- Cancellation checkpoint hoạt động giữa steps và trong motion loops. +- Safe hold giữ joint pose và grasp constraint; không tự home/recover khi + interrupted. +- LLM response/task event cũ bị chặn bằng generation. +- Reset/change-env là transactional: cancel-all, chờ stop acknowledgement rồi + mới mutate scene. +- Manual pose controls bị khóa khi active task đang chạy. + +## Kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- `python -m py_compile frontend\interactive_server.py frontend\web_runtime.py llm_panda\execution\cancellation.py llm_panda\execution\pipeline.py llm_panda\robot_controller.py` + - Thành công. +- `python -m pytest tests\test_web_runtime.py tests\test_monitor.py -q` + - `17 passed` sau test hardening cuối. +- Regression liên quan: + - `96 passed`. +- Toàn bộ suite: + - `141 passed`, `3 skipped`, `13 failed`. + - 10 failure là test RemoteLLM gọi OpenRouter nhưng network bị sandbox chặn. + - 2 failure có sẵn do `PandaApp` thiếu `grasp_planner`. + - 1 failure có sẵn do `config.YCB_CATALOG` không tồn tại. + - Không failure nào đi qua runtime/cancellation mới. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- CLI/GUI không truyền cancellation token nên giữ luồng cũ. +- Grasp/release vẫn atomic; interrupt không tháo constraint. +- Explicit reset và change environment vẫn tồn tại. +- Web drag/manual controls vẫn hoạt động khi runtime idle. +- Goal resolution, conversation memory, swap anchor và goal check giữ nguyên. + +## Vấn đề còn lại + +- Chưa checkpoint PyBullet xuống disk để phục hồi sau backend restart. +- Shared runtime chưa tách simulation theo nhiều người dùng. +- Các failure toàn-suite nêu trên cần yêu cầu riêng nếu muốn xử lý. + diff --git a/development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md b/development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md new file mode 100644 index 0000000000000000000000000000000000000000..a308266185e26d6ed1308da892781cbd6a8a337a --- /dev/null +++ b/development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md @@ -0,0 +1,71 @@ +# Thêm nút gửi/dừng lệnh trong lúc robot thực thi + +## Yêu cầu của người dùng + +Sau khi gửi lệnh, nút gửi chuyển thành icon đang thực thi giống Codex. Người +dùng vẫn nhập được lệnh mới; click nút để dừng task hiện tại hoặc nhấn Enter để +dừng và gửi lệnh mới. + +## Phạm vi và giả định + +- Tận dụng WebRuntime/cancellation protocol đã có (`run` và `cancel`). +- Chỉ thay đổi UX frontend và test contract, không sửa robot, planner, trajectory + hoặc semantic behavior. +- Click nút khi busy luôn có nghĩa là cancel; Enter trong chat input với nội + dung có nghĩa là interrupt-and-send. + +## File đã sửa + +- `frontend/app.js` +- `frontend/index.css` +- `docs/WEB_RUNTIME_INTERRUPTION_PLAN.md` + +## File đã thêm + +- `tests/test_web_command_button.py` +- `development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md` + +Không xóa hoặc đổi tên file. + +## Hành vi trước và sau + +### Trước + +- Nút vẫn hiển thị icon gửi trong lúc task chạy. +- Không có thao tác click rõ ràng để gửi `cancel`. +- Enter và click dùng cùng submit path nên chưa phân biệt stop với replacement + command. + +### Sau + +- Busy state hiển thị stop square và spinner. +- Chat input và submit button không bị disable. +- Click stop gửi `{"type":"cancel"}` và giữ nội dung đang gõ. +- Enter từ chat input gửi `{"type":"run"}`; backend interrupt task cũ và chạy + command mới. +- Stale `interrupted` event không làm nút task mới quay lại mode gửi. +- Runtime snapshot khôi phục đúng mode gửi/dừng sau reload. +- Button có title/ARIA tương ứng. + +## Kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- `python -m pytest tests\test_web_command_button.py tests\test_web_runtime.py -q` + - `11 passed`. +- `python -m pytest tests\test_web_command_button.py tests\test_web_runtime.py tests\test_monitor.py -q` + - `20 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Gửi lệnh lúc idle vẫn dùng form submit cũ. +- Reset button, microphone, autocomplete và preset command không bị xóa. +- Backend cancellation, latest-wins và live-state re-plan giữ nguyên. +- Không thay đổi các local edit ngoài phạm vi. + +## Vấn đề còn lại + +- Cần restart backend và hard-refresh browser để chắc chắn JavaScript/CSS mới + không bị cache. diff --git a/development_logs/2026-07-04_17-10-44_restore-web-runtime-and-live-command-ui.md b/development_logs/2026-07-04_17-10-44_restore-web-runtime-and-live-command-ui.md new file mode 100644 index 0000000000000000000000000000000000000000..5b5cdd02a3aa748404ff33297fdd79ac51b8e5f5 --- /dev/null +++ b/development_logs/2026-07-04_17-10-44_restore-web-runtime-and-live-command-ui.md @@ -0,0 +1,78 @@ +# Khôi phục web runtime và giao diện lệnh trực tiếp + +## Yêu cầu của người dùng + +Khôi phục trạng thái mới nhất của các tính năng đã phát triển trước đó sau khi một +agent khác hoàn tác hoặc ghi đè các file frontend. + +## Phạm vi và giả định + +- Đối chiếu working tree với các development log và test hợp đồng đã tồn tại. +- Khôi phục phần bị mất: runtime sống qua reload, conversation sống qua reconnect, + worker thực thi tuần tự, interrupt/re-plan từ live state và nút gửi/dừng. +- Không đưa phần kéo-thả web đang làm dở sau đó vào bản khôi phục. +- Không ghi đè các thay đổi local ngoài phạm vi. +- `main.py` và `llm_panda/config.py` sạch so với commit hiện tại nên chỉ được kiểm + tra, không sửa. + +## File đã sửa + +- `frontend/interactive_server.py` +- `frontend/app.js` +- `frontend/index.css` +- `frontend/index.html` + +Không thêm hoặc xóa file chức năng. File hiện tại là development log duy nhất được +thêm trong lần thực thi này. + +## Hành vi trước và sau + +### Trước + +- Mỗi WebSocket reconnect reset object và robot về home. +- Pipeline gửi sự kiện vào socket cũ; reload làm mất task/log/plan/result. +- Conversation manager không được nối vào server-owned runtime. +- Các lệnh có thể chạy bằng thread riêng và tranh chấp simulation. +- Frontend khóa input khi task chạy và không có nút dừng. +- Asset quay về `app.js?v=25` và `index.css?v=8`. + +### Sau + +- Reload/reconnect giữ nguyên PyBullet state, conversation, log, plan, result và + vòng đời task trong cùng backend process. +- Một command worker serialize quyền điều khiển robot. +- Prompt mới yêu cầu dừng task cũ và task mới bắt đầu từ live state; cancel giữ + robot ở pose an toàn. +- Runtime event có generation để frontend bỏ qua kết quả cũ. +- Reset và đổi môi trường chờ task dừng rồi mới mutate scene. +- Input vẫn dùng được khi robot chạy; click nút busy để dừng, Enter để gửi lệnh + thay thế. +- Nút busy hiển thị stop square và spinner. +- Asset được cache-bust bằng `app.js?v=26` và `index.css?v=9`; HTML dùng no-cache. + +## Lệnh kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- Python 3.10 `-m py_compile` cho server/runtime/cancellation/pipeline/controller + - Thành công. +- Python 3.10 `-m pytest tests\test_web_command_button.py tests\test_web_runtime.py tests\test_monitor.py -q` + - `21 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo chuyển đổi LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Conversation memory, semantic catalog, goal resolution/check, former-location + swap, A*, U-trajectory và robot model không bị sửa. +- Manual drag/pose controls hiện có vẫn hoạt động khi runtime idle. +- Reset scene, đổi environment, microphone, autocomplete và lịch sử UI vẫn còn. +- `llm_panda/robot_controller.py` vẫn giữ `time_scale = 0.1`. +- Các thay đổi local ngoài bốn file frontend không bị dọn dẹp hoặc hoàn tác. + +## Vấn đề còn lại hoặc cần người dùng quyết định + +- Persistence chỉ sống qua browser reload/WebSocket reconnect trong cùng backend + process; restart backend chưa có checkpoint PyBullet xuống disk. +- Chưa chạy kiểm thử thao tác thật trong browser ở lần này; các kiểm tra tự động, + cú pháp và hợp đồng runtime đều đã qua. diff --git a/development_logs/2026-07-04_17-21-10_restore-context-goal-and-clarification-behavior.md b/development_logs/2026-07-04_17-21-10_restore-context-goal-and-clarification-behavior.md new file mode 100644 index 0000000000000000000000000000000000000000..83c32a26b914a17e564147314e83e772077eb20c --- /dev/null +++ b/development_logs/2026-07-04_17-21-10_restore-context-goal-and-clarification-behavior.md @@ -0,0 +1,82 @@ +# Khôi phục context goal và hành vi clarification + +## Yêu cầu của người dùng + +Khôi phục các tính năng còn bị thay đổi hoặc loại bỏ sau khi đối chiếu code hiện +tại với docs và development log trước đó. + +## Phạm vi và giả định + +- Chỉ khôi phục bốn sai lệch đã xác nhận trong audit: + - web giữ cùng `ResolvedGoal` qua planning, re-plan và Goal Check; + - giới hạn re-plan web lấy từ `MAX_REPLANS`, mặc định 3; + - clarification/reject không bị ghi thành một lần robot thực thi thất bại; + - reset scene hoặc đổi environment trong CLI/Tk xóa conversation memory. +- Không thay đổi Panda model, A*, U-trajectory, placement scoring, semantic + catalog, action primitive hoặc tốc độ robot. +- Bảo toàn mọi thay đổi local đã tồn tại ngoài phạm vi. + +## File đã sửa + +- `frontend/interactive_server.py` +- `frontend/app.js` +- `frontend/index.html` +- `main.py` +- `tests/test_web_runtime.py` +- `tests/test_web_command_button.py` + +Không xóa hoặc đổi tên file. File development log này là file mới duy nhất được +tạo trong lần thực thi. + +## Hành vi trước và sau + +### Trước + +- Web re-plan gọi Goal Resolution lại bằng raw prompt ở mọi attempt. +- Web Goal Check không nhận `ResolvedGoal`, có thể diễn giải lại câu follow-up. +- Web cho phép tối đa 999999 lần re-plan. +- Clarification được gửi với `success=false` và frontend ghi vào history/analytics + như task thất bại. +- `PandaApp.reset_objects()` giữ pending conversation của scene cũ. + +### Sau + +- Attempt đầu lưu `PlanningOutcome.resolved_goal`. +- Re-plan dùng `resolved_goal.canonical_instruction` và `resolve_goal=False`. +- Goal Check nhận đúng cùng `resolved_goal` để dùng deterministic predicates. +- Web đọc `MAX_REPLANS` từ environment, mặc định và fallback là 3. +- Result có `response_type=clarify|reject`; frontend mở khóa input nhưng không ghi + execution history, analytics hoặc phát thông báo hoàn thành. +- `PandaApp.reset_objects()` clear conversation manager; đổi environment đi qua + reset nên cũng clear memory. +- JavaScript cache version tăng từ `v26` lên `v27`. + +## Lệnh kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- Python 3.10 `-m py_compile` cho main, web server/runtime, pipeline, monitor và + LLM agent + - Thành công. +- Regression gồm conversation, semantics, monitor, obstacle graph, occupancy, + cost map và web runtime/UI: + - `104 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Adaptive semantic prompt, dialogue grounding, namespace normalization, + auto-safe intermediate task và former-location swap giữ nguyên. +- Web reload persistence, live interrupt, safe hold và send/stop UI giữ nguyên. +- Clarification vẫn được lưu trong conversation manager để lượt trả lời tiếp theo + bổ sung intent. +- Reset/change environment, manual controls, microphone, autocomplete và UI + history vẫn tồn tại. +- `time_scale = 0.1` không thay đổi. + +## Vấn đề còn lại hoặc cần người dùng quyết định + +- Chưa chạy live OpenRouter trong lần này; schema/behavior được kiểm tra offline. +- Persistence vẫn chỉ sống trong cùng backend process; restart backend chưa phục + hồi PyBullet state từ disk. diff --git a/development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md b/development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md new file mode 100644 index 0000000000000000000000000000000000000000..c35faaaeb82a6717a0dbf3424e5f95b57c2f642b --- /dev/null +++ b/development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md @@ -0,0 +1,78 @@ +# Chuẩn hóa đệ quy standalone compound intents + +## Yêu cầu của người dùng + +Sửa trường hợp lệnh `hoán đổi vị trí giữa quả bóng và lon chip` vẫn hỏi bề mặt +đích, theo hướng scalable và adaptive cho nhiều hành động và môi trường. + +## Phạm vi và giả định + +- Sửa semantic boundary dùng chung, không hard-code câu lệnh, object hoặc + environment cụ thể. +- Mọi intent có `tasks` đều phải được chuẩn hóa theo object/surface namespace của + scene hiện hành, dù là lệnh standalone hay follow-up. +- Giữ nguyên Panda, A*, U-trajectory, goal predicate, scoring, executor và tốc độ. +- Bảo toàn toàn bộ thay đổi local có sẵn ngoài phạm vi. + +## File đã sửa + +- `llm_panda/llm_agent.py` +- `tests/test_conversation_memory.py` + +## File đã thêm + +- `development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md` + +Không xóa hoặc đổi tên file. + +## Hành vi trước và sau + +### Trước + +- Sequence từ pending conversation được chuẩn hóa từng task. +- Sequence mới do Goal Resolver trả cho một lệnh standalone chỉ được chuẩn hóa ở + object ngoài cùng. +- Task `former_location` bên trong giữ `destination=None`, dù scene đã biết surface + của anchor. +- Validator vì vậy hỏi người dùng chọn bề mặt cho một swap vốn đã đủ rõ. + +### Sau + +- `_merge_resolved_intent()` dùng một đường chuẩn hóa task chung cho cả standalone + và follow-up sequences. +- Mỗi child task được: + - loại bỏ placeholder/null; + - chuẩn hóa object/surface namespace; + - gán `auto_safe` cho intermediate task; + - suy ra destination của `former_location` từ anchor trong scene hiện tại. +- Cơ chế áp dụng cho swap, replacement và compound action bất kỳ có `tasks`. +- Surface được đọc động từ environment; test dùng `workbench`, không phụ thuộc + `table` hoặc `tray`. + +## Lệnh kiểm tra và kết quả + +- Python 3.10 `-m py_compile llm_panda\llm_agent.py` + - Thành công. +- Focused conversation và environment semantics: + - `48 passed`. +- Regression conversation, semantics, monitor, obstacle graph, occupancy, cost + map và web runtime/UI: + - `105 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Pending follow-up merge và bảo vệ known slots giữ nguyên. +- Namespace object/surface, constraint provenance và fail-closed validation giữ + nguyên. +- Intermediate task vẫn không tạo Goal Predicate. +- Former-location anchor vẫn dùng tọa độ scene, không lấy tọa độ do LLM sinh. +- Adaptive semantic catalog và aliases của environment hiện hành giữ nguyên. + +## Vấn đề còn lại hoặc cần người dùng quyết định + +- Live OpenRouter cần chạy lại sau khi restart backend để quan sát trọn pipeline. +- Nếu model trả intent không có `tasks` cho một yêu cầu compound, schema guard vẫn + có thể yêu cầu repair/clarification; thay đổi này xử lý chính xác mọi structured + compound intent hợp lệ. diff --git a/development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md b/development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md new file mode 100644 index 0000000000000000000000000000000000000000..2950696707f225f7bf57abcb0a2d4811e576ab11 --- /dev/null +++ b/development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md @@ -0,0 +1,97 @@ +# Thêm kéo thả thủ công và spawn vật từ thư viện trên web + +## Yêu cầu của người dùng + +- Cho phép người dùng kéo thả vật thể và cánh tay robot trực tiếp trong môi trường + web tương tự PyBullet GUI. +- Cho phép kéo avatar/hàng vật thể từ tab thư viện vào viewport để thêm vật thật + vào simulation. +- Thực hiện theo kế hoạch interaction đã cung cấp, đồng thời bảo toàn các tính + năng hiện có. + +## Phạm vi và giả định + +- PyBullet là nguồn sự thật vật lý; Three.js chỉ gửi ý định tương tác. +- Vật thể dùng point-to-point constraint; robot dùng end-effector IK để tránh + constraint chống lại joint motors. +- Manual interaction tự interrupt task đang chạy và chờ safe hold. +- Runtime-spawned YCB object nhận semantic metadata generic, data-driven để xuất + hiện trong scene state và adaptive prompt. +- Không thay planner, Goal Check, A*, U-trajectory, scoring hoặc tốc độ robot. + +## File đã sửa + +- `frontend/app.js` +- `frontend/index.css` +- `frontend/index.html` +- `frontend/interactive_server.py` +- `llm_panda/core/env_builder.py` +- `llm_panda/scene_manager.py` +- `tests/test_web_command_button.py` + +## File đã thêm + +- `tests/test_web_drag_drop.py` +- `development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md` + +Không xóa hoặc đổi tên file. + +## Hành vi trước và sau + +### Trước + +- Frontend chỉ dùng mouse down/move; thiếu mouseup đầy đủ và pointer capture. +- Object và robot cùng đi qua physics constraint. +- Client/server không có drag session ID. +- Manual drag bị bỏ qua khi task đang chạy. +- Disconnect có thể để lại constraint. +- Library chỉ hiển thị catalog, chưa thể thêm object vào simulation. + +### Sau + +- Dùng đầy đủ Pointer Events: down, move, up, cancel, lost capture. +- Mỗi thao tác có `drag_id`; update/end sai session bị bỏ qua. +- Backend raycast xác nhận object được client chọn. +- YCB object dùng point-to-point constraint và state được broadcast 60 Hz. +- Robot dùng IK theo end-effector, clamp workspace và giữ pose khi thả. +- Target được kiểm tra finite, giới hạn workspace và không đi xuyên table/tray. +- Bắt đầu manual interaction tự cancel task, chờ robot dừng an toàn rồi mới kéo. +- Constraint được dọn khi pointer kết thúc hoặc WebSocket disconnect. +- Row/avatar trong catalog có thể kéo vào canvas. +- Điểm thả được raycast xuống mặt placement; backend load URDF YCB thật, tạo tên + instance duy nhất, đăng ký SceneManager và broadcast init/state mới. +- Runtime object nhận aliases, category, attributes và affordances generic để LLM + nhìn thấy trong active scene. +- Asset cache version tăng lên `app.js?v=28`, `index.css?v=10`. + +## Lệnh kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- Python 3.10 `-m py_compile` cho web server, EnvBuilder và SceneManager + - Thành công. +- Test web drag/runtime/button: + - `22 passed`. +- Regression conversation, semantics, monitor, obstacle graph, occupancy, cost + map và web: + - `111 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Reload persistence, live interrupt/re-plan và send/stop UI giữ nguyên. +- Conversation memory và adaptive environment prompts giữ nguyên. +- Existing object pose/joint controls vẫn còn. +- Reset/change environment vẫn xóa runtime additions theo scene lifecycle cũ. +- Planner và robot execution không chạy song song với manual manipulation. + +## Vấn đề còn lại hoặc cần người dùng quyết định + +- Phiên bản này hỗ trợ translate tự do theo camera plane; chưa có gizmo riêng cho + rotate, trục Z hoặc local-axis transform. +- Runtime object dùng semantics generic từ catalog folder. Muốn tên tiếng Việt, + category và thuộc tính chuyên biệt cho mọi YCB item cần một semantic catalog mở + rộng tương ứng. +- Cần kiểm thử trực tiếp trong browser với nhiều model YCB vì từng asset có + footprint, mesh material và khối lượng khác nhau. diff --git a/development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md b/development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md new file mode 100644 index 0000000000000000000000000000000000000000..f070e602764ef79b8c9a00d04c99b4349728ccfb --- /dev/null +++ b/development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md @@ -0,0 +1,83 @@ +# Sửa object drag và visual của runtime-spawned YCB + +## Yêu cầu của người dùng + +Sửa hai lỗi sau khi triển khai kéo thả web: + +- chỉ kéo được robot, object luôn báo không khớp scene vật lý; +- object thêm từ thư viện có physics shape nhưng chưa hiển thị visual đúng. + +## Phạm vi và giả định + +- Giữ PyBullet body được đăng ký theo object name làm nguồn xác thực cho object + drag. +- Không quay lại cơ chế constraint trên robot; robot vẫn dùng end-effector IK. +- Chỉ sửa drag anchor và suy luận metadata visual của runtime-spawned YCB. +- Bảo toàn mọi thay đổi local và tính năng hiện có ngoài phạm vi. + +## File đã sửa + +- `frontend/app.js` +- `frontend/interactive_server.py` +- `frontend/index.html` +- `tests/test_web_drag_drop.py` +- `tests/test_web_command_button.py` + +## File đã thêm + +- `development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md` + +Không xóa hoặc đổi tên file. + +## Hành vi trước và sau + +### Trước + +- Backend yêu cầu PyBullet ray phải trúng đúng cùng body mà Three.js ray đã chọn. +- Sai khác giữa visual mesh và collision mesh làm object hợp lệ bị từ chối. +- Constraint dùng điểm hit từ collision ray trong khi client di chuyển theo visual + hit point, có nguy cơ nhảy offset. +- Runtime visual tìm cố định `model.mtl`, trong khi YCB dùng các cặp như + `textured_simple_reoriented.obj/.mtl`. + +### Sau + +- Frontend gửi target theo base position của Three.js object group. +- Backend resolve object name sang body đã đăng ký và không bắt hai ray engine + phải trúng cùng triangle/body. +- Object constraint gắn vào base frame `[0,0,0]`, child target bắt đầu tại live + base pose nên không nhảy khi drag. +- Robot ray validation và IK path giữ nguyên. +- Runtime visual lấy material có cùng stem với visual mesh được PyBullet báo. +- Smoke test thực tế xác nhận `YcbCrackerBox` trả: + - `textured_simple_reoriented.obj`; + - `textured_simple_reoriented.mtl`. +- JavaScript cache version tăng lên `v29`. + +## Lệnh kiểm tra và kết quả + +- `node --check frontend\app.js` + - Thành công. +- Python 3.10 `-m py_compile frontend\interactive_server.py` + - Thành công. +- Test web drag/button/runtime: + - `23 passed`. +- Headless PyBullet smoke test spawn `YcbCrackerBox` và đọc init payload: + - Thành công, folder/OBJ/MTL đúng. +- Regression conversation, semantics, monitor, occupancy, cost map và web: + - `112 passed`. +- `git diff --check` + - Thành công; chỉ có cảnh báo LF/CRLF của working tree. + +## Tính năng hiện có được bảo toàn + +- Robot end-effector drag bằng IK giữ nguyên. +- Drag ID, pointer capture, workspace clamp và disconnect cleanup giữ nguyên. +- Catalog spawn tạo body vật lý thật và semantic metadata giữ nguyên. +- Reload persistence, cancellation và conversation memory giữ nguyên. + +## Vấn đề còn lại hoặc cần người dùng quyết định + +- Cần restart backend và hard-refresh để browser nhận `app.js?v=29`. +- Một số YCB model có thể có material/texture đặc thù khác; loader vẫn hỗ trợ OBJ + không có MTL làm fallback. diff --git a/docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md b/docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md index bf388da3b2a73afcc1db254ae85c1420abe169a2..56ff3f061a8365c87697b7a83c98366e3af255ba 100644 --- a/docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md +++ b/docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md @@ -5,6 +5,12 @@ Đã triển khai ngày 2026-07-03: - pre-planning LLM Goal Resolution Gate: `ready | clarify | reject`; +- typed intent slots: manipulated `object_id`, surface `destination`, spatial + `relation`, reference-object `relative_to`; +- follow-up chỉ được điền missing slots, không được ghi đè slot đã biết; +- self-reference và plan/goal mismatch bị chặn trước execution; +- compound/swap/replacement goal được lưu thành ordered `tasks`; clarification chỉ + điền slot thiếu của một task và không được làm mất các task còn lại; - planner chỉ nhận canonical goal khi gate trả `ready`; - action thiếu tham số bắt buộc bị chặn và chuyển thành clarification; - `ResolvedGoal`/`PlanningOutcome` và goal predicates; diff --git a/docs/CONVERSATION_MEMORY_PLAN.md b/docs/CONVERSATION_MEMORY_PLAN.md index 39056109aff7e1605b1b52bb9640d5cbaf23326d..7b5695b414c38fa24d043b4c5fa16737c3f8a5f3 100644 --- a/docs/CONVERSATION_MEMORY_PLAN.md +++ b/docs/CONVERSATION_MEMORY_PLAN.md @@ -7,6 +7,9 @@ Ngày lập kế hoạch: 2026-07-03 - 2026-07-03: Hoàn thành Phase 1 — pending clarification memory trong phiên. - 2026-07-03: Hoàn thành Phase 2 — structured dialogue state, cancel/replace, scene revision và structured-output fallback. +- 2026-07-04: Bổ sung adaptive entity grounding từ environment catalog và một + schema-repair turn cho Goal Resolution; unique alias không còn bị hỏi xác nhận, + malformed provider response không làm mất pending context. - Đã tích hợp core agent, CLI/Tkinter, WebSocket, PySide và overlay. - Reset scene/change environment sẽ xóa conversation context. - Có feature flag `CONVERSATION_MEMORY_ENABLED` để quay về stateless mode. @@ -435,3 +438,27 @@ Khuyến nghị mặc định: Việc bật persistence qua Redis/SQLite, lưu dữ liệu dài hạn hoặc tách simulation theo từng người dùng là thay đổi phạm vi và cần phê duyệt riêng. + +## 17. Optional constraints và intermediate-task boundary + +- Trạng thái: hoàn thành ngày 2026-07-04. +- Goal Resolution chỉ yêu cầu làm rõ constraint bắt buộc của kết quả người dùng. +- `relation` và `relative_to` là một cặp nguyên tử, chỉ giữ khi có provenance + `user`/`conversation` hoặc đang là field được người dùng làm rõ. +- Relation rời do model tự suy diễn được loại bỏ trước validation. +- Task `purpose=intermediate` dùng `placement_policy=auto_safe`; planner chọn vị + trí an toàn mà không hỏi người dùng nếu họ không đặt ràng buộc. +- Goal Check được biên dịch từ resolved intent và bỏ qua intermediate task, thay + vì biến toàn bộ execution plan thành điều kiện hoàn thành. + +## 18. Former-location anchor cho swap/replace + +- Trạng thái: hoàn thành ngày 2026-07-04. +- Swap được biểu diễn bằng temporary relocation và hai goal task có + `placement_policy=former_location`. +- Mỗi goal task dùng `anchor_object_id`; tọa độ được snapshot từ scene ban đầu, + không nhận số do LLM tạo. +- `move_to` được annotate nội bộ bằng `target_position`; free-space optimiser + chọn vị trí khả dụng gần anchor nhất trong khi vẫn giữ reachability/clearance. +- Goal Check dùng predicate `position_near` với sai số 4 cm thay vì chỉ kiểm tra + hai vật vẫn nằm trên cùng surface. diff --git a/docs/ENVIRONMENT_SEMANTIC_CATALOG.md b/docs/ENVIRONMENT_SEMANTIC_CATALOG.md new file mode 100644 index 0000000000000000000000000000000000000000..60947db2da20a71e7aa70281ff7df51ec13d1d56 --- /dev/null +++ b/docs/ENVIRONMENT_SEMANTIC_CATALOG.md @@ -0,0 +1,78 @@ +# Environment Semantic Catalog + +## Mục đích + +Mỗi môi trường có hai phần dữ liệu: + +- file environment: robot, geometry, asset và initial pose; +- file semantic catalog: thông tin để LLM hiểu object và surface. + +Ví dụ: + +```json +{ + "semantic_catalog": "env1.semantics.json", + "robot": {}, + "table": {}, + "tray": {}, + "objects": [] +} +``` + +Catalog tương ứng: + +```json +{ + "schema_version": 1, + "environment_id": "env1", + "description": "...", + "surfaces": { + "table": { + "display_name": {"vi": "bàn", "en": "table"}, + "aliases": ["bàn", "table"], + "kind": "support_surface" + } + }, + "objects": { + "object_id": { + "display_name": {"vi": "...", "en": "..."}, + "aliases": [], + "categories": [], + "attributes": {}, + "affordances": [] + } + } +} +``` + +## Trường dữ liệu + +- `environment_id`: định danh ổn định của môi trường. +- `description`: mô tả ngắn cho LLM. +- `surfaces`: metadata của các surface hiện có. +- `objects`: map theo đúng object ID trong environment. +- `display_name`: tên hiển thị, không dùng làm ID thực thi. +- `aliases`: cách người dùng có thể gọi object/surface. +- `categories`: phân loại semantic như fruit, tool, food. +- `attributes`: color, material, weight hoặc thuộc tính tùy môi trường. +- `affordances`: khả năng semantic như pickable, placeable, support_surface. + +## Quy tắc + +- Mọi object trong environment phải có entry trong catalog được tham chiếu. +- Catalog phải mô tả `table` và `tray` trong scope hiện tại. +- Planner luôn dùng canonical object ID; alias chỉ phục vụ grounding. +- Chỉ object thật sự có trong scene hiện tại được đưa vào adaptive prompt. +- Không đưa API key, credential hoặc dữ liệu người dùng vào catalog. + +## Thêm môi trường mới + +1. Tạo `envs/.json`. +2. Tạo `envs/.semantics.json`. +3. Thêm trường `semantic_catalog` vào environment. +4. Mô tả đầy đủ từng object và surface. +5. Chạy `tests/test_environment_semantics.py`. + +Không cần sửa `RemoteLLMPlanner.SYSTEM_PROMPT` khi thêm object, alias, category hoặc +thuộc tính mới. + diff --git a/docs/GENERALIZATION_AUDIT.md b/docs/GENERALIZATION_AUDIT.md new file mode 100644 index 0000000000000000000000000000000000000000..4d3e4c41634bfb0e166341fb40e50797e66b9945 --- /dev/null +++ b/docs/GENERALIZATION_AUDIT.md @@ -0,0 +1,382 @@ +# Kiểm kê giới hạn hard-code và lộ trình tổng quát hóa LLM-Panda + +## 1. Mục tiêu + +Tài liệu này phân biệt ba loại ràng buộc: + +1. **Bất biến phần cứng** — phải tồn tại nhưng nên nằm trong robot profile/capability + registry, không nằm rải rác trong logic. +2. **Tham số heuristic** — cần cấu hình hoặc hiệu chỉnh theo scene/robot. +3. **Hard-code miền bài toán** — đang khiến hệ thống chỉ làm tốt với vài object, + bề mặt, câu lệnh và hành vi; đây là nhóm cần loại bỏ để tổng quát hóa. + +Thay đổi đầu tiên đã thực hiện: Remote LLM không còn dùng danh sách động từ/object +trong `ConversationManager` để quyết định câu mới hay follow-up. LLM Goal Resolution +trả `conversation_mode=standalone|follow_up` bằng semantic reasoning. + +## Quyết định phạm vi của dự án + +Theo yêu cầu ngày 2026-07-04, các giới hạn sau **được giữ nguyên có chủ đích** vì +thuộc scope bài toán: + +- model và controller của Franka Panda; +- A* 2D và U-trajectory; +- bộ Goal Predicate hiện tại; +- scoring hiện tại. + +Các mục này không còn nằm trong backlog bắt buộc tổng quát hóa. Trọng tâm trước mắt +là tổng quát hóa thông tin môi trường và semantic grounding. + +## Trạng thái Phase G1 + +Đã triển khai: + +- mỗi environment trỏ đến một semantic catalog JSON riêng; +- aliases, display names, categories, attributes và affordances được chuyển khỏi + Remote LLM prompt vào catalog; +- `EnvBuilder` nạp và kiểm tra catalog; +- `SceneManager` đưa semantics của object/surface hiện hành vào scene state; +- Goal Resolver, Planner và LLM fallback Goal Check xây prompt adaptive từ scene; +- đổi environment làm thay đổi prompt mà không sửa Python; +- core Remote LLM prompt không còn chứa catalog sáu object của `env1`. + +## 2. Quy trình hiện tại và các điểm bị giới hạn + +### Bước 1 — Nhận hội thoại + +**Hiện tại** + +- `ConversationManager` giữ pending clarification, sáu lượt gần nhất và TTL 10 phút. +- Cancel dùng tập câu cố định Việt/Anh. +- Fallback offline nhận diện lệnh mới bằng `_ACTION_WORDS` và `_OBJECT_WORDS`. +- Remote LLM nay dùng `conversation_mode` thay cho hai danh sách đó. + +**Giới hạn còn lại** + +- Cancel vẫn phụ thuộc danh sách cụm từ. +- Không có dialogue-act ontology tổng quát như cancel/correct/replace/confirm. +- Không có entity memory sau khi task đã hoàn tất; chủ yếu nhớ pending clarification. +- Không có rolling summary/persistence. + +**Hướng tổng quát** + +- Để Goal Resolver trả dialogue act có cấu trúc. +- Entity grounding theo scene ID thay vì từ khóa. +- Dùng bounded semantic state, không đưa toàn bộ chat thô vào planner. + +### Bước 2 — Goal Resolution + +**Hiện tại** + +- Output cố định: `ready|clarify|reject`. +- Missing fields cố định: object, destination, relation, relative object, details. +- Prompt có ví dụ cụ thể banana, pear, chips can. + +**Giới hạn** + +- Goal schema thiên về pick-and-place. +- Chưa biểu diễn số lượng, thứ tự, điều kiện, vòng lặp, vùng tùy ý, orientation, + force, temporal constraint hoặc composite goal. +- Ví dụ cụ thể có thể bias model về sáu object thử nghiệm. + +**Hướng tổng quát** + +- Goal AST/versioned schema: action intent, entity query, constraints, success + predicates và ambiguity set. +- Sinh schema từ capability registry của robot. +- Inject object catalog hiện tại từ scene thay vì viết object trong prompt. + +### Bước 3 — Semantic planner + +**Hard-code nghiêm trọng trong `llm_agent.py`** + +- `ACTIONS`: chỉ `pick_up`, `move_to`, `place_down`, `clarify`, `reject`. +- Destination chỉ `table`, `tray`; `buffer` là location kỹ thuật. +- Relation chỉ `next_to`, `left_of`, `right_of`, `front_of`, `behind`, + `on_top_of`. +- `SYSTEM_PROMPT` ghi trực tiếp thuộc tính của banana, pear, soup can, chips can, + tennis ball, clamp. +- Synonym map và examples ghi trực tiếp sáu object. +- RuleBasedPlanner chứa danh sách động từ, synonym, clear-table phrase và cách xử lý + riêng cho table/tray. +- JSON schema dùng enum action/location/relation đóng. + +**Hệ quả** + +- Thêm object mới trong JSON chưa đủ; LLM có thể không biết alias/thuộc tính. +- Thêm skill mới bắt buộc sửa prompt, schema, validator, executor, monitor và UI. +- Không thể mở cửa, đẩy, xoay, rót, lau, sử dụng dụng cụ hoặc thao tác hai tay. + +**Hướng tổng quát** + +- `CapabilityRegistry`: mỗi skill tự công bố JSON schema, precondition, effect và + verifier. +- Prompt/tool schema được sinh động từ registry. +- Object properties lấy từ environment metadata/perception. +- Planner trả skill calls dựa trên capability hiện có, không dựa vào enum viết tay. + +### Bước 4 — Plan validation và obstacle normalization + +**Hiện tại** + +- `PlanVerifier` chỉ hiểu pick/move/place và location table/tray/buffer. +- Obstacle graph giả định blocker phải được dời sang table. +- Deadlock cycle được giải bằng side grasp trực tiếp. +- Một gripper, giữ tối đa một vật. + +**Giới hạn** + +- Policy clear blocker tối ưu cho tabletop pick-and-place. +- Không search nhiều chiến lược: đổi grasp, đổi thứ tự, đổi buffer/surface, đẩy vật, + hoặc yêu cầu người hỗ trợ. +- Không có symbolic precondition/effect checker tổng quát. + +**Hướng tổng quát** + +- Validator đọc precondition/effect từ skill registry. +- Task-and-motion planning tìm kiếm nhiều strategy và cost. +- Buffer allocator làm việc trên danh sách support surface động. + +### Bước 5 — Scene representation + +**Hard-code trong `SceneManager`/config** + +- Location chỉ `table`, `tray`, `elsewhere`. +- Scene có đúng một table và một tray. +- Quan hệ không gian là một tập sáu relation cố định. +- Quy ước +Y=left, -X=front gắn với robot/table hiện tại. +- Các ngưỡng location, neighbor, blocker, stack và overlap được hiệu chỉnh theo + desktop scene hiện tại. +- Scene state không chứa semantic properties tổng quát từ file môi trường. + +**Hướng tổng quát** + +- Scene graph có danh sách surface/container/region động. +- Relation registry và coordinate frame được khai báo theo workspace. +- Object metadata: aliases, category, material, affordances, graspability, support + surfaces. +- Ngưỡng theo kích thước object/uncertainty thay vì một hằng số toàn cục. + +### Bước 6 — Spawn và environment + +**Hiện tại** + +- Object list trong `envs/*.json` là data-driven, đây là điểm tốt. +- Nhưng environment schema vẫn bắt buộc table + tray. +- Spawn fallback có sáu tọa độ, khoảng cách 0.11 m, tối đa 100 lần thử. +- Loader gắn với YCB folder. + +**Hướng tổng quát** + +- Environment schema khai báo arbitrary static bodies, articulated bodies, + surfaces, containers và semantic regions. +- Collision-aware sampler dựa trên footprint. +- Asset adapter cho YCB/URDF/MJCF/mesh thay vì một loader. + +### Bước 7 — Grasp planning + +**Hard-code** + +- Grasp database có class cube/cylinder/can/box/chips/banana/ball/pear/clamp. +- Fallback luôn top-down tại tâm AABB. +- Chỉ có top-down và một side-grasp tilt cố định. +- Mesh orientation bị rút còn yaw để cứu các case tipped object. +- Side grasp trigger, tilt, pre-distance và height được tune cho bộ vật hiện tại. + +**Hệ quả** + +- Object mới vẫn chạy nhưng chất lượng phụ thuộc AABB fallback. +- Vật lõm, có tay cầm, dễ vỡ, mềm hoặc cần orientation cụ thể không được xử lý đúng. + +**Hướng tổng quát** + +- Sinh nhiều grasp candidate từ geometry/point cloud/affordance. +- Collision checking + IK + force closure để xếp hạng. +- Grasp policy theo object metadata, không theo tên class cố định. + +### Bước 8 — Placement + +**Hard-code** + +- Chỉ đặt trên table/tray/buffer. +- `on_top_of` đặt thẳng tâm reference. +- Footprint bị cap ở 0.115 m. +- Margin thử theo chuỗi cố định: configured, 1 cm, 0. +- `TRAY_CLASS_OFFSET_X` có offset riêng cho sáu class khi fallback. +- Nếu thất bại cuối cùng đặt vào table center hoặc class offset. + +**Rủi ro** + +- Object mới dùng offset 0, dễ chồng nhau. +- Vật lớn bị thu footprint giả tạo. +- Best-effort có thể chọn vị trí overlap thay vì từ chối. + +**Hướng tổng quát** + +- Support-surface sampler động theo geometry thật. +- Stable placement/orientation sampling. +- Không dùng class offset; dùng optimization và explicit failure. + +### Bước 9 — Motion planning + +**Hard-code/giả định** + +- Global cost map 2D cho union của table và tray. +- A* grid 100×100, heuristic weight 1.2, inflation cố định. +- U-shaped lift-horizontal-lower trajectory. +- Safe Z, reach margin, lift height và clearance cố định. +- Panda rest pose và workspace hiện tại được tune thủ công. + +**Hệ quả** + +- Không tổng quát cho shelf, drawer, không gian 3D chật, obstacle chuyển động hoặc + robot khác. + +**Hướng tổng quát** + +- Robot/workspace profile. +- Sampling-based hoặc optimization-based 3D motion planner với collision scene. +- Adaptive clearance theo carried geometry và uncertainty. + +### Bước 10 — Robot controller/phần cứng + +**Bất biến hợp lý nhưng đang gắn chặt** + +- Panda 7 joint, hai finger, một end effector. +- Joint indices, force, home pose, URDF và kinematic assumptions. +- Frontend có đoạn chỉ lấy 7 joint. + +**Hướng tổng quát** + +- `RobotModelAdapter` đọc URDF/SRDF và capability. +- Controller plugin theo robot. +- UI render số joint động. + +Đây là giới hạn phần cứng, không nên giao cho LLM tự reasoning để thay thế. + +### Bước 11 — Execution monitor và Goal Check + +**Hard-code** + +- Step verifier chỉ hiểu ba physical actions. +- Goal predicate chỉ `carried_object_is`, `location_is`, `relation_is`. +- Tolerance XY 0.12 m, lift 0.05 m, fall threshold 0.10 m. +- `next_to` dùng threshold 0.20 m hoặc 1.5× gap. +- `on_top_of` dùng AABB tolerance tune cho object hiện tại. +- Re-plan mặc định 3. + +**Hướng tổng quát** + +- Mỗi skill cung cấp verifier và telemetry riêng. +- Predicate plugin/scene-query language. +- Tolerance theo object, skill và sensor uncertainty. + +### Bước 12 — UI, log và scoring + +**Hard-code** + +- Tên Việt/Anh của sáu object được lặp trong Python và JavaScript. +- UI mô tả sáu relation bằng chuỗi `if/else`. +- Scoring Web chỉ tìm target object/location cuối trong plan. +- Điểm cố định: target 50, knock 15, no-knock 30, execution 20/30. +- Success threshold 50. + +**Hệ quả** + +- Multi-object/category/composite task được chấm sai hoặc thiếu. +- Object/skill mới hiển thị tên kỹ thuật. + +**Hướng tổng quát** + +- UI metadata lấy từ scene/capability registry. +- Scoring theo resolved-goal predicates và execution metrics, không parse plan cuối. + +### Bước 13 — Multi-user và deployment + +**Giới hạn** + +- Conversation memory tách theo WebSocket nhưng simulation là `current_sim` global. +- Nhiều user có thể không có world state độc lập. +- Memory chỉ trong process; restart mất. + +**Hướng tổng quát** + +- Session owns simulation instance hoặc job queue/lease rõ ràng. +- Optional persistent conversation store với TTL và privacy policy. + +## 3. Những phần đã data-driven hoặc có fallback tốt + +- Danh sách object và pose có thể khai báo trong environment JSON. +- Grasp database nằm trong JSON và có AABB fallback. +- Table/tray dimensions đọc từ environment. +- Occupancy grid dùng footprint hình học thay vì slot cố định. +- Obstacle graph lấy từ scene geometry. +- Conversation và goal state tách theo session. +- Feature flags cho memory, goal resolution và structured goal check. + +Các phần này là nền tốt, nhưng chưa đủ để gọi hệ thống là domain-general. + +## 4. Kiến trúc đích đề xuất + +```text +Environment/Perception + → Dynamic Scene Graph + Object Metadata + → LLM Goal Resolver → versioned Goal AST + → Capability Registry → dynamic tool schemas + → Task-and-Motion Planner + → Skill plugins + ├─ preconditions/effects + ├─ motion/grasp/placement policy + └─ verifier + → Predicate-based Goal Monitor + → UI/Scoring generated from the same metadata +``` + +Nguyên tắc: LLM reasoning về ý định và lựa chọn capability; geometry, safety, +kinematics và success verification vẫn phải deterministic. + +## 5. Lộ trình tổng quát hóa theo ưu tiên + +### Phase G1 — Dynamic semantic catalog + +- Chuyển object properties/aliases ra environment metadata. **Đã hoàn thành.** +- Sinh prompt từ scene. **Đã hoàn thành.** +- Xóa map tên object lặp ở UI/server. + +### Phase G2 — Capability registry + +- Tách action schema khỏi `llm_agent.py`. +- Planner tools, validator, executor và monitor đọc cùng registry. +- Giữ ba skill hiện tại dưới dạng plugin để tương thích. + +### Phase G3 — Dynamic scene graph + +- Nhiều surface/container/region. +- Location/relation registry và frame semantics động. +- Bỏ giả định table/tray trong cost map và placement. + +### Phase G4 — General grasp/place + +- Multi-candidate grasp generation và ranking. +- Stable placement sampling theo geometry. +- Loại `TRAY_CLASS_OFFSET_X` và footprint cap. + +### Phase G5 — General task-and-motion planning + +- Search strategy, 3D collision-aware planning. +- Composite goals, ordering, quantities và conditional tasks. + +### Phase G6 — Evaluation và multi-user + +- Chấm theo Goal AST/predicates. +- Session-isolated simulations. +- Bộ benchmark có unseen objects, unseen wording và unseen layouts. + +## 6. Tiêu chí để chứng minh tính tổng quát + +- Thêm object mới chỉ bằng asset + metadata, không sửa Python/JS/prompt. +- Thêm skill mới bằng plugin, không sửa planner core/executor dispatcher. +- Thêm surface mới không sửa location enum. +- Câu lệnh dùng động từ chưa từng có vẫn được Goal Resolver hiểu hoặc hỏi lại đúng. +- Benchmark tách train-like và unseen wording/object/layout. +- Không dùng object name cụ thể trong core prompt hoặc core control logic. diff --git a/docs/WEB_RUNTIME_INTERRUPTION_PLAN.md b/docs/WEB_RUNTIME_INTERRUPTION_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..ccfebdc148605a94ec0fc0477b2f6cba299c892b --- /dev/null +++ b/docs/WEB_RUNTIME_INTERRUPTION_PLAN.md @@ -0,0 +1,117 @@ +# Web runtime persistence và interrupt/re-plan + +## Trạng thái + +Đã triển khai đủ bốn phase ngày 2026-07-04. + +## Mục tiêu + +1. Reload/reconnect trình duyệt không reset PyBullet, robot, object, conversation, + plan, log hoặc task đang chạy. +2. Người dùng có thể gửi prompt mới khi robot đang thực thi. Task cũ dừng + cooperative tại checkpoint gần nhất, giữ pose/gripper/object, rồi task mới + lập kế hoạch từ live scene. + +## Kiến trúc + +### Server-owned runtime + +`frontend.web_runtime.WebRuntime` sống độc lập với WebSocket và sở hữu: + +- `ConversationManager`; +- active/pending command; +- generation và cancellation token; +- execution state; +- latest init/state/plan/result; +- event journal có sequence; +- tập WebSocket subscriber. + +PyBullet vẫn là nguồn sự thật vật lý duy nhất. Runtime không ghi đè pose từ dữ +liệu trình duyệt. + +### Task lifecycle + +Các trạng thái chính: + +```text +idle -> planning -> executing -> completed + | + -> interrupt_requested -> interrupted -> planning +``` + +Re-plan nội bộ dùng trạng thái `replanning`. + +Command chưa chạy dùng chính sách latest-wins. Mỗi command có `task_id` và +`generation`; plan/result/log cũ không được phép ghi đè task mới. + +### Cooperative cancellation + +`CancellationToken` được kiểm tra: + +- trước command/step; +- trước và sau planning; +- giữa các waypoint; +- trong joint interpolation; +- trong catch-up và settle loop; +- trong simulation streaming hook. + +`ExecutionInterrupted` unwind về runtime. Controller gọi `hold_current_pose()`, +không home/recover và không tháo grasp constraint. + +### Reload/reconnect + +Frontend giữ `client_id` và event sequence trong `localStorage`. Khi reconnect: + +- server không gọi `reset_objects()` hoặc `reset_to_home()`; +- static init dùng cache; +- dynamic pose lấy từ latest server state; +- runtime snapshot phục hồi log, plan, result, pipeline state và pending + conversation; +- execution tiếp tục phát sự kiện qua subscriber mới. + +### Nút gửi/dừng + +- Khi runtime idle/completed/interrupted, nút hiển thị icon gửi. +- Khi planning/executing/replanning/interrupt-requested, nút hiển thị stop square + với vòng quay trạng thái. +- Ô nhập và Enter luôn hoạt động: + - click nút trạng thái gửi `cancel`; + - Enter trong ô có nội dung gửi command mới, làm task cũ bị supersede rồi + re-plan từ live state. +- `title` và `aria-label` đổi theo mode để hỗ trợ keyboard/screen reader. + +### Reset/change environment + +Hai thao tác này gọi `cancel_all()`, xóa pending command và chờ active task xác +nhận dừng. Nếu timeout, scene mutation bị từ chối. Không reset/đổi environment +song song với chuyển động. + +## WebSocket messages + +Client gửi: + +```json +{"type": "run", "prompt": "...", "mock": false} +{"type": "cancel"} +{"type": "reset"} +{"type": "change_env", "env": "..."} +``` + +Server phát: + +```json +{"type": "runtime_snapshot"} +{"type": "command_accepted", "task_id": "...", "generation": 2} +{"type": "execution_status", "state": "executing"} +{"type": "interrupt_requested"} +{"type": "interrupted"} +``` + +Các event task có `task_id`, `generation`; event journal có thêm `seq`. + +## Giới hạn + +- Runtime tồn tại trong memory của process server. Restart backend vẫn tạo lại + PyBullet scene; persistence qua process restart chưa nằm trong yêu cầu này. +- Dùng một shared simulation runtime, phù hợp kiến trúc `current_sim` hiện tại. + Multi-tenant simulation isolation là scope riêng. diff --git a/envs/default_desk.json b/envs/default_desk.json index 42a5aa449dcb1b2cf22a1fcb77cd5be0f7c28fd9..08a09c94baa8d8006ab49c5583d1ae9ff2b9a9ac 100644 --- a/envs/default_desk.json +++ b/envs/default_desk.json @@ -1,4 +1,5 @@ { + "semantic_catalog": "default_desk.semantics.json", "robot": { "urdf": "franka_panda/panda.urdf", "base_position": [0.0, 0.0, 0.08], diff --git a/envs/default_desk.semantics.json b/envs/default_desk.semantics.json new file mode 100644 index 0000000000000000000000000000000000000000..c4e8c8ef3dbc72b91f7ea349a1abf3e8d1683dc6 --- /dev/null +++ b/envs/default_desk.semantics.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "environment_id": "default_desk", + "description": "Default Franka Panda desk. Object semantics are available for scenarios that populate this workspace.", + "surfaces": { + "table": { + "display_name": {"vi": "bàn", "en": "table"}, + "aliases": ["bàn", "mặt bàn", "table"], + "kind": "support_surface" + }, + "tray": { + "display_name": {"vi": "khay", "en": "tray"}, + "aliases": ["khay", "khay chứa", "tray"], + "kind": "container_surface" + } + }, + "objects": {} +} diff --git a/envs/env1.json b/envs/env1.json index a7f472c4816279610dfbc491f2612344ff73b6de..6ac1bd55e79981365b5b26aed3c9ac3f6d64270d 100644 --- a/envs/env1.json +++ b/envs/env1.json @@ -1,4 +1,5 @@ { + "semantic_catalog": "env1.semantics.json", "robot": { "urdf": "franka_panda/panda.urdf", "base_position": [0.0, 0.0, 0.08], diff --git a/envs/env1.semantics.json b/envs/env1.semantics.json new file mode 100644 index 0000000000000000000000000000000000000000..bbea122844be93d5b6743a3556160162c0317789 --- /dev/null +++ b/envs/env1.semantics.json @@ -0,0 +1,83 @@ +{ + "schema_version": 1, + "environment_id": "env1", + "description": "Franka Panda tabletop workspace with one table, one tray, and six manipulable YCB objects.", + "surfaces": { + "table": { + "display_name": {"vi": "bàn", "en": "table"}, + "aliases": ["bàn", "mặt bàn", "table"], + "kind": "support_surface" + }, + "tray": { + "display_name": {"vi": "khay", "en": "tray"}, + "aliases": ["khay", "khay chứa", "tray"], + "kind": "container_surface" + } + }, + "objects": { + "banana": { + "display_name": {"vi": "quả chuối", "en": "banana"}, + "aliases": ["chuối", "quả chuối", "trái chuối", "banana"], + "categories": ["fruit", "food", "edible"], + "attributes": { + "color": ["yellow"], + "material": ["organic", "non-metal"], + "weight": "light" + }, + "affordances": ["pickable", "placeable", "stackable"] + }, + "pear": { + "display_name": {"vi": "quả lê", "en": "pear"}, + "aliases": ["lê", "quả lê", "trái lê", "pear"], + "categories": ["fruit", "food", "edible"], + "attributes": { + "color": ["yellow-green"], + "material": ["organic", "non-metal"], + "weight": "light" + }, + "affordances": ["pickable", "placeable", "stackable"] + }, + "soup_can": { + "display_name": {"vi": "lon súp", "en": "soup can"}, + "aliases": ["súp", "canh", "hộp súp", "lon súp", "soup can"], + "categories": ["can", "food", "edible"], + "attributes": { + "contents": ["soup"], + "material": ["metal"], + "weight": "heavy" + }, + "affordances": ["pickable", "placeable", "support_surface"] + }, + "chips_can": { + "display_name": {"vi": "lon chips", "en": "chips can"}, + "aliases": ["chips", "chip", "snack", "bim bim", "lon chip", "lon chips", "chips can"], + "categories": ["can", "snack", "food", "edible"], + "attributes": { + "contents": ["chips"], + "material": ["metal", "cardboard"], + "weight": "light" + }, + "affordances": ["pickable", "placeable", "support_surface"] + }, + "tennis_ball": { + "display_name": {"vi": "quả bóng tennis", "en": "tennis ball"}, + "aliases": ["bóng", "quả bóng", "tennis", "bóng tennis", "tennis ball"], + "categories": ["ball", "sports equipment", "non-food"], + "attributes": { + "material": ["felt", "rubber", "non-metal"], + "weight": "light" + }, + "affordances": ["pickable", "placeable", "rollable"] + }, + "clamp": { + "display_name": {"vi": "chiếc kẹp", "en": "clamp"}, + "aliases": ["kẹp", "cái kẹp", "kìm", "cái kìm", "clamp"], + "categories": ["tool", "non-food"], + "attributes": { + "material": ["steel", "metal"], + "weight": "heavy" + }, + "affordances": ["pickable", "placeable"] + } + } +} diff --git a/envs/scenarios/scenario_1.json b/envs/scenarios/scenario_1.json index 1e16fd2aaf0a3195753b7ed25b07f6caebd11359..53c33f7c46c3bbb16b357566ca329c2b2d7c1e35 100644 --- a/envs/scenarios/scenario_1.json +++ b/envs/scenarios/scenario_1.json @@ -1,4 +1,5 @@ { + "semantic_catalog": "../env1.semantics.json", "objects": [ { "name": "banana", diff --git a/frontend/__pycache__/interactive_server.cpython-310.pyc b/frontend/__pycache__/interactive_server.cpython-310.pyc index cafbb2ecb08a2c5e7d8c15b24588697438914e16..00dcc0dffef40f946a1ae6720c4656102c6af344 100644 Binary files a/frontend/__pycache__/interactive_server.cpython-310.pyc and b/frontend/__pycache__/interactive_server.cpython-310.pyc differ diff --git a/frontend/app.js b/frontend/app.js index 05916a753ca17e4006026218c4aff7212bc3d8d9..a6015edc4e52d87600d6f05a82492410aaa57294 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -6,13 +6,19 @@ let robotGroup, tableMesh, trayMesh; const slotHelpers = []; const joints = {}; const ycbMeshes = {}; -let isDragging = false; -let dragPlane = new THREE.Plane(); -let eeDummy = null; +let isDragging = false; +let dragPlane = new THREE.Plane(); +let eeDummy = null; +let placementSurfaceZ = 0.3; const OBJ_LOADER = new THREE.OBJLoader(); const MTL_LOADER = new THREE.MTLLoader(); -let socket = null; -let currentPrompt = ''; +let socket = null; +let currentPrompt = ''; +const runtimeClientId = localStorage.getItem('llm-panda-client-id') || crypto.randomUUID(); +localStorage.setItem('llm-panda-client-id', runtimeClientId); +let lastEventSeq = Number(localStorage.getItem('llm-panda-last-event-seq') || 0); +let activeGeneration = 0; +let executionState = 'idle'; function initVisualizer() { // Set default coordinate system to Z-up THREE.Object3D.DefaultUp.set(0, 0, 1); @@ -168,13 +174,14 @@ function animate() { } // Align eeDummy position to handJoint if not being dragged - if (eeDummy && joints.handJoint) { + if (eeDummy && joints.handJoint) { const handWorldPos = new THREE.Vector3(); joints.handJoint.getWorldPosition(handWorldPos); - eeDummy.position.copy(handWorldPos); - } - - renderer.render(scene, camera); + eeDummy.position.copy(handWorldPos); + } + updateObjectSelectionOverlay(); + + renderer.render(scene, camera); } // Window resizing window.addEventListener('resize', () => { @@ -187,14 +194,15 @@ window.addEventListener('resize', () => { } }); // ─── Three.js Scene Construction ──────────────────────────────────────────── -function createTable(tableConfig) { +function createTable(tableConfig) { if (tableMesh) scene.remove(tableMesh); const ext = tableConfig.half_extents; const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2); const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3)); const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 }); tableMesh = new THREE.Mesh(geo, mat); - tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]); + placementSurfaceZ = Number(tableConfig.top_z || 0.3); tableMesh.castShadow = true; tableMesh.receiveShadow = true; scene.add(tableMesh); @@ -376,55 +384,78 @@ function initRobotStructure() { eeDummy.visible = false; scene.add(eeDummy); } -function loadYcbObjects(objectsConfig) { - // Clear old meshes/groups from scene - Object.values(ycbMeshes).forEach(group => scene.remove(group)); - for (const key in ycbMeshes) delete ycbMeshes[key]; - - Object.entries(objectsConfig).forEach(([name, config]) => { - const folder = config.folder; - let objFile = config.web_obj ? `/assets/ycb/${folder}/${config.web_obj}` : ""; - let mtlFile = config.web_mtl ? `/assets/ycb/${folder}/${config.web_mtl}` : ""; - - if (!objFile) return; - // Create a parent group to represent the object's body link pose - const objectGroup = new THREE.Group(); - objectGroup.name = name; - objectGroup.position.fromArray(config.initial_pos); - objectGroup.quaternion.fromArray(config.initial_ori); - scene.add(objectGroup); - ycbMeshes[name] = objectGroup; - // 1. Load Visual Mesh - MTL_LOADER.load(mtlFile, (materials) => { - materials.preload(); - - const objLoader = new THREE.OBJLoader(); - objLoader.setMaterials(materials); - objLoader.load(objFile, (visObj) => { - visObj.traverse(child => { - if (child.isMesh) { - child.castShadow = true; - child.receiveShadow = true; - if (child.material) { - const mats = Array.isArray(child.material) ? child.material : [child.material]; - mats.forEach(m => { - if (m.map) m.color.setHex(0xffffff); - }); - } - } - }); - - // Position, rotate and scale relative to parent group - if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); - if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); - if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); - - objectGroup.add(visObj); - }); - }); - // Removed collision mesh loading per user request - }); -} +function loadYcbObjects(objectsConfig) { + // Clear old meshes/groups from scene + Object.values(ycbMeshes).forEach(group => scene.remove(group)); + for (const key in ycbMeshes) delete ycbMeshes[key]; + clearObjectSelection(); + Object.entries(objectsConfig).forEach(([name, config]) => { + addYcbObject(name, config); + }); +} + +function addYcbObject(name, config) { + if (!config || !config.folder || !config.web_obj) return null; + if (ycbMeshes[name]) { + scene.remove(ycbMeshes[name]); + delete ycbMeshes[name]; + } + const objFile = `/assets/ycb/${config.folder}/${config.web_obj}`; + const mtlFile = config.web_mtl + ? `/assets/ycb/${config.folder}/${config.web_mtl}` + : ""; + const objectGroup = new THREE.Group(); + objectGroup.name = name; + objectGroup.position.fromArray(config.initial_pos); + objectGroup.quaternion.fromArray(config.initial_ori); + scene.add(objectGroup); + ycbMeshes[name] = objectGroup; + + const attachVisual = (objLoader) => { + objLoader.load(objFile, (visObj) => { + if (ycbMeshes[name] !== objectGroup) return; + visObj.traverse(child => { + if (!child.isMesh) return; + child.castShadow = true; + child.receiveShadow = true; + const materials = Array.isArray(child.material) + ? child.material + : [child.material]; + materials.filter(Boolean).forEach(material => { + if (material.map) { + material.color.setHex(0xffffff); + material.map.encoding = THREE.sRGBEncoding; + material.map.needsUpdate = true; + } + }); + }); + if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos); + if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori); + if (config.vis_scale) visObj.scale.fromArray(config.vis_scale); + objectGroup.add(visObj); + }); + }; + if (mtlFile) { + MTL_LOADER.load(mtlFile, materials => { + materials.preload(); + const objLoader = new THREE.OBJLoader(); + objLoader.setMaterials(materials); + attachVisual(objLoader); + }); + } else { + attachVisual(new THREE.OBJLoader()); + } + return objectGroup; +} + +function removeYcbObject(name) { + const group = ycbMeshes[name]; + if (!group) return; + if (selectedObjectName === name) clearObjectSelection(); + scene.remove(group); + delete ycbMeshes[name]; + delete targetObjects[name]; +} function updateSimulationState(jointsData, objectsData) { if (jointsData && jointsData.length >= 11) { targetJoints = jointsData; @@ -446,7 +477,7 @@ function connectWebSocket() { reconnectTimeout = null; } const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false`; + const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false&client_id=${runtimeClientId}&last_event_seq=${lastEventSeq}`; updateBadgeStatus('disconnected'); @@ -455,9 +486,15 @@ function connectWebSocket() { console.log("WebSocket connected."); updateBadgeStatus('connected'); }; - socket.onmessage = (event) => { - const msg = JSON.parse(event.data); - handleSocketMessage(msg); + socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + if (msg.seq) { + lastEventSeq = Math.max(lastEventSeq, Number(msg.seq)); + localStorage.setItem('llm-panda-last-event-seq', String(lastEventSeq)); + } + if (msg.generation && ['log', 'plan', 'result', 'execution_status', 'current_step'].includes(msg.type) + && Number(msg.generation) < activeGeneration) return; + handleSocketMessage(msg); }; socket.onclose = () => { console.log("WebSocket disconnected."); @@ -469,9 +506,85 @@ function connectWebSocket() { console.error("WebSocket Error: ", err); }; } -function handleSocketMessage(msg) { - switch(msg.type) { - case 'env_list': +function handleSocketMessage(msg) { + switch(msg.type) { + case 'runtime_snapshot': { + activeGeneration = Number(msg.generation || 0); + executionState = msg.execution_state || 'idle'; + if (msg.active_prompt) currentPrompt = msg.active_prompt; + if (msg.state) updateSimulationState(msg.state.joints, msg.state.objects); + if (msg.events) { + logConsole.innerHTML = ''; + msg.events.filter(item => item.type === 'log').forEach(item => { + writeLog(item.message, getLogClass(item.message)); + updatePipelineUI(item.message); + }); + } + if (msg.plan && msg.plan.plan) displayPlan(msg.plan.plan); + if (['idle', 'completed', 'interrupted', 'failed'].includes(executionState)) { + unlockInput(); + } else { + lockInput(); + } + break; + } + + case 'command_accepted': + activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0)); + currentPrompt = msg.prompt || currentPrompt; + executionState = 'planning'; + lockInput(); + break; + + case 'execution_status': + activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0)); + executionState = msg.state || executionState; + lockInput(); + break; + + case 'interrupt_requested': + activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0)); + executionState = 'interrupt_requested'; + lockInput(); + break; + + case 'interrupted': + writeLog('Đã dừng lệnh đang thực thi.', 'warn'); + if (msg.generation && Number(msg.generation) < activeGeneration) { + lockInput(); + } else { + executionState = 'interrupted'; + unlockInput(); + } + break; + + case 'drag_started': + if (activeDrag) { + activeDrag.dragId = msg.drag_id; + activeDrag.type = msg.target_type; + } + break; + + case 'drag_rejected': + case 'spawn_rejected': + case 'delete_rejected': + case 'environment_rejected': + endActiveDrag(false); + writeLog(msg.reason || 'Không thể thực hiện thao tác kéo thả.', 'warn'); + break; + + case 'object_added': + addYcbObject(msg.name, msg.config); + if (msg.state) { + updateSimulationState(null, { [msg.name]: msg.state }); + } + break; + + case 'object_removed': + removeYcbObject(msg.name); + break; + + case 'env_list': const envSelect = document.getElementById('env-select'); if (envSelect && msg.envs) { envSelect.innerHTML = msg.envs.map(env => ``).join(''); @@ -510,19 +623,17 @@ function handleSocketMessage(msg) { break; case 'result': - unlockInput(); - - // Clarifications and rejections are conversational turns, not - // completed robot executions. Keep the input ready for the reply - // and do not record a misleading failed run in analytics. - if (msg.response_type === 'clarify' || msg.response_type === 'reject') { + if (['clarify', 'reject'].includes(msg.response_type)) { + executionState = 'idle'; + unlockInput(); window.currentPlan = null; window.currentLlmTime = 0; - chatInput.focus(); break; } - - // Add new run record to history log dynamically + executionState = msg.success === false ? 'failed' : 'completed'; + unlockInput(); + + // Add new run record to history log dynamically const now = new Date(); const timeStr = now.toTimeString().split(' ')[0]; @@ -633,9 +744,10 @@ function renderObjectsTable(catalogMap) { const rows = Object.entries(catalogMap).map(([name, config]) => { const displayName = objDict[name] || name; const imageUrl = `/static/thumbnails/${config.folder}.png?v=${new Date().getTime()}`; - return ` - - + return ` + +
${displayName}
@@ -645,8 +757,25 @@ function renderObjectsTable(catalogMap) { `; }); - objectsTableBody.innerHTML = rows.join(''); -} + objectsTableBody.innerHTML = rows.join(''); + objectsTableBody.querySelectorAll('.catalog-object-row').forEach(row => { + row.addEventListener('dragstart', event => { + event.dataTransfer.effectAllowed = 'copy'; + event.dataTransfer.setData( + 'application/x-llm-panda-ycb', + JSON.stringify({ + folder: row.dataset.catalogFolder, + name: row.dataset.catalogName + }) + ); + row.classList.add('is-dragging'); + }); + row.addEventListener('dragend', () => { + row.classList.remove('is-dragging'); + canvas.classList.remove('catalog-drop-target'); + }); + }); +} // 4. History Logs Data & Render const historyData = []; @@ -1055,14 +1184,31 @@ function displayPlan(plan) { }); } -function lockInput() { - chatInput.disabled = true; - submitBtn.disabled = true; - resetBtn.disabled = true; -} -document.getElementById('chat-form').addEventListener('submit', (e) => { - e.preventDefault(); - const prompt = chatInput.value.trim(); +function lockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = true; + setSubmitButtonMode(true); + chatInput.placeholder = 'Nhập lệnh mới rồi Enter để thay thế lệnh hiện tại'; +} +let enterSubmittedFromChatInput = false; +chatInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && !e.shiftKey) { + enterSubmittedFromChatInput = true; + } +}); +document.getElementById('chat-form').addEventListener('submit', (e) => { + e.preventDefault(); + const submittedWithEnter = enterSubmittedFromChatInput; + enterSubmittedFromChatInput = false; + const busy = !['idle', 'completed', 'interrupted', 'failed'].includes(executionState); + if (busy && e.submitter === submitBtn && !submittedWithEnter) { + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ type: 'cancel' })); + } + return; + } + const prompt = chatInput.value.trim(); if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return; currentPrompt = prompt; chatInput.value = ''; @@ -1075,20 +1221,31 @@ document.getElementById('chat-form').addEventListener('submit', (e) => { }); window.currentRunStartTime = Date.now(); writeLog(`Gửi yêu cầu: "${prompt}"`, "info"); - lockInput(); + executionState = 'planning'; + lockInput(); speakFeedback("Start processing your command."); - socket.send(JSON.stringify({ - type: 'run', + socket.send(JSON.stringify({ + type: 'run', prompt: prompt, mock: false })); }); -function unlockInput() { - chatInput.disabled = false; - submitBtn.disabled = false; - resetBtn.disabled = false; -} +function unlockInput() { + chatInput.disabled = false; + submitBtn.disabled = false; + resetBtn.disabled = false; + chatInput.placeholder = 'Nhập câu lệnh của bạn cho robot'; + setSubmitButtonMode(false); +} +function setSubmitButtonMode(executing) { + submitBtn.classList.toggle('is-executing', executing); + submitBtn.title = executing ? 'Dừng lệnh đang thực thi' : 'Gửi lệnh'; + submitBtn.setAttribute('aria-label', submitBtn.title); + submitBtn.innerHTML = executing + ? '' + : ''; +} resetBtn.addEventListener('click', () => { if (!socket || socket.readyState !== WebSocket.OPEN) return; @@ -1133,30 +1290,107 @@ slidersList.forEach(id => { }); } }); -// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls -const raycaster = new THREE.Raycaster(); -const mouse = new THREE.Vector2(); -// State variables for Hover Highlight -let hoveredGroup = null; -canvas.addEventListener('mousedown', onMouseDown); -canvas.addEventListener('mousemove', onMouseMove); -// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot) -function findDraggableTarget(hitObject) { - let curr = hitObject; - while (curr && curr !== scene) { - if (curr === robotGroup) { - return { type: 'robot', group: robotGroup, name: 'robot' }; - } - const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr); - if (ycbEntry) { - return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] }; - } - curr = curr.parent; - } - return null; -} -// Helper to set/restore emissive highlight glow on all child meshes of a group -function highlightGroup(group, highlightColor = null) { +// 11. Authoritative pointer dragging for YCB objects and robot end-effector +const raycaster = new THREE.Raycaster(); +const mouse = new THREE.Vector2(); +let hoveredGroup = null; +let activeDrag = null; +let lastDragUpdateAt = 0; +let selectedObjectName = null; +let selectionHelper = null; +const objectDeleteButton = document.createElement('button'); +objectDeleteButton.type = 'button'; +objectDeleteButton.className = 'object-delete-button hidden'; +objectDeleteButton.textContent = '×'; +objectDeleteButton.title = 'Xóa vật thể'; +objectDeleteButton.setAttribute('aria-label', 'Xóa vật thể đã chọn'); +document.body.appendChild(objectDeleteButton); +objectDeleteButton.addEventListener('click', event => { + event.stopPropagation(); + if ( + selectedObjectName + && socket + && socket.readyState === WebSocket.OPEN + ) { + socket.send(JSON.stringify({ + type: 'delete_object', + name: selectedObjectName + })); + } +}); + +function clearObjectSelection() { + selectedObjectName = null; + if (selectionHelper) { + scene.remove(selectionHelper); + selectionHelper.geometry.dispose(); + selectionHelper.material.dispose(); + selectionHelper = null; + } + objectDeleteButton.classList.add('hidden'); +} + +function selectSceneObject(name) { + clearObjectSelection(); + const group = ycbMeshes[name]; + if (!group) return; + selectedObjectName = name; + selectionHelper = new THREE.BoxHelper(group, 0xef4444); + selectionHelper.material.depthTest = false; + selectionHelper.material.transparent = true; + selectionHelper.material.opacity = 0.95; + selectionHelper.renderOrder = 999; + scene.add(selectionHelper); + objectDeleteButton.classList.remove('hidden'); +} + +function updateObjectSelectionOverlay() { + if (!selectedObjectName || !selectionHelper) return; + const group = ycbMeshes[selectedObjectName]; + if (!group) { + clearObjectSelection(); + return; + } + selectionHelper.setFromObject(group); + const box = new THREE.Box3().setFromObject(group); + const anchor = new THREE.Vector3( + (box.min.x + box.max.x) / 2, + (box.min.y + box.max.y) / 2, + box.max.z + 0.04 + ); + anchor.project(camera); + const rect = canvas.getBoundingClientRect(); + objectDeleteButton.style.left = + `${rect.left + (anchor.x + 1) * rect.width / 2}px`; + objectDeleteButton.style.top = + `${rect.top + (-anchor.y + 1) * rect.height / 2}px`; +} + +// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot) +function findDraggableTarget(hitObject) { + let curr = hitObject; + while (curr && curr !== scene) { + if (curr === robotGroup) { + return { type: 'robot_ee', group: robotGroup, name: 'robot' }; + } + const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr); + if (ycbEntry) { + return { type: 'object', group: ycbEntry[1], name: ycbEntry[0] }; + } + curr = curr.parent; + } + return null; +} + +function updatePointerRay(event) { + const rect = canvas.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(mouse, camera); +} + +// Helper to set/restore emissive highlight glow on all child meshes of a group +function highlightGroup(group, highlightColor = null) { if (!group) return; group.traverse(child => { if (child.isMesh) { @@ -1180,109 +1414,165 @@ function highlightGroup(group, highlightColor = null) { } } }); -} -function onMouseDown(event) { - if (event.button !== 0 || chatInput.disabled) return; - - const rect = canvas.getBoundingClientRect(); - mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; - mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; - raycaster.setFromCamera(mouse, camera); - const hits = raycaster.intersectObjects(scene.children, true); - let targetHit = null; - - for (let i = 0; i < hits.length; i++) { - const found = findDraggableTarget(hits[i].object); - if (found) { - targetHit = hits[i]; - break; - } - } - - if (targetHit) { - isDragging = true; - controls.enabled = false; - dragPlane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()), targetHit.point); - - if (socket && socket.readyState === WebSocket.OPEN) { - const rayTo = new THREE.Vector3().copy(raycaster.ray.origin).add(raycaster.ray.direction.clone().multiplyScalar(100)); - socket.send(JSON.stringify({ - type: 'mouse_pick_start', - rayFrom: [raycaster.ray.origin.x, raycaster.ray.origin.y, raycaster.ray.origin.z], - rayTo: [rayTo.x, rayTo.y, rayTo.z] - })); - } - } -} - -function onMouseMove(event) { - const rect = canvas.getBoundingClientRect(); - mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; - mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; - raycaster.setFromCamera(mouse, camera); - - if (isDragging) { - const targetPos = new THREE.Vector3(); - raycaster.ray.intersectPlane(dragPlane, targetPos); - if (targetPos && socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ - type: 'mouse_pick_update', - targetPos: [targetPos.x, targetPos.y, targetPos.z] - })); - } - return; - } - - // Hover logic - const hits = raycaster.intersectObjects(scene.children, true); - let hoverTarget = null; - - for (let i = 0; i < hits.length; i++) { - const found = findDraggableTarget(hits[i].object); - if (found) { - hoverTarget = found; - break; - } - } - - if (hoverTarget) { - if (hoveredGroup !== hoverTarget.group) { - if (hoveredGroup) { - highlightGroup(hoveredGroup, null); - } - hoveredGroup = hoverTarget.group; - highlightGroup(hoveredGroup, 0x555555); - canvas.style.cursor = 'pointer'; - } - } else { - if (hoveredGroup) { - highlightGroup(hoveredGroup, null); - hoveredGroup = null; - canvas.style.cursor = 'default'; - } - } -} - -function onMouseUp(event) { - if (event.button !== 0) return; - if (isDragging) { - isDragging = false; - controls.enabled = true; - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ type: 'mouse_pick_end' })); - } - } -} - -canvas.addEventListener('mouseleave', () => { - if (isDragging) { - isDragging = false; - controls.enabled = true; - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ type: 'mouse_pick_end' })); - } - } -}); +} + +function onPointerDown(event) { + if (event.button !== 0 || !socket || socket.readyState !== WebSocket.OPEN) return; + updatePointerRay(event); + const hits = raycaster.intersectObjects(scene.children, true); + const hit = hits.find(item => findDraggableTarget(item.object)); + if (!hit) { + clearObjectSelection(); + return; + } + const target = findDraggableTarget(hit.object); + if (target.type === 'object') { + selectSceneObject(target.name); + event.preventDefault(); + return; + } + + const planePoint = hit.point.clone(); + if (target.type === 'robot_ee' && joints.handJoint) { + joints.handJoint.getWorldPosition(planePoint); + } + dragPlane.setFromNormalAndCoplanarPoint( + camera.getWorldDirection(new THREE.Vector3()), + planePoint + ); + const initialPlaneHit = new THREE.Vector3(); + raycaster.ray.intersectPlane(dragPlane, initialPlaneHit); + activeDrag = { + dragId: null, + type: target.type, + name: target.name, + pointerId: event.pointerId, + group: target.group, + offset: planePoint.clone().sub(initialPlaneHit) + }; + isDragging = true; + controls.enabled = false; + canvas.setPointerCapture(event.pointerId); + const rayTo = raycaster.ray.origin.clone().add( + raycaster.ray.direction.clone().multiplyScalar(100) + ); + socket.send(JSON.stringify({ + type: 'mouse_pick_start', + target_type: target.type, + object_id: target.name, + rayFrom: raycaster.ray.origin.toArray(), + rayTo: rayTo.toArray() + })); + event.preventDefault(); +} + +function onPointerMove(event) { + updatePointerRay(event); + if (activeDrag && event.pointerId === activeDrag.pointerId) { + const now = performance.now(); + if (!activeDrag.dragId || now - lastDragUpdateAt < 25) return; + lastDragUpdateAt = now; + const targetPos = new THREE.Vector3(); + if (raycaster.ray.intersectPlane(dragPlane, targetPos)) { + targetPos.add(activeDrag.offset); + socket.send(JSON.stringify({ + type: 'mouse_pick_update', + drag_id: activeDrag.dragId, + targetPos: [targetPos.x, targetPos.y, targetPos.z] + })); + } + return; + } + + const hits = raycaster.intersectObjects(scene.children, true); + const hoverHit = hits.find(item => findDraggableTarget(item.object)); + const hoverTarget = hoverHit ? findDraggableTarget(hoverHit.object) : null; + if (hoverTarget) { + if (hoveredGroup !== hoverTarget.group) { + if (hoveredGroup) highlightGroup(hoveredGroup, null); + hoveredGroup = hoverTarget.group; + highlightGroup(hoveredGroup, 0x555555); + canvas.style.cursor = 'pointer'; + } + } else { + if (hoveredGroup) { + highlightGroup(hoveredGroup, null); + hoveredGroup = null; + } + canvas.style.cursor = 'default'; + } +} + +function endActiveDrag(notifyServer = true) { + if (!activeDrag) return; + if ( + notifyServer + && activeDrag.dragId + && socket + && socket.readyState === WebSocket.OPEN + ) { + socket.send(JSON.stringify({ + type: 'mouse_pick_end', + drag_id: activeDrag.dragId + })); + } + const pointerId = activeDrag.pointerId; + activeDrag = null; + isDragging = false; + controls.enabled = true; + if (canvas.hasPointerCapture(pointerId)) { + canvas.releasePointerCapture(pointerId); + } +} + +function onPointerEnd(event) { + if (activeDrag && event.pointerId === activeDrag.pointerId) { + endActiveDrag(true); + } +} + +canvas.addEventListener('pointerdown', onPointerDown); +canvas.addEventListener('pointermove', onPointerMove); +canvas.addEventListener('pointerup', onPointerEnd); +canvas.addEventListener('pointercancel', onPointerEnd); +canvas.addEventListener('lostpointercapture', () => endActiveDrag(true)); + +canvas.addEventListener('dragover', event => { + if (!event.dataTransfer.types.includes('application/x-llm-panda-ycb')) return; + event.preventDefault(); + event.dataTransfer.dropEffect = 'copy'; + canvas.classList.add('catalog-drop-target'); +}); + +canvas.addEventListener('dragleave', () => { + canvas.classList.remove('catalog-drop-target'); +}); + +canvas.addEventListener('drop', event => { + event.preventDefault(); + canvas.classList.remove('catalog-drop-target'); + if (!socket || socket.readyState !== WebSocket.OPEN) return; + let item; + try { + item = JSON.parse( + event.dataTransfer.getData('application/x-llm-panda-ycb') + ); + } catch (_) { + return; + } + updatePointerRay(event); + const surfacePlane = new THREE.Plane( + new THREE.Vector3(0, 0, 1), + -placementSurfaceZ + ); + const position = new THREE.Vector3(); + if (!raycaster.ray.intersectPlane(surfacePlane, position)) return; + socket.send(JSON.stringify({ + type: 'spawn_catalog_object', + folder: item.folder, + position: [position.x, position.y, placementSurfaceZ + 0.08] + })); +}); // Initialize diff --git a/frontend/index.css b/frontend/index.css index 30791c136f00658d1ded67fee772d16b2f3592eb..ab8a513f82e85a2b1d7506948c037102a779053a 100644 --- a/frontend/index.css +++ b/frontend/index.css @@ -662,10 +662,37 @@ button, input, select, table { background: var(--primary-color); color: white; } -#submit-btn:hover { - background: #1d4ed8; -} -#submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled { +#submit-btn:hover { + background: #1d4ed8; +} +#submit-btn.is-executing { + position: relative; + background: #1e3a8a; +} +#submit-btn.is-executing:hover { + background: #172554; +} +#submit-btn.is-executing::before { + content: ""; + position: absolute; + inset: 5px; + border: 2px solid rgba(255, 255, 255, 0.3); + border-top-color: #fff; + border-radius: 50%; + animation: submitExecutionSpin 0.8s linear infinite; +} +#submit-btn .stop-square { + width: 10px; + height: 10px; + border-radius: 2px; + background: #fff; + position: relative; + z-index: 1; +} +@keyframes submitExecutionSpin { + to { transform: rotate(360deg); } +} +#submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled { opacity: 0.4; cursor: not-allowed; box-shadow: none; @@ -962,7 +989,7 @@ button, input, select, table { color: var(--text-muted); } -.objects-table tbody td { +.objects-table tbody td { padding: 12px 16px; border-bottom: 1px solid #f1f5f9; } @@ -989,4 +1016,42 @@ button, input, select, table { border-color: #94a3b8; opacity: 1; transform: scale(1.1); -} \ No newline at end of file +} +.catalog-object-row { + cursor: grab; + user-select: none; +} +.catalog-object-row:active { + cursor: grabbing; +} +.catalog-object-row.is-dragging { + opacity: 0.45; +} +#pybullet-viewport.catalog-drop-target { + outline: 3px dashed #2563eb; + outline-offset: -6px; + filter: saturate(1.1); +} +.object-delete-button { + position: fixed; + z-index: 1000; + width: 28px; + height: 28px; + transform: translate(-50%, -50%); + border: 2px solid #fff; + border-radius: 50%; + background: #ef4444; + color: #fff; + font-size: 21px; + line-height: 20px; + font-weight: 700; + cursor: pointer; + box-shadow: 0 3px 10px rgba(127, 29, 29, 0.4); +} +.object-delete-button:hover { + background: #dc2626; + transform: translate(-50%, -50%) scale(1.08); +} +.object-delete-button.hidden { + display: none; +} diff --git a/frontend/index.html b/frontend/index.html index 42ecbdc968ca149703221a87d12a73b852606fec..f4f90dfeb4c6adf8a98727dab7eb87fd2a0c2b4d 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -15,7 +15,7 @@ - + @@ -300,6 +300,6 @@ - + - \ No newline at end of file + diff --git a/frontend/interactive_server.py b/frontend/interactive_server.py index 96bdc973e33bfdb6a8c4759788c9c1d73284e0af..6ccfaf9bda8c04748b52824e269f285e74e7bc16 100644 --- a/frontend/interactive_server.py +++ b/frontend/interactive_server.py @@ -2,9 +2,10 @@ import sys import os import json import asyncio -import math -import time -import threading +import math +import time +import threading +import uuid from typing import Optional from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles @@ -19,11 +20,12 @@ if PROJECT_SRC not in sys.path: sys.path.insert(0, PROJECT_SRC) from dotenv import load_dotenv load_dotenv() -from main import PandaApp -from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner -from llm_panda.conversation import ConversationManager -from llm_panda.plan_verifier import PlanVerifier -from llm_panda import config +from main import PandaApp +from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner +from llm_panda.plan_verifier import PlanVerifier +from llm_panda import config +from llm_panda.execution.cancellation import ExecutionInterrupted +from frontend.web_runtime import WebRuntime import pybullet_data from pybullet_object_models import ycb_objects app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation") @@ -39,14 +41,82 @@ app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb") async def get(): html_file = os.path.join(static_dir, "index.html") if os.path.exists(html_file): - with open(html_file, "r", encoding="utf-8") as f: - return HTMLResponse(content=f.read(), status_code=200) + with open(html_file, "r", encoding="utf-8") as f: + return HTMLResponse( + content=f.read(), + status_code=200, + headers={ + "Cache-Control": "no-store, no-cache, must-revalidate", + "Pragma": "no-cache", + "Expires": "0", + }, + ) return HTMLResponse(content="

index.html not found!

", status_code=404) # Global variables to track the current active simulation, lock, and thread lock current_sim: Optional[PandaApp] = None executor_lock = asyncio.Lock() pybullet_lock = threading.RLock() -pipeline_executing = False +pipeline_executing = False +web_runtime = WebRuntime() +command_worker_task = None +physics_settle_task = None + + +def _finite_vec3(value): + return ( + isinstance(value, (list, tuple)) + and len(value) >= 3 + and all( + isinstance(component, (int, float)) + and math.isfinite(component) + for component in value[:3] + ) + ) + + +def _clamp_manual_target(position, target_type="object"): + """Keep browser-controlled targets inside the supported workspace.""" + if not _finite_vec3(position): + raise ValueError("Manual target must contain three finite coordinates") + x, y, z = (float(value) for value in position[:3]) + x = min(max(x, -0.10), 0.90) + y = min(max(y, -0.65), 0.65) + z = min(max(z, 0.08 if target_type == "robot_ee" else 0.03), 0.90) + + cx, cy = config.TABLE_CENTER + hx, hy = config.TABLE_HALF_EXTENTS[:2] + if cx - hx <= x <= cx + hx and cy - hy <= y <= cy + hy: + z = max(z, config.TABLE_TOP_Z + 0.01) + tx, ty, tz = config.TRAY_POSITION + thx, thy = config.TRAY_HALF_EXTENTS[:2] + if tx - thx <= x <= tx + thx and ty - thy <= y <= ty + thy: + z = max(z, tz + 0.01) + return [x, y, z] + + +def _load_environment_config(path): + with open(path, "r", encoding="utf-8") as handle: + data = json.load(handle) + required = {"table", "tray", "robot"} + if not isinstance(data, dict) or not required.issubset(data): + raise ValueError("File được chọn không phải environment JSON hợp lệ.") + if "objects" in data and not isinstance(data["objects"], list): + raise ValueError("Trường objects của environment phải là một danh sách.") + return data + + +def _list_environment_files(directory): + files = [] + for filename in sorted(os.listdir(directory)): + if not filename.endswith(".json") or filename.endswith(".semantics.json"): + continue + path = os.path.join(directory, filename) + try: + _load_environment_config(path) + except (OSError, ValueError, json.JSONDecodeError): + continue + files.append(filename) + return files def get_init_payload(sim: PandaApp) -> dict: """Gathers the initial static geometry and YCB object definitions.""" with pybullet_lock: @@ -92,10 +162,26 @@ def get_init_payload(sim: PandaApp) -> dict: vis_local_pos = list(vis_pos_com) vis_local_ori = list(vis_ori_com) - import os - if not web_obj and vd[4]: - mesh_path = vd[4].decode('utf-8') - web_obj = os.path.basename(mesh_path) + import os + if not web_obj and vd[4]: + mesh_path = vd[4].decode('utf-8') + web_obj = os.path.basename(mesh_path) + if not folder: + folder = os.path.basename(os.path.dirname(mesh_path)) + candidate_mtls = [ + mesh_path + ".mtl", + os.path.splitext(mesh_path)[0] + ".mtl", + ] + matching_mtl = next( + ( + candidate + for candidate in candidate_mtls + if os.path.isfile(candidate) + ), + None, + ) + if not web_mtl and matching_mtl: + web_mtl = os.path.basename(matching_mtl) objects_info[name] = { "class": cls, @@ -273,26 +359,30 @@ def compute_and_format_score(sim: PandaApp, plan: list, executed_successfully: b return score, md def run_pipeline_threadsafe( - websocket: WebSocket, user_prompt: str, loop, use_mock: bool, + runtime: WebRuntime, + cancellation_token, + generation: int, + task_id: str, camera_state: Optional[dict] = None, - conversation_manager: Optional[ConversationManager] = None, ): """Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor.""" global current_sim, pipeline_executing - pipeline_executing = True + pipeline_executing = True + current_sim.pipeline.set_cancellation_token(cancellation_token) + + def publish(payload: dict, journal: bool = True): + payload = {**payload, "task_id": task_id, "generation": generation} + runtime.publish_threadsafe(payload, loop, journal=journal) def log(message: str, step: Optional[int] = None): try: print(f"[WS Log] {message}", flush=True) except Exception: pass - asyncio.run_coroutine_threadsafe( - websocket.send_json({"type": "log", "message": message, "step": step}), - loop - ) + publish({"type": "log", "message": message, "step": step}) # Step 1: Planning log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...") @@ -312,10 +402,13 @@ def run_pipeline_threadsafe( with pybullet_lock: current_sim.pipeline.agent = LLMAgent( planner=planner, - conversation_manager=conversation_manager, + conversation_manager=runtime.conversation_manager, ) - MAX_REPLANS = current_sim.pipeline.MAX_REPLANS + try: + MAX_REPLANS = max(0, int(os.environ.get("MAX_REPLANS", "3"))) + except ValueError: + MAX_REPLANS = 3 last_failed_sig = None last_failed_state_sig = None resolved_goal = None @@ -325,8 +418,9 @@ def run_pipeline_threadsafe( last_stream_time = [0.0] throttle_interval = 0.033 - def wrapped_step(): - original_step() + def wrapped_step(): + cancellation_token.checkpoint() + original_step() if not current_sim.gui: time.sleep(0.001) curr_time = time.time() @@ -334,13 +428,13 @@ def run_pipeline_threadsafe( last_stream_time[0] = curr_time state_payload = get_simulation_state_payload(current_sim) if state_payload: - asyncio.run_coroutine_threadsafe( - websocket.send_json(state_payload), - loop - ) + publish(state_payload, journal=False) - for attempt in range(MAX_REPLANS + 1): - if attempt > 0: + for attempt in range(MAX_REPLANS + 1): + cancellation_token.checkpoint() + if attempt > 0: + runtime.set_status("replanning", generation=generation) + publish({"type": "execution_status", "state": "replanning"}) log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}") log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...") @@ -368,31 +462,30 @@ def run_pipeline_threadsafe( } state_sig = json.dumps(state_sig_dict, sort_keys=True) - try: - with pybullet_lock: - llm_start_time = time.time() - planning_command = ( + try: + with pybullet_lock: + llm_start_time = time.time() + planning_instruction = ( resolved_goal.canonical_instruction if attempt > 0 and resolved_goal is not None else user_prompt ) current_sim.pipeline.agent.last_outcome = None plan_kwargs = { - "previous_failed_reasons": last_failed_sig + "previous_failed_reasons": last_failed_sig, } if attempt > 0: plan_kwargs["resolve_goal"] = False plan = current_sim.pipeline.agent.plan( - planning_command, + planning_instruction, state_text, **plan_kwargs, ) - outcome = getattr( - current_sim.pipeline.agent, "last_outcome", None - ) + outcome = current_sim.pipeline.agent.last_outcome if attempt == 0 and outcome is not None: resolved_goal = outcome.resolved_goal llm_time = time.time() - llm_start_time + cancellation_token.checkpoint() # Summarize plan targets = [] @@ -440,28 +533,22 @@ def run_pipeline_threadsafe( "args": args }) - asyncio.run_coroutine_threadsafe( - websocket.send_json({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time}), - loop - ) + publish({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time}) if plan and plan[0].get("function") in ("clarify", "reject"): log(f"Robot phản hồi: {summary_msg}") header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối" score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n" - asyncio.run_coroutine_threadsafe( - websocket.send_json({ - "type": "result", - "response_type": plan[0].get("function"), - "score_display": score_md, - "score_value": 0, - "success": False - }), - loop - ) + publish({ + "type": "result", + "response_type": plan[0].get("function"), + "score_display": score_md, + "score_value": 0, + "success": False, + }) state_payload = get_simulation_state_payload(current_sim) if state_payload: - asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + publish(state_payload, journal=False) pipeline_executing = False return @@ -469,17 +556,14 @@ def run_pipeline_threadsafe( log("⚠️ [1] Kế hoạch rỗng.") log("⏳ [5/5] Đang tính toán điểm sắp xếp...") score_val, score_md = compute_and_format_score(current_sim, [], True) - asyncio.run_coroutine_threadsafe( - websocket.send_json({ - "type": "result", - "score_display": score_md, - "score_value": score_val - }), - loop - ) + publish({ + "type": "result", + "score_display": score_md, + "score_value": score_val, + }) state_payload = get_simulation_state_payload(current_sim) if state_payload: - asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + publish(state_payload, journal=False) pipeline_executing = False return @@ -499,8 +583,10 @@ def run_pipeline_threadsafe( pipeline_executing = False return - # Step 3: PyBullet Execution (Live!) - log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...") + # Step 3: PyBullet Execution (Live!) + log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...") + runtime.set_status("executing", generation=generation) + publish({"type": "execution_status", "state": "executing"}) with pybullet_lock: pb.stepSimulation = wrapped_step @@ -514,7 +600,7 @@ def run_pipeline_threadsafe( # Trigger an initial simulation state transmission state_payload = get_simulation_state_payload(current_sim) if state_payload: - asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + publish(state_payload, journal=False) def format_skill_vn(step_data): fn = step_data.get("function", "") @@ -540,9 +626,12 @@ def run_pipeline_threadsafe( if fn == "close_gripper": return "Đóng tay kẹp" return f"{fn}" - expected_location = None - for i, step in enumerate(plan, 1): - friendly_text = format_skill_vn(step) + expected_location = None + for i, step in enumerate(plan, 1): + cancellation_token.checkpoint() + runtime.set_status("executing", generation=generation, current_step=i) + publish({"type": "current_step", "step": i}) + friendly_text = format_skill_vn(step) # Make the first letter lowercase for natural sentence integration if friendly_text: friendly_text = friendly_text[0].lower() + friendly_text[1:] @@ -577,7 +666,11 @@ def run_pipeline_threadsafe( log("✅ [3] Tôi đã hoàn tất các bước.") else: log(f"❌ [3] Thực thi lỗi tại bước {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}") - except Exception as e: + except ExecutionInterrupted: + with pybullet_lock: + current_sim.pipeline.interrupt_hold() + raise + except Exception as e: log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}") executed_successfully = False step_failure_reason = str(e) @@ -588,7 +681,7 @@ def run_pipeline_threadsafe( # Send a final state to ensure visual sync state_payload = get_simulation_state_payload(current_sim) if state_payload: - asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop) + publish(state_payload, journal=False) # Now check overall goal using execution monitor goal_completed = False @@ -641,23 +734,107 @@ def run_pipeline_threadsafe( is_success = executed_successfully and goal_completed and score_val >= 50 - asyncio.run_coroutine_threadsafe( - websocket.send_json({ - "type": "result", - "score_display": score_md, - "score_value": score_val, - "error_cause": error_cause, - "success": is_success - }), - loop - ) - pipeline_executing = False -@app.websocket("/ws") + publish({ + "type": "result", + "score_display": score_md, + "score_value": score_val, + "error_cause": error_cause, + "success": is_success, + }) + current_sim.pipeline.set_cancellation_token(None) + pipeline_executing = False + + +async def command_worker_loop(loop): + """Serialize robot commands while allowing the newest prompt to interrupt.""" + global command_worker_task, pipeline_executing + try: + while True: + command = web_runtime.take_pending() + if command is None: + return + generation = command["generation"] + task_id = command["task_id"] + interrupted = False + await web_runtime.publish({ + "type": "command_accepted", + "prompt": command["prompt"], + "task_id": task_id, + "generation": generation, + }) + await web_runtime.publish({ + "type": "execution_status", + "state": "planning", + "task_id": task_id, + "generation": generation, + }) + try: + await asyncio.to_thread( + run_pipeline_threadsafe, + command["prompt"], + loop, + command["use_mock"], + web_runtime, + command["token"], + generation, + task_id, + ) + except ExecutionInterrupted as exc: + interrupted = True + pipeline_executing = False + with pybullet_lock: + if current_sim is not None and current_sim.pipeline is not None: + current_sim.pipeline.interrupt_hold() + web_runtime.set_status("interrupted", generation=generation) + await web_runtime.publish({ + "type": "interrupted", + "reason": str(exc), + "task_id": task_id, + "generation": generation, + }) + state_payload = await asyncio.to_thread( + get_simulation_state_payload, + current_sim, + ) + if state_payload: + await web_runtime.publish(state_payload, journal=False) + except Exception as exc: + pipeline_executing = False + await web_runtime.publish({ + "type": "result", + "success": False, + "error_cause": "runtime", + "score_display": f"### Lỗi thực thi\n\n{exc}", + "task_id": task_id, + "generation": generation, + }) + finally: + if current_sim is not None and current_sim.pipeline is not None: + current_sim.pipeline.set_cancellation_token(None) + web_runtime.complete( + generation, + state="interrupted" if interrupted else "completed", + ) + finally: + command_worker_task = None + if web_runtime.has_pending: + command_worker_task = asyncio.create_task(command_worker_loop(loop)) + + +async def wait_for_active_task_stop(timeout=5.0): + web_runtime.cancel_all("runtime_mutation") + deadline = time.monotonic() + timeout + while web_runtime.active_token is not None and time.monotonic() < deadline: + await asyncio.sleep(0.02) + return web_runtime.active_token is None + + +@app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): - global current_sim + global current_sim, command_worker_task, physics_settle_task await websocket.accept() - loop = asyncio.get_running_loop() - conversation_manager = ConversationManager() + await web_runtime.subscribe(websocket) + loop = asyncio.get_running_loop() # Retrieve user's desktop display preference from client query params client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true" @@ -665,16 +842,15 @@ async def websocket_endpoint(websocket: WebSocket): # Force gui = False to run PyBullet completely headless (DIRECT mode) gui = False - camera_state = { + camera_state = { "target": [0.5, 0.0, 0.3], "dist": 1.3, "yaw": 45.0, - "pitch": -35.0 - } - - settle_task = None + "pitch": -35.0 + } + drag_state = {"constraint_id": None, "active": False} - async def physics_settle_loop(): + async def physics_settle_loop(): try: while True: global pipeline_executing @@ -698,9 +874,9 @@ async def websocket_endpoint(websocket: WebSocket): pb.stepSimulation(physicsClientId=current_sim.client) await asyncio.to_thread(step) - state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) - if state_payload: - await websocket.send_json(state_payload) + state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) + if state_payload: + await web_runtime.publish(state_payload, journal=False) await asyncio.sleep(1/30.0) except asyncio.CancelledError: pass @@ -733,90 +909,165 @@ async def websocket_endpoint(websocket: WebSocket): except Exception: is_connected = False - if is_connected: - current_sim.reset_objects(seed=0) - current_sim.controller.reset_to_home() - for _ in range(5): - pb.stepSimulation(physicsClientId=current_sim.client) + # Reconnect/reload deliberately keeps the live PyBullet state. await asyncio.to_thread(init_sim) # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui) # Send environment list try: - env_files = [f for f in os.listdir(os.path.join(PROJECT_SRC, "envs")) if f.endswith('.json')] - await websocket.send_json({"type": "env_list", "envs": env_files}) + env_files = _list_environment_files( + os.path.join(PROJECT_SRC, "envs") + ) + await websocket.send_json({"type": "env_list", "envs": env_files}) # Send initial static scene data (only needs to be sent once) - init_payload = await asyncio.to_thread(get_init_payload, current_sim) - await websocket.send_json(init_payload) + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + web_runtime.latest_init = init_payload + await websocket.send_json(init_payload) # Send the first simulation state to sync objects and joints state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) - if state_payload: - await websocket.send_json(state_payload) - - settle_task = asyncio.create_task(physics_settle_loop()) + if state_payload: + web_runtime.latest_state = state_payload + await websocket.send_json(state_payload) + await websocket.send_json(web_runtime.snapshot()) + + if physics_settle_task is None or physics_settle_task.done(): + physics_settle_task = asyncio.create_task(physics_settle_loop()) - drag_state = {"constraint_id": None} - while True: + while True: data = await websocket.receive_text() payload = json.loads(data) p_type = payload.get("type") - if p_type == "run": - prompt = payload.get("prompt", "") - use_mock = payload.get("mock", False) - asyncio.create_task( - asyncio.to_thread( - run_pipeline_threadsafe, - websocket, - prompt, - loop, - use_mock, - conversation_manager=conversation_manager, - ) - ) + if p_type == "run": + prompt = payload.get("prompt", "") + use_mock = payload.get("mock", False) + if prompt.strip(): + command = web_runtime.submit(prompt.strip(), use_mock) + await web_runtime.publish({ + "type": "interrupt_requested", + "generation": command["generation"], + "task_id": command["task_id"], + }) + if command_worker_task is None or command_worker_task.done(): + command_worker_task = asyncio.create_task( + command_worker_loop(loop) + ) + + elif p_type == "cancel": + if web_runtime.cancel_all("user_cancelled"): + await web_runtime.publish({ + "type": "interrupt_requested", + "generation": web_runtime.active_generation, + }) - elif p_type == "mouse_pick_start": - rayFrom = payload.get("rayFrom") - rayTo = payload.get("rayTo") - if rayFrom and rayTo: - async with executor_lock: - def do_pick(): - with pybullet_lock: - hit = pb.rayTest(rayFrom, rayTo, physicsClientId=current_sim.client)[0] - obj_uid = hit[0] - link_index = hit[1] - hit_pos = hit[3] - if obj_uid >= 0: - mass = pb.getDynamicsInfo(obj_uid, link_index, physicsClientId=current_sim.client)[0] - is_robot = (obj_uid == current_sim.controller.robot_id) - if mass > 0 or is_robot: - if link_index >= 0: - pos, ori = pb.getLinkState(obj_uid, link_index, physicsClientId=current_sim.client)[4:6] - else: - pos, ori = pb.getBasePositionAndOrientation(obj_uid, physicsClientId=current_sim.client) - inv_pos, inv_ori = pb.invertTransform(pos, ori) - local_pivot, _ = pb.multiplyTransforms(inv_pos, inv_ori, hit_pos, [0,0,0,1]) - drag_state["constraint_id"] = pb.createConstraint( - parentBodyUniqueId=obj_uid, - parentLinkIndex=link_index, - childBodyUniqueId=-1, - childLinkIndex=-1, - jointType=pb.JOINT_POINT2POINT, - jointAxis=[0,0,0], - parentFramePosition=local_pivot, - childFramePosition=hit_pos, - physicsClientId=current_sim.client - ) - pb.changeConstraint(drag_state["constraint_id"], maxForce=500, physicsClientId=current_sim.client) - await asyncio.to_thread(do_pick) - - drag_state["active"] = True - if drag_state.get("task") is None or drag_state["task"].done(): - async def drag_loop(): - while drag_state.get("active") and drag_state.get("constraint_id") is not None: + elif p_type == "mouse_pick_start": + if web_runtime.active_token is not None: + if not await wait_for_active_task_stop(): + await websocket.send_json({ + "type": "drag_rejected", + "reason": "Robot chưa dừng an toàn.", + }) + continue + rayFrom = payload.get("rayFrom") + rayTo = payload.get("rayTo") + requested_type = payload.get("target_type") + requested_name = payload.get("object_id") + if _finite_vec3(rayFrom) and _finite_vec3(rayTo): + async with executor_lock: + def do_pick(): + with pybullet_lock: + if drag_state.get("constraint_id") is not None: + pb.removeConstraint( + drag_state["constraint_id"], + physicsClientId=current_sim.client, + ) + hit = pb.rayTest( + rayFrom, + rayTo, + physicsClientId=current_sim.client, + )[0] + hit_uid, link_index, hit_pos = hit[0], hit[1], hit[3] + drag_id = uuid.uuid4().hex + + if requested_type == "robot_ee": + if hit_uid != current_sim.controller.robot_id: + return None + drag_state.update({ + "drag_id": drag_id, + "target_type": "robot_ee", + "object_name": None, + "constraint_id": None, + "active": True, + }) + return dict(drag_state) + + object_id = current_sim.scene.name_to_id( + requested_name + ) + if object_id is None: + return None + mass = pb.getDynamicsInfo( + object_id, + -1, + physicsClientId=current_sim.client, + )[0] + if mass <= 0: + return None + pos, _ = pb.getBasePositionAndOrientation( + object_id, + physicsClientId=current_sim.client, + ) + constraint_id = pb.createConstraint( + parentBodyUniqueId=object_id, + parentLinkIndex=-1, + childBodyUniqueId=-1, + childLinkIndex=-1, + jointType=pb.JOINT_POINT2POINT, + jointAxis=[0, 0, 0], + parentFramePosition=[0, 0, 0], + childFramePosition=pos, + physicsClientId=current_sim.client, + ) + pb.changeConstraint( + constraint_id, + maxForce=500, + physicsClientId=current_sim.client, + ) + drag_state.update({ + "drag_id": drag_id, + "target_type": "object", + "object_name": requested_name, + "constraint_id": constraint_id, + "active": True, + }) + return dict(drag_state) + started = await asyncio.to_thread(do_pick) + + if not started: + await websocket.send_json({ + "type": "drag_rejected", + "reason": "Vật được chọn trên web không khớp scene vật lý.", + }) + continue + await websocket.send_json({ + "type": "drag_started", + "drag_id": started["drag_id"], + "target_type": started["target_type"], + "object_id": started.get("object_name"), + }) + + if ( + started["target_type"] == "object" + and ( + drag_state.get("task") is None + or drag_state["task"].done() + ) + ): + async def drag_loop(): + while drag_state.get("active") and drag_state.get("constraint_id") is not None: async with executor_lock: def step(): with pybullet_lock: @@ -826,67 +1077,263 @@ async def websocket_endpoint(websocket: WebSocket): state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: try: - await websocket.send_json(state_payload) + await web_runtime.publish(state_payload, journal=False) except Exception: break await asyncio.sleep(1/60.0) drag_state["task"] = asyncio.create_task(drag_loop()) - elif p_type == "mouse_pick_update": - targetPos = payload.get("targetPos") - if targetPos: - async with executor_lock: - def do_update(): - with pybullet_lock: - if drag_state.get("constraint_id") is not None: - pb.changeConstraint(drag_state["constraint_id"], targetPos, maxForce=500, physicsClientId=current_sim.client) - await asyncio.to_thread(do_update) - - elif p_type == "mouse_pick_end": - drag_state["active"] = False - async with executor_lock: - def do_end(): - with pybullet_lock: + elif p_type == "mouse_pick_update": + targetPos = payload.get("targetPos") + drag_id = payload.get("drag_id") + if ( + drag_id + and drag_id == drag_state.get("drag_id") + and _finite_vec3(targetPos) + ): + target_pos = _clamp_manual_target( + targetPos, + drag_state.get("target_type", "object"), + ) + async with executor_lock: + def do_update(): + with pybullet_lock: + if drag_state.get("target_type") == "robot_ee": + link_state = pb.getLinkState( + current_sim.controller.robot_id, + current_sim.controller.ee_index, + physicsClientId=current_sim.client, + ) + solution = pb.calculateInverseKinematics( + current_sim.controller.robot_id, + current_sim.controller.ee_index, + target_pos, + link_state[1], + lowerLimits=current_sim.controller._lower_limits, + upperLimits=current_sim.controller._upper_limits, + jointRanges=current_sim.controller._joint_ranges, + restPoses=current_sim.controller._rest_poses, + maxNumIterations=200, + residualThreshold=1e-5, + physicsClientId=current_sim.client, + ) + for idx, q in enumerate(solution[:7]): + pb.resetJointState( + current_sim.controller.robot_id, + idx, + q, + physicsClientId=current_sim.client, + ) + elif drag_state.get("constraint_id") is not None: + pb.changeConstraint( + drag_state["constraint_id"], + target_pos, + maxForce=500, + physicsClientId=current_sim.client, + ) + await asyncio.to_thread(do_update) + state_payload = await asyncio.to_thread( + get_simulation_state_payload, + current_sim, + ) + if state_payload: + await web_runtime.publish(state_payload, journal=False) + + elif p_type == "mouse_pick_end": + drag_id = payload.get("drag_id") + if drag_id != drag_state.get("drag_id"): + continue + drag_state["active"] = False + async with executor_lock: + def do_end(): + with pybullet_lock: if drag_state.get("constraint_id") is not None: - pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client) - drag_state["constraint_id"] = None - await asyncio.to_thread(do_end) + pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client) + drag_state["constraint_id"] = None + if drag_state.get("target_type") == "robot_ee": + current_sim.controller.hold_current_pose() + await asyncio.to_thread(do_end) + drag_state["drag_id"] = None + drag_state["target_type"] = None + for _ in range(20): + with pybullet_lock: + pb.stepSimulation(physicsClientId=current_sim.client) + state_payload = await asyncio.to_thread( + get_simulation_state_payload, + current_sim, + ) + if state_payload: + await web_runtime.publish(state_payload, journal=False) + + elif p_type == "spawn_catalog_object": + if web_runtime.active_token is not None: + if not await wait_for_active_task_stop(): + continue + folder = payload.get("folder") + position = payload.get("position") + if not _finite_vec3(position): + continue + spawn_position = _clamp_manual_target(position, "object") + async with executor_lock: + def spawn_object(): + with pybullet_lock: + return current_sim.env_builder.spawn_catalog_object( + folder, + spawn_position, + ) + try: + _, object_name = await asyncio.to_thread(spawn_object) + except (ValueError, OSError) as exc: + await websocket.send_json({ + "type": "spawn_rejected", + "reason": str(exc), + }) + continue + for _ in range(30): + with pybullet_lock: + pb.stepSimulation(physicsClientId=current_sim.client) + init_payload = await asyncio.to_thread( + get_init_payload, + current_sim, + ) + web_runtime.latest_init = init_payload + state_payload = await asyncio.to_thread( + get_simulation_state_payload, + current_sim, + ) + await web_runtime.publish({ + "type": "object_added", + "name": object_name, + "config": init_payload["objects"][object_name], + "state": ( + state_payload.get("objects", {}).get(object_name) + if state_payload + else None + ), + }, journal=False) + if state_payload: + await web_runtime.publish(state_payload, journal=False) + await web_runtime.publish({ + "type": "log", + "message": f"Đã thêm '{object_name}' vào môi trường.", + }) + + elif p_type == "delete_object": + if web_runtime.active_token is not None: + if not await wait_for_active_task_stop(): + continue + object_name = payload.get("name") + async with executor_lock: + def delete_object(): + with pybullet_lock: + object_id = current_sim.scene.name_to_id( + object_name + ) + if object_id is None: + return False + if current_sim.pipeline._carried == object_id: + return False + pb.removeBody( + object_id, + physicsClientId=current_sim.client, + ) + current_sim.scene.unregister_object(object_id) + return True + deleted = await asyncio.to_thread(delete_object) + if not deleted: + await websocket.send_json({ + "type": "delete_rejected", + "reason": "Không thể xóa vật đang được giữ hoặc không tồn tại.", + }) + continue + await web_runtime.publish({ + "type": "object_removed", + "name": object_name, + }, journal=False) + state_payload = await asyncio.to_thread( + get_simulation_state_payload, + current_sim, + ) + if state_payload: + await web_runtime.publish(state_payload, journal=False) + await web_runtime.publish({ + "type": "log", + "message": f"Đã xóa '{object_name}' khỏi môi trường.", + }) elif p_type == "reset": - conversation_manager.clear() + if not await wait_for_active_task_stop(): + await web_runtime.publish({ + "type": "log", + "message": "Không thể reset khi robot chưa dừng an toàn.", + }) + continue async with executor_lock: def reset_sim(): with pybullet_lock: current_sim.reset_objects(seed=0) current_sim.controller.reset_to_home() - await asyncio.to_thread(reset_sim) + await asyncio.to_thread(reset_sim) + web_runtime.conversation_manager.clear() + web_runtime.clear_task_history() state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: - await websocket.send_json(state_payload) - await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) + await web_runtime.publish(state_payload, journal=False) + await web_runtime.publish({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."}) elif p_type == "change_env": - conversation_manager.clear() + if not await wait_for_active_task_stop(): + await web_runtime.publish({ + "type": "log", + "message": "Không thể đổi môi trường khi robot chưa dừng an toàn.", + }) + continue env_file = payload.get("env") - env_path = os.path.join(PROJECT_SRC, "envs", env_file) - async with executor_lock: + if ( + not isinstance(env_file, str) + or os.path.basename(env_file) != env_file + ): + await websocket.send_json({ + "type": "environment_rejected", + "reason": "Tên environment không hợp lệ.", + }) + continue + env_path = os.path.join(PROJECT_SRC, "envs", env_file) + try: + _load_environment_config(env_path) + except ( + OSError, + ValueError, + json.JSONDecodeError, + ) as exc: + await websocket.send_json({ + "type": "environment_rejected", + "reason": str(exc), + }) + continue + async with executor_lock: def change_sim_env(): with pybullet_lock: current_sim.change_environment(env_path) - await asyncio.to_thread(change_sim_env) + await asyncio.to_thread(change_sim_env) + web_runtime.conversation_manager.clear() + web_runtime.clear_task_history() # Send the new static data - init_payload = await asyncio.to_thread(get_init_payload, current_sim) - await websocket.send_json(init_payload) + init_payload = await asyncio.to_thread(get_init_payload, current_sim) + web_runtime.latest_init = init_payload + await web_runtime.publish(init_payload, journal=False) # Send the new dynamic state state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: - await websocket.send_json(state_payload) - await websocket.send_json({"type": "log", "message": f"🌍 Đã chuyển sang môi trường {env_file}."}) + await web_runtime.publish(state_payload, journal=False) + await web_runtime.publish({"type": "log", "message": f"🌍 Đã chuyển sang môi trường {env_file}."}) - elif p_type == "update_object_pose": + elif p_type == "update_object_pose": + if web_runtime.active_token is not None: + continue name = payload.get("name") pos = payload.get("pos") ori = payload.get("ori") @@ -900,9 +1347,11 @@ async def websocket_endpoint(websocket: WebSocket): state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: - await websocket.send_json(state_payload) + await web_runtime.publish(state_payload, journal=False) - elif p_type == "update_joints": + elif p_type == "update_joints": + if web_runtime.active_token is not None: + continue joints_data = payload.get("joints") async with executor_lock: def move_joints(): @@ -916,8 +1365,10 @@ async def websocket_endpoint(websocket: WebSocket): state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: - await websocket.send_json(state_payload) - elif p_type == "update_robot_ee": + await web_runtime.publish(state_payload, journal=False) + elif p_type == "update_robot_ee": + if web_runtime.active_token is not None: + continue pos = payload.get("pos") async with executor_lock: def move_robot_ee(): @@ -954,7 +1405,7 @@ async def websocket_endpoint(websocket: WebSocket): state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim) if state_payload: - await websocket.send_json(state_payload) + await web_runtime.publish(state_payload, journal=False) elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"): pass @@ -963,9 +1414,18 @@ async def websocket_endpoint(websocket: WebSocket): except Exception as e: print(f"WS Exception: {e}") finally: - conversation_manager.clear() - if settle_task: - settle_task.cancel() + drag_state["active"] = False + if drag_state.get("constraint_id") is not None: + try: + with pybullet_lock: + pb.removeConstraint( + drag_state["constraint_id"], + physicsClientId=current_sim.client, + ) + except Exception: + pass + drag_state["constraint_id"] = None + await web_runtime.unsubscribe(websocket) if __name__ == "__main__": port = int(os.environ.get("PORT", 8000)) uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False) diff --git a/frontend/web_runtime.py b/frontend/web_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..308aadf3cca0119f4b725207d175052cdef33c54 --- /dev/null +++ b/frontend/web_runtime.py @@ -0,0 +1,225 @@ +"""Server-owned web runtime surviving browser reconnects. + +The PyBullet world remains the source of truth. This object persists only +session/UI metadata, conversation state, task lifecycle, and a bounded event +journal so a reloaded page can catch up without resetting the simulation. +""" + +from __future__ import annotations + +import asyncio +from collections import deque +import threading +import time +import uuid + +from llm_panda.conversation import ConversationManager +from llm_panda.execution.cancellation import CancellationToken + + +class WebRuntime: + def __init__(self, max_events: int = 750): + self.runtime_id = uuid.uuid4().hex + self.conversation_manager = ConversationManager( + session_id=self.runtime_id + ) + self._lock = threading.RLock() + self._subscribers = set() + self._events = deque(maxlen=max_events) + self._seq = 0 + self._generation = 0 + self._active = None + self._pending = None + self.execution_state = "idle" + self.latest_plan = None + self.latest_result = None + self.latest_state = None + self.latest_init = None + self.current_step = None + + async def subscribe(self, websocket): + with self._lock: + self._subscribers.add(websocket) + + async def unsubscribe(self, websocket): + with self._lock: + self._subscribers.discard(websocket) + + def submit(self, prompt: str, use_mock: bool = False): + with self._lock: + self._generation += 1 + command = { + "task_id": uuid.uuid4().hex, + "generation": self._generation, + "prompt": prompt, + "use_mock": bool(use_mock), + "created_at": time.time(), + } + if self._active is not None: + self._active["token"].request("superseded_by_new_command") + self.execution_state = "interrupt_requested" + else: + self.execution_state = "planning" + # Latest-wins for commands not yet started. + self._pending = command + return dict(command) + + def take_pending(self): + with self._lock: + command = self._pending + self._pending = None + if command is None: + return None + token = CancellationToken() + command = {**command, "token": token} + self._active = command + self.execution_state = "planning" + self.current_step = None + self.latest_result = None + return command + + def request_interrupt(self, reason="user_cancelled"): + with self._lock: + if self._active is None: + return False + self._active["token"].request(reason) + self.execution_state = "interrupt_requested" + return True + + def cancel_all(self, reason="user_cancelled"): + """Cancel active work and discard commands that have not started.""" + with self._lock: + self._pending = None + if self._active is None: + self.execution_state = "idle" + return False + self._active["token"].request(reason) + self.execution_state = "interrupt_requested" + return True + + def set_status(self, state, generation=None, current_step=None): + with self._lock: + if ( + generation is not None + and self._active is not None + and generation != self._active["generation"] + ): + return False + self.execution_state = state + self.current_step = current_step + return True + + def complete(self, generation, state="completed"): + with self._lock: + if ( + self._active is None + or generation != self._active["generation"] + ): + return False + self._active = None + self.execution_state = ( + "planning" if self._pending is not None else state + ) + self.current_step = None + return True + + @property + def active_token(self): + with self._lock: + return self._active["token"] if self._active else None + + @property + def active_generation(self): + with self._lock: + return self._active["generation"] if self._active else None + + @property + def has_pending(self): + with self._lock: + return self._pending is not None + + def _prepare_event(self, payload, journal=True): + event = dict(payload) + with self._lock: + event_generation = event.get("generation") + is_current = ( + event_generation is None + or event_generation >= self._generation + ) + if event.get("type") == "state": + self.latest_state = event + elif event.get("type") == "plan" and is_current: + self.latest_plan = event + elif event.get("type") == "result" and is_current: + self.latest_result = event + if journal: + self._seq += 1 + event["seq"] = self._seq + self._events.append(event) + return event + + async def publish(self, payload, journal=True): + event = self._prepare_event(payload, journal=journal) + with self._lock: + subscribers = list(self._subscribers) + stale = [] + for websocket in subscribers: + try: + await websocket.send_json(event) + except Exception: + stale.append(websocket) + if stale: + with self._lock: + for websocket in stale: + self._subscribers.discard(websocket) + return event + + def publish_threadsafe(self, payload, loop, journal=True): + return asyncio.run_coroutine_threadsafe( + self.publish(payload, journal=journal), + loop, + ) + + def events_after(self, seq): + with self._lock: + return [ + dict(event) + for event in self._events + if event.get("seq", 0) > int(seq or 0) + ] + + def clear_task_history(self): + """Clear UI/task history after an explicit reset, preserving sequence.""" + with self._lock: + self._events.clear() + self.latest_plan = None + self.latest_result = None + self.current_step = None + self.execution_state = "idle" + + def snapshot(self): + with self._lock: + pending = self.conversation_manager.pending + return { + "type": "runtime_snapshot", + "runtime_id": self.runtime_id, + "execution_state": self.execution_state, + "active_task_id": ( + self._active["task_id"] if self._active else None + ), + "active_prompt": ( + self._active["prompt"] if self._active else None + ), + "generation": ( + self._active["generation"] + if self._active + else self._generation + ), + "current_step": self.current_step, + "plan": self.latest_plan, + "result": self.latest_result, + "state": self.latest_state, + "events": [dict(event) for event in self._events], + "last_event_seq": self._seq, + "conversation_pending": pending is not None, + } diff --git a/llm_panda/__pycache__/config.cpython-310.pyc b/llm_panda/__pycache__/config.cpython-310.pyc index 1df04c6e98501b824e37b42212492e865f26d9f7..e634a203e501e08757835ef8f7eb9d80aa6380f8 100644 Binary files a/llm_panda/__pycache__/config.cpython-310.pyc and b/llm_panda/__pycache__/config.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/llm_agent.cpython-310.pyc b/llm_panda/__pycache__/llm_agent.cpython-310.pyc index a19d5a1f756ccd800e24a2293f49c069ce052ac1..63ce6c6b515048962095d4fbde1aea421b915a18 100644 Binary files a/llm_panda/__pycache__/llm_agent.cpython-310.pyc and b/llm_panda/__pycache__/llm_agent.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/robot_controller.cpython-310.pyc b/llm_panda/__pycache__/robot_controller.cpython-310.pyc index 5ac68ac07e80ab9ca8257637f5a842ee41d9d4e0..2807f3206cb1471f219ce552df946a8a44b924ba 100644 Binary files a/llm_panda/__pycache__/robot_controller.cpython-310.pyc and b/llm_panda/__pycache__/robot_controller.cpython-310.pyc differ diff --git a/llm_panda/__pycache__/scene_manager.cpython-310.pyc b/llm_panda/__pycache__/scene_manager.cpython-310.pyc index 5a9c46547c18b0f960c8154a906698618c73ac35..7cb485b4232de1374afa69531da68b16acf2e4cb 100644 Binary files a/llm_panda/__pycache__/scene_manager.cpython-310.pyc and b/llm_panda/__pycache__/scene_manager.cpython-310.pyc differ diff --git a/llm_panda/conversation/manager.py b/llm_panda/conversation/manager.py index 7b47d8f89388af8ed5ec73d90e2e897707472c6d..1abe3e0d7b87246759c7d0336bfa6f791ac61493 100644 --- a/llm_panda/conversation/manager.py +++ b/llm_panda/conversation/manager.py @@ -119,7 +119,12 @@ class ConversationManager: self._pending = None return True - def contextualize(self, user_command: str, scene_state=None) -> str: + def contextualize( + self, + user_command: str, + scene_state=None, + use_lexical_boundary: bool = True, + ) -> str: """Return the effective instruction for the planner. A normal one-shot command is returned byte-for-byte. Only a reply made @@ -131,7 +136,7 @@ class ConversationManager: if self._pending is None: return command - if self._looks_like_new_command(command): + if use_lexical_boundary and self._looks_like_new_command(command): self._pending = None return command @@ -251,6 +256,11 @@ class ConversationManager: self._pending = None self._turns.clear() + def clear_pending(self) -> None: + """Close only the unresolved request while preserving bounded history.""" + with self._lock: + self._pending = None + def _expire_pending_locked(self, now: Optional[float] = None) -> None: if self._pending is None: return diff --git a/llm_panda/conversation/models.py b/llm_panda/conversation/models.py index dbcaa1cf5f0761f41cc99218f433f7335f678e17..5fc573ee208bacdf892330101acfbbbe1c6ce038 100644 --- a/llm_panda/conversation/models.py +++ b/llm_panda/conversation/models.py @@ -36,6 +36,8 @@ class GoalPredicate: location_id: Optional[str] = None relation: Optional[str] = None relative_to: Optional[str] = None + target_position: Optional[tuple[float, float]] = None + tolerance: Optional[float] = None @dataclass(frozen=True) diff --git a/llm_panda/core/env_builder.py b/llm_panda/core/env_builder.py index b93598513e04766a44919d299c974a8e43fb8aa6..3e3fdbd04bfffd5a76e2c5412936019493c79f82 100644 --- a/llm_panda/core/env_builder.py +++ b/llm_panda/core/env_builder.py @@ -1,6 +1,7 @@ import json import os import random +import re import pybullet as pb from pybullet_object_models import ycb_objects @@ -45,6 +46,38 @@ class EnvBuilder: def load_configs(self): with open(self.env_json_path, 'r', encoding='utf-8') as f: self.env_data = json.load(f) + + catalog_ref = self.env_data.get("semantic_catalog") + catalog = {} + catalog_path = None + if catalog_ref: + catalog_path = catalog_ref + if not os.path.isabs(catalog_path): + catalog_path = os.path.join( + os.path.dirname(os.path.abspath(self.env_json_path)), + catalog_path, + ) + with open(catalog_path, "r", encoding="utf-8") as f: + catalog = json.load(f) + configured_objects = { + obj["name"] for obj in self.env_data.get("objects", []) + } + described_objects = set(catalog.get("objects", {})) + missing_objects = sorted(configured_objects - described_objects) + if missing_objects: + raise ValueError( + "Semantic catalog is missing configured object(s): " + + ", ".join(missing_objects) + ) + missing_surfaces = sorted( + {"table", "tray"} - set(catalog.get("surfaces", {})) + ) + if missing_surfaces: + raise ValueError( + "Semantic catalog is missing surface(s): " + + ", ".join(missing_surfaces) + ) + self.scene.set_semantic_catalog(catalog, source=catalog_path) # Dynamically patch config.py with loaded environment settings # to ensure backward compatibility with pipeline_executor.py and other modules @@ -141,6 +174,49 @@ class EnvBuilder: spawned.append(spawn_pos) body = _load_ycb(ycb_folder, spawn_pos, spawn_ori) self.scene.register_object(body, obj_name, obj_class) + + def spawn_catalog_object(self, folder, position, name=None): + """Spawn and register one YCB catalog item at runtime. + + Runtime objects receive generic, data-driven semantics so they are + immediately visible to scene state and adaptive LLM prompts without + requiring an environment-specific hard-coded object list. + """ + folder_path = os.path.join(_YCB_DATA, folder) + if not ( + isinstance(folder, str) + and folder.startswith("Ycb") + and os.path.isdir(folder_path) + and os.path.isfile(os.path.join(folder_path, "model.urdf")) + ): + raise ValueError(f"Unknown YCB catalog folder: {folder!r}") + + stem = folder[3:] or "object" + base_name = re.sub(r"(? None: + self.reason = reason + self._event.set() + + @property + def requested(self) -> bool: + return self._event.is_set() + + def checkpoint(self) -> None: + if self.requested: + raise ExecutionInterrupted(self.reason or "interrupted") + diff --git a/llm_panda/execution/monitor.py b/llm_panda/execution/monitor.py index 353f1b5eafabb99222810d4de7596ab9bd2636b8..5213c38f929d750da03470e33dbfb98a17887ae7 100644 --- a/llm_panda/execution/monitor.py +++ b/llm_panda/execution/monitor.py @@ -122,6 +122,34 @@ class ExecutionMonitor: f"{predicate.object_id}.location={actual!r}, expected " f"{expected!r}" ) + elif predicate.type == "position_near": + obj = objects.get(predicate.object_id, {}) + actual_position = obj.get("position") + target_position = predicate.target_position + tolerance = predicate.tolerance or 0.04 + same_surface = ( + not predicate.location_id + or obj.get("location") == predicate.location_id + ) + if ( + isinstance(actual_position, (list, tuple)) + and len(actual_position) >= 2 + and target_position + and len(target_position) >= 2 + ): + distance = ( + (actual_position[0] - target_position[0]) ** 2 + + (actual_position[1] - target_position[1]) ** 2 + ) ** 0.5 + ok = distance <= tolerance and same_surface + else: + distance = None + ok = False + detail = ( + f"{predicate.object_id}.position={actual_position!r}, " + f"expected near {target_position!r} " + f"(tolerance={tolerance:.3f}, distance={distance!r})" + ) elif predicate.type == "relation_is": obj = objects.get(predicate.object_id, {}) relations = obj.get("relations", {}) or {} diff --git a/llm_panda/execution/pipeline.py b/llm_panda/execution/pipeline.py index 0c1500a40772f65394e1f6fe9669c24786167d20..624e5e9b1b00048168d68e15fe29456f7b6b7bb2 100644 --- a/llm_panda/execution/pipeline.py +++ b/llm_panda/execution/pipeline.py @@ -68,6 +68,20 @@ class ExecutionPipeline: self._carried = None self._pending_target_pos = None + self._cancellation_token = None + + def set_cancellation_token(self, token): + self._cancellation_token = token + self.controller.set_cancellation_token(token) + + def _checkpoint(self): + if self._cancellation_token is not None: + self._cancellation_token.checkpoint() + + def interrupt_hold(self): + """Freeze the arm at its live pose without releasing a carried object.""" + self.controller.hold_current_pose() + self._pending_target_pos = None @property def _PLACE_FALL_Z(self): @@ -88,6 +102,7 @@ class ExecutionPipeline: return reachability_fn def run_command(self, nl_command, verbose=True): + self._checkpoint() nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command) reachability_fn = self._reachability_fn() last_failed_sig = None @@ -196,6 +211,7 @@ class ExecutionPipeline: expected_location = None n_steps = len(plan) for i, step in enumerate(plan): + self._checkpoint() pre_positions = { oid: pb.getBasePositionAndOrientation(oid)[0] for oid in self.scene.object_ids @@ -351,6 +367,16 @@ class ExecutionPipeline: footprint = (min(footprint[0], 0.115), min(footprint[1], 0.115)) reachable_fn = self._reachable_placement_fn() margins = (config.PLACEMENT_SAFETY_MARGIN, 0.01, 0.0) + preferred_position = args.get("target_position") + if not ( + isinstance(preferred_position, (list, tuple)) + and len(preferred_position) >= 2 + and all( + isinstance(value, (int, float)) + for value in preferred_position[:2] + ) + ): + preferred_position = None if location_id == "buffer": avoid_names = args.get("avoid", []) @@ -376,6 +402,7 @@ class ExecutionPipeline: spots = self.scene.find_free_tray_placements( footprint, exclude_ids=[self._carried], max_results=1, reachable_fn=reachable_fn, margin=m, + preferred_position=preferred_position, ) if spots: if m < config.PLACEMENT_SAFETY_MARGIN: @@ -384,6 +411,7 @@ class ExecutionPipeline: spots = self.scene.find_free_tray_placements( footprint, exclude_ids=[self._carried], max_results=1, reachable_fn=reachable_fn, margin=0.0, best_effort=True, + preferred_position=preferred_position, ) if spots: logger.warning("[WARN ] Tray crowded — using least-overlap spot " @@ -416,6 +444,7 @@ class ExecutionPipeline: footprint, exclude_ids=[self._carried], max_results=1, reachable_fn=reachable_fn, margin=m, relative_to_pos=relative_to_pos, relation=relation, + preferred_position=preferred_position, ) if spots: return spots[0] @@ -423,6 +452,7 @@ class ExecutionPipeline: spots = self.scene.find_free_placements( footprint, exclude_ids=[self._carried], max_results=1, reachable_fn=reachable_fn, margin=m, + preferred_position=preferred_position, ) if spots: if m < config.PLACEMENT_SAFETY_MARGIN: @@ -431,6 +461,7 @@ class ExecutionPipeline: spots = self.scene.find_free_placements( footprint, exclude_ids=[self._carried], max_results=1, reachable_fn=reachable_fn, margin=0.0, best_effort=True, + preferred_position=preferred_position, ) if spots: logger.warning("[WARN ] Table crowded — using least-overlap spot " diff --git a/llm_panda/llm_agent.py b/llm_panda/llm_agent.py index 7882c672a76ca61ff5ee152150cffa33a596af41..592faa2e78d31176fc2f2a7063378b8df6323faa 100644 --- a/llm_panda/llm_agent.py +++ b/llm_panda/llm_agent.py @@ -375,6 +375,17 @@ The instruction has normally passed a Goal Resolution Gate. Plan only the stated canonical goal. Never guess, omit, or emit an empty object_id/location_id. If any critical field is still ambiguous, return one structured clarify step instead of an incomplete physical action. + +User constraints and execution details are different: +- A plain surface destination does not require relation/relative_to. +- If the canonical goal says to relocate an object to an automatically selected + safe spot, choose a collision-free reachable surface using the current scene. + This is an execution decision; never ask the user for an exact temporary spot. +- If the canonical goal says "at the former location of ", emit the + normal move_to for that location's surface. The deterministic intent layer + attaches the original scene coordinate; do not invent coordinates yourself. +- Blocker clearing, temporary parking, route waypoints, and grasp approach are + planner/executor responsibilities unless the user explicitly constrained them. ## DESTINATIONS Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id. @@ -396,13 +407,10 @@ Only two destinations exist: "table" and "tray". You do NOT compute coordinates 6. STACK CLEARING: If you want to pick_up an object that has other objects stacked on top of it (i.e., its "supporting" list in "relations" is not empty), you MUST first clear all those supported objects by picking them up and placing them elsewhere on the table (one by one) before picking the target object. 7. If the instruction is a general command to clear or tidy the table (e.g. "dọn bàn", "dọn dẹp", "dọn dẹp bàn", "clear table", "clear the table", "tidy up the table") and names no specific target object, plan to move ALL objects currently on the table to the tray. Output a sequence of pick_up, move_to(tray), and place_down for each table object. If carried_object is not null, place the carried object in the tray first, then pick up and move the other table objects. -## OBJECT PROPERTIES (FACTS) -- banana: fruit, edible, yellow, light, non-metal. -- pear: fruit, edible, yellow-green, light, non-metal. -- soup_can: canned food, edible (contains soup), metal, heavy. -- chips_can: canned snack, edible (contains chips), metal/cardboard, light. -- tennis_ball: sports ball, non-food, felt/rubber, light, non-metal. -- clamp: metal clamp, tool, non-food, steel/metal, heavy. +## ADAPTIVE ENVIRONMENT FACTS +The authoritative object IDs, aliases, categories, attributes, affordances, and +surface aliases are appended to this prompt from the active environment's semantic +catalog. Never assume an object exists unless it appears in the current scene. ## SEMANTIC CATEGORIZATION & GENERAL SORTING LOGIC When an instruction requests to keep only a specific category of items (e.g. food/edible, metal, toys, colors, etc.) on a target location (e.g. "tray" / "khay") and implicitly or explicitly excludes others: @@ -427,37 +435,10 @@ Analyze if the user's instruction is valid, complete, and physically possible gi 1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended. - Schema: [{"function":"clarify","args":{"message":"","missing_fields":["object_id|destination|relation|relative_to|details"],"partial_intent":{"action":"","object_id":"","destination":""}}}] - Always include `missing_fields` and `partial_intent` for clarify. Omit unknown keys from `partial_intent` instead of inventing values. -- Examples: - - User: "gắp lên" or "di chuyển" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp hoặc di chuyển vật thể nào?","missing_fields":["object_id"],"partial_intent":{"action":"pick_up"}}}] - - User: "đặt vào khay" (when carried_object is null) -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp vật nào để đặt vào khay?","missing_fields":["object_id"],"partial_intent":{"action":"pick_and_place","destination":"tray"}}}] - - User: "di chuyển quả chuối" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi di chuyển quả chuối đến đâu (khay hay bàn)?","missing_fields":["destination"],"partial_intent":{"action":"pick_and_place","object_id":"banana"}}}] - -2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules. -- Schema: [{"function":"reject","args":{"message":""}}] -- Examples: - - User: "gắp quả táo" (no apple/quả táo in the scene) -> [{"function":"reject","args":{"message":"Trong môi trường không có quả táo nào cả, tôi không thể thực hiện được."}}] - - User: "gắp quả bóng tennis" when tennis_ball has "reachable": false -> [{"function":"reject","args":{"message":"Quả bóng tennis hiện đang nằm ngoài tầm với của tôi, tôi không thể gắp nó."}}] - - User: "gắp quả chuối đặt lên đầu robot" -> [{"function":"reject","args":{"message":"Tôi chỉ có thể đặt đồ vật lên bàn hoặc vào khay, không thể đặt lên đầu robot."}}] - - User: "hoán đổi bàn và khay" -> [{"function":"reject","args":{"message":"Tôi chỉ có thể hoán đổi vị trí của các vật thể, không thể hoán đổi vị trí bàn và khay."}}] - - User: "gắp quả chuối" when carried_object is "banana" -> [{"function":"reject","args":{"message":"Tôi đang cầm quả chuối rồi, bạn muốn tôi đặt nó đi đâu không?"}}] - -## SYNONYMS (VIETNAMESE/ENGLISH) -Objects: chuối/trái chuối/banana->banana, súp/canh/hộp súp/lon súp/soup->soup_can, snack/bim bim/khoai tây/hộp bim bim/lon chips/chips->chips_can, bóng/quả bóng/bóng tennis/ball->tennis_ball, lê/quả lê/pear->pear, kẹp/cái kẹp/kìm/clamp->clamp. Locations: khay/khay chứa->tray, bàn/lên bàn/table->table. Verbs: gắp/nhặt/nhấc/cầm/di chuyển->pick_up, đặt/để/thả/bỏ->place_down. - -## EXAMPLES (compact, one line each) -"gắp quả chuối lên" (no destination): [{"function":"pick_up","args":{"object_id":"banana"}}] -"di chuyển lon súp vào khay": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] -carried_object="banana", "để vào khay": [{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] -"gắp lon súp đặt lên bàn": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}] -"đặt lon chips bên cạnh quả chuối": [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table","relation":"next_to","relative_to":"banana"}},{"function":"place_down","args":{}}] -carried_object="banana", "đặt nó bên trái lon súp": [{"function":"move_to","args":{"location_id":"table","relation":"left_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}] -"gắp vật nằm bên trái quả chuối đặt vào khay" (banana relations: left_of=["soup_can"]): [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] -"đặt quả chuối lên trên lon súp": [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"table","relation":"on_top_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}] -"gắp lon súp" (soup_can relations: supporting=["banana"]): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"soup_can"}}] -"gắp vật gần quả chuối nhất" (banana distances: {"soup_can":0.08,"pear":0.15}): [{"function":"pick_up","args":{"object_id":"soup_can"}}] -"gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}] -# Category Sorting Example: Keep only food on the tray (banana is on table; tennis_ball and clamp are on tray): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"tennis_ball"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"clamp"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}] - + +2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules. +- Schema: [{"function":"reject","args":{"message":""}}] + Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text.""" ) @@ -474,23 +455,93 @@ Use the current SCENE and any conversation context embedded in the instruction. Rules: 1. Never guess an object. Generic words such as "quả", "lon", "vật", or "cái đó" are ambiguous whenever multiple scene objects match. -2. If banana and pear exist, "gắp quả lên lon chip" MUST ask which fruit. Preserve - the known on_top_of chips_can relation in partial_intent. +2. If a generic noun or category matches multiple current objects, ask the user + to choose among the matching display names. Preserve every already-known + relation and reference object in partial_intent. 3. A pick-up-only request needs no destination. A pick-and-place request does. 4. Use only object IDs present in SCENE. Never emit an empty identifier. 5. canonical_instruction must fully express the resolved intent with canonical IDs. 6. The planner receives canonical_instruction, so preserve all stated constraints and never add an unstated destination or exclusivity constraint. 7. Ask one concise Vietnamese question and offer scene-valid choices when possible. +8. Slot meanings are strict: + - object_id: the object the robot will pick/manipulate. + - destination: a destination surface ID such as table or tray. + - relation: the requested spatial relation such as on_top_of. + - relative_to: the reference OBJECT ID used by relation. + - purpose: "goal" for a user-visible outcome or "intermediate" for a + planner-selected temporary relocation. + - constraint_sources: an object mapping constrained field names to + "user" or "conversation". Omit fields that are merely planner choices. + Never put a reference object into destination and never replace object_id with + the user's answer when the missing field is relative_to. +9. For every status, partial_intent must contain all known slots using canonical + IDs. Omit unknown slots; never write null, "unknown", or placeholders. +10. For status="ready", partial_intent must describe the complete resolved goal. + When resolving a follow-up, copy all previously known slots unchanged and fill + only fields listed as missing. +11. object_id and relative_to must never be the same for a spatial relation. + relation and relative_to are an atomic pair. Do not emit either field unless + the user explicitly requested a spatial relation. A plain destination such as + "table" or "tray" never needs relation/relative_to. +12. Compound, swap, and replacement requests MUST use + partial_intent={"action":"sequence","tasks":[...]}. + Each task uses the same typed slots: object_id, destination, relation, + relative_to. Preserve task order and every task across clarification turns. +13. "Replace X with Y", "thế chỗ X bằng Y", or equivalent means: + (a) relocate displaced X; if the user names a destination it is a goal task, + otherwise mark it purpose="intermediate", placement_policy="auto_safe" + and do NOT ask where to park it; + (b) place replacement Y at X's former semantic surface/support relation from + the current scene snapshot. Never encode this as Y relative_to X, because + X will already have moved. + Encode exact former-position placement with + placement_policy="former_location" and anchor_object_id="". + Do not output coordinates; the system snapshots them deterministically. + For a mutual swap of X and Y, return three ordered tasks: + (1) X as intermediate/auto_safe, + (2) Y as former_location anchored to X, + (3) X as former_location anchored to Y. +14. For status="ready" after a compound-goal clarification, return the complete + tasks array, not only the task completed by the latest user answer. +15. Resolve names against ACTIVE ENVIRONMENT aliases. If a phrase matches exactly + one current object, it is unambiguous: use that canonical ID and do NOT ask the + user to confirm it. Clarify only when two or more current objects genuinely + match the same phrase, or no object matches. +16. A follow-up may be only a noun phrase, option, correction, yes/no, or short + fragment. Combine it with pending partial_intent and robot_question. Never ask + the user to repeat action/destination/relation slots that are already known. +17. For swap/replace/compound follow-ups, preserve and return the entire ordered + tasks array after filling the missing entity. A confirmation such as + "tennis và quả chuối" grounds entities; it does not start an unrelated task. +18. Ask only for constraints required by the USER'S requested final outcome. + Exact placement on a surface is optional unless the user requested it. + Temporary parking, blocker relocation, waypoints, approach direction, and + other execution details belong to the planner and must never trigger a + clarification. +19. Never invent a relation for a task. When the user says only "put X on/in + surface S", emit object_id + destination and nothing else spatial. +20. "Swap positions" means exchanging the original planar positions, not merely + leaving both objects on the same surface. Every goal task in a swap must use + placement_policy="former_location" plus anchor_object_id. Return one JSON object with exactly: { "status": "ready|clarify|reject", + "conversation_mode": "standalone|follow_up", "canonical_instruction": "", "message": "", "missing_fields": ["object_id|destination|relation|relative_to|details"], "partial_intent": {} -}""" +} + +conversation_mode rules: +- "follow_up" only when the latest user message answers or completes the pending + request shown in context. +- "standalone" when the latest message expresses a complete new command, regardless + of its wording. Do semantic reasoning; do not depend on a fixed verb list. +- Example: "cho quả lê lên lon chip" is a standalone complete command even if + "cho" was not used in earlier examples.""" def __init__(self, model=None, api_key=None, base_url=None): @@ -516,6 +567,94 @@ Return one JSON object with exactly: "auto", ).lower() self._structured_outputs_available = None + + @staticmethod + def _environment_prompt_context(scene_state): + """Build compact authoritative semantics from the active scene only.""" + if isinstance(scene_state, str): + try: + state = json.loads(scene_state) + except (TypeError, ValueError, json.JSONDecodeError): + state = {} + else: + state = scene_state if isinstance(scene_state, dict) else {} + + environment = state.get("environment", {}) + objects = [] + for obj in state.get("objects", []): + if not isinstance(obj, dict): + continue + objects.append( + { + "id": obj.get("name"), + "class": obj.get("class"), + "semantic": obj.get("semantic", {}), + } + ) + catalog = { + "environment_id": environment.get("id", "unspecified"), + "description": environment.get("description", ""), + "surfaces": environment.get("surfaces", {}), + "objects_present": objects, + } + return ( + "\n\n## ACTIVE ENVIRONMENT SEMANTIC CATALOG (AUTHORITATIVE)\n" + + json.dumps(catalog, ensure_ascii=False, sort_keys=True) + + "\nUse only IDs and facts from this catalog and the current scene state." + ) + + @staticmethod + def _entity_grounding_hints(user_command, scene_state): + """Ground user mentions using only aliases from the active environment.""" + if isinstance(scene_state, str): + try: + state = json.loads(scene_state) + except (TypeError, ValueError, json.JSONDecodeError): + state = {} + else: + state = scene_state if isinstance(scene_state, dict) else {} + text = str(user_command or "").casefold() + matches = [] + for obj in state.get("objects", []): + if not isinstance(obj, dict) or not obj.get("name"): + continue + semantic = obj.get("semantic", {}) or {} + aliases = list(semantic.get("aliases", []) or []) + display = semantic.get("display_name", {}) or {} + aliases.extend( + value for value in display.values() if isinstance(value, str) + ) + aliases.append(obj["name"]) + matched = sorted( + { + alias + for alias in aliases + if isinstance(alias, str) + and alias.strip() + and re.search( + rf"(?= 2 + and all(isinstance(value, (int, float)) for value in position[:2]) + ): + continue + args = annotated[plan_index]["args"] + args["target_position"] = [ + float(position[0]), + float(position[1]), + ] + args["placement_anchor"] = anchor_object_id + return annotated + + @staticmethod + def _compile_goal( + user_command, + effective_command, + plan, + scene_state, + resolved_intent=None, + ): + """Compile only user-visible outcomes into goal predicates. + + When a resolved intent is available it is authoritative. In particular, + tasks marked ``purpose=intermediate`` are execution mechanics and must + not become conditions that Goal Check later enforces. + """ try: state = json.loads(scene_state) if isinstance(scene_state, str) else scene_state except (TypeError, ValueError, json.JSONDecodeError): state = {} + predicates = [] + + if resolved_intent: + initial_objects = { + obj.get("name"): obj + for obj in ( + state.get("objects", []) if isinstance(state, dict) else [] + ) + if isinstance(obj, dict) and obj.get("name") + } + for task in LLMAgent._intent_tasks(resolved_intent): + if task.get("purpose", "goal") == "intermediate": + continue + target = task.get("object_id") + action = task.get("action") or resolved_intent.get("action") + destination = task.get("destination") + relation = task.get("relation") + reference = task.get("relative_to") + placement_policy = task.get("placement_policy") + anchor_object_id = task.get("anchor_object_id") + if not target: + continue + if ( + placement_policy == "former_location" + and anchor_object_id in initial_objects + ): + anchor_position = initial_objects[anchor_object_id].get( + "position", [] + ) + if len(anchor_position) >= 2: + predicates.append( + GoalPredicate( + type="position_near", + object_id=target, + location_id=destination, + target_position=( + float(anchor_position[0]), + float(anchor_position[1]), + ), + tolerance=0.04, + ) + ) + elif relation and reference: + predicates.append( + GoalPredicate( + type="relation_is", + object_id=target, + location_id=destination, + relation=relation, + relative_to=reference, + ) + ) + elif destination: + predicates.append( + GoalPredicate( + type="location_is", + object_id=target, + location_id=destination, + ) + ) + elif action == "pick_up": + predicates.append( + GoalPredicate( + type="carried_object_is", + object_id=target, + ) + ) + + if predicates: + return LLMAgent._resolved_goal_from_predicates( + user_command, + effective_command, + predicates, + scene_state, + ) + # A resolved intent containing only execution mechanics has no + # user-visible completion condition. Never fall back to compiling + # those intermediate steps as if the user had requested them. + return None + carried = state.get("carried_object") if isinstance(state, dict) else None held = carried destination = None - predicates = [] for step in plan: function = step.get("function") @@ -1178,6 +2109,22 @@ class LLMAgent: if not predicates: return None + return LLMAgent._resolved_goal_from_predicates( + user_command, + effective_command, + predicates, + scene_state, + ) + + @staticmethod + def _resolved_goal_from_predicates( + user_command, + effective_command, + predicates, + scene_state, + ): + """Build the immutable goal without changing predicate semantics.""" + descriptions = [] for predicate in predicates: if predicate.type == "carried_object_is": @@ -1186,6 +2133,11 @@ class LLMAgent: descriptions.append( f"đặt {predicate.object_id} vào {predicate.location_id}" ) + elif predicate.type == "position_near": + descriptions.append( + f"đặt {predicate.object_id} vào vị trí " + f"{predicate.target_position}" + ) else: descriptions.append( f"đặt {predicate.object_id} {predicate.relation} " diff --git a/llm_panda/robot_controller.py b/llm_panda/robot_controller.py index f73f702cab42221538c28621d50322758b724b5c..1a8e3915533391f46ae95951517775a01bc0a748 100644 --- a/llm_panda/robot_controller.py +++ b/llm_panda/robot_controller.py @@ -18,7 +18,7 @@ import logging import pybullet as pb from . import config -from .gripper_controller import GripperController +from .gripper_controller import GripperController logger = logging.getLogger(__name__) @@ -63,7 +63,29 @@ class RobotController: # resets it before each high-level action and reads it afterwards to # decide whether to abort, recover and re-plan. Sticky (not cleared on a # later successful sub-move) so a mid-trajectory stall is never masked. - self._stuck = False + self._stuck = False + self._cancellation_token = None + + def set_cancellation_token(self, token): + """Attach the active task token; ``None`` restores non-interruptible use.""" + self._cancellation_token = token + + def _checkpoint(self): + token = self._cancellation_token + if token is not None: + token.checkpoint() + + def hold_current_pose(self): + """Stop trajectory progress while preserving grasp and physical state.""" + current_q = self._current_joint_positions() + for index, joint in enumerate(self.arm_indices): + pb.setJointMotorControl2( + self.robot_id, + joint, + pb.POSITION_CONTROL, + targetPosition=current_q[index], + force=config.ARM_MAX_FORCE, + ) # ------------------------------------------------------------------ # # Kinematics helpers @@ -204,10 +226,11 @@ class RobotController: z += step return min_z - def _settle(self, steps=60): - scaled_steps = int(steps * self.time_scale) - for _ in range(scaled_steps): - pb.stepSimulation() + def _settle(self, steps=60): + scaled_steps = int(steps * self.time_scale) + for _ in range(scaled_steps): + self._checkpoint() + pb.stepSimulation() # ------------------------------------------------------------------ # # Stuck-state signalling (for the closed-loop monitor) @@ -307,7 +330,8 @@ class RobotController: scaled_steps_per_wp = int(steps_per_wp * self.time_scale) # ── traverse waypoints ─────────────────────────────────────────── - for wp_idx, (wp_pos, wp_ori) in enumerate(waypoints): + for wp_idx, (wp_pos, wp_ori) in enumerate(waypoints): + self._checkpoint() current_q = self._current_joint_positions() target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q) @@ -359,8 +383,9 @@ class RobotController: # Smooth joint-space interpolation toward this waypoint. start_q = self._current_joint_positions() - for s in range(1, scaled_steps_per_wp + 1): - alpha = s / scaled_steps_per_wp + for s in range(1, scaled_steps_per_wp + 1): + self._checkpoint() + alpha = s / scaled_steps_per_wp for k, j in enumerate(self.arm_indices): q = start_q[k] + alpha * (target_q[k] - start_q[k]) pb.setJointMotorControl2( @@ -372,8 +397,9 @@ class RobotController: # Catch-up phase: if the arm lagged behind due to velocity limits (e.g. near max reach), # give it some extra simulation steps to physically catch up to the final target_q. max_catch_up = int(400 * self.time_scale) - for _ in range(max_catch_up): - if _m.dist(self.tcp_position(), position) < 0.03: + for _ in range(max_catch_up): + self._checkpoint() + if _m.dist(self.tcp_position(), position) < 0.03: break pb.stepSimulation() @@ -462,9 +488,10 @@ class RobotController: Cartesian-interpolated, ``stepSimulation``-paced motion (and its ``[IK-STUCK]`` guard). Returns the final TCP position. """ - orientation = orientation or self._down_ori - for wp in waypoints: - self.move_to_pose(wp, orientation, steps=steps, settle=settle) + orientation = orientation or self._down_ori + for wp in waypoints: + self._checkpoint() + self.move_to_pose(wp, orientation, steps=steps, settle=settle) return self.tcp_position() # ------------------------------------------------------------------ # diff --git a/llm_panda/scene_manager.py b/llm_panda/scene_manager.py index 5b9891b98530ef09f1a82f35365d5457a92f744c..b2b2d86ff63f46f83cff2591a2cd620157c73992 100644 --- a/llm_panda/scene_manager.py +++ b/llm_panda/scene_manager.py @@ -24,19 +24,46 @@ from .geometry.math_utils import convex_hull, rasterize_footprint class SceneManager: """Tracks registered bodies and turns world state into text for the LLM.""" - def __init__(self): + def __init__(self): # object_id -> {"name": str, "object_class": str} self._registry = {} # object_id -> cached LOCAL mesh vertices (re-projected each query by pose) - self._mesh_cache = {} + self._mesh_cache = {} + self._semantic_catalog = { + "environment_id": "unspecified", + "description": "", + "surfaces": {}, + "objects": {}, + } + self._semantic_catalog_source = None + + def set_semantic_catalog(self, catalog, source=None): + """Attach environment-owned semantics used to build adaptive LLM prompts.""" + self._semantic_catalog = dict(catalog or {}) + self._semantic_catalog.setdefault("objects", {}) + self._semantic_catalog.setdefault("surfaces", {}) + self._semantic_catalog_source = source # ------------------------------------------------------------------ # # Registration # ------------------------------------------------------------------ # - def register_object(self, object_id, name, object_class): - """Register a body so it shows up in the scene state.""" - self._registry[object_id] = {"name": name, "object_class": object_class} - logger.debug(f"registered object id={object_id} name={name} class={object_class}") + def register_object(self, object_id, name, object_class): + """Register a body so it shows up in the scene state.""" + self._registry[object_id] = {"name": name, "object_class": object_class} + logger.debug(f"registered object id={object_id} name={name} class={object_class}") + + def register_semantic_object(self, name, semantic): + """Add runtime-spawned object semantics to the active scene catalog.""" + objects = self._semantic_catalog.setdefault("objects", {}) + objects[name] = dict(semantic or {}) + + def unregister_object(self, object_id): + """Remove a runtime object and its per-instance semantic metadata.""" + meta = self._registry.pop(object_id, None) + self._mesh_cache.pop(object_id, None) + if meta is not None: + self._semantic_catalog.get("objects", {}).pop(meta["name"], None) + return meta @property def object_ids(self): @@ -320,10 +347,10 @@ class SceneManager: return wrong + 20.0 * (y - ry) ** 2 + 10.0 * ((x - rx) - gap) ** 2 return 0.0 - def _find_free_placements(self, grid, meta, center, surface, footprint_xy, - exclude_ids=None, max_results=5, reachable_fn=None, - step_cells=1, relative_to_pos=None, relation=None, - best_effort=False): + def _find_free_placements(self, grid, meta, center, surface, footprint_xy, + exclude_ids=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False, preferred_position=None): """Shared optimiser: world ``[x, y, z]`` centres where ``footprint_xy`` fits on a rasterised surface, ranked by a cost function. @@ -366,7 +393,15 @@ class SceneManager: y = meta["y_min"] + (j0 + wy / 2.0) * cell pos = [round(x, 3), round(y, 3), config.TABLE_TOP_Z] - cost = 0.5 * ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5 + cost = 0.5 * ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5 + if preferred_position is not None: + px, py = preferred_position[:2] + # A former-location anchor is a user goal, so dominate the + # normal compactness score while still requiring a free, + # reachable footprint. + cost += 1000.0 * ( + (x - px) ** 2 + (y - py) ** 2 + ) ** 0.5 # Best-effort overlap penalty: a free window (window==0) is unaffected; # an occupied one is pushed far down the ranking, in proportion to how # much it overlaps, so the least-overlapping spot surfaces first. @@ -401,10 +436,10 @@ class SceneManager: break return results - def find_free_placements(self, footprint_xy, exclude_ids=None, - margin=None, max_results=5, reachable_fn=None, - step_cells=1, relative_to_pos=None, relation=None, - best_effort=False): + def find_free_placements(self, footprint_xy, exclude_ids=None, + margin=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False, preferred_position=None): """World ``[x, y, z]`` centres where ``footprint_xy`` fits on the *table*. The grid is dilated by ``margin`` (default @@ -421,14 +456,15 @@ class SceneManager: grid, meta, config.TABLE_CENTER, "table", footprint_xy, exclude_ids=exclude_ids, max_results=max_results, reachable_fn=reachable_fn, step_cells=step_cells, - relative_to_pos=relative_to_pos, relation=relation, - best_effort=best_effort, - ) + relative_to_pos=relative_to_pos, relation=relation, + best_effort=best_effort, + preferred_position=preferred_position, + ) - def find_free_tray_placements(self, footprint_xy, exclude_ids=None, - margin=None, max_results=5, reachable_fn=None, - step_cells=1, relative_to_pos=None, relation=None, - best_effort=False): + def find_free_tray_placements(self, footprint_xy, exclude_ids=None, + margin=None, max_results=5, reachable_fn=None, + step_cells=1, relative_to_pos=None, relation=None, + best_effort=False, preferred_position=None): """World ``[x, y, z]`` centres where ``footprint_xy`` fits on the *tray*.""" if margin is None: margin = config.PLACEMENT_SAFETY_MARGIN @@ -442,9 +478,10 @@ class SceneManager: grid, meta, (cx, cy_near), "tray", footprint_xy, exclude_ids=exclude_ids, max_results=max_results, reachable_fn=reachable_fn, step_cells=step_cells, - relative_to_pos=relative_to_pos, relation=relation, - best_effort=best_effort, - ) + relative_to_pos=relative_to_pos, relation=relation, + best_effort=best_effort, + preferred_position=preferred_position, + ) def grasp_obstruction_dir(self, object_id, exclude_ids=None): """Perception: is a top-down grasp of ``object_id`` blocked by a near @@ -534,12 +571,15 @@ class SceneManager: location = "elsewhere" else: location = self.classify_location(pos) - entry = { - "name": name, - "class": self._registry[oid]["object_class"], - "location": location, - "position": [round(c, 3) for c in pos], - } + entry = { + "name": name, + "class": self._registry[oid]["object_class"], + "location": location, + "position": [round(c, 3) for c in pos], + } + semantic = self._semantic_catalog.get("objects", {}).get(name) + if isinstance(semantic, dict): + entry["semantic"] = semantic if reachability_fn: entry["reachable"] = reachability_fn(oid) objects.append(entry) @@ -636,9 +676,16 @@ class SceneManager: exclude = [carried_id] if carried_id is not None else [] occupancy = self.get_occupancy_summary(exclude_ids=exclude) - return { - "objects": objects, - "occupancy": occupancy, + return { + "objects": objects, + "environment": { + "id": self._semantic_catalog.get( + "environment_id", "unspecified" + ), + "description": self._semantic_catalog.get("description", ""), + "surfaces": self._semantic_catalog.get("surfaces", {}), + }, + "occupancy": occupancy, "carried_object": carried_object, "tray": { "empty": len(tray_occupants) == 0, diff --git a/main.py b/main.py index 1b086ce9b6d9a7f138eb77e3d969c3f442e8cbcc..9f0ca4fd0ca01ce4f558d6c800f04f73792ad83b 100644 --- a/main.py +++ b/main.py @@ -63,9 +63,6 @@ class PandaApp: def reset_objects(self, seed=None): """Remove current objects and re-spawn them (optionally re-randomised).""" - if hasattr(self.pipeline.agent, "reset_conversation"): - self.pipeline.agent.reset_conversation() - for oid in self.scene.object_ids: pb.removeBody(oid) @@ -82,6 +79,13 @@ class PandaApp: self.pipeline.scene = self.scene self.pipeline._carried = None self.pipeline._pending_target_pos = None + conversation_manager = getattr( + self.pipeline.agent, + "conversation_manager", + None, + ) + if conversation_manager is not None: + conversation_manager.clear() for _ in range(480): self.sim_engine.step() diff --git a/note.md b/note.md new file mode 100644 index 0000000000000000000000000000000000000000..f8c5d8094807e983f624a27ea88aa0a0d5255822 --- /dev/null +++ b/note.md @@ -0,0 +1,34 @@ +> Gửi yêu cầu: "cho quả lê lên lon chip" +> Tôi đang suy nghĩ cách thực hiện... +> Tôi đang phân tích yêu cầu... +> I will pick up the tennis ball, soup can, chips can and pear and move to the table. +> Tôi đang kiểm tra mức độ an toàn của kế hoạch... +> Kế hoạch an toàn và hợp lệ. +> Tôi bắt đầu thực hiện các bước... +> Tôi đang gắp quả bóng tennis lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp lon súp lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp lon snack lên... +> Tôi đang di chuyển đến bàn... +> Tôi đang đặt đồ vật xuống... +> Tôi đang gắp quả lê lên... +> Thực thi lỗi tại bước 10 'pick_up': pick_up('pear') did not secure the object (gripper missed) +> [MONITOR] Phát hiện lỗi. Đang khôi phục cánh tay robot và lập kế hoạch lại (thử lần 1)... +> [MONITOR] Re-plan attempt 1/3 due to: Step 10 'pick_up' failed: pick_up('pear') did not secure the object (gripper missed) +> Tôi đang suy nghĩ cách thực hiện... +> I will pick up the chips can, banana, soup can, chips can and pear and move to the table. +> Tôi đang kiểm tra mức độ an toàn của kế hoạch... +> Phát hiện 1 rủi ro tiềm ẩn. +> - step 12: pick_up target 'pear' is OUT OF REACH +> Tôi bắt đầu thực hiện các bước... +> Tôi đang gắp lon snack lên... +> Thực thi lỗi tại bước 1 'pick_up': pick_up('chips_can') did not secure the object (gripper missed) +> [MONITOR] Phát hiện lỗi. Đang khôi phục cánh tay robot và lập kế hoạch lại (thử lần 2)... +> [MONITOR] Re-plan attempt 2/3 due to: Step 1 'pick_up' failed: pick_up('chips_can') did not secure the object (gripper missed) +> Tôi đang suy nghĩ cách thực hiện... +> Tôi chưa có đủ thông tin để tạo kế hoạch an toàn. Bạn muốn thao tác với vật nào và đặt nó ở đâu? +> Robot phản hồi: Tôi chưa có đủ thông tin để tạo kế hoạch an toàn. Bạn muốn thao tác với vật nào và đặt nó ở đâu? + diff --git a/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc b/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc index 8cc2b49d0eff2c6f2cd6c4601eb16c5334126f06..91a6077d02245a9a40a023241c597f741adb7087 100644 Binary files a/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc differ diff --git a/tests/test_conversation_memory.py b/tests/test_conversation_memory.py index bc9dfca5176e4b2e43c8bec68d823741975f8b1b..8cf333f88ed9dba1dfab075c365b7f9522873ade 100644 --- a/tests/test_conversation_memory.py +++ b/tests/test_conversation_memory.py @@ -583,8 +583,9 @@ def test_invalid_physical_action_is_converted_to_clarification(): result = agent.plan("gắp quả lên", scene) - assert result[0]["function"] == "clarify" + assert result[0]["function"] == "reject" assert result[0]["args"]["reason"] == "invalid_or_empty_plan" + assert "đã hiểu mục tiêu" in result[0]["args"]["message"] def test_replan_can_skip_goal_resolution_gate(): @@ -681,3 +682,770 @@ def test_goal_check_falls_back_to_live_geometry_for_on_top_relation(): assert completed is True assert "verified_from_live_aabb" in reason + + +def test_llm_semantically_replaces_pending_without_fixed_verb_list(): + memory = ConversationManager(session_id="semantic-boundary") + scene = _scene( + ("banana", "banana", "table"), + ("pear", "pear", "table"), + ("chips_can", "chips", "table"), + ) + memory.observe( + "đặt vào khay", + [ + { + "function": "clarify", + "args": { + "message": "Bạn muốn đặt vật nào vào khay?", + "missing_fields": ["object_id"], + "partial_intent": { + "action": "pick_and_place", + "destination": "tray", + }, + }, + } + ], + scene_state=scene, + ) + planner = _GoalAwarePlanner( + { + "status": "ready", + "conversation_mode": "standalone", + "canonical_instruction": ( + "đặt pear on_top_of chips_can trên table" + ), + "message": "", + "missing_fields": [], + "partial_intent": {}, + }, + plan=[ + {"function": "pick_up", "args": {"object_id": "pear"}}, + { + "function": "move_to", + "args": { + "location_id": "table", + "relation": "on_top_of", + "relative_to": "chips_can", + }, + }, + {"function": "place_down", "args": {}}, + ], + ) + agent = LLMAgent(planner=planner, conversation_manager=memory) + + result = agent.plan("cho quả lê lên lon chip", scene) + + assert len(result) == 3 + # The LLM receives the pending context and decides semantically that this + # wording is a standalone command; no hard-coded recognition of "cho". + assert "Yêu cầu trước chưa hoàn chỉnh: đặt vào khay" in ( + planner.resolve_commands[0] + ) + assert planner.plan_commands == [ + "đặt pear on_top_of chips_can trên table" + ] + assert memory.pending is None + + +def test_follow_up_cannot_overwrite_manipulated_object_slot(): + memory = ConversationManager(session_id="protected-slots") + scene = _scene( + ("clamp", "clamp", "table"), + ("soup_can", "can", "table"), + ("chips_can", "chips", "table"), + ) + memory.observe( + "cho kẹp lên trên lon", + [ + { + "function": "clarify", + "args": { + "message": "Bạn muốn đặt kẹp lên lon nào?", + # This reproduces metadata emitted by the earlier prompt, + # which called the reference-object slot "destination". + "missing_fields": ["destination"], + "partial_intent": { + "action": "pick_and_place", + "object_id": "clamp", + "relation": "on_top_of", + }, + }, + } + ], + scene_state=scene, + ) + planner = _GoalAwarePlanner( + { + "status": "ready", + "conversation_mode": "follow_up", + "canonical_instruction": "place soup_can on_top_of soup_can", + "message": "", + "missing_fields": [], + "partial_intent": { + "action": "pick_and_place", + "object_id": "soup_can", + "destination": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + }, + plan=[ + {"function": "pick_up", "args": {"object_id": "clamp"}}, + { + "function": "move_to", + "args": { + "location_id": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + }, + {"function": "place_down", "args": {}}, + ], + ) + agent = LLMAgent(planner=planner, conversation_manager=memory) + + result = agent.plan("lon súp", scene) + + assert len(result) == 3 + assert planner.plan_commands == [ + "place clamp on_top_of soup_can on table" + ] + assert result[0]["args"]["object_id"] == "clamp" + assert result[1]["args"]["relative_to"] == "soup_can" + + +def test_self_referential_spatial_goal_is_blocked_before_planner(): + planner = _GoalAwarePlanner( + { + "status": "ready", + "conversation_mode": "standalone", + "canonical_instruction": "place soup_can on_top_of soup_can", + "message": "", + "missing_fields": [], + "partial_intent": { + "action": "pick_and_place", + "object_id": "soup_can", + "destination": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + } + ) + agent = LLMAgent(planner=planner) + scene = _scene(("soup_can", "can", "table")) + + result = agent.plan("đặt lon súp lên chính nó", scene) + + assert result[0]["function"] == "clarify" + assert "cùng một vật" in result[0]["args"]["message"] + assert planner.plan_commands == [] + + +def test_replacement_follow_up_preserves_all_ordered_tasks(): + memory = ConversationManager(session_id="replacement-sequence") + scene = _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ("soup_can", "can", "table"), + ) + memory.observe( + "thế chỗ cái kẹp bằng quả bóng", + [ + { + "function": "clarify", + "args": { + "message": "Bạn muốn đặt chiếc kẹp vào đâu sau khi lấy nó ra?", + "missing_fields": ["destination"], + "partial_intent": { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + }, + { + "object_id": "tennis_ball", + "destination": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + ], + }, + }, + } + ], + scene_state=scene, + ) + planner = _GoalAwarePlanner( + { + "status": "ready", + "conversation_mode": "follow_up", + # Reproduce the failure: resolver returns only the latest subtask. + "canonical_instruction": "place clamp on table", + "message": "", + "missing_fields": [], + "partial_intent": { + "action": "pick_and_place", + "object_id": "clamp", + "destination": "table", + }, + }, + plan=[ + {"function": "pick_up", "args": {"object_id": "clamp"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + { + "function": "pick_up", + "args": {"object_id": "tennis_ball"}, + }, + { + "function": "move_to", + "args": { + "location_id": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + }, + {"function": "place_down", "args": {}}, + ], + ) + agent = LLMAgent(planner=planner, conversation_manager=memory) + + result = agent.plan("để trên bàn", scene) + + assert len(result) == 6 + assert planner.plan_commands == [ + ( + "place clamp on table; then " + "place tennis_ball on_top_of soup_can on table" + ) + ] + assert result[3]["args"]["object_id"] == "tennis_ball" + assert result[4]["args"]["relative_to"] == "soup_can" + + +def test_replacement_plan_missing_second_task_is_rejected(): + planner = _GoalAwarePlanner( + { + "status": "ready", + "conversation_mode": "standalone", + "canonical_instruction": "replace clamp with tennis_ball", + "message": "", + "missing_fields": [], + "partial_intent": { + "action": "sequence", + "tasks": [ + {"object_id": "clamp", "destination": "table"}, + { + "object_id": "tennis_ball", + "destination": "table", + "relation": "on_top_of", + "relative_to": "soup_can", + }, + ], + }, + }, + plan=[ + {"function": "pick_up", "args": {"object_id": "clamp"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + ], + ) + agent = LLMAgent(planner=planner) + scene = _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ("soup_can", "can", "table"), + ) + + result = agent.plan("thế chỗ kẹp bằng bóng", scene) + + assert result[0]["function"] == "reject" + assert result[0]["args"]["reason"] == "plan_goal_mismatch" + + +def test_goal_resolution_repairs_empty_provider_response_without_losing_context(): + repaired = { + "status": "ready", + "conversation_mode": "follow_up", + "canonical_instruction": ( + "swap tennis_ball and banana while preserving ordered tasks" + ), + "message": "", + "missing_fields": [], + "partial_intent": { + "action": "sequence", + "tasks": [ + {"object_id": "tennis_ball", "destination": "table"}, + {"object_id": "banana", "destination": "table"}, + ], + }, + } + + class RepairCompletions: + def __init__(self): + self.calls = [] + + def create(self, **kwargs): + self.calls.append(kwargs) + content = None if len(self.calls) == 1 else json.dumps(repaired) + return SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace( + content=content, + reasoning=None, + reasoning_content=None, + ) + ) + ] + ) + + completions = RepairCompletions() + planner = RemoteLLMPlanner( + model="test/model", + api_key="test-key", + base_url="https://openrouter.ai/api/v1", + ) + planner._client = SimpleNamespace( + chat=SimpleNamespace(completions=completions) + ) + scene = _scene( + ("tennis_ball", "ball", "table"), + ("banana", "banana", "table"), + ) + contextualized = ( + "Đây là lượt tiếp theo của một yêu cầu đang được làm rõ.\n" + "Yêu cầu trước chưa hoàn chỉnh: đổi vị trí quả bóng và quả chuối\n" + "Robot đã hỏi: Bạn xác nhận quả bóng tennis và quả chuối?\n" + "Người dùng vừa trả lời: Tennis và quả chuối" + ) + + result = planner.resolve_goal(contextualized, scene) + + assert result["status"] == "ready" + assert result["conversation_mode"] == "follow_up" + assert result["partial_intent"]["tasks"][0]["object_id"] == "tennis_ball" + assert len(completions.calls) == 2 + assert "Repair your previous response" in ( + completions.calls[1]["messages"][-1]["content"] + ) + + +def test_surface_reference_is_normalized_to_surface_destination(): + normalized = LLMAgent._normalize_intent_task( + { + "object_id": "tennis_ball", + "destination": "table", + "relation": "on_top_of", + "relative_to": "table", + }, + {"banana", "tennis_ball"}, + {"table", "tray"}, + ) + + assert normalized == { + "object_id": "tennis_ball", + "destination": "table", + } + + +def test_surface_reference_normalization_applies_to_every_sequence_task(): + scene = _scene( + ("banana", "banana", "table"), + ("tennis_ball", "ball", "table"), + ) + pending = SimpleNamespace( + partial_intent={ + "action": "sequence", + "tasks": [ + { + "object_id": "banana", + "destination": "tray", + "relation": "on_top_of", + "relative_to": "tray", + }, + { + "object_id": "tennis_ball", + "destination": "table", + "relation": "on_top_of", + "relative_to": "table", + }, + ], + }, + missing_fields=(), + ) + + normalized = LLMAgent._merge_resolved_intent(pending, {}, scene) + + assert normalized["tasks"] == [ + {"object_id": "banana", "destination": "tray"}, + {"object_id": "tennis_ball", "destination": "table"}, + ] + assert LLMAgent._resolved_intent_error(normalized, scene) is None + + +def test_standalone_compound_intent_normalizes_every_task_adaptively(): + scene = json.loads( + _scene( + ("chips_can", "chips", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + scene["environment"] = { + "surfaces": { + "workbench": { + "kind": "support_surface", + "aliases": ["bench"], + } + } + } + for obj in scene["objects"]: + obj["location"] = "workbench" + + normalized = LLMAgent._merge_resolved_intent( + None, + { + "action": "sequence", + "tasks": [ + { + "object_id": "tennis_ball", + "purpose": "intermediate", + "destination": None, + "relation": None, + }, + { + "object_id": "chips_can", + "placement_policy": "former_location", + "anchor_object_id": "tennis_ball", + "destination": None, + }, + { + "object_id": "tennis_ball", + "placement_policy": "former_location", + "anchor_object_id": "chips_can", + "destination": None, + }, + ], + }, + scene, + ) + + assert normalized == { + "action": "sequence", + "tasks": [ + { + "object_id": "tennis_ball", + "purpose": "intermediate", + "placement_policy": "auto_safe", + }, + { + "object_id": "chips_can", + "placement_policy": "former_location", + "anchor_object_id": "tennis_ball", + "destination": "workbench", + }, + { + "object_id": "tennis_ball", + "placement_policy": "former_location", + "anchor_object_id": "chips_can", + "destination": "workbench", + }, + ], + } + assert LLMAgent._resolved_intent_error(normalized, scene) is None + + +def test_directional_relation_to_surface_is_not_silently_rewritten(): + scene = _scene(("tennis_ball", "ball", "table")) + intent = { + "action": "pick_and_place", + "object_id": "tennis_ball", + "destination": "table", + "relation": "left_of", + "relative_to": "table", + } + + normalized = LLMAgent._normalize_intent_task( + intent, + {"tennis_ball"}, + {"table", "tray"}, + ) + error = LLMAgent._resolved_intent_error(normalized, scene) + + assert normalized["relative_to"] == "table" + assert error is not None + assert "không phải vật tham chiếu" in error + + +def test_unconstrained_dangling_relation_is_removed_after_destination_reply(): + scene = json.loads( + _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + pending = SimpleNamespace( + partial_intent={ + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "relation": "on_top_of", + }, + { + "object_id": "tennis_ball", + "destination": "table", + }, + ], + }, + missing_fields=("destination",), + ) + + normalized = LLMAgent._merge_resolved_intent( + pending, + { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "destination": "tray", + } + ], + }, + scene, + ) + + assert normalized["tasks"][0] == { + "object_id": "clamp", + "destination": "tray", + } + assert LLMAgent._resolved_intent_error(normalized, scene) is None + + +def test_explicit_relation_without_reference_still_requires_clarification(): + scene = _scene(("pear", "pear", "table")) + normalized = LLMAgent._normalize_intent_task( + { + "object_id": "pear", + "destination": "table", + "relation": "left_of", + "constraint_sources": {"relation": "user"}, + }, + {"pear"}, + {"table", "tray"}, + ) + + assert normalized["relation"] == "left_of" + assert LLMAgent._resolved_intent_error(normalized, scene) is not None + + +def test_intermediate_task_needs_no_user_selected_destination_or_relation(): + scene = json.loads( + _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + intent = { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "purpose": "intermediate", + "relation": "on_top_of", + }, + { + "object_id": "tennis_ball", + "destination": "table", + }, + ], + } + normalized = { + "action": "sequence", + "tasks": [ + LLMAgent._normalize_intent_task( + task, + {"clamp", "tennis_ball"}, + {"table", "tray"}, + ) + for task in intent["tasks"] + ], + } + + assert normalized["tasks"][0] == { + "object_id": "clamp", + "purpose": "intermediate", + "placement_policy": "auto_safe", + } + assert LLMAgent._resolved_intent_error(normalized, scene) is None + assert "automatically selected safe free spot" in ( + LLMAgent._canonical_instruction_from_intent(normalized) + ) + + +def test_intermediate_execution_is_excluded_from_resolved_goal(): + scene = _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + intent = { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "purpose": "intermediate", + "placement_policy": "auto_safe", + }, + { + "object_id": "tennis_ball", + "destination": "table", + }, + ], + } + plan = [ + {"function": "pick_up", "args": {"object_id": "clamp"}}, + {"function": "move_to", "args": {"location_id": "tray"}}, + {"function": "place_down", "args": {}}, + {"function": "pick_up", "args": {"object_id": "tennis_ball"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + ] + + assert LLMAgent._plan_matches_intent(plan, intent) + goal = LLMAgent._compile_goal( + "replace clamp with tennis ball", + "replace clamp with tennis_ball", + plan, + scene, + resolved_intent=intent, + ) + + assert goal is not None + assert len(goal.predicates) == 1 + assert goal.predicates[0].object_id == "tennis_ball" + assert goal.predicates[0].location_id == "table" + + +def test_swap_former_locations_are_anchored_from_initial_scene(): + scene = json.loads( + _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + scene["objects"][0]["position"] = [0.49, -0.10, 0.35] + scene["objects"][1]["position"] = [0.61, 0.02, 0.35] + intent = { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "purpose": "intermediate", + "placement_policy": "auto_safe", + }, + { + "object_id": "tennis_ball", + "destination": "table", + "placement_policy": "former_location", + "anchor_object_id": "clamp", + }, + { + "object_id": "clamp", + "destination": "table", + "placement_policy": "former_location", + "anchor_object_id": "tennis_ball", + }, + ], + } + plan = [ + {"function": "pick_up", "args": {"object_id": "clamp"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + {"function": "pick_up", "args": {"object_id": "tennis_ball"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + {"function": "pick_up", "args": {"object_id": "clamp"}}, + {"function": "move_to", "args": {"location_id": "table"}}, + {"function": "place_down", "args": {}}, + ] + + anchored = LLMAgent._apply_intent_placement_anchors(plan, intent, scene) + + assert "target_position" not in anchored[1]["args"] + assert anchored[4]["args"]["target_position"] == [0.49, -0.10] + assert anchored[4]["args"]["placement_anchor"] == "clamp" + assert anchored[7]["args"]["target_position"] == [0.61, 0.02] + assert anchored[7]["args"]["placement_anchor"] == "tennis_ball" + assert LLMAgent._plan_matches_intent(anchored, intent) + + +def test_swap_goal_compiles_position_predicates_not_surface_only(): + scene = json.loads( + _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + scene["objects"][0]["position"] = [0.49, -0.10, 0.35] + scene["objects"][1]["position"] = [0.61, 0.02, 0.35] + intent = { + "action": "sequence", + "tasks": [ + { + "object_id": "clamp", + "purpose": "intermediate", + "placement_policy": "auto_safe", + }, + { + "object_id": "tennis_ball", + "destination": "table", + "placement_policy": "former_location", + "anchor_object_id": "clamp", + }, + { + "object_id": "clamp", + "destination": "table", + "placement_policy": "former_location", + "anchor_object_id": "tennis_ball", + }, + ], + } + + goal = LLMAgent._compile_goal( + "swap ball and clamp", + "swap tennis_ball and clamp", + [], + scene, + resolved_intent=intent, + ) + + assert [predicate.type for predicate in goal.predicates] == [ + "position_near", + "position_near", + ] + assert goal.predicates[0].target_position == (0.49, -0.10) + assert goal.predicates[1].target_position == (0.61, 0.02) + + +def test_former_location_infers_anchor_surface_from_scene(): + scene = json.loads( + _scene( + ("clamp", "clamp", "table"), + ("tennis_ball", "ball", "table"), + ) + ) + + resolved = LLMAgent._merge_resolved_intent( + None, + { + "action": "pick_and_place", + "object_id": "tennis_ball", + "placement_policy": "former_location", + "anchor_object_id": "clamp", + }, + scene, + ) + + assert resolved["destination"] == "table" + assert LLMAgent._resolved_intent_error(resolved, scene) is None diff --git a/tests/test_environment_semantics.py b/tests/test_environment_semantics.py new file mode 100644 index 0000000000000000000000000000000000000000..530c4903ab43d2004bc2e50bdb32f87ad4994da4 --- /dev/null +++ b/tests/test_environment_semantics.py @@ -0,0 +1,147 @@ +"""Tests for environment-owned semantics and adaptive LLM prompts.""" + +import json +from pathlib import Path + +from llm_panda.llm_agent import RemoteLLMPlanner +from llm_panda.core.env_builder import EnvBuilder + + +ROOT = Path(__file__).resolve().parents[1] + + +def _load(path): + return json.loads(path.read_text(encoding="utf-8")) + + +def test_env1_references_catalog_covering_every_configured_object(): + environment = _load(ROOT / "envs" / "env1.json") + catalog_path = ROOT / "envs" / environment["semantic_catalog"] + catalog = _load(catalog_path) + + configured = {obj["name"] for obj in environment["objects"]} + described = set(catalog["objects"]) + + assert configured == described + assert catalog["environment_id"] == "env1" + for object_id, semantic in catalog["objects"].items(): + assert semantic["aliases"], object_id + assert semantic["display_name"]["vi"], object_id + assert semantic["categories"], object_id + assert semantic["affordances"], object_id + + +def test_env_builder_loads_referenced_catalog_into_scene(): + builder = EnvBuilder( + sim_client=None, + env_json_path=str(ROOT / "envs" / "env1.json"), + ) + + builder.load_configs() + + assert builder.scene._semantic_catalog["environment_id"] == "env1" + assert "pear" in builder.scene._semantic_catalog["objects"] + assert builder.scene._semantic_catalog_source.endswith( + "env1.semantics.json" + ) + + +def test_adaptive_prompt_uses_only_active_environment_catalog(): + planner = RemoteLLMPlanner( + model="test/model", + api_key="test-key", + base_url="https://openrouter.ai/api/v1", + ) + apple_scene = { + "environment": { + "id": "orchard", + "description": "A custom environment unseen by the core prompt.", + "surfaces": { + "basket": { + "aliases": ["giỏ", "basket"], + "kind": "container_surface", + } + }, + }, + "objects": [ + { + "name": "green_apple", + "class": "fruit", + "location": "table", + "semantic": { + "aliases": ["táo xanh", "green apple"], + "categories": ["fruit", "food"], + "attributes": {"color": ["green"]}, + "affordances": ["pickable"], + }, + } + ], + "carried_object": None, + } + bolt_scene = { + "environment": { + "id": "workshop", + "description": "A workshop environment.", + "surfaces": {}, + }, + "objects": [ + { + "name": "bolt_7", + "class": "fastener", + "location": "table", + "semantic": { + "aliases": ["bu lông số 7"], + "categories": ["fastener"], + "attributes": {"material": ["steel"]}, + "affordances": ["pickable"], + }, + } + ], + "carried_object": None, + } + + apple_prompt = planner.build_adaptive_system_prompt(apple_scene) + bolt_prompt = planner.build_adaptive_system_prompt(bolt_scene) + + assert "green_apple" in apple_prompt + assert "táo xanh" in apple_prompt + assert "basket" in apple_prompt + assert "bolt_7" not in apple_prompt + + assert "bolt_7" in bolt_prompt + assert "bu lông số 7" in bolt_prompt + assert "green_apple" not in bolt_prompt + assert apple_prompt != bolt_prompt + + +def test_remote_core_prompt_no_longer_contains_env1_object_catalog(): + prompt = RemoteLLMPlanner.SYSTEM_PROMPT + + for environment_specific_id in ( + "soup_can", + "chips_can", + "tennis_ball", + ): + assert environment_specific_id not in prompt + + +def test_entity_grounding_uses_unique_aliases_from_active_catalog(): + catalog = _load(ROOT / "envs" / "env1.semantics.json") + scene = { + "objects": [ + { + "name": name, + "semantic": catalog["objects"][name], + } + for name in ("tennis_ball", "banana", "pear") + ] + } + + hints = RemoteLLMPlanner._entity_grounding_hints( + "Tennis và quả chuối", + scene, + ) + + assert '"object_id": "tennis_ball"' in hints + assert '"object_id": "banana"' in hints + assert '"object_id": "pear"' not in hints diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 82b7a44f64ca99373715a56be3acc8e6793357dc..e8edfdaafcd4018f83789132d66543481c5978e0 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -119,7 +119,7 @@ def test_verify_step_flags_joint_stuck(sim): sim.controller._stuck = False -def test_recover_returns_arm_to_safe_height(sim): +def test_recover_returns_arm_to_safe_height(sim): """Recovery lifts the TCP to (at least) the safe travel height and clears the stuck flag, so the next plan starts from a known-good pose.""" from llm_panda import config @@ -127,4 +127,100 @@ def test_recover_returns_arm_to_safe_height(sim): sim._recover_to_safe_state(verbose=False) tcp = sim.controller.tcp_position() assert tcp[2] > config.TABLE_TOP_Z + 0.5 * config.LIFT_HEIGHT - assert not sim.controller.is_stuck() + assert not sim.controller.is_stuck() + + +def test_position_near_goal_requires_actual_swap_coordinate(): + from llm_panda.conversation import GoalPredicate, ResolvedGoal + from llm_panda.execution.monitor import ExecutionMonitor + + goal = ResolvedGoal( + task_id="swap-position", + canonical_instruction="place tennis_ball at clamp former location", + predicates=( + GoalPredicate( + type="position_near", + object_id="tennis_ball", + location_id="table", + target_position=(0.49, -0.10), + tolerance=0.04, + ), + ), + source_command="swap", + effective_command="swap", + ) + wrong_spot = { + "objects": [ + { + "name": "tennis_ball", + "location": "table", + "position": [0.60, 0.03, 0.35], + } + ] + } + correct_spot = { + "objects": [ + { + "name": "tennis_ball", + "location": "table", + "position": [0.50, -0.09, 0.35], + } + ] + } + + failed, _ = ExecutionMonitor._verify_predicates(goal, wrong_spot) + passed, _ = ExecutionMonitor._verify_predicates(goal, correct_spot) + + assert not failed + assert passed + + +def test_pipeline_interrupts_between_steps_without_recovery(sim, monkeypatch): + from llm_panda.execution.cancellation import ( + CancellationToken, + ExecutionInterrupted, + ) + + token = CancellationToken() + sim.pipeline.set_cancellation_token(token) + calls = [] + + def execute_once(step, verbose=True): + calls.append(step) + token.request("superseded") + + monkeypatch.setattr(sim.pipeline, "_execute", execute_once) + monkeypatch.setattr( + sim.pipeline.execution_monitor, + "verify_step", + lambda *args, **kwargs: (True, ""), + ) + plan = [ + {"function": "place_down", "args": {}}, + {"function": "place_down", "args": {}}, + ] + + with pytest.raises(ExecutionInterrupted): + sim.pipeline._execute_plan(plan, verbose=False) + + assert len(calls) == 1 + sim.pipeline.set_cancellation_token(None) + + +def test_controller_cancellation_stops_inside_cartesian_motion(sim): + from llm_panda.execution.cancellation import ( + CancellationToken, + ExecutionInterrupted, + ) + + token = CancellationToken() + sim.controller.set_cancellation_token(token) + start = sim.controller.tcp_position() + token.request("new prompt") + + with pytest.raises(ExecutionInterrupted): + sim.controller.move_to_pose(start, steps=20, settle=0) + + sim.controller.hold_current_pose() + assert sim.controller.gripper._constraint_id is None + sim.controller.set_cancellation_token(None) diff --git a/tests/test_occupancy.py b/tests/test_occupancy.py index 36aea1a76f5e502c34cac354fea8e8552721d1e5..71592248d33e7d2cfd2d02c3bb7379167fae7c2c 100644 --- a/tests/test_occupancy.py +++ b/tests/test_occupancy.py @@ -146,6 +146,24 @@ def test_relation_left_of_places_on_correct_side(): assert spots[0][1] > ref[1] +def test_preferred_position_biases_free_placement_to_swap_anchor(): + scene = FakeScene({}) + anchor = (config.TABLE_CENTER[0] + 0.08, config.TABLE_CENTER[1] - 0.08) + + spots = scene.find_free_placements( + (0.04, 0.04), + max_results=1, + preferred_position=anchor, + ) + + assert spots + distance = ( + (spots[0][0] - anchor[0]) ** 2 + + (spots[0][1] - anchor[1]) ** 2 + ) ** 0.5 + assert distance <= 0.02 + + def test_on_top_detection_accepts_small_physics_interpenetration(): support = ((0.45, -0.05, 0.30), (0.55, 0.05, 0.40)) # The upper object's AABB settles 4 cm into the support AABB. This can diff --git a/tests/test_web_command_button.py b/tests/test_web_command_button.py new file mode 100644 index 0000000000000000000000000000000000000000..c497f285e44a729501a3457f34d85fd072ff6c13 --- /dev/null +++ b/tests/test_web_command_button.py @@ -0,0 +1,57 @@ +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_command_input_stays_enabled_while_execution_is_active(): + source = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + lock_body = source.split("function lockInput()", 1)[1].split( + "document.getElementById('chat-form')", + 1, + )[0] + + assert "chatInput.disabled = false" in lock_body + assert "submitBtn.disabled = false" in lock_body + assert "setSubmitButtonMode(true)" in lock_body + + +def test_click_stops_but_enter_submits_replacement_command(): + source = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + + assert "enterSubmittedFromChatInput" in source + assert "e.submitter === submitBtn && !submittedWithEnter" in source + assert "JSON.stringify({ type: 'cancel' })" in source + assert "type: 'run'" in source + + +def test_execution_button_has_spinner_and_stop_square(): + script = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + styles = (ROOT / "frontend" / "index.css").read_text(encoding="utf-8") + + assert "stop-square" in script + assert "is-executing" in script + assert "#submit-btn.is-executing::before" in styles + assert "@keyframes submitExecutionSpin" in styles + + +def test_html_cache_busts_live_command_assets(): + html = (ROOT / "frontend" / "index.html").read_text(encoding="utf-8") + + assert "/static/app.js?v=30" in html + assert "/static/index.css?v=11" in html + + +def test_clarification_result_is_not_recorded_as_failed_execution(): + source = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + + result_handler = source.split("case 'result':", 1)[1].split( + "const badge =", + 1, + )[0] + clarification_guard = result_handler.index( + "['clarify', 'reject'].includes(msg.response_type)" + ) + history_write = result_handler.index("historyData.unshift") + + assert clarification_guard < history_write diff --git a/tests/test_web_drag_drop.py b/tests/test_web_drag_drop.py new file mode 100644 index 0000000000000000000000000000000000000000..380837559aab3ee8ebc8679c8ab0a8a2bceb0724 --- /dev/null +++ b/tests/test_web_drag_drop.py @@ -0,0 +1,134 @@ +from pathlib import Path + +import pytest + +from frontend.interactive_server import _clamp_manual_target + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_manual_target_rejects_non_finite_coordinates(): + with pytest.raises(ValueError): + _clamp_manual_target([float("nan"), 0.0, 0.3]) + + +def test_manual_target_is_clamped_to_workspace_and_surface(): + target = _clamp_manual_target([99.0, -99.0, -1.0], "object") + + assert target == [0.9, -0.65, 0.03] + + +def test_frontend_uses_complete_pointer_lifecycle_and_drag_ids(): + source = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + + for event_name in ( + "pointerdown", + "pointermove", + "pointerup", + "pointercancel", + "lostpointercapture", + ): + assert f"addEventListener('{event_name}'" in source + assert "setPointerCapture" in source + assert "drag_id: activeDrag.dragId" in source + assert "target_type: target.type" in source + + +def test_robot_and_object_drag_have_separate_backend_paths(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert 'requested_type == "robot_ee"' in source + assert "calculateInverseKinematics" in source + assert "pb.createConstraint" in source + assert 'drag_state.get("target_type") == "robot_ee"' in source + assert "hit_uid != object_id" not in source + assert "parentFramePosition=[0, 0, 0]" in source + + +def test_runtime_visual_metadata_uses_mesh_matching_material(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert 'mesh_path + ".mtl"' in source + assert 'os.path.splitext(mesh_path)[0] + ".mtl"' in source + assert "web_mtl = os.path.basename(matching_mtl)" in source + + +def test_catalog_rows_spawn_real_runtime_objects(): + client = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + server = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + builder = (ROOT / "llm_panda" / "core" / "env_builder.py").read_text( + encoding="utf-8" + ) + + assert 'draggable="true"' in client + assert "application/x-llm-panda-ycb" in client + assert "type: 'spawn_catalog_object'" in client + assert 'p_type == "spawn_catalog_object"' in server + assert "spawn_catalog_object(" in builder + assert "register_semantic_object" in builder + + +def test_disconnect_cleans_up_physics_constraint(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + finalizer = source.rsplit("finally:", 1)[1] + + assert 'drag_state["active"] = False' in finalizer + assert "pb.removeConstraint" in finalizer + + +def test_objects_are_selected_for_deletion_not_manually_dragged(): + source = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + pointer_handler = source.split("function onPointerDown", 1)[1].split( + "function onPointerMove", + 1, + )[0] + + selection = pointer_handler.index("selectSceneObject(target.name)") + drag_session = pointer_handler.index("activeDrag =") + assert selection < drag_session + assert "if (target.type === 'object')" in pointer_handler + assert "return;" in pointer_handler[selection:drag_session] + + +def test_delete_ui_and_incremental_object_events_exist(): + client = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8") + server = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert "new THREE.BoxHelper(group, 0xef4444)" in client + assert "object-delete-button" in client + assert "type: 'delete_object'" in client + assert "case 'object_added':" in client + assert "case 'object_removed':" in client + assert '"type": "object_added"' in server + assert 'p_type == "delete_object"' in server + + +def test_environment_dropdown_excludes_semantic_catalogs(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert 'filename.endswith(".semantics.json")' in source + assert "_load_environment_config(path)" in source + assert '"type": "environment_rejected"' in source + + +def test_environment_listing_keeps_valid_empty_scene_templates(): + from frontend.interactive_server import _list_environment_files + + environments = _list_environment_files(str(ROOT / "envs")) + + assert "env1.json" in environments + assert "default_desk.json" in environments + assert all(not name.endswith(".semantics.json") for name in environments) diff --git a/tests/test_web_runtime.py b/tests/test_web_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..3d356c08cd6db20cd6e7289f8680e2fa737d6c50 --- /dev/null +++ b/tests/test_web_runtime.py @@ -0,0 +1,208 @@ +import asyncio +from pathlib import Path + +from frontend.web_runtime import WebRuntime +from llm_panda.execution.cancellation import ( + CancellationToken, + ExecutionInterrupted, +) + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_reload_snapshot_preserves_runtime_state_and_event_history(): + runtime = WebRuntime(max_events=10) + + async def exercise(): + await runtime.publish({"type": "log", "message": "planning"}) + await runtime.publish( + {"type": "plan", "plan": [{"step": 1}], "generation": 0} + ) + await runtime.publish( + { + "type": "state", + "joints": [0.1, 0.2], + "objects": {"banana": {"pos": [0.4, 0.1, 0.3]}}, + }, + journal=False, + ) + + asyncio.run(exercise()) + snapshot = runtime.snapshot() + + assert snapshot["state"]["joints"] == [0.1, 0.2] + assert snapshot["plan"]["plan"] == [{"step": 1}] + assert [event["message"] for event in snapshot["events"] if event["type"] == "log"] == [ + "planning" + ] + + +def test_new_command_cancels_active_and_latest_pending_wins(): + runtime = WebRuntime() + first = runtime.submit("first") + active = runtime.take_pending() + + second = runtime.submit("second") + third = runtime.submit("third") + + assert active["task_id"] == first["task_id"] + assert active["token"].requested + pending = runtime.take_pending() + assert pending["task_id"] == third["task_id"] + assert pending["task_id"] != second["task_id"] + + +def test_stale_result_is_journaled_but_does_not_replace_latest_result(): + runtime = WebRuntime() + first = runtime.submit("first") + runtime.take_pending() + second = runtime.submit("second") + + async def exercise(): + await runtime.publish( + { + "type": "result", + "generation": first["generation"], + "success": False, + } + ) + await runtime.publish( + { + "type": "result", + "generation": second["generation"], + "success": True, + } + ) + + asyncio.run(exercise()) + + assert runtime.latest_result["generation"] == second["generation"] + assert runtime.latest_result["success"] + + +def test_event_journal_is_bounded_and_replayable(): + runtime = WebRuntime(max_events=3) + + async def exercise(): + for index in range(5): + await runtime.publish({"type": "log", "message": str(index)}) + + asyncio.run(exercise()) + + assert [event["message"] for event in runtime.events_after(0)] == [ + "2", + "3", + "4", + ] + assert [event["message"] for event in runtime.events_after(4)] == ["4"] + + +def test_cancellation_token_raises_only_after_request(): + token = CancellationToken() + token.checkpoint() + token.request("new command") + + try: + token.checkpoint() + except ExecutionInterrupted as exc: + assert "new command" in str(exc) + else: + raise AssertionError("checkpoint did not interrupt") + + +def test_runtime_conversation_survives_client_disconnect(): + runtime = WebRuntime() + runtime.conversation_manager.observe( + "move banana", + [ + { + "function": "clarify", + "args": { + "message": "Where?", + "missing_fields": ["destination"], + "partial_intent": { + "action": "pick_and_place", + "object_id": "banana", + }, + }, + } + ], + ) + + class Socket: + def __init__(self): + self.events = [] + + async def send_json(self, event): + self.events.append(event) + + socket = Socket() + + async def connect_disconnect(): + await runtime.subscribe(socket) + await runtime.publish({"type": "log", "message": "waiting"}) + await runtime.unsubscribe(socket) + + asyncio.run(connect_disconnect()) + + assert runtime.snapshot()["conversation_pending"] + assert socket.events[0]["message"] == "waiting" + + +def test_explicit_reset_clears_ui_history_but_keeps_monotonic_sequence(): + runtime = WebRuntime() + + async def exercise(): + await runtime.publish({"type": "log", "message": "old"}) + + asyncio.run(exercise()) + old_seq = runtime.snapshot()["last_event_seq"] + runtime.clear_task_history() + asyncio.run(runtime.publish({"type": "log", "message": "new"})) + + snapshot = runtime.snapshot() + assert [event["message"] for event in snapshot["events"]] == ["new"] + assert snapshot["last_event_seq"] > old_seq + + +def test_cancel_all_interrupts_active_and_discards_pending_command(): + runtime = WebRuntime() + runtime.submit("active") + active = runtime.take_pending() + runtime.submit("pending") + + assert runtime.cancel_all("reset") + assert active["token"].requested + assert not runtime.has_pending + + +def test_web_pipeline_keeps_resolved_goal_across_replans_and_goal_check(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert "resolved_goal = None" in source + assert "resolved_goal.canonical_instruction" in source + assert 'plan_kwargs["resolve_goal"] = False' in source + assert "resolved_goal=resolved_goal" in source + + +def test_web_replan_limit_uses_environment_configuration(): + source = (ROOT / "frontend" / "interactive_server.py").read_text( + encoding="utf-8" + ) + + assert 'os.environ.get("MAX_REPLANS", "3")' in source + assert "MAX_REPLANS = 999999" not in source + + +def test_scene_reset_clears_cli_conversation_memory(): + source = (ROOT / "main.py").read_text(encoding="utf-8") + reset_body = source.split("def reset_objects", 1)[1].split( + "def change_environment", + 1, + )[0] + + assert '"conversation_manager"' in reset_body + assert "conversation_manager.clear()" in reset_body