sessions-index-workflow-activity.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // ============================================================
  2. // sessions-index 的工作流运行摘要
  3. // ============================================================
  4. // 侧栏要在会话标题下画一条「Workflow 图标 + 迷你轨道灯 + 当前 phase 名」,却不能为此订阅整个
  5. // workflowRuns(那是 conversation 权威投影,按 run 进度高频变化)。这里把同一 snapshot 的
  6. // `workflowRuns` + `backgroundWorks` 派生成一份**有界、只装侧栏真正读的字段**的摘要:
  7. // 纯函数、无时钟——「已结束的行何时折叠」由渲染端的已确认集合决定,不在这里记时间。
  8. import { z } from "zod";
  9. import { timestampSchema } from "./core.js";
  10. import type { BackgroundWorkSummary } from "./snapshot.js";
  11. import {
  12. WORKFLOW_RUNS_LIMITS,
  13. workflowRunSchema,
  14. type WorkflowRunNode,
  15. type WorkflowRunState,
  16. type WorkflowRunsState,
  17. } from "./workflow-runs.js";
  18. /** 每会话最多下发的 run 数:在跑的按启动序在前,其后是最近结束的。 */
  19. export const SESSION_WORKFLOW_ACTIVITY_MAX_RUNS = 4;
  20. /**
  21. * 站点灯的四态,与卡片时间线同一词汇(`STATUS_DOT`)。控制流给出骨架:在跑时当前 phase
  22. * running、已进入 done、其余 pending;completed 已进入 done;errored 当前 failed;stopped 当前 pending。
  23. *
  24. * 成员节点再补一条:run 在跑时,
  25. * **出生在这一站**且此刻真在跑的节点把它点亮。并行阶段因此能同时烧——控制流只记得最后一个标记,
  26. * 而 A 的子代理在 B 的标记之后仍在干活。节点只会说「还在跑」,绝不把 done / failed / pending
  27. * 改成别的:失败词留给控制流。
  28. */
  29. export const sessionWorkflowPhaseStatusSchema = z.enum(["pending", "running", "done", "failed"]);
  30. export type SessionWorkflowPhaseStatus = z.infer<typeof sessionWorkflowPhaseStatusSchema>;
  31. export const sessionWorkflowPhaseSummarySchema = z.object({
  32. name: z.string().min(1).max(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength),
  33. status: sessionWorkflowPhaseStatusSchema,
  34. /**
  35. * 进入本站时仍在跑的其他站的**下标**(下标落在本 `phases` 数组上),来自
  36. * `run.phaseAlongside`。侧栏据此把并行的两站之间画成双线段。只有声明表那条路有这个事实——
  37. * 退化路(已进入的 phase)是按进入序拼出来的,没有并行可言,所以那时整个键缺席。
  38. */
  39. alongside: z.array(z.number().int().nonnegative()).max(WORKFLOW_RUNS_LIMITS.maxPhases).optional(),
  40. /**
  41. * 这一站是一处**还开着的留白**(docs/dynamic-workflow/presentation.md「Holes on the timeline」):
  42. * `open` = 还没走到,`waiting` = run 停在这里等主代理补全。侧栏据此把灯画成虚线(等待时警示色)。
  43. * 补全之后它就是一个普通的站,键缺席。只有声明表那条路有这个事实(`run.phaseHoles`)。
  44. */
  45. hole: z.enum(["open", "waiting"]).optional(),
  46. });
  47. export type SessionWorkflowPhaseSummary = z.infer<typeof sessionWorkflowPhaseSummarySchema>;
  48. export const sessionWorkflowRunSummarySchema = z.object({
  49. runId: z.string().min(1),
  50. /** 发起行的工具调用 id:点击运行行打开 run pane 的键;直接启动的 run 也有(`launch-` 前缀)。 */
  51. toolCallId: z.string().min(1).optional(),
  52. /** 工作流后台工作的标题(= run 的展示名);投影里没有对应后台工作时缺席。 */
  53. name: z.string().min(1).optional(),
  54. status: workflowRunSchema.shape.status,
  55. stopReason: workflowRunSchema.shape.stopReason,
  56. /** 后台工作的开始时刻,tooltip 的 elapsed 用;没有后台工作时缺席。 */
  57. startedAt: timestampSchema.optional(),
  58. /**
  59. * 站点表,声明序:`run.phaseNames`(run-launched 带来的声明表)在场用它,否则退化为已进入的
  60. * phase + 当前 phase(进入序)。两者都没有时为空数组,UI 画一个隐含站点「Workflow」。
  61. */
  62. phases: z.array(sessionWorkflowPhaseSummarySchema).max(WORKFLOW_RUNS_LIMITS.maxPhases),
  63. currentPhase: z.string().min(1).max(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength).optional(),
  64. /** status === "running" 的子代理数(tooltip 的「{n} agents working」)。 */
  65. agentsWorking: z.number().int().nonnegative(),
  66. /**
  67. * 正在等主代理补全的留白名(`run.holes` 里第一条 waiting 的 `name`):侧栏运行行写
  68. * 「{name} · 等待补全」(docs/dynamic-workflow/presentation.md「Holes on the timeline」的「The sidebar」)。
  69. * 没有停驻的留白时缺席。
  70. */
  71. waitingHole: z.string().min(1).max(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength).optional(),
  72. });
  73. export type SessionWorkflowRunSummary = z.infer<typeof sessionWorkflowRunSummarySchema>;
  74. export const sessionWorkflowActivitySchema = z.object({
  75. runs: z.array(sessionWorkflowRunSummarySchema).max(SESSION_WORKFLOW_ACTIVITY_MAX_RUNS),
  76. });
  77. export type SessionWorkflowActivity = z.infer<typeof sessionWorkflowActivitySchema>;
  78. export function isSessionWorkflowRunLive(status: SessionWorkflowRunSummary["status"]): boolean {
  79. return status === "pending" || status === "running";
  80. }
  81. /**
  82. * 「这个节点此刻真在跑」:与 packages/ui 的 `statusOfRunNode` 的 running 臂逐条相同,也与
  83. * reducer 推 actor 三态用的那一组相同(workflow-runs-reducer.ts),所以站点灯与
  84. * 「{n} agents working」永远对同一件事说「在跑」。
  85. *
  86. * `dispatched` / `waiting` 不算:前者是「会话就绪、首个请求尚未准入」的短暂相位,后者在等槽位
  87. * 或在退避——真正发出去了由 `node-executing` 说。
  88. */
  89. function isRunNodeRunning(node: WorkflowRunNode): boolean {
  90. return node.phase === "executing" || node.phase === "repairing" || node.phase === "nudged";
  91. }
  92. /**
  93. * 站名 ↔ 实例出生戳的关联规则。与 packages/ui 的 `phaseNameMatches`(workflow-graph/phase-name.ts)
  94. * 逐条相同:精确匹配,站名**恰好顶到上界**时才按前缀兜底——前缀只在截断真的发生过时才开,
  95. * 否则「计划」会误认「计划修复」。那个 helper 在 ui 层,shared 不能反向依赖,所以这里内联同一条规则。
  96. */
  97. function phaseNameMatches(stationName: string, stamp: string): boolean {
  98. return (
  99. stationName === stamp ||
  100. (stationName.length >= WORKFLOW_RUNS_LIMITS.maxPhaseNameLength && stamp.startsWith(stationName))
  101. );
  102. }
  103. /**
  104. * 站点表的唯一推导。侧栏运行行(经 `summarizeRun`)与任务岛的 run 行都读它,所以两处的灯
  105. * 永远对同一件事说同一句话;任务岛不另写第二套。
  106. */
  107. export function deriveSessionWorkflowPhases(run: WorkflowRunState): SessionWorkflowPhaseSummary[] {
  108. const entered = new Set((run.phases ?? []).map((phase) => phase.name));
  109. const current = run.currentPhase;
  110. let names: string[];
  111. // 「同时在跑」的下标说的是**声明表**里的位置,所以只有走声明表这条路时它才有意义;退化路
  112. // (已进入的 phase + 当前 phase)是另一个下标空间,那时整张表不带。
  113. let alongside: readonly (readonly number[])[] | undefined;
  114. // 还开着的留白(声明表的下标);等待中的按名字从 `run.holes` 认——留白名按规则 9012 唯一。
  115. let holeIndexes: ReadonlySet<number> = new Set();
  116. const waitingNames = new Set(
  117. (run.holes ?? []).filter((hole) => hole.state === "waiting").map((hole) => hole.name),
  118. );
  119. if (run.phaseNames !== undefined && run.phaseNames.length > 0) {
  120. names = run.phaseNames;
  121. alongside = run.phaseAlongside;
  122. holeIndexes = new Set(run.phaseHoles ?? []);
  123. } else {
  124. names = (run.phases ?? []).map((phase) => phase.name);
  125. if (current !== undefined && !entered.has(current)) names = [...names, current];
  126. }
  127. const live = isSessionWorkflowRunLive(run.status);
  128. // 在跑的节点的出生戳。run 不在跑时整张表为空:终态 run 里没有人还在干活,哪怕某条 settled
  129. // 事件没来得及落下(与 actor 三态里「终态压过一切」同一姿态)。
  130. const burning = live
  131. ? run.nodes.filter(isRunNodeRunning).flatMap((node) => node.phaseName ?? [])
  132. : [];
  133. const emitted = Math.min(names.length, WORKFLOW_RUNS_LIMITS.maxPhases);
  134. return names.slice(0, WORKFLOW_RUNS_LIMITS.maxPhases).map((name, index) => {
  135. const isCurrent = name === current;
  136. const wasEntered = entered.has(name) || isCurrent;
  137. // 出生在这一站的节点还在跑 → 这一站还在烧,哪怕控制流早已走到下一个标记。
  138. const burningHere = burning.some((stamp) => phaseNameMatches(name, stamp));
  139. let status: SessionWorkflowPhaseStatus;
  140. if (live) {
  141. status = isCurrent || burningHere ? "running" : wasEntered ? "done" : "pending";
  142. } else if (run.status === "completed") {
  143. status = wasEntered ? "done" : "pending";
  144. } else if (run.status === "errored") {
  145. status = isCurrent ? "failed" : wasEntered ? "done" : "pending";
  146. } else {
  147. // stopped:控制流停在当前 phase,它没有完成也没有失败——留空心灯。
  148. status = isCurrent ? "pending" : wasEntered ? "done" : "pending";
  149. }
  150. // 裁表之后下标空间跟着变窄:指向被裁掉的站的引用一起丢掉,剩下空的就不建键。
  151. const beside = (alongside?.[index] ?? []).filter(
  152. (other) => Number.isInteger(other) && other >= 0 && other < emitted && other !== index,
  153. );
  154. // 留白站:等待中的按 `run.holes` 认(名字唯一),其余下标表点名的是还没走到的留白。
  155. const hole = waitingNames.has(name) ? "waiting" : holeIndexes.has(index) ? "open" : undefined;
  156. return {
  157. name,
  158. status,
  159. ...(beside.length === 0 ? {} : { alongside: beside }),
  160. ...(hole === undefined ? {} : { hole }),
  161. };
  162. });
  163. }
  164. function summarizeRun(
  165. run: WorkflowRunState,
  166. work: BackgroundWorkSummary | undefined,
  167. ): SessionWorkflowRunSummary {
  168. const name = work?.title.trim();
  169. // 在跑的 run 才有「等补全」可言:终态 run 的 waiting 记录已被 reducer 剥掉,这里再守一道。
  170. const waitingHole = isSessionWorkflowRunLive(run.status)
  171. ? (run.holes ?? []).find((hole) => hole.state === "waiting")?.name
  172. : undefined;
  173. return {
  174. runId: run.runId,
  175. ...(run.toolCallId === undefined ? {} : { toolCallId: run.toolCallId }),
  176. ...(name === undefined || name.length === 0 ? {} : { name }),
  177. status: run.status,
  178. ...(run.stopReason === undefined ? {} : { stopReason: run.stopReason }),
  179. ...(work === undefined ? {} : { startedAt: work.startedAt }),
  180. phases: deriveSessionWorkflowPhases(run),
  181. ...(run.currentPhase === undefined ? {} : { currentPhase: run.currentPhase }),
  182. agentsWorking: run.actors.filter((actor) => actor.status === "running").length,
  183. ...(waitingHole === undefined ? {} : { waitingHole }),
  184. };
  185. }
  186. /**
  187. * 从同一 snapshot 的 `workflowRuns` + `backgroundWorks` 派生会话的工作流运行摘要。
  188. * 在跑的 run(pending / running)按 `runs[]` 序(= 启动序)在前;其后是已结束的,按后台工作的
  189. * `endedAt` 倒序、无 endedAt 时按 `runs[]` 倒序(越晚建的越新)。总数裁到 4。
  190. * 会话一个 run 都没有 → `undefined`(键整个缺席,旧 CLI 因此什么都不变)。
  191. */
  192. export function deriveSessionWorkflowActivity(input: {
  193. workflowRuns: WorkflowRunsState | undefined;
  194. backgroundWorks: readonly BackgroundWorkSummary[];
  195. }): SessionWorkflowActivity | undefined {
  196. const runs = input.workflowRuns?.runs;
  197. if (runs === undefined || runs.length === 0) return undefined;
  198. const workByRunId = new Map<string, BackgroundWorkSummary>();
  199. for (const work of input.backgroundWorks) {
  200. if (work.kind === "workflow") workByRunId.set(work.workId, work);
  201. }
  202. const live: SessionWorkflowRunSummary[] = [];
  203. const settled: { summary: SessionWorkflowRunSummary; endedAt: number; index: number }[] = [];
  204. runs.forEach((run, index) => {
  205. const work = workByRunId.get(run.runId);
  206. const summary = summarizeRun(run, work);
  207. if (isSessionWorkflowRunLive(run.status)) live.push(summary);
  208. else settled.push({ summary, endedAt: work?.endedAt ?? 0, index });
  209. });
  210. settled.sort((a, b) => b.endedAt - a.endedAt || b.index - a.index);
  211. return {
  212. runs: [...live, ...settled.map((entry) => entry.summary)].slice(
  213. 0,
  214. SESSION_WORKFLOW_ACTIVITY_MAX_RUNS,
  215. ),
  216. };
  217. }