feat: create task-center project tasks from native DSH conversations

This commit is contained in:
阿白叔 committed 2026-10-30 14:42:50 +08:00
1 parent e9b77186dc
commit ef40f339cd
23 files changed
+773 -31

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
import json
from pathlib import Path
import pytest
from dx_productivity.dsh.task_creation import validate_creation_spec
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService, _quick_run_lease
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def setup(tmp_path):
root = tmp_path / 'projects'
paths = []
for name in ['Board-A', 'Board-B']:
path = root / name / 'board.prj'
path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
paths.append(path)
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
yield service, store, root, tuple(paths)
store.close()
def spec(**values):
return validate_creation_spec({'name': 'DSH换料任务', 'note': '对话创建',
'rules': [{'old_part_number': 'OLD', 'new_part_number': 'NEW'}], **values})
def test_create_real_project_tasks_with_rules_and_no_cad_writes(setup):
service, store, root, paths = setup
before = [path.read_bytes() for path in paths]
result = service.create_assistant_project_tasks('a' * 32, spec(copy_part_number_to_value=True), root, paths)
assert result['status'] == 'created' and result['created_count'] == 2
tasks = store.list_tasks()
assert len(tasks) == 2 and len({t.group_id for t in tasks}) == 1
for task in tasks:
assert task.primary_project_id and task.copy_part_number_to_value and task.status.value == 'draft'
rules = store.list_rules(task.task_id)
assert [(r.old_part_number, r.new_part_number) for r in rules] == [('OLD', 'NEW')]
assert [path.read_bytes() for path in paths] == before
assert not list((service.layout_settings_path.parent).rglob('command.tsv'))
def test_same_request_replay_is_persistent_and_changed_input_is_rejected(setup):
service, store, root, paths = setup
result = service.create_assistant_project_tasks('a' * 32, spec(), root, paths)
again = service.create_assistant_project_tasks('a' * 32, spec(), root, paths)
assert result['task_ids'] == again['task_ids'] and again['replayed']
assert len(store.list_tasks()) == 2
with pytest.raises(TaskCenterError, match='assistant_request_conflict'):
service.create_assistant_project_tasks('a' * 32, spec(name='不同任务'), root, paths)
reopened = TaskStore(store.path)
try:
assert reopened.assistant_creation_receipt('a' * 32)['result']['task_ids'] == result['task_ids']
finally:
reopened.close()
def test_existing_projects_are_not_renamed_or_reconfigured(setup):
service, store, root, paths = setup
existing = service.create_project_tasks(root, selected_paths=(paths[0],))[0]
service.add_rule(existing.task_id, 'PREVIOUS', 'KEEP')
result = service.create_assistant_project_tasks('b' * 32, spec(), root, paths)
assert result['created_count'] == 1 and result['existing_count'] == 1
assert store.get_task(existing.task_id).name == existing.name
assert store.list_rules(existing.task_id)[0].new_part_number == 'KEEP'
def test_failed_rule_application_rolls_back_all_new_tasks_and_receipt(setup, monkeypatch):
service, store, root, paths = setup
original = store.add_rule
calls = []
def fail_after_one(*args, **kwargs):
calls.append(1)
if len(calls) == 2:
raise TaskCenterError('controlled_rule_failure', '受控规则失败')
return original(*args, **kwargs)
monkeypatch.setattr(store, 'add_rule', fail_after_one)
with pytest.raises(TaskCenterError):
service.create_assistant_project_tasks('c' * 32, spec(), root, paths)
assert not store.list_tasks()
monkeypatch.setattr(store, 'add_rule', original)
assert service.create_assistant_project_tasks('c' * 32, spec(), root, paths)['created_count'] == 2
def test_creation_respects_existing_execution_lease(setup):
service, store, root, paths = setup
with _quick_run_lease(service.layout_settings_path.parent):
with pytest.raises(TaskCenterError):
service.create_assistant_project_tasks('d' * 32, spec(), root, paths)
assert not store.list_tasks()
def test_missing_rules_remain_a_real_configurable_draft_and_old_value_defaults_are_preserved(setup):
service, store, root, paths = setup
result = service.create_assistant_project_tasks('f' * 32, spec(rules=[]), root, paths)
assert result['created_count'] == 2 and result['rules_count'] == 0
assert all(not store.list_rules(task_id) for task_id in result['task_ids'])
assert all(not store.get_task(task_id).copy_part_number_to_value for task_id in result['task_ids'])
@pytest.mark.parametrize('extra', [{'execute': True}, {'confirmed': True}, {'rules': [{'old_part_number': 'A', 'new_part_number': 'A'}]},
{'rules': [{'old_part_number': 'A', 'new_part_number': 'B'}, {'old_part_number': 'A', 'new_part_number': 'C'}]},
{'copy_part_number_to_value': 'true'}, {'name': ''}])
def test_untrusted_fields_and_invalid_rules_are_rejected(extra):
with pytest.raises(TaskCenterError):
spec(**extra)
+8
View File
@@ -6,11 +6,16 @@ from dx_productivity.trial_task_center.errors import TaskCenterError
class HarnessView(QWidget):
action_requested = Signal(object)
task_creation_requested = Signal(object)
task_creation_cancelled = Signal(object)
stopped = Signal()
def __init__(self, parent):
super().__init__(parent)
self.starts = 0
self.binds = []
self.creation = {}
self.results = []
def start(self):
self.starts += 1
@@ -22,6 +27,9 @@ class HarnessView(QWidget):
def shutdown(self):
pass
def complete_task_creation(self, value):
self.results.append(value)
def test_direct_navigation_opens_harness_and_returns_without_losing_task(ui, monkeypatch, qtbot):
window = ui.window
+90
View File
@@ -0,0 +1,90 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.trial_task_center.ui.dsh_task_creation import DshTaskCreationController
from test_dsh_native_menu import HarnessView
def request(key='a'):
return {'request_id': key * 32, 'session_id': 'native-session',
'spec': {'name': 'DSH新增任务', 'rules': [{'old_part_number': 'A', 'new_part_number': 'B'}]}}
def setup_controller(ui, monkeypatch):
monkeypatch.setattr(type(ui.window), '_create_dsh_view', lambda self: HarnessView(self))
ui.window._open_dsh()
return ui.window._dsh_task_creation, ui.window._dsh_view
def test_cancel_native_creation_leaves_database_unchanged(ui, monkeypatch, qtbot):
controller, view = setup_controller(ui, monkeypatch)
before = len(ui.store.list_tasks())
controller.request(request())
assert controller.dialog.isVisible()
assert not controller.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
qtbot.mouseClick(controller.dialog.buttons.button(QDialogButtonBox.StandardButton.Cancel), Qt.MouseButton.LeftButton)
assert view.results[-1]['status'] == 'cancelled'
assert len(ui.store.list_tasks()) == before
def test_model_abort_closes_preview_without_task_creation(ui, monkeypatch):
controller, view = setup_controller(ui, monkeypatch)
controller.request(request())
controller.cancel({'request_id': 'a' * 32})
assert controller.dialog is None and view.results[-1]['status'] == 'cancelled'
def test_native_selection_creates_and_selects_real_task_without_executing(ui, monkeypatch, qtbot, tmp_path):
controller, view = setup_controller(ui, monkeypatch)
root = tmp_path / 'new-engineering'
root.mkdir()
path = root / 'new.prj'
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
original = path.read_bytes()
controller.request(request())
dialog = controller.dialog
qtbot.keyClicks(dialog.directory, str(root))
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: dialog._worker is None and dialog.projects.count() == 1, timeout=5000)
qtbot.mouseClick(dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: controller.worker is None and bool(view.results), timeout=5000)
assert view.results[-1]['created_count'] == 1
task_id = view.results[-1]['task_ids'][0]
assert ui.window._task_id == task_id
assert ui.store.list_rules(task_id)[0].new_part_number == 'B'
assert path.read_bytes() == original and not ui.calls
ui.settle()
def test_unknown_fields_and_busy_state_do_not_open_creation_dialog(ui, monkeypatch):
controller, view = setup_controller(ui, monkeypatch)
value = request(); value['spec']['confirmed'] = True
controller.request(value)
assert view.results[-1]['status'] == 'rejected' and controller.dialog is None
token = object(); ui.window._workers.add(token)
try:
controller.request(request('b'))
assert view.results[-1]['status'] == 'busy' and controller.dialog is None
finally:
ui.window._workers.discard(token)
def test_snapshot_publication_failure_does_not_interrupt_creation_and_latest_state_wins(qtbot, tmp_path, monkeypatch):
from types import SimpleNamespace
from PySide6.QtCore import QTimer
from dx_productivity.trial_task_center.ui import dsh_native
from dx_productivity.dsh.snapshot import TaskSnapshot
from dx_productivity.dsh.native_runtime import write_context
state = SimpleNamespace(data_root=tmp_path, _stopping=False, _pending_context=None, _context_attempts=0,
context=None, automation={}, creation={}, last_error='', context_retry=QTimer())
state._publish_pending_context = lambda: dsh_native.NativeHarnessView._publish_pending_context(state)
state.context_retry.setSingleShot(True)
state.context_retry.timeout.connect(state._publish_pending_context)
def temporarily_locked(*args, **kwargs):
raise PermissionError('temporary reader lock')
monkeypatch.setattr(dsh_native, 'write_context', temporarily_locked)
dsh_native.NativeHarnessView.bind(state, TaskSnapshot('old', 'draft'))
dsh_native.NativeHarnessView.bind(state, TaskSnapshot('new', 'draft'))
assert state.context is None and state.context_retry.isActive()
monkeypatch.setattr(dsh_native, 'write_context', write_context)
qtbot.waitUntil(lambda: state.context is not None, timeout=3000)
assert state.context['task_id'] == 'new' and state._pending_context is None