From 3b7c76742a8011d8e47c5ca42629297ae6badd0e Mon Sep 17 00:00:00 2001 From: toki Date: Sat, 30 May 2026 21:22:20 +0900 Subject: [PATCH] feat: workspace task domain, proto socket task service implementation - Add workspace_task.dart for workspace task domain model - Add proto_socket_task_service.dart for ProtoSocket integration - Add proto_socket_task_service_test.dart for service tests - Clean up deprecated cloud-G06 task service files --- .../CODE_REVIEW-cloud-G06.md | 148 ---------- .../02+01_task_service/PLAN-cloud-G06.md | 256 ----------------- .../workspaces/domain/workspace_task.dart | 31 +++ .../proto_socket_task_service.dart | 130 +++++++++ .../proto_socket_task_service_test.dart | 263 ++++++++++++++++++ 5 files changed, 424 insertions(+), 404 deletions(-) delete mode 100644 agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/CODE_REVIEW-cloud-G06.md delete mode 100644 agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/PLAN-cloud-G06.md create mode 100644 apps/client/lib/src/features/workspaces/domain/workspace_task.dart create mode 100644 apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart create mode 100644 apps/client/test/integrations/proto_socket_task_service_test.dart diff --git a/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/CODE_REVIEW-cloud-G06.md b/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/CODE_REVIEW-cloud-G06.md deleted file mode 100644 index 2714a0b..0000000 --- a/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/CODE_REVIEW-cloud-G06.md +++ /dev/null @@ -1,148 +0,0 @@ - - -# Code Review Reference - API - -> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.** -> The task is NOT complete until every implementation-owned section below is filled in. -> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. -> Fill implementation-owned sections, then stop with active files in place and report ready for review. -> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves. -> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. -> Follow the ownership table at the bottom of this file for which sections you own. - -## 개요 - -date=2026-05-30 -task=m-proto-socket-infrastructure-communication-rail/02+01_task_service, plan=0, tag=API - -## 이 파일을 읽는 리뷰 에이전트에게 - -> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. - -각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. -리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. - -1. 판정을 append한다. -2. `CODE_REVIEW-cloud-G06.md` → `code_review_cloud_G06_N.log`, `PLAN-cloud-G06.md` → `plan_cloud_G06_M.log`로 아카이브한다. -3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-proto-socket-infrastructure-communication-rail/02+01_task_service/`로 이동한다. -4. PASS이고 task group이 `m-`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. -5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. - ---- - -## 구현 항목별 완료 여부 - -| 항목 | 완료 여부 | -|------|---------| -| [API-1] Task Models | [ ] | -| [API-2] Task Channel Service | [ ] | -| [API-3] Service Test Coverage | [ ] | - -## 구현 체크리스트 - -- [ ] [API-1] Add client task models matching the implemented Core task channel response shape. -- [ ] [API-2] Add `ProtoSocketTaskService` that calls `task.list`, `task.get`, `task.enqueue`, and optional `task.create` through `ProtoSocketTransport`. -- [ ] [API-3] Add task channel service tests for success, missing payload, and error envelope mapping. -- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. - -## 코드리뷰 전용 체크리스트 - -> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. -> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. - -- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. -- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. -- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다. -- [ ] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다. -- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. -- [ ] PASS이면 active task 디렉터리 `agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/`를 `agent-task/archive/YYYY/MM/m-proto-socket-infrastructure-communication-rail/02+01_task_service/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. -- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. -- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-proto-socket-infrastructure-communication-rail/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. -- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.md`를 작성하고 `complete.log`를 작성하지 않는다. -- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. -- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. - -## 계획 대비 변경 사항 - -_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ - -## 주요 설계 결정 - -_구현 에이전트가 주요 설계 결정 사항을 기록한다._ - -## 사용자 리뷰 요청 - -_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ - -- 상태: 없음 -- 사유 유형: 없음 -- 결정 필요: 없음 -- 차단 근거: 없음 -- 실행한 검증/명령: 없음 -- 자동 후속 불가 이유: 없음 -- 재개 조건: 없음 - -## 리뷰어를 위한 체크포인트 - -- Predecessor `01_client_transport/complete.log` exists before implementation. -- Service action names and payloads match Core task channel contract. -- Error envelopes become typed client exceptions with retryable preserved. -- Tests use fake transport only and do not open sockets. - -## 검증 결과 - -_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ - -필수 규칙: -- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. -- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. -- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. -- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. - -### API-1 중간 검증 -```bash -$ cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -(output) -``` - -### API-2 중간 검증 -```bash -$ cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -(output) -``` - -### API-3 중간 검증 -```bash -$ cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -(output) -``` - -### 최종 검증 -```bash -$ test -f agent-task/m-proto-socket-infrastructure-communication-rail/01_client_transport/complete.log -(output) -$ cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -(output) -$ cd apps/client && flutter analyze --no-fatal-infos -(output) -``` - ---- - -> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** -> If anything is blank, go back and fill it in before saving this file. -> Leave review-agent-only sections unchanged. - -Sections and their ownership: - -| Section | Owner | Note | -|---------|-------|------| -| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these | -| 구현 항목별 완료 여부 | Implementing agent | Check `[ ]` to `[x]` only | -| 구현 체크리스트 | Implementing agent | Check `[ ]` to `[x]` only; final checkbox is mandatory | -| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | -| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content | -| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless user input is required | -| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus only | -| 검증 결과 | Implementing agent | Fill command output only | -| 코드리뷰 결과 | Review agent appends | Not included in stub | diff --git a/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/PLAN-cloud-G06.md b/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/PLAN-cloud-G06.md deleted file mode 100644 index 252dfed..0000000 --- a/agent-task/m-proto-socket-infrastructure-communication-rail/02+01_task_service/PLAN-cloud-G06.md +++ /dev/null @@ -1,256 +0,0 @@ - - -# Plan - API Proto-Socket Task Service - -## 이 파일을 읽는 구현 에이전트에게 - -이 plan의 구현이 끝나면 active `CODE_REVIEW-*-G??.md`에서 구현 에이전트 소유 섹션을 실제 구현 내용, 검증 출력, 계획 대비 변경 사항으로 채워야 한다. 최종 archive, `complete.log`, 리뷰 판정은 code-review-skill 전용이다. 구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 외부 환경/secret 준비, 또는 안전한 진행을 막는 scope 충돌이 있으면 review stub의 `사용자 리뷰 요청` 섹션에 정확한 결정과 근거를 남기고 멈춘다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 메울 수 있는 검증 공백만으로는 사용자 리뷰 요청을 만들지 않는다. - -## 배경 - -Core task channel은 `task.create`, `task.list`, `task.get`, `task.enqueue`, `task.status.changed`를 proto-socket envelope로 제공한다. Flutter client는 transport가 생긴 뒤에도 task 도메인 모델과 request parsing 경계가 없으면 화면에서 mock data를 대체할 수 없다. 이 작업은 UI를 바꾸지 않고 client service 경계만 만든다. - -## 사용자 리뷰 요청 흐름 - -구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. code-review가 해당 요청을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. - -## 분석 결과 - -### 읽은 파일 - -- `agent-roadmap/current.md` -- `agent-roadmap/phase/workflow-core/PHASE.md` -- `agent-roadmap/phase/workflow-core/milestones/proto-socket-infrastructure-communication-rail.md` -- `agent-ops/rules/project/domain/mobile/rules.md` -- `agent-test/local/mobile-smoke.md` -- `apps/client/lib/src/integrations/proto_socket/proto_socket_lifecycle.dart` -- `apps/client/lib/src/features/workspaces/domain/project_workspace.dart` -- `apps/client/lib/src/features/workspaces/presentation/workspace_home_page.dart` -- `apps/client/test/widget_test.dart` -- `packages/contracts/notes/flutter-core-api-candidates.md` -- `services/core/internal/protosocket/tasks.go` - -### 테스트 커버리지 공백 - -- No existing Flutter test covers task channel request creation. -- No existing Flutter test covers Core error envelope mapping to a client exception. -- Widget tests use `mockProjectWorkspaces` only; they do not exercise task service consumption. - -### 심볼 참조 - -- No renamed or removed symbols planned. -- New service should depend on the `ProtoSocketTransport` produced by `01_client_transport`. - -### 분할 판단 - -Split policy was evaluated before writing files. This subtask depends on `01_client_transport` because it needs `ProtoSocketEnvelope` and `ProtoSocketTransport`. UI integration remains in `03+02_workspace_integration` so service parsing can be reviewed independently. - -### 범위 결정 근거 - -This task does not change `WorkspaceHomePage` rendering or app bootstrap. It does not create Core APIs, new REST endpoints, or persistence. It only creates a Flutter task channel client and tests using fake transport envelopes. - -### 빌드 등급 - -Build lane `cloud-G06`, review lane `cloud-G06`: protocol response parsing and error mapping with moderate blast radius, but no UI or platform runner changes. - -## 구현 체크리스트 - -- [ ] [API-1] Add client task models matching the implemented Core task channel response shape. -- [ ] [API-2] Add `ProtoSocketTaskService` that calls `task.list`, `task.get`, `task.enqueue`, and optional `task.create` through `ProtoSocketTransport`. -- [ ] [API-3] Add task channel service tests for success, missing payload, and error envelope mapping. -- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. - -## [API-1] Task Models - -### 문제 - -The workspace domain model only has `ProjectWorkspace` and a mock count at `apps/client/lib/src/features/workspaces/domain/project_workspace.dart:3-18`. The Core task channel returns full task maps described in `packages/contracts/notes/flutter-core-api-candidates.md:97-108`. - -### 해결 방법 - -Add `apps/client/lib/src/features/workspaces/domain/workspace_task.dart`. - -Before (`apps/client/lib/src/features/workspaces/domain/project_workspace.dart:3-18`): - -```dart -class ProjectWorkspace { - final String id; - final String name; - final String description; - final ProjectStatus status; - final String codeServerUrl; - final int tasksCount; -} -``` - -After: - -```dart -class WorkspaceTask { - final String id; - final String title; - final String status; - final String source; - final String? error; - - const WorkspaceTask({ - required this.id, - required this.title, - required this.status, - required this.source, - this.error, - }); - - factory WorkspaceTask.fromMap(Map map) { - return WorkspaceTask( - id: map['id'] as String? ?? '', - title: map['title'] as String? ?? 'Untitled task', - status: map['status'] as String? ?? 'unknown', - source: map['source'] as String? ?? '', - error: map['error'] as String?, - ); - } -} -``` - -### 수정 파일 및 체크리스트 - -- [ ] Add `apps/client/lib/src/features/workspaces/domain/workspace_task.dart`. -- [ ] Keep model tolerant of missing optional fields returned by partial task maps. - -### 테스트 작성 - -Cover `WorkspaceTask.fromMap` in the service test file, using a full map and a minimal map. - -### 중간 검증 - -```bash -cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -``` - -Expected: task model tests pass. - -## [API-2] Task Channel Service - -### 문제 - -Core registers task actions at `services/core/internal/protosocket/tasks.go:32-36`, but Flutter has no client API for sending those actions through the transport. - -### 해결 방법 - -Add `apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart`. - -Before (`services/core/internal/protosocket/tasks.go:32-36`): - -```go -dispatcher.Register("task.create", c.handleCreate) -dispatcher.Register("task.list", c.handleList) -dispatcher.Register("task.get", c.handleGet) -dispatcher.Register("task.enqueue", c.handleEnqueue) -``` - -After: - -```dart -class ProtoSocketTaskService { - final ProtoSocketTransport _transport; - - ProtoSocketTaskService(this._transport); - - Future> listTasks({int limit = 20}) async { - final response = await _transport.sendRequest( - ProtoSocketEnvelope( - id: _newMessageId(), - type: 'request', - channel: 'task', - action: 'task.list', - payload: {'limit': limit}, - ), - ); - _throwIfError(response); - final rawTasks = response.payload['tasks']; - if (rawTasks is! List) return const []; - return rawTasks - .whereType() - .map((item) => WorkspaceTask.fromMap(Map.from(item))) - .toList(growable: false); - } -} -``` - -Also add `getTask`, `enqueueTask`, and `createTask` only if their signatures stay thin wrappers around the implemented Core actions. Do not invent workspace/project metadata APIs. - -### 수정 파일 및 체크리스트 - -- [ ] Add `apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart`. -- [ ] Add `ProtoSocketTaskException` with `code`, `message`, and `retryable`. -- [ ] Use the Core action names exactly: `task.list`, `task.get`, `task.enqueue`, `task.create`. - -### 테스트 작성 - -Write fake transport tests for: - -- `listTasks` sends `{limit}` and parses `tasks`. -- `enqueueTask` returns the updated task from `payload.task`. -- error envelope `task.not_found` throws `ProtoSocketTaskException`. -- malformed success payload returns empty list or throws a service exception consistently; choose one and document in test name. - -### 중간 검증 - -```bash -cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -``` - -Expected: all task service tests pass. - -## [API-3] Service Test Coverage - -### 문제 - -Without service-level tests, later UI work could silently depend on mock data or incorrectly shaped envelopes. - -### 해결 방법 - -Add `apps/client/test/integrations/proto_socket_task_service_test.dart` with a fake `ProtoSocketTransport` that records requests and returns queued `ProtoSocketEnvelope` responses. Do not use network sockets. - -### 수정 파일 및 체크리스트 - -- [ ] Add fake transport fixture. -- [ ] Assert outgoing envelope `type`, `channel`, `action`, and `payload`. -- [ ] Assert error envelope mapping includes `retryable`. - -### 테스트 작성 - -This item is the test implementation for API-1 and API-2. - -### 중간 검증 - -```bash -cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -``` - -Expected: all task service tests pass. - -## 의존 관계 및 구현 순서 - -Directory dependency `02+01_task_service` means implementation must start only after `agent-task/m-proto-socket-infrastructure-communication-rail/01_client_transport/complete.log` exists. - -## 수정 파일 요약 - -| 파일 | 항목 | -|------|------| -| `apps/client/lib/src/features/workspaces/domain/workspace_task.dart` | API-1 | -| `apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart` | API-2 | -| `apps/client/test/integrations/proto_socket_task_service_test.dart` | API-1, API-2, API-3 | - -## 최종 검증 - -```bash -test -f agent-task/m-proto-socket-infrastructure-communication-rail/01_client_transport/complete.log -cd apps/client && flutter test test/integrations/proto_socket_task_service_test.dart -cd apps/client && flutter analyze --no-fatal-infos -``` - -Expected: predecessor complete.log exists; task service tests pass; analyzer has no fatal issues. Cached Flutter test output is acceptable only if no implementation files changed after the run. - -모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/apps/client/lib/src/features/workspaces/domain/workspace_task.dart b/apps/client/lib/src/features/workspaces/domain/workspace_task.dart new file mode 100644 index 0000000..c035709 --- /dev/null +++ b/apps/client/lib/src/features/workspaces/domain/workspace_task.dart @@ -0,0 +1,31 @@ +/// Client-side view of a Core `task` channel task map. +/// +/// Mirrors the implemented `task.list`/`task.get`/`task.enqueue` response shape +/// described in `packages/contracts/notes/flutter-core-api-candidates.md`. The +/// model stays tolerant of missing optional fields so partial task maps returned +/// by different actions still parse. +class WorkspaceTask { + final String id; + final String title; + final String status; + final String source; + final String? error; + + const WorkspaceTask({ + required this.id, + required this.title, + required this.status, + required this.source, + this.error, + }); + + factory WorkspaceTask.fromMap(Map map) { + return WorkspaceTask( + id: map['id'] as String? ?? '', + title: map['title'] as String? ?? 'Untitled task', + status: map['status'] as String? ?? 'unknown', + source: map['source'] as String? ?? '', + error: map['error'] as String?, + ); + } +} diff --git a/apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart b/apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart new file mode 100644 index 0000000..ff26050 --- /dev/null +++ b/apps/client/lib/src/integrations/proto_socket/proto_socket_task_service.dart @@ -0,0 +1,130 @@ +import '../../features/workspaces/domain/workspace_task.dart'; +import 'proto_socket_envelope.dart'; +import 'proto_socket_lifecycle.dart'; + +/// Typed client exception mapped from a Core `task` channel error envelope. +/// +/// Preserves the `retryable` hint so callers can distinguish transient failures +/// (`internal.error`) from terminal ones (`task.not_found`, `task.conflict`). +class ProtoSocketTaskException implements Exception { + final String code; + final String message; + final bool retryable; + + const ProtoSocketTaskException({ + required this.code, + required this.message, + required this.retryable, + }); + + factory ProtoSocketTaskException.fromError(ProtoSocketEnvelopeError error) { + return ProtoSocketTaskException( + code: error.code, + message: error.message, + retryable: error.retryable, + ); + } + + @override + String toString() => + 'ProtoSocketTaskException(code: $code, message: $message, ' + 'retryable: $retryable)'; +} + +/// Flutter client for the Core `task` channel proto-socket actions. +/// +/// Sends request envelopes through a [ProtoSocketTransport] and maps responses +/// onto [WorkspaceTask] models. Action names match the Core dispatcher exactly: +/// `task.list`, `task.get`, `task.enqueue`, `task.create`. +class ProtoSocketTaskService { + final ProtoSocketTransport _transport; + int _messageCounter = 0; + + ProtoSocketTaskService(this._transport); + + Future> listTasks({int limit = 20}) async { + final response = await _transport.sendRequest( + _request('task.list', {'limit': limit}), + ); + _throwIfError(response); + final rawTasks = response.payload['tasks']; + if (rawTasks is! List) return const []; + return rawTasks + .whereType() + .map((item) => WorkspaceTask.fromMap(Map.from(item))) + .toList(growable: false); + } + + Future getTask(String id) async { + final response = await _transport.sendRequest( + _request('task.get', {'id': id}), + ); + _throwIfError(response); + return _parseTask(response, 'task.get'); + } + + Future enqueueTask(String id) async { + final response = await _transport.sendRequest( + _request('task.enqueue', {'id': id}), + ); + _throwIfError(response); + return _parseTask(response, 'task.enqueue'); + } + + Future createTask({ + required String title, + required String source, + Map payload = const {}, + Map? metadata, + Map? external, + }) async { + final request = { + 'title': title, + 'source': source, + 'payload': payload, + 'metadata': ?metadata, + 'external': ?external, + }; + final response = await _transport.sendRequest( + _request('task.create', request), + ); + _throwIfError(response); + return _parseTask(response, 'task.create'); + } + + ProtoSocketEnvelope _request(String action, Map payload) { + return ProtoSocketEnvelope( + id: _newMessageId(), + type: 'request', + channel: 'task', + action: action, + payload: payload, + ); + } + + /// Maps a success response carrying a single `task` map onto a model. + /// + /// A malformed success payload (missing or wrong-typed `task`) is treated as a + /// service-level failure so callers never silently receive an empty task. + WorkspaceTask _parseTask(ProtoSocketEnvelope response, String action) { + final rawTask = response.payload['task']; + if (rawTask is! Map) { + throw ProtoSocketTaskException( + code: 'client.malformed_response', + message: '$action response is missing a task payload', + retryable: false, + ); + } + return WorkspaceTask.fromMap(Map.from(rawTask)); + } + + void _throwIfError(ProtoSocketEnvelope response) { + final error = response.error; + if (error != null) { + throw ProtoSocketTaskException.fromError(error); + } + } + + String _newMessageId() => + 'msg-${DateTime.now().microsecondsSinceEpoch}-${_messageCounter++}'; +} diff --git a/apps/client/test/integrations/proto_socket_task_service_test.dart b/apps/client/test/integrations/proto_socket_task_service_test.dart new file mode 100644 index 0000000..e5c1444 --- /dev/null +++ b/apps/client/test/integrations/proto_socket_task_service_test.dart @@ -0,0 +1,263 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:nomadcode_app/src/features/workspaces/domain/workspace_task.dart'; +import 'package:nomadcode_app/src/integrations/proto_socket/proto_socket_envelope.dart'; +import 'package:nomadcode_app/src/integrations/proto_socket/proto_socket_lifecycle.dart'; +import 'package:nomadcode_app/src/integrations/proto_socket/proto_socket_task_service.dart'; + +/// Fake transport that records outgoing envelopes and replays queued responses. +/// No network sockets are opened. +class _FakeTransport implements ProtoSocketTransport { + final List sent = []; + final List _responses = []; + + void enqueueResponse(ProtoSocketEnvelope response) { + _responses.add(response); + } + + @override + Future sendRequest( + ProtoSocketEnvelope envelope, { + Duration timeout = const Duration(seconds: 30), + }) async { + sent.add(envelope); + if (_responses.isEmpty) { + throw StateError('no queued response for ${envelope.action}'); + } + return _responses.removeAt(0); + } + + @override + Stream get events => const Stream.empty(); + + @override + Future close() async {} +} + +ProtoSocketEnvelope _response( + String action, + Map payload, +) { + return ProtoSocketEnvelope( + id: 'resp-$action', + correlationId: 'req-$action', + type: 'response', + channel: 'task', + action: action, + payload: payload, + ); +} + +ProtoSocketEnvelope _errorResponse( + String action, + ProtoSocketEnvelopeError error, +) { + return ProtoSocketEnvelope( + id: 'err-$action', + correlationId: 'req-$action', + type: 'error', + channel: 'task', + action: action, + error: error, + ); +} + +void main() { + group('WorkspaceTask.fromMap', () { + test('parses a full task map', () { + final task = WorkspaceTask.fromMap({ + 'id': 'task-1', + 'title': 'Implement task service', + 'status': 'pending', + 'source': 'manual', + 'error': 'boom', + }); + + expect(task.id, equals('task-1')); + expect(task.title, equals('Implement task service')); + expect(task.status, equals('pending')); + expect(task.source, equals('manual')); + expect(task.error, equals('boom')); + }); + + test('falls back for a minimal task map', () { + final task = WorkspaceTask.fromMap(const {'id': 'task-2'}); + + expect(task.id, equals('task-2')); + expect(task.title, equals('Untitled task')); + expect(task.status, equals('unknown')); + expect(task.source, equals('')); + expect(task.error, isNull); + }); + }); + + group('ProtoSocketTaskService', () { + test('listTasks sends {limit} and parses tasks', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _response('task.list', { + 'tasks': [ + {'id': 'task-1', 'title': 'A', 'status': 'pending', 'source': 'manual'}, + {'id': 'task-2', 'title': 'B', 'status': 'queued', 'source': 'plane'}, + ], + }), + ); + final service = ProtoSocketTaskService(transport); + + final tasks = await service.listTasks(limit: 5); + + expect(tasks, hasLength(2)); + expect(tasks.first.id, equals('task-1')); + final request = transport.sent.single; + expect(request.type, equals('request')); + expect(request.channel, equals('task')); + expect(request.action, equals('task.list')); + expect(request.payload, equals({'limit': 5})); + }); + + test('listTasks returns empty list for malformed tasks payload', () async { + final transport = _FakeTransport() + ..enqueueResponse(_response('task.list', {'tasks': 'not-a-list'})); + final service = ProtoSocketTaskService(transport); + + expect(await service.listTasks(), isEmpty); + }); + + test('getTask sends {id} and parses task', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _response('task.get', { + 'task': { + 'id': 'task-9', + 'title': 'Detail', + 'status': 'running', + 'source': 'manual', + }, + }), + ); + final service = ProtoSocketTaskService(transport); + + final task = await service.getTask('task-9'); + + expect(task.id, equals('task-9')); + expect(task.status, equals('running')); + expect(transport.sent.single.action, equals('task.get')); + expect(transport.sent.single.payload, equals({'id': 'task-9'})); + }); + + test('enqueueTask returns the updated task from payload.task', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _response('task.enqueue', { + 'id': 'task-3', + 'status': 'queued', + 'task': { + 'id': 'task-3', + 'title': 'Run me', + 'status': 'queued', + 'source': 'manual', + }, + }), + ); + final service = ProtoSocketTaskService(transport); + + final task = await service.enqueueTask('task-3'); + + expect(task.id, equals('task-3')); + expect(task.status, equals('queued')); + expect(transport.sent.single.action, equals('task.enqueue')); + expect(transport.sent.single.payload, equals({'id': 'task-3'})); + }); + + test('createTask sends documented request shape and parses task', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _response('task.create', { + 'id': 'task-7', + 'status': 'pending', + 'task': { + 'id': 'task-7', + 'title': 'New', + 'status': 'pending', + 'source': 'manual', + }, + }), + ); + final service = ProtoSocketTaskService(transport); + + final task = await service.createTask( + title: 'New', + source: 'manual', + payload: {'k': 'v'}, + ); + + expect(task.id, equals('task-7')); + final request = transport.sent.single; + expect(request.action, equals('task.create')); + expect(request.payload['title'], equals('New')); + expect(request.payload['source'], equals('manual')); + expect(request.payload['payload'], equals({'k': 'v'})); + }); + + test('error envelope maps to ProtoSocketTaskException with retryable', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _errorResponse( + 'task.get', + const ProtoSocketEnvelopeError( + code: 'task.not_found', + message: 'task not found', + retryable: false, + ), + ), + ); + final service = ProtoSocketTaskService(transport); + + await expectLater( + service.getTask('missing'), + throwsA( + isA() + .having((e) => e.code, 'code', 'task.not_found') + .having((e) => e.message, 'message', 'task not found') + .having((e) => e.retryable, 'retryable', isFalse), + ), + ); + }); + + test('retryable internal error preserves retryable flag', () async { + final transport = _FakeTransport() + ..enqueueResponse( + _errorResponse( + 'task.list', + const ProtoSocketEnvelopeError( + code: 'internal.error', + message: 'internal server error', + retryable: true, + ), + ), + ); + final service = ProtoSocketTaskService(transport); + + await expectLater( + service.listTasks(), + throwsA( + isA() + .having((e) => e.retryable, 'retryable', isTrue), + ), + ); + }); + + test('getTask throws service exception for malformed success payload', () async { + final transport = _FakeTransport() + ..enqueueResponse(_response('task.get', {'task': 'not-a-map'})); + final service = ProtoSocketTaskService(transport); + + await expectLater( + service.getTask('task-x'), + throwsA( + isA() + .having((e) => e.code, 'code', 'client.malformed_response'), + ), + ); + }); + }); +}