From 8c227d05ef55ffa654ffeb2665e90fec36b61901 Mon Sep 17 00:00:00 2001 From: zyh Date: Sat, 19 Oct 2024 08:56:52 +0000 Subject: [PATCH] =?UTF-8?q?feat(docs):=20=E6=B7=BB=E5=8A=A0=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E6=89=A7=E8=A1=8C=E4=B8=8E=E7=BB=88=E7=AB=AF=E4=BA=A4?= =?UTF-8?q?=E4=BA=92=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/modules/任务执行-TaskExecution.md | 64 ++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 5 deletions(-) diff --git a/docs/modules/任务执行-TaskExecution.md b/docs/modules/任务执行-TaskExecution.md index 8225f3c..51ce4b7 100644 --- a/docs/modules/任务执行-TaskExecution.md +++ b/docs/modules/任务执行-TaskExecution.md @@ -40,25 +40,77 @@ ```typescript import { ActionRunner } from '~/lib/runtime/action-runner'; import { webcontainer } from '~/lib/webcontainer'; + const actionRunner = new ActionRunner(webcontainer); + // 添加任务 actionRunner.addAction({ actionId: 'action1', action: { type: 'shell', - content: 'npm install lodash', - }, + content: 'npm install lodash' + } }); + // 运行任务 actionRunner.runAction({ actionId: 'action1', action: { type: 'shell', - content: 'npm install lodash', - }, + content: 'npm install lodash' + } }); ``` +## 任务执行与终端交互 + +任务执行模块与终端组件之间有密切的交互,特别是在执行 shell 类型的任务时。这种交互主要通过以下方式实现: + +1. 输出流重定向: 当执行 shell 命令时,命令的输出会被重定向到终端组件,使用户能够实时看到命令执行的结果。 + +2. 进程管理: `ActionRunner` 负责创建和管理 shell 进程,而终端组件则负责显示这些进程的输出。 + +3. 状态同步: 任务的执行状态(如开始、进行中、完成、失败)会实时同步到终端组件,以便用户了解当前任务的执行情况。 + +4. 交互式输入: 对于需要用户输入的 shell 命令,终端组件可以捕获用户输入并传递给正在执行的进程。 + +### 示例代码 + +以下是 `ActionRunner` 中与终端交互的部分代码示例: + +```typescript +async #runShellAction(action: ActionState) { + if (action.type !== 'shell') { + unreachable('Expected shell action'); + } + + const webcontainer = await this.#webcontainer; + + const process = await webcontainer.spawn('jsh', ['-c', action.content], { + env: { npm_config_yes: true }, + }); + + action.abortSignal.addEventListener('abort', () => { + process.kill(); + }); + + // 将进程输出重定向到终端 + process.output.pipeTo( + new WritableStream({ + write(data) { + console.log(data); // 这里可以替换为向终端组件发送数据的逻辑 + }, + }), + ); + + const exitCode = await process.exit; + + // 更新任务状态,终端组件可以订阅这个状态变化 + this.#updateAction(action.id, { status: exitCode === 0 ? 'complete' : 'failed' }); +} +``` + +在这个例子中,shell 命令的输出被重定向到一个 `WritableStream`,这个流可以连接到终端组件,实现实时显示命令输出。同时,任务的状态更新也可以被终端组件订阅,以显示任务的执行进度和结果。 ## 安全考虑 @@ -70,7 +122,7 @@ actionRunner.runAction({ ## 错误处理 -任务执行过程中可能遇到的错误会被捕获并记录,同时更新任务状态为 "failed"。 +任务执行过程中可能遇到的错误会被捕获并记录,同时更新任务状态为 "failed"。这些错误信息也会通过终端组件显示给用户。 ## 性能优化 @@ -86,9 +138,11 @@ actionRunner.runAction({ 1. 在 `ActionState` 类型中定义新的任务结构 2. 在 `ActionRunner` 类中实现相应的执行逻辑 3. 更新 AI 模型,使其能够生成新任务类型的指令 +4. 如果需要,为新任务类型添加相应的终端交互逻辑 ## 注意事项 - 确保 AI 响应的格式符合预定义的任务指令结构 - 定期审查和更新可执行的任务类型,以适应新的需求和潜在的安全风险 - 监控任务执行的性能,及时优化高耗时或高资源消耗的操作 +- 在设计新的任务类型时,考虑如何在终端中展示其执行过程和结果