瀏覽代碼

feat(ui): 任务分发模块 M4——统一权限确认与分组分发执行

- 统一权限确认栏(spec §8):清单在主区勾选/编辑后,底部一次确认——
  已选计数 + 会话级权限说明 + 执行模式(创建并执行 / 仅创建,TD-2)
- useTaskDispatchExecutor:parallelGroup 升序逐组 v4 createSession
  (origin="task-dispatch" + permissionScope="session" + firstInput),
  组内并发;跨组顺序由会话终态事件驱动(watcher 上报 sessions-index
  终态,当前组清零后推进下一组);全组创建失败不阻塞推进;单项失败隔离
- 分发进度(组 current/total + 待完成会话数)与结果摘要
  (started/created/failed 计数)随状态机呈现;watcher 泛化为多会话
  TaskDispatchSessionWatcher,分析与分发共用
- 拆出 TaskDispatchHistoryAside(模块历史侧区),主文件回到 max-lines 限内
- spec §8 回写 M4 实现口径:模块入口在 UI 侧驱动组序(与 S2 tasks/dispatch
  同一原语,协议方法保留为 agent 工具链入口);TaskList 来源徽标拆为 M4b
  (依赖 wire 级 createSource 透传,origin 已随 payload 下发)

验证:pnpm typecheck 通过;pnpm lint 63 警告 0 错误(与基线一致)。
wubinggen 1 月之前
父節點
當前提交
352c0e93a7

+ 5 - 0
docs/specs/workspace-task-dispatch.md

@@ -135,6 +135,10 @@
   `"task-dispatch"`),TaskList 任务行渲染来源徽标(如 "分发" chip / 专属图标),
   `"task-dispatch"`),TaskList 任务行渲染来源徽标(如 "分发" chip / 专属图标),
   与手动新建任务可视觉区分;归因字段随快照持久化,恢复/远控可见。
   与手动新建任务可视觉区分;归因字段随快照持久化,恢复/远控可见。
 - §7-a 对话框保留为快速手动入口(无模型参与);agent 工具链保留为编程入口。
 - §7-a 对话框保留为快速手动入口(无模型参与);agent 工具链保留为编程入口。
+- **M4 实现口径(2026-10-18 落地)**:模块入口在 UI 侧驱动组序——逐组 v4 createSession
+  (`origin:"task-dispatch"` + `permissionScope:"session"` + firstInput,与 S2 handler 同一
+  原语);跨组顺序由模块监听 sessions-index 组内会话终态推进(=「组完成事件驱动」)。
+  `tasks/dispatch` 协议方法保留为 agent 工具链入口,语义一致。
 
 
 ### 实现分片
 ### 实现分片
 
 
@@ -144,6 +148,7 @@
 | M2 | 模块页面骨架:路由/入口、项目选择器、分组清单视图、**模块会话历史列表**(遵守 DESIGN.md 完整 UI 设计) |
 | M2 | 模块页面骨架:路由/入口、项目选择器、分组清单视图、**模块会话历史列表**(遵守 DESIGN.md 完整 UI 设计) |
 | M3 | 分析会话编排:创建模块 scope 会话 → 发送提示词 → 解析结构化输出 → 呈现;**会话记录入模块空间** |
 | M3 | 分析会话编排:创建模块 scope 会话 → 发送提示词 → 解析结构化输出 → 呈现;**会话记录入模块空间** |
 | M4 | 确认与执行:统一权限确认 → tasks/dispatch(parallelGroup 并发、跨组顺序);**createSource="task-dispatch" 归因 + TaskList 徽标** |
 | M4 | 确认与执行:统一权限确认 → tasks/dispatch(parallelGroup 并发、跨组顺序);**createSource="task-dispatch" 归因 + TaskList 徽标** |
+| M4b(后续分片) | TaskList 来源徽标:依赖 wire 级 createSource 透传(CLI createSession→record→tasks-index/sessions-index),M4 先随 payload 下发 `origin:"task-dispatch"`,徽标等 wire 打通后补 |
 | M5 | 测试与 i18n |
 | M5 | 测试与 i18n |
 
 
 历史分片(S1-S4,agent 工具链,已完成):contracts schema + core DispatchTasks 工具 +
 历史分片(S1-S4,agent 工具链,已完成):contracts schema + core DispatchTasks 工具 +

+ 10 - 0
packages/ui/src/i18n/locales/en-US.ts

@@ -1882,6 +1882,16 @@ const enUS: Record<string, string> = {
   "taskDispatch.module.groupsSequentialHint": "concurrent within group · groups run in order",
   "taskDispatch.module.groupsSequentialHint": "concurrent within group · groups run in order",
   "taskDispatch.module.dependsOnLabel": "Depends on: {titles}",
   "taskDispatch.module.dependsOnLabel": "Depends on: {titles}",
   "taskDispatch.module.removeTask": "Remove task",
   "taskDispatch.module.removeTask": "Remove task",
+  "taskDispatch.module.selectedCount": "{selected}/{total} selected",
+  "taskDispatch.module.permissionScopeHint":
+    "Confirm to batch-create tasks under the target project with session-scoped permissions; concurrent within groups, groups in order",
+  "taskDispatch.module.executeMode": "Create and run",
+  "taskDispatch.module.createOnly": "Create only",
+  "taskDispatch.module.confirmDispatch": "Confirm dispatch",
+  "taskDispatch.module.dispatchProgress": "Dispatching · group {current}/{total}",
+  "taskDispatch.module.awaitingGroup": "waiting for {count} sessions to finish",
+  "taskDispatch.module.dispatchDone": "Done: {started} started / {created} created / {failed} failed",
+  "taskDispatch.module.dispatchBack": "Back",
   "workspaceSidebar.renameProjectPlaceholder": "Custom project name (leave empty to reset)",
   "workspaceSidebar.renameProjectPlaceholder": "Custom project name (leave empty to reset)",
   "workspaceSidebar.renameProjectFailed": "Could not save project name",
   "workspaceSidebar.renameProjectFailed": "Could not save project name",
   "chat.dashboard.turnsSteps": "{turns} turns · {steps} steps",
   "chat.dashboard.turnsSteps": "{turns} turns · {steps} steps",

+ 10 - 0
packages/ui/src/i18n/locales/zh-CN.ts

@@ -1755,6 +1755,16 @@ const zhCN: Record<string, string> = {
   "taskDispatch.module.groupsSequentialHint": "组内并行 · 组间按序",
   "taskDispatch.module.groupsSequentialHint": "组内并行 · 组间按序",
   "taskDispatch.module.dependsOnLabel": "依赖:{titles}",
   "taskDispatch.module.dependsOnLabel": "依赖:{titles}",
   "taskDispatch.module.removeTask": "移除任务",
   "taskDispatch.module.removeTask": "移除任务",
+  "taskDispatch.module.selectedCount": "已选 {selected}/{total} 项",
+  "taskDispatch.module.permissionScopeHint":
+    "确认后按会话级权限在目标项目下批量创建任务;同组并行、组间按序",
+  "taskDispatch.module.executeMode": "创建并执行",
+  "taskDispatch.module.createOnly": "仅创建",
+  "taskDispatch.module.confirmDispatch": "确认分发",
+  "taskDispatch.module.dispatchProgress": "分发中 · 组 {current}/{total}",
+  "taskDispatch.module.awaitingGroup": "等待 {count} 个会话完成",
+  "taskDispatch.module.dispatchDone": "完成:{started} 启动 / {created} 创建 / {failed} 失败",
+  "taskDispatch.module.dispatchBack": "返回",
   "workspaceSidebar.renameProjectPlaceholder": "自定义项目名称(留空恢复默认)",
   "workspaceSidebar.renameProjectPlaceholder": "自定义项目名称(留空恢复默认)",
   "workspaceSidebar.renameProjectFailed": "保存项目名称失败",
   "workspaceSidebar.renameProjectFailed": "保存项目名称失败",
   "chat.dashboard.turnsSteps": "{turns} 轮 · {steps} 步",
   "chat.dashboard.turnsSteps": "{turns} 轮 · {steps} 步",

+ 73 - 0
packages/ui/src/task-dispatch/TaskDispatchHistoryAside.tsx

@@ -0,0 +1,73 @@
+// 任务分发模块:侧区分析历史列表(M3/M4)。
+// 数据源:taskDispatchHistoryStore(UI 注册表)+ sessions-index 活性(spec §8 M3 口径)。
+import { Loader2 } from "lucide-react";
+import { useZCodeIntl } from "@/i18n/IntlProvider.js";
+import { cn } from "@/components/lib/utils.js";
+import type { TaskDispatchAnalysisRecord } from "@/task-dispatch/taskDispatchHistoryStore.js";
+
+function formatHistoryStatus(
+  intl: ReturnType<typeof useZCodeIntl>["intl"],
+  record: TaskDispatchAnalysisRecord,
+): string {
+  if (record.status === "analyzing") {
+    return intl.formatMessage({ id: "taskDispatch.module.historyStatusAnalyzing" });
+  }
+  if (record.status === "failed") {
+    return intl.formatMessage({ id: "taskDispatch.module.historyStatusFailed" });
+  }
+  return intl.formatMessage(
+    { id: "taskDispatch.module.historyStatusDone" },
+    { count: record.plan?.tasks.length ?? 0 },
+  );
+}
+
+export function TaskDispatchHistoryAside({
+  records,
+  onLoad,
+}: {
+  records: TaskDispatchAnalysisRecord[];
+  onLoad: (record: TaskDispatchAnalysisRecord) => void;
+}) {
+  const { intl } = useZCodeIntl();
+  return (
+    <aside className="flex w-72 shrink-0 flex-col border-l border-border">
+      <div className="border-b border-border px-3 py-2 text-ui-sm font-medium text-foreground-subtle">
+        {intl.formatMessage({ id: "taskDispatch.module.history" })}
+      </div>
+      <div className="min-h-0 flex-1 overflow-y-auto p-2">
+        {records.length === 0 ? (
+          <div className="flex h-full items-center justify-center p-3 text-ui-caption text-foreground-subtlest">
+            {intl.formatMessage({ id: "taskDispatch.module.historyEmpty" })}
+          </div>
+        ) : (
+          <ul className="flex flex-col gap-1">
+            {records.map((record) => (
+              <li key={record.id}>
+                <button
+                  type="button"
+                  onClick={() => onLoad(record)}
+                  disabled={record.status !== "done"}
+                  className={cn(
+                    "flex w-full flex-col gap-0.5 rounded-[var(--ui-radius,8px)] px-2 py-1.5 text-left",
+                    "hover:bg-surface-hover disabled:cursor-default disabled:opacity-70",
+                  )}
+                >
+                  <span className="flex items-center gap-1 truncate text-ui-sm text-foreground">
+                    {record.status === "analyzing" ? (
+                      <Loader2 className="size-3 shrink-0 animate-spin" />
+                    ) : null}
+                    {record.workspaceLabel}
+                  </span>
+                  <span className="text-ui-caption text-foreground-subtle">
+                    {formatHistoryStatus(intl, record)} ·{" "}
+                    {new Date(record.createdAt).toLocaleString()}
+                  </span>
+                </button>
+              </li>
+            ))}
+          </ul>
+        )}
+      </div>
+    </aside>
+  );
+}

+ 144 - 71
packages/ui/src/task-dispatch/TaskDispatchModule.tsx

@@ -17,7 +17,6 @@ import {
   SelectValue,
   SelectValue,
 } from "@/components/ui/select.js";
 } from "@/components/ui/select.js";
 import { useZCodeIntl } from "@/i18n/IntlProvider.js";
 import { useZCodeIntl } from "@/i18n/IntlProvider.js";
-import { cn } from "@/components/lib/utils.js";
 import { useTabStore } from "@/store/TabStoreProvider.js";
 import { useTabStore } from "@/store/TabStoreProvider.js";
 import { isWorkspaceTab } from "@/store/tabStore.js";
 import { isWorkspaceTab } from "@/store/tabStore.js";
 import { useLocalWorkspaceScopes } from "@/hooks/useLocalWorkspaceScopes.js";
 import { useLocalWorkspaceScopes } from "@/hooks/useLocalWorkspaceScopes.js";
@@ -28,6 +27,10 @@ import {
   useTaskDispatchAnalysis,
   useTaskDispatchAnalysis,
   type TaskDispatchTarget,
   type TaskDispatchTarget,
 } from "@/task-dispatch/useTaskDispatchAnalysis.js";
 } from "@/task-dispatch/useTaskDispatchAnalysis.js";
+import {
+  useTaskDispatchExecutor,
+  type TaskDispatchExecTask,
+} from "@/task-dispatch/useTaskDispatchExecutor.js";
 import {
 import {
   taskDispatchHistoryStore,
   taskDispatchHistoryStore,
   type TaskDispatchAnalysisRecord,
   type TaskDispatchAnalysisRecord,
@@ -36,6 +39,7 @@ import {
   TaskDispatchPlanList,
   TaskDispatchPlanList,
   type TaskDispatchDraft,
   type TaskDispatchDraft,
 } from "@/task-dispatch/TaskDispatchPlanList.js";
 } from "@/task-dispatch/TaskDispatchPlanList.js";
+import { TaskDispatchHistoryAside } from "@/task-dispatch/TaskDispatchHistoryAside.js";
 
 
 /** 模块内可选的项目目标(本地 + 远程 workspace)。 */
 /** 模块内可选的项目目标(本地 + 远程 workspace)。 */
 export interface TaskDispatchWorkspaceOption {
 export interface TaskDispatchWorkspaceOption {
@@ -84,47 +88,33 @@ function planToDrafts(
 }
 }
 
 
 /**
 /**
- * 分析会话终态监听器:仅在活跃分析存在时挂载(hooks 不能条件调用,用子组件承载订阅)。
- * sessions-index 里该会话 phase 到终态 → 一次性回调 onTerminal。
+ * 会话终态监听器:仅在存在待监听会话时挂载(hooks 不能条件调用,用子组件承载订阅)。
+ * sessions-index 里任一目标会话 phase 到终态 → 每会话一次性回调 onTerminal。
  */
  */
-function TaskDispatchAnalysisWatcher({
+function TaskDispatchSessionWatcher({
   target,
   target,
-  sessionId,
+  sessionIds,
   onTerminal,
   onTerminal,
 }: {
 }: {
   target: TaskDispatchTarget;
   target: TaskDispatchTarget;
-  sessionId: string;
-  onTerminal: (phase: string) => void;
+  sessionIds: string[];
+  onTerminal: (sessionId: string, phase: string) => void;
 }) {
 }) {
   const { sessions } = useSessionsIndex(target.workspacePath, target.workspaceIdentity ?? undefined);
   const { sessions } = useSessionsIndex(target.workspacePath, target.workspaceIdentity ?? undefined);
-  const firedRef = useRef(false);
+  const firedRef = useRef<Set<string>>(new Set());
   useEffect(() => {
   useEffect(() => {
-    if (firedRef.current) return;
-    const summary = sessions.find((session) => session.sessionId === sessionId);
-    if (summary && isTerminalSessionPhase(summary.phase)) {
-      firedRef.current = true;
-      onTerminal(summary.phase);
+    if (sessionIds.length === 0) return;
+    for (const session of sessions) {
+      if (firedRef.current.has(session.sessionId)) continue;
+      if (sessionIds.includes(session.sessionId) && isTerminalSessionPhase(session.phase)) {
+        firedRef.current.add(session.sessionId);
+        onTerminal(session.sessionId, session.phase);
+      }
     }
     }
-  }, [sessions, sessionId, onTerminal]);
+  }, [sessions, sessionIds, onTerminal]);
   return null;
   return null;
 }
 }
 
 
-function formatHistoryStatus(
-  intl: ReturnType<typeof useZCodeIntl>["intl"],
-  record: TaskDispatchAnalysisRecord,
-): string {
-  if (record.status === "analyzing") {
-    return intl.formatMessage({ id: "taskDispatch.module.historyStatusAnalyzing" });
-  }
-  if (record.status === "failed") {
-    return intl.formatMessage({ id: "taskDispatch.module.historyStatusFailed" });
-  }
-  return intl.formatMessage(
-    { id: "taskDispatch.module.historyStatusDone" },
-    { count: record.plan?.tasks.length ?? 0 },
-  );
-}
-
 export function TaskDispatchModule({
 export function TaskDispatchModule({
   workspaceOptions,
   workspaceOptions,
 }: {
 }: {
@@ -217,6 +207,40 @@ export function TaskDispatchModule({
     [],
     [],
   );
   );
 
 
+  // ── M4:统一权限确认 + 分组分发执行 ──
+  const executor = useTaskDispatchExecutor();
+  const [executeMode, setExecuteMode] = useState<"execute" | "createOnly">("execute");
+  const checkedCount = drafts.filter((draft) => draft.checked).length;
+
+  const handleConfirmDispatch = useCallback(() => {
+    if (!selected || checkedCount === 0) return;
+    const tasks: TaskDispatchExecTask[] = drafts
+      .filter((draft) => draft.checked && draft.title.trim() && draft.prompt.trim())
+      .map((draft, index) => ({
+        id: draft.key || `task-${index}`,
+        title: draft.title.trim(),
+        prompt: draft.prompt.trim(),
+        ...(draft.parallelGroup !== undefined ? { parallelGroup: draft.parallelGroup } : {}),
+      }));
+    if (tasks.length === 0) return;
+    void executor.start(tasks, targetFromOption(selected), executeMode === "execute");
+  }, [checkedCount, drafts, executor, executeMode, selected, targetFromOption]);
+
+  const dispatchSessionIds = useMemo(
+    () =>
+      executor.state.results
+        .filter((item) => item.sessionId && item.status !== "failed")
+        .map((item) => item.sessionId as string),
+    [executor.state.results],
+  );
+  const handleDispatchTerminal = useCallback(
+    (sessionId: string) => {
+      executor.reportSessionTerminal(sessionId);
+    },
+    [executor],
+  );
+  const dispatchPhase = executor.state.phase;
+
   const analyzing = activeAnalysis !== null && drafts.length === 0 && error === null;
   const analyzing = activeAnalysis !== null && drafts.length === 0 && error === null;
 
 
   return (
   return (
@@ -297,51 +321,100 @@ export function TaskDispatchModule({
           )}
           )}
         </section>
         </section>
         {/* 侧区:模块会话历史(UI 注册表 + sessions-index 活性;spec §8 M3 口径)。 */}
         {/* 侧区:模块会话历史(UI 注册表 + sessions-index 活性;spec §8 M3 口径)。 */}
-        <aside className="flex w-72 shrink-0 flex-col border-l border-border">
-          <div className="border-b border-border px-3 py-2 text-ui-sm font-medium text-foreground-subtle">
-            {intl.formatMessage({ id: "taskDispatch.module.history" })}
+        <TaskDispatchHistoryAside records={historyForSelected} onLoad={handleLoadHistory} />
+      </div>
+      {/* 统一权限确认栏(spec §8):清单在主区勾选/编辑,此处一次确认权限范围与执行模式。 */}
+      {drafts.length > 0 && dispatchPhase === "idle" ? (
+        <footer className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-t border-border px-4 py-2">
+          <div className="flex min-w-0 items-center gap-3">
+            <span className="text-ui-sm text-foreground">
+              {intl.formatMessage(
+                { id: "taskDispatch.module.selectedCount" },
+                { selected: checkedCount, total: drafts.length },
+              )}
+            </span>
+            <span className="truncate text-ui-caption text-foreground-subtle">
+              {intl.formatMessage({ id: "taskDispatch.module.permissionScopeHint" })}
+            </span>
           </div>
           </div>
-          <div className="min-h-0 flex-1 overflow-y-auto p-2">
-            {historyForSelected.length === 0 ? (
-              <div className="flex h-full items-center justify-center p-3 text-ui-caption text-foreground-subtlest">
-                {intl.formatMessage({ id: "taskDispatch.module.historyEmpty" })}
-              </div>
-            ) : (
-              <ul className="flex flex-col gap-1">
-                {historyForSelected.map((record) => (
-                  <li key={record.id}>
-                    <button
-                      type="button"
-                      onClick={() => handleLoadHistory(record)}
-                      disabled={record.status !== "done"}
-                      className={cn(
-                        "flex w-full flex-col gap-0.5 rounded-[var(--ui-radius,8px)] px-2 py-1.5 text-left",
-                        "hover:bg-surface-hover disabled:cursor-default disabled:opacity-70",
-                      )}
-                    >
-                      <span className="flex items-center gap-1 truncate text-ui-sm text-foreground">
-                        {record.status === "analyzing" ? (
-                          <Loader2 className="size-3 shrink-0 animate-spin" />
-                        ) : null}
-                        {record.workspaceLabel}
-                      </span>
-                      <span className="text-ui-caption text-foreground-subtle">
-                        {formatHistoryStatus(intl, record)} ·{" "}
-                        {new Date(record.createdAt).toLocaleString()}
-                      </span>
-                    </button>
-                  </li>
-                ))}
-              </ul>
-            )}
+          <div className="flex items-center gap-2">
+            <Select
+              value={executeMode}
+              onValueChange={(value) => setExecuteMode(value as "execute" | "createOnly")}
+            >
+              <SelectTrigger className="h-8 w-[150px]" size="sm">
+                <SelectValue />
+              </SelectTrigger>
+              <SelectContent>
+                <SelectItem value="execute">
+                  {intl.formatMessage({ id: "taskDispatch.module.executeMode" })}
+                </SelectItem>
+                <SelectItem value="createOnly">
+                  {intl.formatMessage({ id: "taskDispatch.module.createOnly" })}
+                </SelectItem>
+              </SelectContent>
+            </Select>
+            <Button
+              size="sm"
+              disabled={checkedCount === 0}
+              onClick={handleConfirmDispatch}
+            >
+              {intl.formatMessage({ id: "taskDispatch.module.confirmDispatch" })}
+            </Button>
           </div>
           </div>
-        </aside>
-      </div>
+        </footer>
+      ) : null}
+      {dispatchPhase === "running" ? (
+        <footer className="flex shrink-0 items-center gap-2 border-t border-border px-4 py-2 text-ui-sm text-foreground">
+          <Loader2 className="size-4 animate-spin" />
+          <span>
+            {intl.formatMessage(
+              { id: "taskDispatch.module.dispatchProgress" },
+              {
+                current: executor.state.completedGroups + 1,
+                total: executor.state.totalGroups,
+              },
+            )}
+          </span>
+          {executor.state.currentGroupPending > 0 ? (
+            <span className="text-ui-caption text-foreground-subtle">
+              {intl.formatMessage(
+                { id: "taskDispatch.module.awaitingGroup" },
+                { count: executor.state.currentGroupPending },
+              )}
+            </span>
+          ) : null}
+        </footer>
+      ) : null}
+      {dispatchPhase === "done" ? (
+        <footer className="flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-2 text-ui-sm text-foreground">
+          <span>
+            {intl.formatMessage(
+              { id: "taskDispatch.module.dispatchDone" },
+              {
+                created: executor.state.results.filter((item) => item.status === "created").length,
+                started: executor.state.results.filter((item) => item.status === "started").length,
+                failed: executor.state.results.filter((item) => item.status === "failed").length,
+              },
+            )}
+          </span>
+          <Button size="sm" variant="ghost" onClick={executor.reset}>
+            {intl.formatMessage({ id: "taskDispatch.module.dispatchBack" })}
+          </Button>
+        </footer>
+      ) : null}
       {activeAnalysis ? (
       {activeAnalysis ? (
-        <TaskDispatchAnalysisWatcher
+        <TaskDispatchSessionWatcher
           target={activeAnalysis.target}
           target={activeAnalysis.target}
-          sessionId={activeAnalysis.record.sessionId}
-          onTerminal={handleTerminal}
+          sessionIds={[activeAnalysis.record.sessionId]}
+          onTerminal={(_sessionId, phase) => handleTerminal(phase)}
+        />
+      ) : null}
+      {dispatchPhase === "running" && selected && dispatchSessionIds.length > 0 ? (
+        <TaskDispatchSessionWatcher
+          target={selected}
+          sessionIds={dispatchSessionIds}
+          onTerminal={handleDispatchTerminal}
         />
         />
       ) : null}
       ) : null}
     </div>
     </div>

+ 246 - 0
packages/ui/src/task-dispatch/useTaskDispatchExecutor.ts

@@ -0,0 +1,246 @@
+// 任务分发模块:确认后的分发执行编排(M4)。
+// 设计合同:docs/specs/workspace-task-dispatch.md §8——同 parallelGroup 并发创建并执行,
+// 跨组按序(当前组全部会话到终态后才创建下一组);「仅创建」= 不带 firstInput(TD-2)。
+// 创建原语与 S2 handler(tasks/dispatch)同一 v4 createSession(origin=task-dispatch +
+// permissionScope=session);模块入口在 UI 侧驱动组序(组完成事件 = sessions-index 终态)。
+import { useCallback, useRef, useState } from "react";
+import { createCommandEnvelope } from "@/v4/commandFactory.js";
+import {
+  acquireWorkspaceConnection,
+  type WorkspaceConnectionLease,
+} from "@/v4/workspaceConnectionRegistry.js";
+import { useServices } from "@/hooks/useServices.js";
+import { logger } from "@/logger.js";
+import { getWorkspaceKey } from "@/lib/workspaceKey.js";
+
+export interface TaskDispatchExecTask {
+  id: string;
+  title: string;
+  prompt: string;
+  /** undefined = 独立任务(并入最后一组,组内并发)。 */
+  parallelGroup?: number;
+}
+
+export interface TaskDispatchExecResultItem {
+  id: string;
+  title: string;
+  status: "created" | "started" | "failed";
+  sessionId?: string;
+  failure?: string;
+}
+
+export interface TaskDispatchExecState {
+  phase: "idle" | "running" | "done";
+  execute: boolean;
+  totalGroups: number;
+  completedGroups: number;
+  /** 当前组尚未到终态的会话数(进度展示)。 */
+  currentGroupPending: number;
+  results: TaskDispatchExecResultItem[];
+}
+
+type Group = { tasks: TaskDispatchExecTask[]; pending: Set<string> };
+
+const IDLE_STATE: TaskDispatchExecState = {
+  phase: "idle",
+  execute: true,
+  totalGroups: 0,
+  completedGroups: 0,
+  currentGroupPending: 0,
+  results: [],
+};
+
+/** 分组规则:parallelGroup 升序;独立任务(无组)并入最后一组并发执行。 */
+function buildGroups(tasks: TaskDispatchExecTask[]): Group[] {
+  const byGroup = new Map<number, TaskDispatchExecTask[]>();
+  const independent: TaskDispatchExecTask[] = [];
+  for (const task of tasks) {
+    if (task.parallelGroup === undefined) independent.push(task);
+    else if (byGroup.has(task.parallelGroup)) byGroup.get(task.parallelGroup)!.push(task);
+    else byGroup.set(task.parallelGroup, [task]);
+  }
+  const groups: Group[] = [...byGroup.entries()]
+    .sort((a, b) => a[0] - b[0])
+    .map(([, groupTasks]) => ({ tasks: groupTasks, pending: new Set<string>() }));
+  if (independent.length > 0) {
+    groups.push({ tasks: independent, pending: new Set<string>() });
+  }
+  return groups;
+}
+
+export function useTaskDispatchExecutor() {
+  const { zcodeAgentService } = useServices();
+  const [state, setState] = useState<TaskDispatchExecState>(IDLE_STATE);
+  const groupsRef = useRef<Group[]>([]);
+  const groupIndexRef = useRef(0);
+  const executeRef = useRef(true);
+  const leaseRef = useRef<WorkspaceConnectionLease | null>(null);
+  const runningRef = useRef(false);
+  const workspaceIdRef = useRef("");
+
+  const patchState = useCallback((patch: Partial<TaskDispatchExecState>) => {
+    setState((current) => ({ ...current, ...patch }));
+  }, []);
+
+  /** 创建一个任务会话;失败隔离(单项失败不阻断组内其余)。 */
+  const createTaskSession = useCallback(
+    async (
+      lease: WorkspaceConnectionLease,
+      workspaceId: string,
+      task: TaskDispatchExecTask,
+    ): Promise<TaskDispatchExecResultItem> => {
+      try {
+        const ack = await lease.transport.sendCommand(
+          createCommandEnvelope({
+            type: "createSession",
+            payload: {
+              workspaceId,
+              // 归因标记(spec §8 任务归因):TaskList 来源徽标依赖 wire 级透传,先随 payload 下发。
+              origin: "task-dispatch",
+              // 统一权限确认的授权落点:整批共用 session 级权限范围(与 S2 handler 一致)。
+              permissionScope: "session",
+              ...(executeRef.current ? { firstInput: { text: task.prompt } } : {}),
+            },
+            sessionId: null,
+          }),
+        );
+        if (ack.status !== "accepted" || ack.result?.type !== "createSession") {
+          return {
+            id: task.id,
+            title: task.title,
+            status: "failed",
+            failure: (ack.message ?? ack.reasonCode ?? ack.status).slice(0, 400),
+          };
+        }
+        return {
+          id: task.id,
+          title: task.title,
+          status: executeRef.current ? "started" : "created",
+          sessionId: ack.result.sessionId,
+        };
+      } catch (error) {
+        return {
+          id: task.id,
+          title: task.title,
+          status: "failed",
+          failure: (error instanceof Error ? error.message : String(error)).slice(0, 400),
+        };
+      }
+    },
+    [],
+  );
+
+  const finish = useCallback(() => {
+    runningRef.current = false;
+    leaseRef.current?.release();
+    leaseRef.current = null;
+    patchState({ phase: "done", currentGroupPending: 0 });
+  }, [patchState]);
+
+  /** 创建第 index 组(组内并发);最后一组或仅创建 → 直接收口,否则等终态事件推进。 */
+  const runGroup = useCallback(
+    async (workspaceId: string) => {
+      const groups = groupsRef.current;
+      const index = groupIndexRef.current;
+      const group = groups[index];
+      if (!group) {
+        finish();
+        return;
+      }
+      patchState({
+        completedGroups: index,
+        currentGroupPending: group.tasks.length,
+      });
+      const items = await Promise.all(
+        group.tasks.map((task) => createTaskSession(leaseRef.current!, workspaceId, task)),
+      );
+      setState((current) => ({ ...current, results: [...current.results, ...items] }));
+      const succeeded = items.filter((item) => item.status !== "failed");
+      // 仅创建模式或最后一组:无需等组完成事件,直接收口(TD-2 / 收尾)。
+      if (!executeRef.current || index >= groups.length - 1) {
+        finish();
+        return;
+      }
+      // 记录本组待终态会话;watcher 的 reportSessionTerminal 逐个消减。
+      for (const item of succeeded) {
+        if (item.sessionId) group.pending.add(item.sessionId);
+      }
+      patchState({ currentGroupPending: group.pending.size });
+      if (group.pending.size === 0) {
+        // 本组全部创建失败:无会话可等,直接推进下一组。
+        groupIndexRef.current = index + 1;
+        void runGroup(workspaceId);
+      }
+    },
+    [createTaskSession, finish, patchState],
+  );
+
+  const start = useCallback(
+    async (
+      tasks: TaskDispatchExecTask[],
+      target: { workspacePath: string; workspaceIdentity?: string },
+      execute: boolean,
+    ): Promise<boolean> => {
+      if (runningRef.current || tasks.length === 0) return false;
+      runningRef.current = true;
+      executeRef.current = execute;
+      groupsRef.current = buildGroups(tasks);
+      groupIndexRef.current = 0;
+      const workspaceId =
+        target.workspaceIdentity?.trim() || target.workspacePath;
+      workspaceIdRef.current = workspaceId;
+      const lease = acquireWorkspaceConnection(
+        {
+          workspacePath: target.workspacePath,
+          ...(target.workspaceIdentity ? { workspaceIdentity: target.workspaceIdentity } : {}),
+        },
+        zcodeAgentService,
+      );
+      leaseRef.current = lease;
+      setState({
+        ...IDLE_STATE,
+        phase: "running",
+        execute,
+        totalGroups: groupsRef.current.length,
+      });
+      logger.info("[task-dispatch] 开始分发", {
+        event: "task_dispatch.start",
+        workspaceKey: getWorkspaceKey(target.workspacePath, target.workspaceIdentity),
+        taskCount: tasks.length,
+        groupCount: groupsRef.current.length,
+        execute,
+      });
+      await runGroup(workspaceId);
+      return true;
+    },
+    [runGroup, zcodeAgentService],
+  );
+
+  /** watcher 上报某会话到终态;当前组清零后推进下一组。 */
+  const reportSessionTerminal = useCallback(
+    (sessionId: string) => {
+      if (!runningRef.current) return;
+      const group = groupsRef.current[groupIndexRef.current];
+      if (!group || !group.pending.has(sessionId)) return;
+      group.pending.delete(sessionId);
+      patchState({ currentGroupPending: group.pending.size });
+      if (group.pending.size === 0) {
+        // 组完成事件驱动跨组顺序(spec §8)。
+        groupIndexRef.current += 1;
+        if (groupIndexRef.current >= groupsRef.current.length) {
+          finish();
+          return;
+        }
+        void runGroup(workspaceIdRef.current);
+      }
+    },
+    [finish, patchState, runGroup],
+  );
+
+  const reset = useCallback(() => {
+    if (runningRef.current) return;
+    setState(IDLE_STATE);
+  }, []);
+
+  return { state, start, reportSessionTerminal, reset };
+}