app-workflow-mirror.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // ============================================================
  2. // TUI 侧的 workflowRuns 镜像
  3. // ============================================================
  4. // 单时钟:运行态**只**由共享 reducer 逐事件归约维护(@zcode/shared 的
  5. // workflow-runs-reducer,与 v4 投影同一份实现),外加冷启动/恢复时的一次性补种。
  6. // 没有轮询、没有 setInterval——legacy workflow 面板每秒全量重拉是反面教材。
  7. //
  8. // 镜像比协议状态键多两样东西,都是刻意的:
  9. // 1. `logTailByRunId`:log 事件**不在** workflowRuns schema 里(它们只进 journal 事件日志),
  10. // 但展开详情要显示 log 尾,所以 TUI 自己留最近若干条(有界)。
  11. // 2. `seedByRunId`:冷补种从 listDynamicWorkflowRuns 带回的**展示元信息**(label / updatedAt)。
  12. // 运行态(状态、步数、用量、resumable)**不**从摘要来:冷启动 / `/resume` 时 journal 的事件
  13. // 经 `replayWorkflowRuns` 回放进同一个 reducer(冷回放),镜像里的 run 与重启前逐字节一致;`resumable` 是状态位,由 CLI 在
  14. // run-settled 载荷上裁定——dynamic-workflow-run.port.ts 的既有裁定「渲染服务端布尔」照旧。
  15. import {
  16. reduceWorkflowRunsState,
  17. workflowRunStepCounts as sharedWorkflowRunStepCounts,
  18. type WorkflowRunActor,
  19. type WorkflowRunUsage,
  20. type WorkflowRunProgressEnvelope,
  21. type WorkflowRunState,
  22. type WorkflowRunsState,
  23. } from "@zcode/shared/zcode-protocol-v4";
  24. /** log 尾的界:条数与单条长度都限,避免一个话多的 run 把镜像吃成无界。 */
  25. const TUI_WORKFLOW_LOG_TAIL_LIMITS = {
  26. maxEntries: 10,
  27. maxEntryLength: 200,
  28. } as const;
  29. /**
  30. * 冷补种摘要里 TUI 会渲染的**展示**字段(运行态一律走回放,见文件头)。
  31. *
  32. * `label` / `updatedAt` 是 additive optional(见 spec 的 `/dwf` 边界行「实现期修订」):
  33. * 服务端还没带上时就是 undefined,渲染侧一律退回 runId,绝不在这里造一个假 label。
  34. */
  35. export type TuiWorkflowRunSeed = {
  36. runId: string;
  37. label?: string;
  38. updatedAt?: number;
  39. };
  40. export type TuiWorkflowMirror = {
  41. /** 共享 reducer 维护的权威运行态。 */
  42. state: WorkflowRunsState;
  43. logTailByRunId: Readonly<Record<string, readonly string[]>>;
  44. seedByRunId: Readonly<Record<string, TuiWorkflowRunSeed>>;
  45. };
  46. export const EMPTY_TUI_WORKFLOW_MIRROR: TuiWorkflowMirror = {
  47. state: { revision: 0, runs: [] },
  48. logTailByRunId: {},
  49. seedByRunId: {},
  50. };
  51. /**
  52. * 一条 dwf 进度事件 → 新镜像。
  53. *
  54. * **无变化时返回传入的同一个引用**,这样 React 的 setState 会直接跳过重渲染:
  55. * 共享 reducer 的「null = 语义无变化」契约在这里落成「不重绘」,不需要额外的相等判断。
  56. */
  57. export function applyWorkflowProgressToMirror(
  58. mirror: TuiWorkflowMirror,
  59. envelope: WorkflowRunProgressEnvelope,
  60. ): TuiWorkflowMirror {
  61. const state = reduceWorkflowRunsState(mirror.state, envelope);
  62. const logTailByRunId = appendWorkflowLogTail(mirror.logTailByRunId, envelope);
  63. if (state === null && logTailByRunId === mirror.logTailByRunId) return mirror;
  64. return {
  65. ...mirror,
  66. ...(state === null ? {} : { state }),
  67. logTailByRunId,
  68. };
  69. }
  70. /**
  71. * 冷补种:把 `listDynamicWorkflowRuns` 的会话级摘要里的**展示名**并进镜像。
  72. *
  73. * 只填元信息,**不**伪造运行态条目——运行态由冷回放(`replayWorkflowRuns` → 共享 reducer)
  74. * 给出,与重启前逐字节一致;摘要没有的东西(label 之外)这里一个也不造。
  75. */
  76. export function seedWorkflowMirror(
  77. mirror: TuiWorkflowMirror,
  78. seeds: readonly TuiWorkflowRunSeed[],
  79. ): TuiWorkflowMirror {
  80. if (seeds.length === 0) return mirror;
  81. const seedByRunId = { ...mirror.seedByRunId };
  82. let changed = false;
  83. for (const seed of seeds) {
  84. if (!seed.runId) continue;
  85. const existing = seedByRunId[seed.runId];
  86. if (existing && sameSeed(existing, seed)) continue;
  87. seedByRunId[seed.runId] = seed;
  88. changed = true;
  89. }
  90. return changed ? { ...mirror, seedByRunId } : mirror;
  91. }
  92. /**
  93. * 步数进度:**已结算 / 已排程**(settled / observed)。
  94. *
  95. * 动态工作流没有静态总数,所以分母是已排程节点数,绝不冒充全程百分比。
  96. *
  97. * 数法只有一处——@zcode/shared 的 `workflowRunStepCounts`(run 卡、时间线摘要与这里共用)。
  98. * 这里此前自己数 `nodes`,于是一条撞过节点界的 run 在三个读面上显示三个数字,而且三个都比
  99. * 真实步数小:触界是**拒新**,被拒的实例根本不在 `nodes` 里,只在 usage 的两个计数器上。
  100. * 本函数只保留 TUI 的字段名(卡片与 i18n 说的是 nodesSettled / nodesTotal)。
  101. */
  102. export function workflowRunStepCounts(run: WorkflowRunState): {
  103. nodesSettled: number;
  104. nodesTotal: number;
  105. } {
  106. const { total, settled } = sharedWorkflowRunStepCounts(run);
  107. return { nodesSettled: settled, nodesTotal: total };
  108. }
  109. /** 卡片渲染需要的全部事实——让视图成为 props 的纯函数(TUI 测试按函数式调用组件)。 */
  110. export type TuiWorkflowCard = {
  111. runId: string;
  112. status: WorkflowRunState["status"];
  113. /** `stopped` 的原因;reducer 从 run-settled 载荷搬运。 */
  114. stopReason?: WorkflowRunState["stopReason"];
  115. nodesSettled: number;
  116. nodesTotal: number;
  117. label?: string;
  118. resumable?: boolean;
  119. usage?: WorkflowRunUsage;
  120. actors: readonly WorkflowRunActor[];
  121. logTail: readonly string[];
  122. error?: string;
  123. resultPreview?: string;
  124. truncated?: boolean;
  125. };
  126. /**
  127. * 工具卡 → workflow run 的联接,按 `toolCallId`(schema 注释里它就是「工具卡 → 详情页的关联键」)。
  128. * 与 GUI `buildWorkflowRunByToolCallId` 同规。运行态只有一个来源——镜像状态(live 事件与
  129. * 冷回放经同一个 reducer),补种只给展示名。
  130. */
  131. export function buildTuiWorkflowCardIndex(
  132. mirror: TuiWorkflowMirror,
  133. ): ReadonlyMap<string, TuiWorkflowCard> {
  134. const byToolCallId = new Map<string, TuiWorkflowCard>();
  135. for (const run of mirror.state.runs) {
  136. // 没有 toolCallId 的 run 没有可联接的卡片,不进表。
  137. if (!run.toolCallId) continue;
  138. byToolCallId.set(run.toolCallId, cardFromRun(run, mirror));
  139. }
  140. return byToolCallId;
  141. }
  142. function cardFromRun(run: WorkflowRunState, mirror: TuiWorkflowMirror): TuiWorkflowCard {
  143. const { nodesSettled, nodesTotal } = workflowRunStepCounts(run);
  144. const seed = mirror.seedByRunId[run.runId];
  145. return {
  146. runId: run.runId,
  147. status: run.status,
  148. ...(run.stopReason === undefined ? {} : { stopReason: run.stopReason }),
  149. nodesSettled,
  150. nodesTotal,
  151. // label 只有服务端知道;投影条目不带它,命中补种就用补种的。
  152. ...(seed?.label === undefined ? {} : { label: seed.label }),
  153. // resumable 是状态位(CLI 在 run-settled 载荷上裁定,reducer 搬运),TUI 不重推导。
  154. ...(run.resumable === undefined ? {} : { resumable: run.resumable }),
  155. usage: run.usage,
  156. actors: run.actors,
  157. logTail: mirror.logTailByRunId[run.runId] ?? [],
  158. ...(run.error === undefined ? {} : { error: run.error }),
  159. ...(run.resultPreview === undefined ? {} : { resultPreview: run.resultPreview }),
  160. ...(run.truncated === undefined ? {} : { truncated: run.truncated }),
  161. };
  162. }
  163. function appendWorkflowLogTail(
  164. current: Readonly<Record<string, readonly string[]>>,
  165. envelope: WorkflowRunProgressEnvelope,
  166. ): Readonly<Record<string, readonly string[]>> {
  167. if (envelope.eventType !== "log" || !envelope.runId) return current;
  168. const message = logMessage(envelope.payload);
  169. if (message === undefined) return current;
  170. const previous = current[envelope.runId] ?? [];
  171. const appended = [...previous, message].slice(-TUI_WORKFLOW_LOG_TAIL_LIMITS.maxEntries);
  172. return { ...current, [envelope.runId]: appended };
  173. }
  174. function logMessage(payload: Record<string, unknown> | undefined): string | undefined {
  175. if (!payload) return undefined;
  176. const raw = payload.message;
  177. if (typeof raw !== "string") return undefined;
  178. const collapsed = raw.replace(/\s+/gu, " ").trim();
  179. if (collapsed.length === 0) return undefined;
  180. return collapsed.slice(0, TUI_WORKFLOW_LOG_TAIL_LIMITS.maxEntryLength);
  181. }
  182. function sameSeed(left: TuiWorkflowRunSeed, right: TuiWorkflowRunSeed): boolean {
  183. return left.label === right.label && left.updatedAt === right.updatedAt;
  184. }