conversationStatusPanelModel.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import type { GitRepositorySummary } from "@zcode/shared";
  2. import type {
  3. BackgroundWorkSummary,
  4. GoalState,
  5. PlanState,
  6. RunningSubagentSummary,
  7. ToolCallRow,
  8. WorkflowRunState,
  9. } from "@zcode/shared/zcode-protocol-v4";
  10. import type { SessionWorkflowPhaseSummary } from "@zcode/shared/zcode-protocol-v4";
  11. import {
  12. deriveSessionWorkflowPhases,
  13. workflowRunStepCounts,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import { extractPlanToolCallContent, getPlanDirectoryTitle } from "@/lib/planToolCall.js";
  16. import { workflowRunParallelPhaseLabel } from "@/lib/workflowRunLine.js";
  17. export interface ConversationStatusPanelGitModel {
  18. branchName: string | null;
  19. headRefType: GitRepositorySummary["headRefType"];
  20. dirtyFileCount: number;
  21. added: number;
  22. removed: number;
  23. ahead: number;
  24. behind: number;
  25. isClean: boolean;
  26. }
  27. export interface ConversationStatusPanelPlanModel {
  28. items: PlanState["items"];
  29. displayItems: PlanState["items"];
  30. completedCount: number;
  31. waitingCount: number;
  32. totalCount: number;
  33. }
  34. export interface ConversationStatusPanelSessionPlanItem {
  35. rowId: number;
  36. toolCallId: string;
  37. markdown: string;
  38. title?: string;
  39. planFilePath?: string;
  40. }
  41. export interface ConversationStatusPanelSessionPlansModel {
  42. items: ConversationStatusPanelSessionPlanItem[];
  43. }
  44. export interface ConversationStatusPanelRunningSubagent extends RunningSubagentSummary {
  45. controlWorkId?: string;
  46. cancellable?: boolean;
  47. }
  48. /**
  49. * Workflows 分区的一行。
  50. *
  51. * 字段成三簇,因为三种事实各自可以缺席:`status` / `nodesSettled` / `nodesTotal` 来自
  52. * `workflowRuns` 投影;`title` / `startedAt` 是后台任务的静态元数据;`workId` /
  53. * `cancellable` 是 Stop 的前提,只在后台任务仍 running 时出现。**缺席用字段不存在表达,
  54. * 而不是 0 或空串**——渲染层据此决定这行有没有状态词/步数、有没有时长、能不能停,一个假
  55. * 的 0/0 会显示成「一步都没跑」。分簇的理由见 `buildRunningWorkflowRuns`。
  56. */
  57. export interface ConversationStatusPanelWorkflowRun {
  58. /** 身份与 React key;偏斜降级行用 workId 顶替(两者本就 ≡)。 */
  59. runId: string;
  60. /** 缺席即该行不可点(没有可开的详情页 tab),与投影里 run 无 toolCallId 同义。 */
  61. toolCallId?: string;
  62. /** 有 run 支撑才有状态词;降级行没有。 */
  63. status?: "pending" | "running";
  64. nodesSettled?: number;
  65. nodesTotal?: number;
  66. /**
  67. * 站点表(声明序)与当前站,与侧栏运行行同一条推导(shared 的 `deriveSessionWorkflowPhases`)。
  68. * 与 `status` 同簇:有 run 支撑才有;降级行没有。空数组 = 脚本没声明阶段。
  69. */
  70. phases?: SessionWorkflowPhaseSummary[];
  71. currentPhase?: string;
  72. /**
  73. * 展示名。**`title ≡ workId` 即「未命名」**,渲染层据此换成 i18n 兜底名:core 的
  74. * `workflowTaskSubject` 兜底链最终落到 taskId(≡ runId ≡ workId),而投影把非空
  75. * description 原样抄进 title——所以「题名恰好等于 id」是唯一可靠的未命名信号。
  76. * 模型不做这个替换(i18n 不属于模型层),只保证 title 原样透出。
  77. */
  78. title?: string;
  79. startedAt?: number;
  80. /** 停止按钮要的控制句柄;只在 work 仍 running 时出现(已结束的 work 没有可取消的东西)。 */
  81. workId?: string;
  82. cancellable?: boolean;
  83. }
  84. /**
  85. * 「打开哪个 run 的详情页」的意图。会话与 workspace 身份由宿主补齐,面板不感知 scope
  86. * (与工具卡走同一个 handler,不存在第二条打开路径)。
  87. *
  88. * 住在模型文件而不是组件里:composer 徽标的直达判定(`resolveSoleRunningWorkflowRunTarget`)
  89. * 与面板行产出同一形状,组件层从模型取类型,不反向依赖。
  90. */
  91. export interface ConversationStatusPanelWorkflowRunTarget {
  92. runId: string;
  93. toolCallId: string;
  94. workflowName?: string;
  95. }
  96. /**
  97. * 面板行 → 打开意图。无 `toolCallId` 即 null(没有可开的详情页 tab)。名字只在真有时带上:
  98. * `title ≡ runId` 是未命名 run 的兜底样子(core 的 workflowTaskSubject 落到 taskId),把 runId
  99. * 冻进 tab 标签比通用兜底名更糟。面板行与 composer 徽标直达共用这一处换算。
  100. */
  101. export function workflowRunOpenTarget(
  102. run: ConversationStatusPanelWorkflowRun,
  103. ): ConversationStatusPanelWorkflowRunTarget | null {
  104. if (!run.toolCallId) return null;
  105. return {
  106. runId: run.runId,
  107. toolCallId: run.toolCallId,
  108. ...(run.title && run.title !== run.runId ? { workflowName: run.title } : {}),
  109. };
  110. }
  111. export interface ConversationStatusPanelModel {
  112. hasContent: boolean;
  113. git: ConversationStatusPanelGitModel | null;
  114. goal: GoalState | null;
  115. sessionPlans: ConversationStatusPanelSessionPlansModel | null;
  116. plan: ConversationStatusPanelPlanModel | null;
  117. runningBashWorks: BackgroundWorkSummary[];
  118. runningSubagentWorks: ConversationStatusPanelRunningSubagent[];
  119. runningWorkflowRuns: ConversationStatusPanelWorkflowRun[];
  120. }
  121. export interface BuildConversationStatusPanelModelInput {
  122. isOfficeMode?: boolean;
  123. gitSummary?: GitRepositorySummary | null;
  124. gitDirtyFileCount?: number;
  125. gitWorktreeChangeSummary?: { added: number; removed: number } | null;
  126. goal?: GoalState | null;
  127. sessionPlans?: readonly ToolCallRow[];
  128. workspacePath?: string;
  129. plan?: PlanState | null;
  130. backgroundWorks?: readonly BackgroundWorkSummary[];
  131. runningSubagents?: readonly RunningSubagentSummary[];
  132. workflowRuns?: readonly WorkflowRunState[];
  133. }
  134. function buildGitModel({
  135. gitSummary,
  136. gitDirtyFileCount = 0,
  137. gitWorktreeChangeSummary,
  138. }: Pick<
  139. BuildConversationStatusPanelModelInput,
  140. "gitSummary" | "gitDirtyFileCount" | "gitWorktreeChangeSummary"
  141. >): ConversationStatusPanelGitModel | null {
  142. if (!gitSummary?.isGitAvailable || !gitSummary.isRepository) {
  143. return null;
  144. }
  145. const added = gitWorktreeChangeSummary?.added ?? 0;
  146. const removed = gitWorktreeChangeSummary?.removed ?? 0;
  147. // v4 之前只要是 Git repository 就创建 Git model,导致 clean repo
  148. // 也挂出右上角状态卡;旧 ChatView 只在 worktree 有行级变化时展示 Git Tools。
  149. if (added + removed <= 0) {
  150. return null;
  151. }
  152. const isClean =
  153. !gitSummary.isDirty &&
  154. gitDirtyFileCount === 0 &&
  155. added === 0 &&
  156. removed === 0 &&
  157. gitSummary.ahead === 0;
  158. return {
  159. branchName: gitSummary.branchName,
  160. headRefType: gitSummary.headRefType,
  161. dirtyFileCount: gitDirtyFileCount,
  162. added,
  163. removed,
  164. ahead: gitSummary.ahead,
  165. behind: gitSummary.behind,
  166. isClean,
  167. };
  168. }
  169. function buildPlanModel(plan: PlanState | null | undefined) {
  170. if (!plan || plan.items.length === 0) {
  171. return null;
  172. }
  173. const completed = plan.items.filter((item) => item.status === "completed");
  174. return {
  175. items: plan.items,
  176. // 按状态重新分组会让 Todo 完成时从原位置跳到列表末尾,破坏 TodoWrite
  177. // snapshot 的权威顺序。这里完整保留原数组,只由 renderer 负责滚动和状态样式。
  178. displayItems: plan.items,
  179. completedCount: completed.length,
  180. waitingCount: plan.items.length - completed.length,
  181. totalCount: plan.items.length,
  182. };
  183. }
  184. function buildSessionPlansModel(
  185. rows: readonly ToolCallRow[] | undefined,
  186. workspacePath: string | undefined,
  187. ): ConversationStatusPanelSessionPlansModel | null {
  188. if (!rows?.length) return null;
  189. const items = rows
  190. .filter(
  191. (row) =>
  192. row.toolName === "ExitPlanMode" &&
  193. (row.status === "success" || row.status === "error" || row.status === "cancelled"),
  194. )
  195. .toSorted((left, right) => right.rowId - left.rowId)
  196. .flatMap((row) => {
  197. const content = extractPlanToolCallContent(row, workspacePath ?? "");
  198. if (!content.markdown) return [];
  199. const title = getPlanDirectoryTitle(content.markdown);
  200. return [
  201. {
  202. rowId: row.rowId,
  203. toolCallId: row.toolCallId,
  204. markdown: content.markdown,
  205. ...(title ? { title } : {}),
  206. ...(content.planFilePath ? { planFilePath: content.planFilePath } : {}),
  207. },
  208. ];
  209. });
  210. return items.length > 0 ? { items } : null;
  211. }
  212. /**
  213. * Workflows 分区:活动 run 与 workflow 后台任务按 **workId ≡ runId** 联接。
  214. *
  215. * 这条等式不是猜的,是 schema 上写明的既有事实(`backgroundWorkSummarySchema` 的
  216. * kind 注释与 `backgroundResultOriginMetaSchema` 的 "workflow" 注释);所以联接用主键
  217. * 直接对上,不需要 Agent 行那套「重复身份宁可不显示」的消歧。
  218. *
  219. * 两侧各自可以单方面缺席,缺席的处理按**字段含义**分簇,而不是按 work 的 status 一刀切:
  220. * - `title` / `startedAt` 是静态元数据,work 无论什么 status 都取。work 走到 resultPending
  221. * 时若一并丢掉它们,run 还在跑的那一行会当场闪成 i18n 兜底名并失去时长——纯视觉故障。
  222. * - `workId` / `cancellable` 是 Stop 的前提,**只在 work 仍 running 时给**:已结束的 work
  223. * 没有可取消的东西,留着按钮就是一个点了没反应的 Stop。
  224. * - run 有、work 全无:仍成行(状态词与步数是投影自己的事实),只是没有题名/时长/Stop。
  225. * - work 有、run 无:说明 CLI 老到不发 `workflowRuns` 投影键。降级成只有题名/时长/Stop
  226. * 的一行,**追加在 run 支撑的行之后**——它没有启动序上的位置,插进中间等于编造顺序。
  227. * 这条兜底的全部理由是:**cancel 入口在任何偏斜下都不许消失**;因此降级行只收 running
  228. * 的 work——既没有 run、work 也已结束的那条没有任何可操作的东西,显示它就是一条死行。
  229. */
  230. function buildRunningWorkflowRuns(
  231. runs: readonly WorkflowRunState[] | undefined,
  232. workflowWorkByWorkId: ReadonlyMap<string, BackgroundWorkSummary>,
  233. ): ConversationStatusPanelWorkflowRun[] {
  234. const rows: ConversationStatusPanelWorkflowRun[] = [];
  235. const joinedWorkIds = new Set<string>();
  236. for (const run of runs ?? []) {
  237. // pending 也是活动态:run 已经起跑、只是还没派发第一个节点,藏起来等于让用户
  238. // 在「工作流启动了」和「面板出现它」之间看到一段空窗。
  239. if (run.status !== "pending" && run.status !== "running") continue;
  240. const work = workflowWorkByWorkId.get(run.runId);
  241. if (work) joinedWorkIds.add(run.runId);
  242. // 计数与聊天紧凑卡同源(唯一实现在 @zcode/shared 的 workflowRunStepCounts:表内 + 表外)。
  243. const steps = workflowRunStepCounts(run);
  244. rows.push({
  245. runId: run.runId,
  246. ...(run.toolCallId ? { toolCallId: run.toolCallId } : {}),
  247. status: run.status,
  248. nodesSettled: steps.settled,
  249. nodesTotal: steps.total,
  250. phases: deriveSessionWorkflowPhases(run),
  251. ...(run.currentPhase === undefined ? {} : { currentPhase: run.currentPhase }),
  252. ...(work ? { title: work.title, startedAt: work.startedAt } : {}),
  253. ...(work?.status === "running"
  254. ? {
  255. workId: work.workId,
  256. // 缺省即可停,与 Agent 行同款 `!== false`:能停而不给按钮比反过来更糟。
  257. cancellable: work.cancellable !== false,
  258. }
  259. : {}),
  260. });
  261. }
  262. // 顺序 = 投影 runs 序 = 启动序,模型不排序;重排会让面板行在每次投影更新时跳位。
  263. for (const [workId, work] of workflowWorkByWorkId) {
  264. if (joinedWorkIds.has(workId) || work.status !== "running") continue;
  265. rows.push({
  266. runId: workId,
  267. workId,
  268. title: work.title,
  269. startedAt: work.startedAt,
  270. cancellable: work.cancellable !== false,
  271. });
  272. }
  273. return rows;
  274. }
  275. /**
  276. * 一条 run「此刻在做什么」的词(docs/dynamic-workflow/presentation.md「Other places a run appears」),
  277. * run 行第二行与胶囊共用这一条规则:
  278. * - pending → 状态词;
  279. * - 没声明阶段 → 步数(这是步数唯一还露面的地方);
  280. * - 不止一站在烧 → 这些站名以 ` ∥ ` 相连(并行时谁都不比谁更当前);
  281. * - 否则当前站;连当前站都没有(进了 run、还没进第一个 phase)→ 状态词;
  282. * - 降级行(无 status)→ null:不知道状态,就什么都不说。
  283. * 模型只给结构,文案(状态词、步数 key)由渲染层按 i18n 拼。
  284. */
  285. export type ConversationStatusPanelWorkflowRunWords =
  286. | { kind: "status"; status: "pending" | "running" }
  287. | { kind: "steps"; done: number; total: number }
  288. | { kind: "phases"; text: string };
  289. export function workflowRunWords(
  290. run: ConversationStatusPanelWorkflowRun,
  291. ): ConversationStatusPanelWorkflowRunWords | null {
  292. if (run.status === undefined) return null;
  293. if (run.status === "pending") return { kind: "status", status: "pending" };
  294. const phases = run.phases ?? [];
  295. if (phases.length === 0) {
  296. return { kind: "steps", done: run.nodesSettled ?? 0, total: run.nodesTotal ?? 0 };
  297. }
  298. const parallel = workflowRunParallelPhaseLabel(phases);
  299. if (parallel !== undefined) return { kind: "phases", text: parallel };
  300. if (run.currentPhase !== undefined) return { kind: "phases", text: run.currentPhase };
  301. return { kind: "status", status: "running" };
  302. }
  303. /**
  304. * composer 徽标直达:本会话的运行态**恰好**
  305. * 是一条可开详情页的 workflow run 时,返回它的打开意图;否则 null,徽标退回展开胶囊。
  306. *
  307. * 判定条件逐项都有理由:终端 / 子代理为零——徽标是它们唯一的入口,直达会把它们藏掉;
  308. * workflow 恰一条——两条以上选哪条是用户的事;带 `toolCallId`——降级行(work 有、run 无)与
  309. * 旧 CLI 的 run 没有可开的详情页,与面板行「不可点」同义,退回胶囊让 Stop 仍可达。
  310. * 输入就是 `buildConversationStatusPanelModel` 的产出:徽标与胶囊共用同一份运行态真值。
  311. */
  312. export function resolveSoleRunningWorkflowRunTarget(
  313. model: Pick<
  314. ConversationStatusPanelModel,
  315. "runningBashWorks" | "runningSubagentWorks" | "runningWorkflowRuns"
  316. >,
  317. ): ConversationStatusPanelWorkflowRunTarget | null {
  318. if (model.runningBashWorks.length > 0 || model.runningSubagentWorks.length > 0) return null;
  319. if (model.runningWorkflowRuns.length !== 1) return null;
  320. return workflowRunOpenTarget(model.runningWorkflowRuns[0]!);
  321. }
  322. export function buildConversationStatusPanelModel(
  323. input: BuildConversationStatusPanelModelInput,
  324. ): ConversationStatusPanelModel {
  325. const git = input.isOfficeMode ? null : buildGitModel(input);
  326. const goal = input.goal ?? null;
  327. const sessionPlans = buildSessionPlansModel(input.sessionPlans, input.workspacePath);
  328. const plan = buildPlanModel(input.plan);
  329. const runningBashWorks: BackgroundWorkSummary[] = [];
  330. const workflowWorkByWorkId = new Map<string, BackgroundWorkSummary>();
  331. const subagentControlByChildSessionId = new Map<string, BackgroundWorkSummary | null>();
  332. for (const work of input.backgroundWorks ?? []) {
  333. if (work.kind === "workflow") {
  334. // "workflow"(workflow run)曾与 bash 同列在 Terminals 下,那是保住停止入口的已记录错标;
  335. // 现在它有自己的 Workflows 分区,于是**只**按 workId ≡ runId 进 workflow 联接表。
  336. // 留在 runningBashWorks 里就是让同一个 run 在两个分区各出现一次。
  337. //
  338. // 这一支**收在 running 闸门之前**:题名与启动时刻对已结束的 work 依然有效(见
  339. // buildRunningWorkflowRuns 的分簇说明),status 的判断留到那里按字段做。workId 是
  340. // 主键,重复即上游损坏,不做消歧。
  341. workflowWorkByWorkId.set(work.workId, work);
  342. continue;
  343. }
  344. if (work.status !== "running") continue;
  345. if (work.kind === "bash") {
  346. runningBashWorks.push(work);
  347. } else if (work.kind === "subagent" && work.childSessionId) {
  348. // 目录投影接管 Agent 展示后,旧 backgroundWorks 的 workId/cancellable
  349. // 没有再关联回来,导致 Stop 入口消失。只接受唯一 childSessionId 精确匹配;重复或
  350. // 缺失身份时宁可不显示控制,也不能按标题、时间猜测并停止错误任务。
  351. const existing = subagentControlByChildSessionId.get(work.childSessionId);
  352. subagentControlByChildSessionId.set(
  353. work.childSessionId,
  354. existing === undefined ? work : null,
  355. );
  356. }
  357. }
  358. const runningSubagentWorks: ConversationStatusPanelRunningSubagent[] = (
  359. input.runningSubagents ?? []
  360. ).map((subagent) => {
  361. const controlWork = subagentControlByChildSessionId.get(subagent.childSessionId);
  362. if (!controlWork) return subagent;
  363. return {
  364. ...subagent,
  365. controlWorkId: controlWork.workId,
  366. cancellable: controlWork.cancellable !== false,
  367. };
  368. });
  369. const projectedChildSessionIds = new Set(
  370. runningSubagentWorks.map((subagent) => subagent.childSessionId),
  371. );
  372. for (const [childSessionId, controlWork] of subagentControlByChildSessionId) {
  373. if (!controlWork || projectedChildSessionIds.has(childSessionId)) continue;
  374. // backgroundWorks 已有精确 childSessionId 的 running 事实,但
  375. // subagents cold/live 投影交接的短窗口可能暂时缺行;旧模型会把 Agent 控制
  376. // 整条隐藏。这里只用唯一身份的权威 work 补齐同一控制,重复身份仍拒绝猜测。
  377. runningSubagentWorks.push({
  378. agentId: controlWork.workId,
  379. childSessionId,
  380. controlWorkId: controlWork.workId,
  381. subagentType: "subagent",
  382. title: controlWork.title,
  383. status: controlWork.blocked ? "blocked" : "running",
  384. startedAt: controlWork.startedAt,
  385. cancellable: controlWork.cancellable !== false,
  386. });
  387. }
  388. const runningWorkflowRuns = buildRunningWorkflowRuns(input.workflowRuns, workflowWorkByWorkId);
  389. return {
  390. git,
  391. goal,
  392. sessionPlans,
  393. plan,
  394. runningBashWorks,
  395. runningSubagentWorks,
  396. runningWorkflowRuns,
  397. hasContent: Boolean(
  398. git ||
  399. goal ||
  400. sessionPlans ||
  401. plan ||
  402. runningBashWorks.length > 0 ||
  403. runningSubagentWorks.length > 0 ||
  404. runningWorkflowRuns.length > 0,
  405. ),
  406. };
  407. }