tasks.service.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import { computed, inject, Injectable, signal } from '@angular/core';
  2. import { FmodeApi } from './api/fmode-api';
  3. import { LoadState, Task, TaskStatus } from './api/models';
  4. import { LiveService } from './live.service';
  5. /**
  6. * 任务看板服务 —— 任务域的**唯一 owner**(FR-07b)
  7. *
  8. * 依据 SPEC FR-07b 的依赖声明与《数据访问层设计.md》§五:
  9. * · **一期只读**:无派发 / 评论 / 修改入口(AC-07b.6)
  10. * · 云函数接收端**未就绪**时,抽象层返回空数组 → 界面显示空态,
  11. * **禁止伪造数据**、禁止把「未接入」伪装成「没有任务」
  12. * · 双端走**同一服务**,口径一致(AC-07b.4)
  13. */
  14. @Injectable({ providedIn: 'root' })
  15. export class TasksService {
  16. private readonly api = inject(FmodeApi);
  17. private readonly live = inject(LiveService);
  18. /** 已按 agent 加载的任务缓存 */
  19. private readonly _byAgent = signal<Record<string, Task[]>>({});
  20. private readonly _state = signal<LoadState>('idle');
  21. private readonly _error = signal<string | null>(null);
  22. /** 当前选中的数字生命(任务按 agent 过滤,AC-07b.1) */
  23. readonly agentId = signal<string>('');
  24. /** 当前状态筛选 */
  25. readonly statusFilter = signal<TaskStatus | 'all'>('all');
  26. /** 当前选中任务 */
  27. readonly selectedId = signal<string | null>(null);
  28. readonly state = this._state.asReadonly();
  29. readonly error = this._error.asReadonly();
  30. /** 全部已加载任务(供事件派生用) */
  31. readonly all = computed(() => Object.values(this._byAgent()).flat());
  32. /** 当前数字生命的任务,按更新时间倒序 */
  33. readonly current = computed(() => {
  34. const list = this._byAgent()[this.agentId()] ?? [];
  35. return [...list].sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
  36. });
  37. readonly filtered = computed(() => {
  38. const f = this.statusFilter();
  39. const list = this.current();
  40. return f === 'all' ? list : list.filter((t) => t.status === f);
  41. });
  42. readonly selected = computed(() => {
  43. const id = this.selectedId();
  44. return id ? this.all().find((t) => t.id === id) : undefined;
  45. });
  46. /** 七态计数(筛选 chip 上的数字) */
  47. readonly counts = computed<Record<TaskStatus | 'all', number>>(() => {
  48. const list = this.current();
  49. const base = {
  50. all: list.length, triage: 0, todo: 0, scheduled: 0, ready: 0,
  51. running: 0, blocked: 0, done: 0,
  52. } as Record<TaskStatus | 'all', number>;
  53. for (const t of list) base[t.status] += 1;
  54. return base;
  55. });
  56. /** 阻塞任务(工作台/首页上浮用) */
  57. readonly blocked = computed(() => this.all().filter((t) => t.status === 'blocked'));
  58. /**
  59. * 强制重新拉取全部任务(手动「刷新」用);跳过缓存。
  60. * 事件派生的「执行」类事件依赖任务数据,故刷新须带上本方法。
  61. */
  62. async refresh(): Promise<void> {
  63. this._byAgent.set({});
  64. this._state.set('idle');
  65. await this.ensureAllLoaded();
  66. }
  67. /** 确保**全部**数字生命的任务已加载(事件派生需要全量) */
  68. async ensureAllLoaded(): Promise<void> {
  69. // empty 也算已加载,避免空列表反复请求
  70. if (this._state() === 'ready' || this._state() === 'empty' || this._state() === 'loading') return;
  71. this._state.set('loading');
  72. this._error.set(null);
  73. try {
  74. await this.live.ensureLoaded();
  75. const agents = this.live.agents();
  76. const results = await Promise.all(
  77. agents.map(async (a) => [a.id, await this.api.fetchTasks(a.id)] as const),
  78. );
  79. const map: Record<string, Task[]> = {};
  80. for (const [id, tasks] of results) map[id] = tasks;
  81. this._byAgent.set(map);
  82. const total = Object.values(map).flat().length;
  83. this._state.set(total === 0 ? 'empty' : 'ready');
  84. } catch (e) {
  85. this._state.set('error');
  86. this._error.set(e instanceof Error ? e.message : '任务数据加载失败');
  87. }
  88. }
  89. /** 单数字生命任务加载(进入任务看板时) */
  90. async loadFor(agentId: string): Promise<void> {
  91. this.agentId.set(agentId);
  92. if (this._byAgent()[agentId]) return;
  93. this._state.set('loading');
  94. try {
  95. const tasks = await this.api.fetchTasks(agentId);
  96. this._byAgent.update((m) => ({ ...m, [agentId]: tasks }));
  97. this._state.set(tasks.length === 0 ? 'empty' : 'ready');
  98. } catch (e) {
  99. this._state.set('error');
  100. this._error.set(e instanceof Error ? e.message : '任务数据加载失败');
  101. }
  102. }
  103. select(id: string | null): void {
  104. this.selectedId.set(id);
  105. }
  106. setStatusFilter(f: TaskStatus | 'all'): void {
  107. this.statusFilter.set(f);
  108. }
  109. selectFirstIfNeeded(): void {
  110. if (!this.selectedId() && this.filtered().length > 0) {
  111. this.selectedId.set(this.filtered()[0].id);
  112. }
  113. }
  114. }