Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
ExternalEngineConnectionError,
type ExternalEngineSessionInput,
type ExternalEnginePermissionRequest,
} from "@zcode/contracts";
import {
engineConfigOptionSchema,
Expand All @@ -14,6 +15,12 @@ import { AIR_SESSION_FAILURE_CAPABILITY_META } from "./failure.js";
/** AcpConnection 的无状态协议细则与轮间推送缓存;拆出只为保持连接主体在文件行数上限内。 */
type JsonObject = Record<string, unknown>;

export function object(value: unknown): JsonObject {
if (value === null || typeof value !== "object" || Array.isArray(value))
throw new ExternalEngineConnectionError({ code: "protocol" }, "Invalid ACP object");
return value as JsonObject;
}

/**
* typed failure 扩展挂在 JetBrains AIR 客户端标记下,声明即被 adapter 视为 AIR 客户端
* (核查见 docs/desktop/native-plan-errors-spec.md「能力声明」):
Expand Down Expand Up @@ -117,6 +124,20 @@ export function isContinuationEnd(update: JsonObject): boolean {
);
}

// ACP 在 prompt 结束后仍可能发元数据,这些帧没有后续的续跑收尾信号。
const PASSIVE_IDLE_UPDATES = new Set([
"available_commands_update",
"config_option_update",
"current_mode_update",
"session_info_update",
"notice",
"usage_update",
]);

export function isIdleContinuationUpdate(update: JsonObject): boolean {
return !PASSIVE_IDLE_UPDATES.has(String(update.sessionUpdate)) || isContinuationEnd(update);
}

/**
* 子智能体命名约束(docs/desktop/external-agent-engines-spec.md「跨轮观察与引擎自发续跑」):
* 原生帧只带模型自填的名称,未约束时多为类型名或空;追加为系统/开发者指令,界面直接展示。
Expand Down Expand Up @@ -184,3 +205,31 @@ export class IdleActivity {
this.listener?.();
}
}


/** 严格校验 ACP 请求,保留原生选项 ID 与子会话来源。 */
export function readPermissionRequest(
params: JsonObject,
childSessionId: string | undefined,
): ExternalEnginePermissionRequest {
const toolCall = object(params.toolCall);
if (typeof toolCall.toolCallId !== "string" || !Array.isArray(params.options))
throw new Error("Invalid ACP permission request");
const options = params.options.map((value) => {
const option = object(value);
if (
typeof option.optionId !== "string" ||
typeof option.name !== "string" ||
!["allow_once", "allow_always", "reject_once", "reject_always"].includes(
String(option.kind),
)
)
throw new Error("Invalid ACP permission option");
return option as unknown as ExternalEnginePermissionRequest["options"][number];
});
return {
toolCall: toolCall as ExternalEnginePermissionRequest["toolCall"],
options,
...(childSessionId ? { childNativeSessionId: childSessionId } : {}),
};
}
53 changes: 24 additions & 29 deletions apps/zcode-cli/packages/adapters/src/external-engine/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
type ExternalEngineSessionInput,
type ExternalEngineTurnInput,
type ExternalEngineTurnResult,
type ExternalEnginePermissionRequest,
} from "@zcode/contracts";
import {
type EngineConfigOption,
Expand All @@ -31,17 +30,15 @@ import {
clientCapabilities,
configOptions,
isContinuationEnd,
isIdleContinuationUpdate,
object,
readPermissionRequest,
} from "./acp-session-support.js";
export { SUBAGENT_NAMING_INSTRUCTIONS } from "./acp-session-support.js";
const MAX_FRAME_BYTES = 16 * 1024 * 1024;
const CANCEL_GRACE_MS = 5000;
const HANDSHAKE_TIMEOUT_MS = 30000;
type JsonObject = Record<string, unknown>;
function object(value: unknown): JsonObject {
if (value === null || typeof value !== "object" || Array.isArray(value))
throw new ExternalEngineConnectionError({ code: "protocol" }, "Invalid ACP object");
return value as JsonObject;
}
type SessionMethod = NonNullable<EngineConnectionFailure["method"]>;
/** 已建立(或已预建)的原生会话;回调与配置恢复由 execute 继续完成。 */
interface OpenedSession {
Expand Down Expand Up @@ -89,6 +86,7 @@ export class AcpConnection {
private subagents = new Map<string, KnownSubagent>();
/** 轮间推送缓存与边沿唤醒(acp-session-support.ts)。 */
private idle = new IdleActivity();
private supportsIdleContinuation = false;
/** 进行中的 continuation:收到引擎续跑收尾标记时 resolve。 */
private continuation?: { resolve(): void; reject(error: Error): void };
get healthy(): boolean {
Expand All @@ -107,8 +105,15 @@ export class AcpConnection {
if (!this.active) {
// 修复:轮间引擎主动推送(Claude 后台任务完成后的自发续跑、子会话唤醒)曾在此被直接丢弃,
// “等通知”的会话结束后再无下文。改为按序缓存并边沿唤醒 Runtime 准入一轮 continuation。
if (!this.loadingHistory && !this.forking)
// Codex 没有对应的续跑收尾协议。普通空闲帧曾触发无法正常终止的空轮。
if (
this.supportsIdleContinuation &&
!this.loadingHistory &&
!this.forking &&
isIdleContinuationUpdate(object(params.update))
) {
this.idle.buffer(params, sessionId === this.externalSessionId || child);
}
return;
}
if (sessionId !== this.externalSessionId && !child) {
Expand Down Expand Up @@ -325,37 +330,26 @@ export class AcpConnection {
const routed = params.sessionId === this.externalSessionId || Boolean(childSessionId);
// 修复:轮间权限请求(续跑或子会话唤醒时的工具审批)曾一律回 cancelled,续跑随即失败;
// 已路由的请求改为唤醒 Runtime,等 continuation 接管后走正常审批。
if (!this.active && routed && this.sessionReady && !this.forking && !this.loadingHistory)
if (
!this.active &&
routed &&
this.supportsIdleContinuation &&
this.sessionReady &&
!this.forking &&
!this.loadingHistory
)
await this.idle.waitForActive();
if (this.forking || !this.active || !routed) {
if (this.active && params.sessionId !== this.externalSessionId)
this.diagnose("external_engine.subagent.unrouted_permission", params.sessionId);
this.send({ jsonrpc: "2.0", id: frame.id, result: { outcome: { outcome: "cancelled" } } });
return;
}
const toolCall = object(params.toolCall);
if (typeof toolCall.toolCallId !== "string" || !Array.isArray(params.options))
throw new Error("Invalid ACP permission request");
const options = params.options.map((value) => {
const option = object(value);
if (
typeof option.optionId !== "string" ||
typeof option.name !== "string" ||
!["allow_once", "allow_always", "reject_once", "reject_always"].includes(
String(option.kind),
)
)
throw new Error("Invalid ACP permission option");
return option as unknown as ExternalEnginePermissionRequest["options"][number];
});
const outcome = await this.active.requestPermission({
toolCall: toolCall as ExternalEnginePermissionRequest["toolCall"],
options,
...(childSessionId ? { childNativeSessionId: childSessionId } : {}),
});
const request = readPermissionRequest(params, childSessionId);
const outcome = await this.active.requestPermission(request);
if (
outcome.outcome === "selected" &&
!options.some((option) => option.optionId === outcome.optionId)
!request.options.some((option) => option.optionId === outcome.optionId)
)
throw new Error("Invalid ACP permission response");
this.send({ jsonrpc: "2.0", id: frame.id, result: { outcome } });
Expand Down Expand Up @@ -400,6 +394,7 @@ export class AcpConnection {
*/
initialize(engine: ExternalEngineSessionInput["engine"]): Promise<JsonObject> {
this.initialized ??= (async () => {
this.supportsIdleContinuation = engine === "claude-code";
const initialized = await this.request("initialize", {
protocolVersion: 1,
clientCapabilities: clientCapabilities(engine),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
text("permission:" + JSON.stringify(message.result.outcome));
send({ method: "session/update", params: { sessionId: sid, update: { sessionUpdate: "usage_update", used: 2, size: 10, cost: { amount: 0.2, currency: "USD" }, _meta: { "_claude/origin": { kind: "task-notification" } } } } });
}
else if (message.method === "session/set_config_option" && mode === "idle-metadata") {
for (const update of [
{ sessionUpdate: "usage_update", used: 1, size: 10 },
{ sessionUpdate: "current_mode_update", currentModeId: "auto" },
]) send({ method: "session/update", params: { sessionId: sid, update } });
send({ id: message.id, result: { configOptions: [] } });
}
else if (message.method === "session/prompt") {
prompt = message;
const env = {};
Expand Down Expand Up @@ -214,6 +221,23 @@ describe("轮间推送与引擎自发续跑", () => {
}
});

test.each(["codex", "claude-code"] as const)(
"%s 空闲期间的元数据通知不启动续跑",
async (engine) => {
const { port } = await setup(engine, { FIXTURE_MODE: "idle-metadata" });
const input = turn(engine);
const onIdleActivity = vi.fn();
try {
await port.runTurn({ ...input, onIdleActivity });
await port.setConfigOption(input.sessionId, "mode", "auto");
expect(onIdleActivity).not.toHaveBeenCalled();
expect(port.hasPendingContinuation?.(input.sessionId)).toBe(false);
} finally {
await port.closeSession(input.sessionId);
}
},
);

test("没有未消费推送时 continuation 立即结束,不发 session/prompt", async () => {
const { port } = await setup("claude-code", { FIXTURE_MODE: "session-params" });
const input = turn("claude-code");
Expand Down
2 changes: 2 additions & 0 deletions docs/composer-model-thinking.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## 交互

中文和英文界面均使用英文显示已知思考深度档位,例如 `High`、`Extra high` 和 `Max`。外部引擎的未知档位沿用目录名。

普通输入框的模型与 Think 使用一个入口。入口不显示 Provider 前缀:

```text
Expand Down
2 changes: 1 addition & 1 deletion docs/conversation-session-case-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2850,7 +2850,7 @@ scroll / before-mutation scope snapshot
| ID | 前置状态 | 用户/系统事件 | 规则命中 | 期望结果 | Review |
| ----- | --------------------------------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| SRM01 | 当前 renderer 首次打开有历史的 session,当前 pane 对该 session 没有记忆 | timeline 挂载并完成首轮测高 | scrollMemoryMissingDefaultsToBottom | 定位到当前最新底部,`following=true`,不显示“回到底部”;不创建协议、snapshot 或持久化字段 | accepted |
| SRM02 | 长会话中用户已上滚离底,`following=false` | 同一 pane 切到 draft/其它 task 后再切回 | scrollMemoryRestoresHistoricalPosition | before-mutation snapshot 从旧 DOM 保存离开前 `scrollTop`;切回在 layout + 下一帧恢复并 clamp 到当前合法范围,保持 `following=false` 且显示“回到底部”;若用户已再次滚动,下一帧校正不得覆盖用户落点 | accepted |
| SRM02 | 长会话中用户已上滚离底,`following=false` | 同一 pane 切到 draft/其它 task 后再切回 | scrollMemoryRestoresHistoricalPosition | before-mutation snapshot 从旧 DOM 保存离开前 `scrollTop`;切回在 layout + 下一帧恢复并 clamp 到当前合法范围,保持 `following=false` 且显示“回到底部”;若用户已再次滚动,下一帧校正不得覆盖用户落点。恢复后相邻历史轮次的实际矩形不得相交 | accepted |
| SRM03 | session 离开前处于吸底,切走后该 session 在后台继续流式输出 | 同一 pane 切回 running/completed session | scrollMemoryRestoresPinnedIntent | 不恢复旧像素值,而是滚到当前最新底部并继续跟随;后续 delta/测高增长仍自动吸底 | accepted |
| SRM04 | 同一 session 同时或先后出现在不同 workspace identity、pane、桌面窗口或手机 Web renderer | 各视图独立滚动并切换 session | scrollMemoryRendererPaneIsolation | workspace identity 与 pane 分桶;不同 renderer 不同步阅读位置;桌面 continuous 与手机 replayable 只共享 conversation 事实,不共享 UI 滚动状态 | accepted |
| SRM05 | 长会话中用户已上滚离底,`following=false`,当前输入路由可立即开始 | 用户从 composer 提交新 prompt,command accepted | promptSubmitFocusesLatest | 复用现有“滚动到底部”的 instant 动作:定位到最新内容并恢复 `following=true`;这是一次性意图,用户随后上滚仍立即解除跟随 | accepted |
Expand Down
2 changes: 2 additions & 0 deletions docs/desktop/external-agent-engines-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,8 @@ sequenceDiagram
- **结果**:子会话最终摘要优先取子会话最后一段完整正文,其次才取 reply;运行中到达的 reply 只暂存,不能在子会话仍可能继续时成为结果。
- **父轮结束不终结子会话**:父轮正常结束时仍 running 的 RFD 子会话保持 running——其 Agent 行从父 writer 的收尾清扫中摘出(不记 “did not complete”),不发 SubagentStopped;只有用户停止父轮(cancelled)、连接断开/进程退出(lost)或引擎报告终态才结束。
- **引擎自发续跑**:无 active 轮时到达的主会话更新与已宣告子会话的帧由 connection 按序缓存,并对每段空闲期只边沿触发一次 `onIdleActivity`。父 Runtime 收到后经既有 runtime 命令队列(与内置引擎 task-notification 同一串行准入,`CommandInbox` 不变)接纳一轮 **external-engine-continuation**:写一条 model-only 的合成输入(`inputPresentation: task_notification`,界面显示“后台任务完成,继续处理”),执行时**不发送 session/prompt**,只回放缓存并继续观察;遇到带 task-notification origin 的 `usage_update` 收尾为 TurnComplete。轮内子会话事件绑定本轮 writer;先前轮摘出的 Agent 行仍在其原行上收尾,SubagentStopped 写入本轮。
- **续跑准入**:目前只有 Claude 提供续跑结束协议。Codex 空闲期帧不启动续跑。Claude 主会话的普通用量、会话信息、配置、模式、命令目录和 notice 更新不单独启动续跑。带 task-notification 来源的结束帧、有效的子会话活动、正文/工具推送及权限请求仍由连接按既有顺序交给父 Runtime。配置确认继续使用既有配置请求响应。

- **与用户输入的关系**:续跑轮占用同一串行准入,用户新消息排在其后(引擎本身也串行);用户 Stop 续跑轮时发送 `session/cancel` 并按 cancelled 收尾。不以超时结束续跑轮:结束只来自引擎收尾标记、用户停止或连接失败。
- **回收**:存在 running 子会话或已缓存未消费的续跑时,会话不参与闲置回收(process-pool 的 busy 判定)。

Expand Down
11 changes: 11 additions & 0 deletions docs/renderer-performance-timeline-cleanup.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,14 @@ performance.getEntriesByType("measure").length
```

该数量应保持在较低范围,不再随运行时间无界增长。

## 会话切换后的历史布局

历史虚拟列表只使用当前会话的行键与实测高度。工作区或会话切换时,清除旧缓存并在恢复滚动前同步重测已挂载的历史行。即使两个会话的历史行数或行 ID 相同,相邻轮次也不得重叠。沿用现有会话滚动记忆和内容投影。

```mermaid
flowchart LR
A[当前会话投影] --> B[时间线按会话隔离行键]
B --> C[清除旧测高并同步重测历史行]
C --> D[按当前布局恢复滚动记忆]
```
2 changes: 1 addition & 1 deletion docs/testing/conversation-session-e2e-coverage-matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -1593,7 +1593,7 @@ BTA01/BTA02/BTA05/BTA08 的 Desktop manual-review 证据。无状态迁移后的
| Catalog ID | 覆盖状态 | 自动化 | 备注 |
| ---------- | -------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| SRM01 | covered | V4-SCROLL + SRM-UT | 无记忆 session 初次挂载默认吸底;E2E 与 timeline 单测共同断言 |
| SRM02 | covered | V4-SCROLL + SRM-UT | 长会话离底后切 draft 再切回,恢复旧 `scrollTop`、保持离底;单测补下一帧校正让位于用户滚动 |
| SRM02 | covered | V4-SCROLL + SRM-UT | 长会话离底后切 draft 再切回,恢复旧 `scrollTop`、保持离底、历史轮次不重叠。单测补下一帧校正让位于用户滚动 |
| SRM03 | covered | V4-SCROLL | running session 吸底切走,断言隐藏期间流式片段数增长;切回当前底部并继续跟随 |
| SRM04 | covered | SRM-UT | key 使用 workspace identity/path fallback + pane + session;不同 renderer 由进程内 Map 不共享这一不变量剪枝 |
| SRM05 | planned | SRM-UT | composer start-now accepted 后复用 instant bottom action,恢复 following;用户后续上滚仍可解除 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ describe("v4 M5④ 门禁:长会话虚拟滚动", () => {
},
);

const historyRects = await browser.execute(() =>
Array.from(
document.querySelectorAll('[data-v4-timeline-virtual-history="true"] > [data-index]'),
).map((row) => {
const { top, bottom } = row.getBoundingClientRect();
return { top, bottom };
}),
);
expect(historyRects.length).toBeGreaterThan(1);
for (let index = 1; index < historyRects.length; index += 1) {
expect(historyRects[index]!.top).toBeGreaterThanOrEqual(historyRects[index - 1]!.bottom - 1);
}

// ── turn2:慢流期间停在顶部,流式增量不得拉回 ──
await clickV4TimelineBackToBottom();
await sendV4Prompt("E2E_V4_SCROLL_TURN2 保持输出");
Expand Down
Loading