mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-19 06:45:15 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a012702b79 | ||
|
|
093866a3f0 | ||
|
|
5b99f85213 | ||
|
|
5e964a3847 | ||
|
|
51baa2beb8 | ||
|
|
31b6c2ebd3 | ||
|
|
3da26f32ab | ||
|
|
bcf52f93b1 | ||
|
|
d8c98400fb | ||
|
|
77392d3c1b | ||
|
|
8edccf0503 | ||
|
|
ac633eb096 | ||
|
|
25ff8adf06 | ||
|
|
09a15abb06 | ||
|
|
81fb9c03f6 |
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
|
||||
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
|
||||
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
|
||||
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
|
||||
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
|
||||
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath))
|
||||
- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery))
|
||||
- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto))
|
||||
- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82))
|
||||
- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid))
|
||||
- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem))
|
||||
- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun))
|
||||
- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### 修复
|
||||
|
||||
+2
-2
@@ -50,8 +50,8 @@ or without a control.
|
||||
reject. A key the running session cannot apply (one the provider reads only when it opens) is
|
||||
rejected too, so a stored option always describes what runs. Claude reads most options when it
|
||||
starts its query, and replacing a started query would end its background work, so after the
|
||||
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
|
||||
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
|
||||
first prompt only Fast and Ultracode can change. Codex fixes its approval policy and sandbox
|
||||
when the thread starts, so it applies only `service_tier` and `plan_mode` live. A session with no
|
||||
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
|
||||
it ended up with when they differ from the request. The daemon stores the patch and that
|
||||
result in one step after the call resolves. Throwing rejects the whole patch and none of it is
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
|
||||
sha256-yLTaVMgu3tc/dgngJ7RP0htJcWE0ZtQ4mouypevyv0s=
|
||||
|
||||
Generated
+28
-28
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37468,7 +37468,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39637,13 +39637,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39890,11 +39890,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39906,7 +39906,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40149,7 +40149,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40195,7 +40195,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40225,7 +40225,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40233,8 +40233,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40244,8 +40244,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40267,7 +40267,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40295,7 +40295,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40517,17 +40517,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
@@ -41474,7 +41474,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43084,7 +43084,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -56,11 +56,20 @@ function inFlightTurn(page: Page) {
|
||||
return page.getByTestId("turn-working-indicator");
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses a fork trigger until its menu shows.
|
||||
*
|
||||
* The in-flight turn's trigger sits below text that is still streaming in. While the chat is
|
||||
* shorter than the viewport, each new line moves the trigger down. A line that arrives between
|
||||
* the press and the release moves the trigger away from the pointer, so the press opens nothing,
|
||||
* and the next press lands on the trigger where it is now.
|
||||
*/
|
||||
async function openForkMenu(page: Page, trigger: ReturnType<Page["getByRole"]>): Promise<void> {
|
||||
await trigger.click();
|
||||
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
const forkInNewTab = page.getByRole("menuitem", { name: "Fork in a new tab" });
|
||||
await expect(async () => {
|
||||
await trigger.click({ timeout: 5_000 });
|
||||
await expect(forkInNewTab).toBeVisible({ timeout: 5_000 });
|
||||
}).toPass({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -30,6 +30,25 @@ function answer(
|
||||
}
|
||||
|
||||
describe("draft options model", () => {
|
||||
it("retains an Ultracode option only after the current host advertises it", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
const legacy = { provider: "claude", cwd: "/repo", thinkingOptionId: "ultracode" };
|
||||
model.applyResolved(answer("claude", "old-host", {}, []));
|
||||
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
|
||||
expect(draftControlsRequest(model.getState(), legacy)).toEqual(legacy);
|
||||
|
||||
model.applyResolved(
|
||||
answer("claude", "new-host", { ultracode: true }, [
|
||||
{ type: "toggle", key: "ultracode", label: "Ultracode" },
|
||||
]),
|
||||
);
|
||||
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
|
||||
expect(model.retainResolvedOption("ultracode", "new-host")).toEqual({ ultracode: true });
|
||||
expect(
|
||||
draftControlsRequest(model.getState(), { ...legacy, thinkingOptionId: "high" }),
|
||||
).toMatchObject({ thinkingOptionId: "high", providerOptions: { ultracode: true } });
|
||||
});
|
||||
|
||||
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
|
||||
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
|
||||
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
|
||||
|
||||
@@ -47,6 +47,7 @@ export interface DraftOptionsModel {
|
||||
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
|
||||
setRemembered: (remembered: ProviderOptions) => void;
|
||||
setOption: (key: string, value: unknown) => void;
|
||||
retainResolvedOption: (key: string, requestKey: string) => ProviderOptions | undefined;
|
||||
applyResolved: (resolved: ResolvedDraftOptions) => void;
|
||||
}
|
||||
|
||||
@@ -112,6 +113,17 @@ export function openDraftOptions(input: {
|
||||
: { ...current, edits: { ...current.edits, [key]: value } },
|
||||
);
|
||||
},
|
||||
retainResolvedOption: (key, requestKey) => {
|
||||
const resolved = state.resolved;
|
||||
if (resolved?.requestKey !== requestKey || key in state.edits) return undefined;
|
||||
const value = resolved.options[key];
|
||||
if (value === undefined || !resolved.controls.some((control) => control.key === key)) {
|
||||
return undefined;
|
||||
}
|
||||
const patch = { [key]: value };
|
||||
publish((current) => ({ ...current, edits: { ...current.edits, ...patch } }));
|
||||
return patch;
|
||||
},
|
||||
applyResolved: (resolved) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -215,6 +215,32 @@ describe("Mermaid sandbox runtime", () => {
|
||||
expect(widths).toEqual([240, 350, 900]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Agents often write a label that starts with a mention or holds an email address. Mermaid 11
|
||||
* read the text up to the "@" as an edge id, so these diagrams failed to parse.
|
||||
*/
|
||||
it.each([
|
||||
"flowchart LR\n F[@mention in any workspace] --> G[Look up token]",
|
||||
"flowchart LR\n A[ops@example.com] --> B",
|
||||
"flowchart LR\n A -->|@user approves| B",
|
||||
"graph TD\n A(@x) --> B{@x?}",
|
||||
])("renders a flowchart whose label contains an @: %s", async (source) => {
|
||||
const frame = await mountRuntime();
|
||||
|
||||
const result = await render(frame, { revision: 1, source });
|
||||
|
||||
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
|
||||
});
|
||||
|
||||
it("still renders a flowchart edge id", async () => {
|
||||
const frame = await mountRuntime();
|
||||
const source = "flowchart LR\n A[Start] e1@--> B[End]";
|
||||
|
||||
const result = await render(frame, { revision: 1, source });
|
||||
|
||||
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
|
||||
});
|
||||
|
||||
it("coalesces queued input and never reports an obsolete result", async () => {
|
||||
const frame = await mountRuntime();
|
||||
const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment jsdom
|
||||
import type { ReactNode } from "react";
|
||||
import { cleanup, renderHook, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import type { AttachmentStore } from "@/attachments/types";
|
||||
import { useMarkdownSource, type MarkdownImageContext } from "./images";
|
||||
import { PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
|
||||
const memoryStore: AttachmentStore = {
|
||||
storageType: "web-indexeddb",
|
||||
async save(input) {
|
||||
return {
|
||||
id: input.id ?? "att_chart",
|
||||
mimeType: input.mimeType ?? "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: input.id ?? "att_chart",
|
||||
fileName: input.fileName,
|
||||
createdAt: 1,
|
||||
};
|
||||
},
|
||||
async encodeBase64() {
|
||||
return "";
|
||||
},
|
||||
async resolvePreviewUrl() {
|
||||
return "blob:chart";
|
||||
},
|
||||
async releasePreviewUrl() {},
|
||||
async delete() {},
|
||||
async garbageCollect() {},
|
||||
};
|
||||
|
||||
function createHostFiles() {
|
||||
const reads: { cwd: string; path: string }[] = [];
|
||||
return {
|
||||
reads,
|
||||
async readFile(cwd: string, path: string): Promise<FileReadResult> {
|
||||
reads.push({ cwd, path });
|
||||
return {
|
||||
kind: "image",
|
||||
path,
|
||||
mime: "image/png",
|
||||
size: 4,
|
||||
modifiedAt: "2026-11-18T00:00:00.000Z",
|
||||
bytes: new Uint8Array([1, 2, 3, 4]),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
__setAttachmentStoreForTests(memoryStore);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
__setAttachmentStoreForTests(null);
|
||||
});
|
||||
|
||||
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
|
||||
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
|
||||
// retries have run out on a host that is slow to connect.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
|
||||
wrapper,
|
||||
initialProps,
|
||||
});
|
||||
return { ...rendered, queryClient };
|
||||
}
|
||||
|
||||
it("waits for the host's client before reading a workspace image", async () => {
|
||||
const context = { serverId: "srv_test", workspaceRoot: "/repo" };
|
||||
const { result, rerender, queryClient } = renderMarkdownSource("", {
|
||||
...context,
|
||||
client: null,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe(
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
const files = createHostFiles();
|
||||
rerender({ ...context, client: files });
|
||||
|
||||
await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" }));
|
||||
expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]);
|
||||
});
|
||||
|
||||
it("shows the alt text of a file image in Markdown that belongs to no host", async () => {
|
||||
const { result } = renderMarkdownSource("", {});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
|
||||
);
|
||||
});
|
||||
@@ -81,7 +81,10 @@ export function useMarkdownSource(
|
||||
const results = useFetchQueries(
|
||||
acquisitions.map((acquisition, index) => ({
|
||||
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
|
||||
enabled: acquisition !== null,
|
||||
// A host that hasn't connected yet has no client. Its images stay pending until it does: the
|
||||
// key doesn't change when the client arrives, so a read that already failed would not run
|
||||
// again. Markdown with no host has no client to wait for and falls back to its alt text.
|
||||
enabled: acquisition !== null && (context.client != null || !context.serverId),
|
||||
immutableWhen: () => true,
|
||||
dataShape: "value",
|
||||
gcTime: 0,
|
||||
|
||||
@@ -21,7 +21,7 @@ import { highlightDiffLines } from "@/utils/diff-highlight";
|
||||
import { hasMeaningfulToolCallDetail } from "@/utils/tool-call-detail-state";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
|
||||
import { extensionFromPath, highlightToKeyedLines } from "@/utils/highlight-cache";
|
||||
import { highlightToKeyedLines } from "@/utils/highlight-cache";
|
||||
import { HighlightedLines } from "./highlighted-content";
|
||||
import { DiffViewer } from "./diff-viewer";
|
||||
import { getCodeInsets } from "./code-insets";
|
||||
@@ -226,7 +226,7 @@ function ScrollableTextSection({
|
||||
startLine,
|
||||
}: ScrollableContentProps) {
|
||||
const keyedLines = useMemo(
|
||||
() => (filePath ? highlightToKeyedLines(content, extensionFromPath(filePath)) : null),
|
||||
() => highlightToKeyedLines(content, filePath ?? null),
|
||||
[content, filePath],
|
||||
);
|
||||
const body = (
|
||||
|
||||
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
|
||||
expect(trigger.textContent).not.toContain("Large");
|
||||
});
|
||||
|
||||
it("flips a toggle on press in the toolbar", () => {
|
||||
it("keeps the toolbar toggle name and flips it on press", () => {
|
||||
const onChange = vi.fn();
|
||||
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Context" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Context$/ }));
|
||||
expect(onChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
@@ -94,6 +94,12 @@ describe("ComposerControls", () => {
|
||||
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
|
||||
});
|
||||
|
||||
it("keeps the provider's tooltip for a toolbar toggle", () => {
|
||||
const tooltip = "Fast is enabled but does not apply to this model.";
|
||||
renderControls([{ ...base, type: "toggle", value: true, tooltip, onChange: () => undefined }]);
|
||||
expect(screen.getByRole("button", { name: tooltip })).toBeDefined();
|
||||
});
|
||||
|
||||
it("gives a sheet row's value the row's width, so a short value is not truncated", () => {
|
||||
const toast = createToast();
|
||||
render(
|
||||
@@ -157,6 +163,8 @@ describe("ComposerControls", () => {
|
||||
});
|
||||
|
||||
const FAST_ON = { fast_mode: true };
|
||||
const ULTRACODE_ON = { ultracode: true };
|
||||
const ignoreOption = () => undefined;
|
||||
|
||||
describe("provider option controls", () => {
|
||||
const fastMode: AgentOptionControl = {
|
||||
@@ -173,7 +181,11 @@ describe("provider option controls", () => {
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}) {
|
||||
const optionControls = React.useMemo(
|
||||
() => ({ controls: [fastMode], options, onSetOption }),
|
||||
() => ({
|
||||
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
|
||||
options,
|
||||
onSetOption,
|
||||
}),
|
||||
[onSetOption, options],
|
||||
);
|
||||
const items = useAgentControlItems({
|
||||
@@ -197,4 +209,9 @@ describe("provider option controls", () => {
|
||||
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
|
||||
expect(writes).toEqual([["fast_mode", false]]);
|
||||
});
|
||||
|
||||
it("announces the state of a provider toggle with no custom tooltip", () => {
|
||||
render(<OptionControls options={ULTRACODE_ON} onSetOption={ignoreOption} />);
|
||||
expect(screen.getByRole("button", { name: "Ultracode: On" })).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ interface ComposerControlBase {
|
||||
title: string;
|
||||
icon: AgentControlIcon;
|
||||
/** Tints the icon; muted when absent. */
|
||||
highlight?: "blue" | "green" | "yellow";
|
||||
highlight?: "blue" | "green" | "purple" | "yellow";
|
||||
/** Defaults to the title, or to "title: choice" on an icon-only select. */
|
||||
tooltip?: string;
|
||||
/** Defaults to the tooltip. */
|
||||
@@ -393,6 +393,7 @@ function ComposerControlSlot({
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
fieldIcon: { color: theme.colors.foregroundMuted },
|
||||
blue: { color: theme.colors.palette.blue[400] },
|
||||
purple: { color: theme.colors.palette.purple[500] },
|
||||
green: { color: theme.colors.palette.green[400] },
|
||||
yellow: { color: theme.colors.palette.yellow[400] },
|
||||
tooltipText: {
|
||||
|
||||
@@ -33,6 +33,8 @@ function getFeatureHighlight(
|
||||
function toFeatureItem(
|
||||
control: AgentOptionControl,
|
||||
optionControls: ComposerOptionControls,
|
||||
surface: ComposerControlSurface,
|
||||
t: TFunction,
|
||||
): ComposerControlItem {
|
||||
const { options, onSetOption } = optionControls;
|
||||
const base = {
|
||||
@@ -43,11 +45,15 @@ function toFeatureItem(
|
||||
testID: `agent-feature-${control.key}`,
|
||||
};
|
||||
if (control.type === "toggle") {
|
||||
const enabled = readToggleOption(control, options);
|
||||
const stateLabel = enabled ? t("agentControls.features.on") : t("agentControls.features.off");
|
||||
return {
|
||||
...base,
|
||||
type: "toggle",
|
||||
tooltip: getControlTooltip(control),
|
||||
value: readToggleOption(control, options),
|
||||
tooltip:
|
||||
control.tooltip ??
|
||||
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
|
||||
value: enabled,
|
||||
onChange: (value) => onSetOption(control.key, value),
|
||||
};
|
||||
}
|
||||
@@ -92,9 +98,11 @@ export function useAgentControlItems({
|
||||
const features = useMemo(
|
||||
() =>
|
||||
optionControls
|
||||
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
|
||||
? optionControls.controls.map((control) =>
|
||||
toFeatureItem(control, optionControls, surface, t),
|
||||
)
|
||||
: [],
|
||||
[optionControls],
|
||||
[optionControls, surface, t],
|
||||
);
|
||||
return { thinking: thinkingItem, features };
|
||||
}
|
||||
|
||||
@@ -1316,8 +1316,7 @@ export function DraftAgentControls({
|
||||
return toThinkingControlOptions(thinkingOptions);
|
||||
}, [thinkingOptions]);
|
||||
|
||||
const effectiveSelectedThinkingOption =
|
||||
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
|
||||
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(
|
||||
() =>
|
||||
|
||||
@@ -20,6 +20,7 @@ describe("feature metadata helpers", () => {
|
||||
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
|
||||
expect(getFeatureHighlightColor("ultracode")).toBe("purple");
|
||||
expect(getFeatureHighlightColor("other")).toBe("default");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "@/agent-controls/policy";
|
||||
|
||||
export type ExplainedAgentControl = "mode" | "model" | "thinking";
|
||||
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
|
||||
export type FeatureHighlightColor = "blue" | "default" | "green" | "purple" | "yellow";
|
||||
export type AgentControlHintKey =
|
||||
| "agentControls.hints.thinking"
|
||||
| "agentControls.hints.model"
|
||||
@@ -48,6 +48,8 @@ export function getFeatureHighlightColor(featureId: string): FeatureHighlightCol
|
||||
return "yellow";
|
||||
case "auto_accept":
|
||||
return "green";
|
||||
case "ultracode":
|
||||
return "purple";
|
||||
case PLAN_MODE_FEATURE_ID:
|
||||
return "blue";
|
||||
default:
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
resolveEffectiveComposerThinkingOptionId,
|
||||
type ProviderSelectionState,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
|
||||
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
|
||||
import { AfterPaintPublication } from "@/composer/after-paint-publication";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
@@ -293,6 +294,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
options: draftOptions,
|
||||
shownOptions: draftShownOptions,
|
||||
setOption: setDraftOption,
|
||||
retainLegacyUltracode,
|
||||
applyProfile: applyProfileOptions,
|
||||
} = useDraftProviderOptions({
|
||||
serverId: formState.selectedServerId,
|
||||
@@ -312,6 +314,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
},
|
||||
[applyProfileOptions, formState],
|
||||
);
|
||||
const setDraftThinking = useCallback(
|
||||
(thinkingOptionId: string) =>
|
||||
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
|
||||
[formState, retainLegacyUltracode],
|
||||
);
|
||||
|
||||
const commandDraft = useMemo(
|
||||
() =>
|
||||
@@ -330,8 +337,18 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
|
||||
const draftForm = {
|
||||
...formState,
|
||||
selectedThinkingOptionId:
|
||||
findThinkingOptionReplacement(
|
||||
formState.availableThinkingOptions,
|
||||
formState.selectedThinkingOptionId,
|
||||
) ?? formState.selectedThinkingOptionId,
|
||||
setThinkingOptionFromUser: setDraftThinking,
|
||||
};
|
||||
return {
|
||||
...draftForm,
|
||||
workingDir,
|
||||
effectiveModeId,
|
||||
effectiveModelId,
|
||||
@@ -339,7 +356,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
providerOptions: draftOptions,
|
||||
metadata,
|
||||
agentControls: buildDraftAgentControls({
|
||||
formState,
|
||||
formState: draftForm,
|
||||
optionControls: draftOptionControls,
|
||||
options: draftShownOptions,
|
||||
onSetOption: setDraftOption,
|
||||
@@ -360,6 +377,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
draftOptions,
|
||||
draftShownOptions,
|
||||
setDraftOption,
|
||||
setDraftThinking,
|
||||
applyDraftAgentProfile,
|
||||
formState,
|
||||
metadata,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
AgentMode,
|
||||
AgentModelDefinition,
|
||||
AgentProvider,
|
||||
ProviderOptions,
|
||||
ProviderSnapshotEntry,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import { buildProviderDefinitions } from "@/utils/provider-definitions";
|
||||
@@ -58,7 +59,7 @@ export interface UseAgentFormStateResult {
|
||||
selectedModel: string;
|
||||
setModelFromUser: (modelId: string) => void;
|
||||
selectedThinkingOptionId: string;
|
||||
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
|
||||
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
|
||||
workingDir: string;
|
||||
providerDefinitions: AgentProviderDefinition[];
|
||||
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
|
||||
@@ -419,7 +420,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
);
|
||||
|
||||
const setThinkingOptionFromUser = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
(thinkingOptionId: string, retainedOptions?: ProviderOptions) => {
|
||||
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
|
||||
const { provider, model: modelId } = formStore.getState().form;
|
||||
if (provider && modelId) {
|
||||
@@ -431,6 +432,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
thinkingByModel: {
|
||||
[modelId]: thinkingOptionId,
|
||||
},
|
||||
options: retainedOptions,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -69,6 +69,14 @@ export function useDraftProviderOptions(input: {
|
||||
[draftConfig, serverId],
|
||||
);
|
||||
const requestKey = JSON.stringify(queryKey);
|
||||
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
|
||||
const retainLegacyUltracode = useCallback(
|
||||
() =>
|
||||
thinkingOptionId === "ultracode"
|
||||
? model.retainResolvedOption("ultracode", requestKey)
|
||||
: undefined,
|
||||
[model, requestKey, thinkingOptionId],
|
||||
);
|
||||
|
||||
const { data } = useFetchQuery({
|
||||
queryKey,
|
||||
@@ -129,6 +137,7 @@ export function useDraftProviderOptions(input: {
|
||||
options: ownOptions,
|
||||
shownOptions,
|
||||
setOption,
|
||||
retainLegacyUltracode,
|
||||
applyProfile: model.applyProfile,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -167,6 +167,14 @@ function resolvePreferredThinkingOptionId(input: {
|
||||
return "";
|
||||
}
|
||||
|
||||
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
|
||||
export function findThinkingOptionReplacement(
|
||||
options: NonNullable<AgentModelDefinition["thinkingOptions"]>,
|
||||
legacyId: string,
|
||||
): string | undefined {
|
||||
return options.find((option) => option.metadata?.replacesThinkingOptionId === legacyId)?.id;
|
||||
}
|
||||
|
||||
export function resolveThinkingOptionId(args: {
|
||||
availableModels: AgentModelDefinition[] | null;
|
||||
modelId: string;
|
||||
@@ -183,6 +191,9 @@ export function resolveThinkingOptionId(args: {
|
||||
) {
|
||||
return normalizedThinkingOptionId;
|
||||
}
|
||||
if (findThinkingOptionReplacement(thinkingOptions, normalizedThinkingOptionId)) {
|
||||
return normalizedThinkingOptionId;
|
||||
}
|
||||
|
||||
return effectiveModel?.defaultThinkingOptionId ?? thinkingOptions[0]?.id ?? "";
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ function scheduleOnHost(input: {
|
||||
serverName: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
provider?: string;
|
||||
thinkingOptionId?: string | null;
|
||||
cadence?: ScheduleSummary["cadence"];
|
||||
}): TestSchedule {
|
||||
@@ -109,7 +110,7 @@ function scheduleOnHost(input: {
|
||||
target: {
|
||||
type: "new-agent",
|
||||
config: {
|
||||
provider: "mock",
|
||||
provider: input.provider ?? "mock",
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
modeId: "load-test",
|
||||
@@ -186,6 +187,56 @@ function applyPreferences(form: ReturnType<typeof open>, preferences: FormPrefer
|
||||
}
|
||||
|
||||
describe("schedule form model", () => {
|
||||
it("keeps Ultra Code available in the schedule effort picker", () => {
|
||||
const model = "claude-opus-4-8";
|
||||
const form = open({
|
||||
mode: "edit",
|
||||
schedule: scheduleOnHost({
|
||||
serverId: "host-a",
|
||||
serverName: "Host A",
|
||||
cwd: "/repo/a",
|
||||
provider: "claude",
|
||||
model,
|
||||
thinkingOptionId: "ultracode",
|
||||
}),
|
||||
defaults: { serverId: null, projectTargets: PROJECT_TARGETS, preferences: {} },
|
||||
});
|
||||
form.applyProviderSnapshot("host-a", {
|
||||
...providerSnapshot([]),
|
||||
entries: [
|
||||
{
|
||||
provider: "claude",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
models: [
|
||||
{
|
||||
provider: "claude",
|
||||
id: model,
|
||||
label: "Opus 4.8",
|
||||
thinkingOptions: [
|
||||
{ id: "high", label: "High" },
|
||||
{
|
||||
id: "xhigh",
|
||||
label: "Extra high",
|
||||
metadata: { replacesThinkingOptionId: "ultracode" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(form.getState().selectedThinkingOptionId).toBe("ultracode");
|
||||
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
|
||||
"ultracode",
|
||||
);
|
||||
form.setThinking("high");
|
||||
expect(form.getState().selectedThinkingOptionId).toBe("high");
|
||||
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
|
||||
"ultracode",
|
||||
);
|
||||
});
|
||||
|
||||
it("opens edit from the schedule host snapshot and completes that host resolution", () => {
|
||||
const previous = open({
|
||||
mode: "edit",
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { filterSelectableModels, findModelByReference } from "@/provider-selection/model-catalog";
|
||||
import {
|
||||
buildProviderDefinitionMapForStatuses,
|
||||
findThinkingOptionReplacement,
|
||||
INITIAL_USER_MODIFIED,
|
||||
RESOLVABLE_PROVIDER_STATUSES,
|
||||
resolveDefaultModelId,
|
||||
@@ -273,7 +274,14 @@ function resolveThinkingOptions(
|
||||
modelId: string,
|
||||
): NonNullable<AgentModelDefinition["thinkingOptions"]> {
|
||||
const model = resolveEffectiveModel(resolveAvailableModels(entries, provider), modelId);
|
||||
return model?.thinkingOptions ?? [];
|
||||
const options = model?.thinkingOptions ?? [];
|
||||
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18
|
||||
// once schedules edit the Ultracode option independently.
|
||||
// Schedules still use a single effort field.
|
||||
return findThinkingOptionReplacement(options, "ultracode") &&
|
||||
!options.some((option) => option.id === "ultracode")
|
||||
? [...options, { id: "ultracode", label: "Ultra Code" }]
|
||||
: options;
|
||||
}
|
||||
|
||||
function resolveModelDisplay(input: {
|
||||
|
||||
@@ -26,6 +26,16 @@ describe("highlightDiffLines", () => {
|
||||
expect(add?.tokens?.some((token) => token.style === "keyword")).toBe(true);
|
||||
});
|
||||
|
||||
it("highlights a Dockerfile diff using the filename", () => {
|
||||
const diff = buildLineDiff("FROM alpine:3.21", "FROM alpine:3.22");
|
||||
const result = highlightDiffLines(diff, "/repo/docker/Dockerfile");
|
||||
|
||||
expect(result.find((line) => line.type === "add")?.tokens).toContainEqual({
|
||||
text: "FROM",
|
||||
style: "keyword",
|
||||
});
|
||||
});
|
||||
|
||||
it("highlights a Codex-style unified diff with bare @@ headers (no line ranges)", () => {
|
||||
const unified = ["@@", "-const x = 1;", "+const x = 2;", " const y = 3;"].join("\n");
|
||||
const result = highlightDiffLines(parseUnifiedDiff(unified), "/repo/a.ts");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isLanguageSupported, type HighlightToken } from "@getpaseo/highlight";
|
||||
import { extensionFromPath, tokenizeToLines } from "@/utils/highlight-cache";
|
||||
import { tokenizeToLines } from "@/utils/highlight-cache";
|
||||
import type { DiffLine } from "@/utils/tool-call-parsers";
|
||||
|
||||
// The leading diff marker glyph for a line. The code on the line is the content
|
||||
@@ -30,7 +30,7 @@ function diffLineCode(line: DiffLine): string {
|
||||
}
|
||||
|
||||
// Attach syntax-highlight tokens to each diff line. Language comes from the file
|
||||
// path (extension only). We reconstruct the old and new document text from the
|
||||
// path. We reconstruct the old and new document text from the
|
||||
// diff lines by position — counting context/remove into "old" and context/add
|
||||
// into "new" — so this works regardless of whether the source diff carried real
|
||||
// `@@ -n,m +n,m @@` line ranges (Codex emits bare `@@`). Each document is
|
||||
@@ -41,11 +41,10 @@ export function highlightDiffLines(
|
||||
diffLines: DiffLine[],
|
||||
filePath: string | null | undefined,
|
||||
): DiffLine[] {
|
||||
const ext = extensionFromPath(filePath);
|
||||
// Gate on real grammar support: an unsupported language would tokenize to a
|
||||
// single style-less token per line, which would shadow the word-level change
|
||||
// segments the diff already computes. Better to keep those.
|
||||
if (!ext || diffLines.length === 0 || !isLanguageSupported(`x.${ext}`)) {
|
||||
if (!filePath || diffLines.length === 0 || !isLanguageSupported(filePath)) {
|
||||
return diffLines;
|
||||
}
|
||||
|
||||
@@ -72,8 +71,8 @@ export function highlightDiffLines(
|
||||
return { oldIndex: -1, newIndex: -1 };
|
||||
});
|
||||
|
||||
const oldTokens = oldCode.length > 0 ? tokenizeToLines(oldCode.join("\n"), ext) : null;
|
||||
const newTokens = newCode.length > 0 ? tokenizeToLines(newCode.join("\n"), ext) : null;
|
||||
const oldTokens = oldCode.length > 0 ? tokenizeToLines(oldCode.join("\n"), filePath) : null;
|
||||
const newTokens = newCode.length > 0 ? tokenizeToLines(newCode.join("\n"), filePath) : null;
|
||||
if (!oldTokens && !newTokens) {
|
||||
return diffLines;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
extensionFromPath,
|
||||
highlightToKeyedLines,
|
||||
MAX_HIGHLIGHT_CHARS,
|
||||
tokenizeToLines,
|
||||
} from "./highlight-cache";
|
||||
|
||||
describe("extensionFromPath", () => {
|
||||
it("extracts a lowercased extension regardless of absolute/relative path", () => {
|
||||
expect(extensionFromPath("/repo/src/Index.TS")).toBe("ts");
|
||||
expect(extensionFromPath("src/index.ts")).toBe("ts");
|
||||
expect(extensionFromPath("a.b/c.tsx")).toBe("tsx");
|
||||
});
|
||||
|
||||
it("returns null for paths without a usable extension", () => {
|
||||
expect(extensionFromPath(null)).toBeNull();
|
||||
expect(extensionFromPath(undefined)).toBeNull();
|
||||
expect(extensionFromPath("Makefile")).toBeNull();
|
||||
expect(extensionFromPath(".gitignore")).toBeNull();
|
||||
expect(extensionFromPath("trailingdot.")).toBeNull();
|
||||
});
|
||||
});
|
||||
import { highlightToKeyedLines, MAX_HIGHLIGHT_CHARS, tokenizeToLines } from "./highlight-cache";
|
||||
|
||||
describe("tokenizeToLines", () => {
|
||||
it("returns one token array per line for a supported language", () => {
|
||||
@@ -30,7 +9,7 @@ describe("tokenizeToLines", () => {
|
||||
expect(lines?.[0].some((token) => token.style === "keyword")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns null when there is no extension", () => {
|
||||
it("returns null when there is no filename", () => {
|
||||
expect(tokenizeToLines("whatever", null)).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { highlightCode, type HighlightToken } from "@getpaseo/highlight";
|
||||
// Shared, theme-independent tokenization + cache for syntax highlighting.
|
||||
// Used by markdown code blocks, file preview, and tool-call detail blocks
|
||||
// (Edit diff / Write / Read). Colors are applied at render time, so the cache
|
||||
// key is just (extension, code) and one entry serves both light and dark.
|
||||
// key is just (filename, code) and one entry serves both light and dark.
|
||||
|
||||
export interface KeyedToken {
|
||||
key: string;
|
||||
@@ -44,18 +44,17 @@ class LRUCache<K, V> {
|
||||
|
||||
const tokenizationCache = new LRUCache<string, HighlightToken[][]>(200);
|
||||
|
||||
// Tokenize `code` to per-line tokens, cached. Returns null when the language is
|
||||
// unsupported, the input is over the size cap, or parsing throws — callers then
|
||||
// render plain text.
|
||||
export function tokenizeToLines(code: string, ext: string | null): HighlightToken[][] | null {
|
||||
if (!ext) return null;
|
||||
// Tokenize `code` to per-line tokens, cached. Returns null when the filename is absent,
|
||||
// the input exceeds the size cap, or parsing throws.
|
||||
export function tokenizeToLines(code: string, filename: string | null): HighlightToken[][] | null {
|
||||
if (!filename) return null;
|
||||
if (code.length > MAX_HIGHLIGHT_CHARS) return null;
|
||||
const cacheKey = `${ext}:${code}`;
|
||||
const cacheKey = `${filename.length}:${filename}${code}`;
|
||||
const cached = tokenizationCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
let lines: HighlightToken[][];
|
||||
try {
|
||||
lines = highlightCode(code, `x.${ext}`);
|
||||
lines = highlightCode(code, filename);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -73,17 +72,7 @@ function toKeyedLine(tokens: HighlightToken[], lineIndex: number): KeyedLine {
|
||||
};
|
||||
}
|
||||
|
||||
export function highlightToKeyedLines(code: string, ext: string | null): KeyedLine[] | null {
|
||||
const lines = tokenizeToLines(code, ext);
|
||||
export function highlightToKeyedLines(code: string, filename: string | null): KeyedLine[] | null {
|
||||
const lines = tokenizeToLines(code, filename);
|
||||
return lines ? lines.map(toKeyedLine) : null;
|
||||
}
|
||||
|
||||
// Extension for grammar selection from a file path. We only need the suffix —
|
||||
// absolute vs relative paths are equivalent here.
|
||||
export function extensionFromPath(filePath: string | null | undefined): string | null {
|
||||
if (!filePath) return null;
|
||||
const name = filePath.split(/[\\/]/).pop() ?? filePath;
|
||||
const dot = name.lastIndexOf(".");
|
||||
if (dot <= 0 || dot === name.length - 1) return null;
|
||||
return name.slice(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
@@ -92,7 +92,11 @@ const pinnedTheme = {
|
||||
const testTheme = {
|
||||
...lightTheme,
|
||||
...pinnedTheme,
|
||||
colors: { ...lightTheme.colors, ...pinnedTheme.colors },
|
||||
colors: {
|
||||
...lightTheme.colors,
|
||||
...pinnedTheme.colors,
|
||||
palette: { ...lightTheme.colors.palette, ...pinnedTheme.colors.palette },
|
||||
},
|
||||
};
|
||||
|
||||
type StyleFactory<T> = (theme: typeof testTheme) => T;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -368,6 +368,29 @@ async function waitForGuestActiveElement(client, browserId, elementId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A wait whose condition never matches must say which condition expired, not blame the host.
|
||||
async function verifyExpiredWaitNamesItsCondition(client, targetUrl) {
|
||||
const created = await callBrowserTool(client, "browser_new_tab", { url: targetUrl });
|
||||
const browserId = created.browserId;
|
||||
assert(typeof browserId === "string", "browser_new_tab returned no browserId for the wait page");
|
||||
try {
|
||||
await callBrowserTool(client, "browser_wait", { browserId, text: "Bridge target" });
|
||||
// The page title is not body text, so this wait expires.
|
||||
const response = await client.callTool({
|
||||
name: "browser_wait",
|
||||
args: { browserId, text: "Desktop browser target", timeoutMs: 1_000 },
|
||||
});
|
||||
const text = response.content?.[0]?.text;
|
||||
assert(
|
||||
response.structuredContent?.ok === false &&
|
||||
text === "Timed out waiting for browser text: Desktop browser target",
|
||||
`browser_wait did not name its expired condition: ${JSON.stringify(response.content)}`,
|
||||
);
|
||||
} finally {
|
||||
await callBrowserTool(client, "browser_close_tab", { browserId });
|
||||
}
|
||||
}
|
||||
|
||||
// A page whose Content Security Policy omits 'unsafe-eval' refuses eval(); the tools must still work.
|
||||
async function verifyEvaluateOnPageWithoutUnsafeEval(client, targetUrl) {
|
||||
const created = await callBrowserTool(client, "browser_new_tab", {
|
||||
@@ -791,6 +814,7 @@ async function runRegression({
|
||||
|
||||
await verifyReactFormFill((name, args) => callBrowserTool(client, name, args), targetUrl);
|
||||
await verifyEvaluateOnPageWithoutUnsafeEval(client, targetUrl);
|
||||
await verifyExpiredWaitNamesItsCondition(client, targetUrl);
|
||||
|
||||
const created = await callBrowserTool(client, "browser_new_tab", { url: targetUrl });
|
||||
const browserId = created.browserId;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -34,6 +34,21 @@ describe("highlightCode", () => {
|
||||
expect(stringToken?.style).toBe("string");
|
||||
});
|
||||
|
||||
it.each(["scripts/build.sh", "build.bash", "build.zsh"])("highlights shell in %s", (path) => {
|
||||
const lines = highlightCode('export MESSAGE="hello"', path);
|
||||
expect(lines[0]).toContainEqual({ text: "export", style: "keyword" });
|
||||
expect(lines[0]).toContainEqual({ text: '"hello"', style: "string" });
|
||||
});
|
||||
|
||||
it.each(["Dockerfile", "docker/Dockerfile", "C:\\docker\\Dockerfile", "build.dockerfile"])(
|
||||
"highlights Docker instructions in %s",
|
||||
(path) => {
|
||||
const lines = highlightCode("FROM alpine\n# Build stage", path);
|
||||
expect(lines[0]).toContainEqual({ text: "FROM", style: "keyword" });
|
||||
expect(lines[1]).toEqual([{ text: "# Build stage", style: "comment" }]);
|
||||
},
|
||||
);
|
||||
|
||||
it("highlights Swift code", () => {
|
||||
const code = 'struct Greeter {\n let message = "hello"\n}';
|
||||
const result = highlightCode(code, "test.swift");
|
||||
|
||||
@@ -39,6 +39,8 @@ describe("isLanguageSupported", () => {
|
||||
|
||||
it("returns false for files without extensions", () => {
|
||||
expect(isLanguageSupported("Makefile")).toBe(false);
|
||||
expect(isLanguageSupported("src/ts")).toBe(false);
|
||||
expect(isLanguageSupported("bin/bash")).toBe(false);
|
||||
});
|
||||
|
||||
it("handles nested paths", () => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { defineLanguageFacet, Language, StreamLanguage } from "@codemirror/language";
|
||||
import { dart } from "@codemirror/legacy-modes/mode/clike";
|
||||
import { dockerFile } from "@codemirror/legacy-modes/mode/dockerfile";
|
||||
import { shell } from "@codemirror/legacy-modes/mode/shell";
|
||||
import { swift } from "@codemirror/legacy-modes/mode/swift";
|
||||
import { parser as jsParser } from "@lezer/javascript";
|
||||
import { parser as jsonParser } from "@lezer/json";
|
||||
@@ -28,6 +30,9 @@ function language(parser: Parser): Language {
|
||||
return new Language(defineLanguageFacet(), parser);
|
||||
}
|
||||
|
||||
const shellLanguage = StreamLanguage.define(shell);
|
||||
const dockerfileLanguage = StreamLanguage.define(dockerFile);
|
||||
|
||||
const languagesByExtension: Record<string, Language> = {
|
||||
// JavaScript/TypeScript
|
||||
js: language(jsParser),
|
||||
@@ -75,6 +80,12 @@ const languagesByExtension: Record<string, Language> = {
|
||||
yml: language(yamlParser),
|
||||
// Rust
|
||||
rs: language(rustParser),
|
||||
// Shell
|
||||
sh: shellLanguage,
|
||||
bash: shellLanguage,
|
||||
zsh: shellLanguage,
|
||||
// Docker
|
||||
dockerfile: dockerfileLanguage,
|
||||
// Swift
|
||||
swift: StreamLanguage.define(swift),
|
||||
// Dart
|
||||
@@ -96,7 +107,16 @@ const languagesByExtension: Record<string, Language> = {
|
||||
};
|
||||
|
||||
export function getLanguageForFile(filename: string): Language | null {
|
||||
const ext = filename.split(".").pop()?.toLowerCase();
|
||||
const basename = filename.slice(
|
||||
Math.max(filename.lastIndexOf("/"), filename.lastIndexOf("\\")) + 1,
|
||||
);
|
||||
if (basename.toLowerCase() === "dockerfile") return dockerfileLanguage;
|
||||
|
||||
const dot = basename.lastIndexOf(".");
|
||||
// Callers also pass bare language keys for code fences.
|
||||
if (dot === -1 && basename !== filename) return null;
|
||||
|
||||
const ext = basename.slice(dot + 1).toLowerCase();
|
||||
if (!ext) return null;
|
||||
return languagesByExtension[ext] ?? null;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo backend server",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -109,11 +109,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
applyProviderOptionsPatch,
|
||||
exposeFeatureValuesToHook,
|
||||
convertLegacyOptions,
|
||||
convertLegacyClaudeUltracode,
|
||||
MalformedLegacyOptionError,
|
||||
resolveAdapter,
|
||||
foldHookFeatureValues,
|
||||
@@ -6194,7 +6195,15 @@ export class AgentManager {
|
||||
|
||||
private withConvertedOptions(config: AgentSessionConfig): AgentSessionConfig {
|
||||
const providerOptions = this.convertLegacyOptions(config.provider, config.providerOptions);
|
||||
return providerOptions === config.providerOptions ? config : { ...config, providerOptions };
|
||||
return this.convertLegacySessionConfig(
|
||||
providerOptions === config.providerOptions ? config : { ...config, providerOptions },
|
||||
);
|
||||
}
|
||||
|
||||
convertLegacySessionConfig<T extends Parameters<typeof convertLegacyClaudeUltracode>[0]>(
|
||||
config: T,
|
||||
): T {
|
||||
return convertLegacyClaudeUltracode(config, this.adapterOf(config.provider));
|
||||
}
|
||||
|
||||
private async prepareSessionConfig(
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18
|
||||
// once schedules stop writing the legacy effort and existing records have migrated.
|
||||
export function convertLegacyClaudeUltracode<
|
||||
T extends { provider: string; thinkingOptionId?: string; providerOptions?: ProviderOptions },
|
||||
>(config: T, adapter = config.provider): T {
|
||||
if (adapter !== "claude" || config.thinkingOptionId !== "ultracode") return config;
|
||||
return {
|
||||
...config,
|
||||
thinkingOptionId: "xhigh",
|
||||
providerOptions: { ultracode: true, ...config.providerOptions },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A patch over an agent's own options: top-level keys replace, `null` removes the key so the
|
||||
* `config.json` default (or the provider's own default) applies again.
|
||||
|
||||
@@ -605,6 +605,8 @@ class ProviderRuntimeSession {
|
||||
>();
|
||||
private readonly activeTurnIds = new Set<string>();
|
||||
private terminal = false;
|
||||
// The provider ended this session with session.closed, so it has nothing left to close.
|
||||
private closedByProvider = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
|
||||
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
|
||||
@@ -723,7 +725,7 @@ class ProviderRuntimeSession {
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.history.length = 0;
|
||||
if (this.restoration === "parent") {
|
||||
if (this.restoration === "parent" || this.closedByProvider) {
|
||||
this.runtime.removeSession(this.id, this.providerSessionId);
|
||||
return;
|
||||
}
|
||||
@@ -788,6 +790,7 @@ class ProviderRuntimeSession {
|
||||
return;
|
||||
}
|
||||
if (event.type === "session.runtime_failed" || event.type === "session.closed") {
|
||||
if (event.type === "session.closed") this.closedByProvider = true;
|
||||
if (this.terminal) return;
|
||||
this.terminal = true;
|
||||
this.publish(event);
|
||||
|
||||
@@ -1548,7 +1548,7 @@ describe("model merging", () => {
|
||||
models
|
||||
.find((model) => model.id === "claude-sonnet-5")
|
||||
?.thinkingOptions?.map((option) => option.id),
|
||||
).toEqual(["off", "low", "medium", "high", "xhigh", "max", "ultracode"]);
|
||||
).toEqual(["off", "low", "medium", "high", "xhigh", "max"]);
|
||||
expect(models.find((model) => model.id === "claude-opus-5")?.thinkingOptions).toEqual([]);
|
||||
expect(models.find((model) => model.id === "custom-explicit")).toMatchObject({
|
||||
thinkingOptions: [{ id: "bespoke", label: "Bespoke", isDefault: true }],
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
resolveSnapshotCwd,
|
||||
} from "./provider-snapshot-manager.js";
|
||||
import { OpenCodeAgentClient } from "./providers/opencode-agent.js";
|
||||
import { getClaudeModels } from "./providers/claude/models.js";
|
||||
|
||||
const TEST_CAPABILITIES = {
|
||||
supportsStreaming: false,
|
||||
@@ -311,6 +312,29 @@ describe("ProviderSnapshotManager public surface", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("accepts a legacy Ultra Code choice on a model with an independent effort catalog", async () => {
|
||||
const manager = new ProviderSnapshotManager({
|
||||
logger: createTestLogger(),
|
||||
extraClients: {
|
||||
claude: createExtraClient("claude", {
|
||||
isAvailable: async () => true,
|
||||
fetchCatalog: async () => ({ models: getClaudeModels("2.1.284"), modes: [] }),
|
||||
}),
|
||||
},
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
manager.validateAgentConfiguration({
|
||||
provider: "claude",
|
||||
model: "claude-opus-4-8",
|
||||
thinkingOptionId: "ultracode",
|
||||
}),
|
||||
).resolves.toEqual([]);
|
||||
} finally {
|
||||
manager.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test("reports an unavailable Hub agent provider at the authored provider field", async () => {
|
||||
const manager = new ProviderSnapshotManager({ logger: createTestLogger() });
|
||||
try {
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
} from "./agent-configuration-validator.js";
|
||||
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
|
||||
import { PluginAgentClientRegistry } from "./plugin-provider.js";
|
||||
import { convertLegacyClaudeUltracode, resolveAdapter } from "./option-controls.js";
|
||||
|
||||
const DEFAULT_REFRESH_TIMEOUT_MS = 120_000;
|
||||
const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647;
|
||||
@@ -516,7 +517,13 @@ export class ProviderSnapshotManager {
|
||||
}
|
||||
|
||||
return validateAgentConfigurationAgainstProvider({
|
||||
input,
|
||||
input: convertLegacyClaudeUltracode(
|
||||
input,
|
||||
resolveAdapter({
|
||||
provider: input.provider,
|
||||
extendsOf: (id) => this.generation.definitions[id]?.derivedFromProviderId,
|
||||
}),
|
||||
),
|
||||
provider,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test } from "vitest";
|
||||
import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import { convertLegacyClaudeUltracode } from "../../option-controls.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
import type { ClaudeQueryInput } from "./query.js";
|
||||
|
||||
@@ -18,6 +19,7 @@ function deferred<T>() {
|
||||
class ForegroundQuery {
|
||||
readonly work = deferred<void>();
|
||||
readonly closed = deferred<void>();
|
||||
readonly flagSettings: Parameters<Query["applyFlagSettings"]>[0][] = [];
|
||||
private stopped = false;
|
||||
private readonly output: AsyncGenerator<SDKMessage>;
|
||||
|
||||
@@ -72,6 +74,9 @@ class ForegroundQuery {
|
||||
}
|
||||
async setPermissionMode() {}
|
||||
async setModel() {}
|
||||
async applyFlagSettings(settings: Parameters<Query["applyFlagSettings"]>[0]) {
|
||||
this.flagSettings.push(settings);
|
||||
}
|
||||
async supportedCommands() {
|
||||
return [];
|
||||
}
|
||||
@@ -156,3 +161,122 @@ test.each(["mode", "model", "commands"] as const)(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("Ultracode toggles at Medium and stays enabled when effort changes live", async () => {
|
||||
const queries: ForegroundQuery[] = [];
|
||||
const launchOptions: ClaudeQueryInput["options"][] = [];
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveBinary: async () => "/test/claude",
|
||||
resolveVersion: async () => "2.1.284",
|
||||
queryFactory: (input) => {
|
||||
const query = new ForegroundQuery(input);
|
||||
queries.push(query);
|
||||
launchOptions.push(input.options);
|
||||
return query as unknown as Query;
|
||||
},
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
model: "claude-opus-4-8",
|
||||
thinkingOptionId: "medium",
|
||||
providerOptions: { ultracode: false },
|
||||
});
|
||||
try {
|
||||
expect(session.controls).toContainEqual(
|
||||
expect.objectContaining({ key: "ultracode", type: "toggle" }),
|
||||
);
|
||||
await session.startTurn("Start at Medium");
|
||||
expect(launchOptions[0]).toMatchObject({ effort: "medium", settings: { ultracode: false } });
|
||||
await session.applyOptions?.({ ultracode: true });
|
||||
await session.setThinkingOption?.("high");
|
||||
await session.applyOptions?.({ ultracode: false });
|
||||
expect(queries).toHaveLength(1);
|
||||
expect(queries[0].flagSettings).toEqual([
|
||||
{ fastMode: false, ultracode: false },
|
||||
{ ultracode: true },
|
||||
{ effortLevel: "high", ultracode: true },
|
||||
{ ultracode: false },
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["xhigh", true],
|
||||
["high", false],
|
||||
] as const)("older Claude Code launches %s with Ultracode set to %s", async (effort, enabled) => {
|
||||
const launchOptions: ClaudeQueryInput["options"][] = [];
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveBinary: async () => "/test/claude",
|
||||
resolveVersion: async () => "2.1.283",
|
||||
queryFactory: (input) => {
|
||||
launchOptions.push(input.options);
|
||||
return new ForegroundQuery(input) as unknown as Query;
|
||||
},
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
model: "claude-opus-4-8",
|
||||
thinkingOptionId: effort,
|
||||
providerOptions: { ultracode: true },
|
||||
});
|
||||
try {
|
||||
expect(session.controls?.some((control) => control.key === "ultracode")).toBe(false);
|
||||
await session.startTurn("Start the agent");
|
||||
expect(launchOptions[0]).toMatchObject({ effort, settings: { ultracode: enabled } });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("reopens an older Claude Code agent with Ultracode after choosing Ultra Code again", async () => {
|
||||
const launchOptions: ClaudeQueryInput["options"][] = [];
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveBinary: async () => "/test/claude",
|
||||
resolveVersion: async () => "2.1.283",
|
||||
queryFactory: (input) => {
|
||||
launchOptions.push(input.options);
|
||||
return new ForegroundQuery(input) as unknown as Query;
|
||||
},
|
||||
});
|
||||
const config = {
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
model: "claude-opus-4-8",
|
||||
thinkingOptionId: "xhigh",
|
||||
providerOptions: { ultracode: true },
|
||||
};
|
||||
const session = await client.createSession(config);
|
||||
let savedOptions = config.providerOptions;
|
||||
session.subscribe((event) => {
|
||||
if (event.type === "options_changed" && typeof event.patch.ultracode === "boolean") {
|
||||
savedOptions = { ultracode: event.patch.ultracode };
|
||||
}
|
||||
});
|
||||
try {
|
||||
await session.setThinkingOption?.("high");
|
||||
expect(savedOptions.ultracode).toBe(false);
|
||||
await session.setThinkingOption?.("ultracode");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
const reopened = await client.createSession(
|
||||
convertLegacyClaudeUltracode({
|
||||
...config,
|
||||
thinkingOptionId: "ultracode",
|
||||
providerOptions: savedOptions,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await reopened.startTurn("Start the agent");
|
||||
expect(launchOptions[0]).toMatchObject({ effort: "xhigh", settings: { ultracode: true } });
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -543,21 +543,20 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
return models.find((model) => model.id === modelId)?.thinkingOptions?.map(({ id }) => id);
|
||||
};
|
||||
|
||||
expect(getThinkingIds("claude-opus-5")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-5")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-mythos-5-1")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"ultracode",
|
||||
]);
|
||||
expect(getThinkingIds("claude-fable-5-1")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-fable-5")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-8[1m]")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-8")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-fable-5-1")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-fable-5")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-8[1m]")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-8")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-sonnet-5")).toContain("xhigh");
|
||||
expect(getThinkingIds("claude-sonnet-5")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-sonnet-5")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-haiku-5-5")).toEqual([
|
||||
"off",
|
||||
"low",
|
||||
@@ -565,12 +564,11 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"ultracode",
|
||||
]);
|
||||
expect(getThinkingIds("claude-sonnet-5-5")).toContain("xhigh");
|
||||
expect(getThinkingIds("claude-sonnet-5-5")).not.toContain("off");
|
||||
expect(getThinkingIds("claude-opus-4-7[1m]")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-7")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-7[1m]")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-7")).not.toContain("ultracode");
|
||||
expect(getThinkingIds("claude-sonnet-4-6")).not.toContain("ultracode");
|
||||
} finally {
|
||||
await fs.rm(emptyConfigDir, { recursive: true, force: true });
|
||||
@@ -1181,8 +1179,8 @@ describe("ClaudeAgentSession features", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("lists fast mode only for supported Opus models", async () => {
|
||||
const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" });
|
||||
test("lists Claude controls by model capability", async () => {
|
||||
const client = new ClaudeAgentClient({ logger, resolveVersion: async () => "2.1.284" });
|
||||
|
||||
await expect(
|
||||
client.listControls({
|
||||
@@ -1191,7 +1189,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
model: "claude-opus-4-8",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
|
||||
controls: [
|
||||
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
|
||||
expect.objectContaining({ key: "ultracode", type: "toggle" }),
|
||||
],
|
||||
options: {},
|
||||
});
|
||||
|
||||
@@ -1202,7 +1203,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
model: "claude-opus-4-8[1m]",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
|
||||
controls: [
|
||||
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
|
||||
expect.objectContaining({ key: "ultracode", type: "toggle" }),
|
||||
],
|
||||
options: {},
|
||||
});
|
||||
|
||||
@@ -1213,7 +1217,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
model: "claude-opus-4-8-20260101",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
|
||||
controls: [
|
||||
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
|
||||
expect.objectContaining({ key: "ultracode", type: "toggle" }),
|
||||
],
|
||||
options: {},
|
||||
});
|
||||
|
||||
@@ -1224,7 +1231,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
model: "claude-opus-5",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
|
||||
controls: [
|
||||
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
|
||||
expect.objectContaining({ key: "ultracode", type: "toggle" }),
|
||||
],
|
||||
options: {},
|
||||
});
|
||||
|
||||
@@ -1234,7 +1244,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
cwd: process.cwd(),
|
||||
model: "openrouter/anthropic/claude-opus-4-8",
|
||||
}),
|
||||
).resolves.toEqual({ controls: [], options: {} });
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
|
||||
options: {},
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.listControls({
|
||||
@@ -1242,7 +1255,10 @@ describe("ClaudeAgentSession features", () => {
|
||||
cwd: process.cwd(),
|
||||
model: "claude-sonnet-5",
|
||||
}),
|
||||
).resolves.toEqual({ controls: [], options: {} });
|
||||
).resolves.toEqual({
|
||||
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
|
||||
options: {},
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.listControls({
|
||||
|
||||
@@ -50,8 +50,10 @@ import {
|
||||
import {
|
||||
CLAUDE_DISABLED_THINKING_OPTION_ID,
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
claudeManifestModelSupportsUltracode,
|
||||
parseClaudeCodeVersion,
|
||||
resolveClaudeDisabledThinkingForModel,
|
||||
supportsIndependentClaudeUltracode,
|
||||
} from "./model-manifest.js";
|
||||
import { expandTilde } from "../../../../utils/path.js";
|
||||
import { parsePartialJsonObject } from "./partial-json.js";
|
||||
@@ -496,6 +498,7 @@ interface ClaudeAgentSessionOptions {
|
||||
logger: Logger;
|
||||
queryFactory?: ClaudeQueryFactory;
|
||||
resolveBinary: () => Promise<string>;
|
||||
independentUltracode: boolean;
|
||||
rewindSdk?: ClaudeRewindSdk;
|
||||
}
|
||||
|
||||
@@ -1618,6 +1621,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
private readonly queryFactory?: ClaudeQueryFactory;
|
||||
private readonly resolveBinary: () => Promise<string>;
|
||||
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
|
||||
private version: Promise<string | undefined> | undefined;
|
||||
private readonly rewindSdk: ClaudeRewindSdk;
|
||||
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
|
||||
(candidate: ClaudeSessionCandidate, signal) => this.readImportDescriptor(candidate, signal),
|
||||
@@ -1661,6 +1665,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
logger: this.logger,
|
||||
queryFactory: this.queryFactory,
|
||||
resolveBinary: this.resolveBinary,
|
||||
independentUltracode: await this.supportsIndependentUltracode(),
|
||||
rewindSdk: this.rewindSdk,
|
||||
});
|
||||
}
|
||||
@@ -1690,6 +1695,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
logger: this.logger,
|
||||
queryFactory: this.queryFactory,
|
||||
resolveBinary: this.resolveBinary,
|
||||
independentUltracode: await this.supportsIndependentUltracode(),
|
||||
rewindSdk: this.rewindSdk,
|
||||
});
|
||||
await session.ensureHistoryReady();
|
||||
@@ -1714,6 +1720,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error }, "Failed to resolve Claude Code version for model catalog");
|
||||
}
|
||||
this.version = Promise.resolve(claudeCodeVersion);
|
||||
const env = this.buildProviderEnv();
|
||||
let discoveredModelIds = new Set<string>();
|
||||
try {
|
||||
@@ -1770,11 +1777,19 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
|
||||
async listControls(config: AgentSessionConfig): Promise<AgentDraftControls> {
|
||||
return {
|
||||
controls: buildClaudeControls(this.assertConfig(config).model),
|
||||
controls: buildClaudeControls(
|
||||
this.assertConfig(config).model,
|
||||
await this.supportsIndependentUltracode(),
|
||||
),
|
||||
options: config.providerOptions ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
private async supportsIndependentUltracode(): Promise<boolean> {
|
||||
this.version ??= this.resolveVersion().catch(() => undefined);
|
||||
return supportsIndependentClaudeUltracode(await this.version);
|
||||
}
|
||||
|
||||
async listImportableSessions(
|
||||
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
|
||||
): Promise<ImportableProviderSession[]> {
|
||||
@@ -2307,6 +2322,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private readonly logger: Logger;
|
||||
private readonly queryFactory?: ClaudeQueryFactory;
|
||||
private readonly resolveBinary: () => Promise<string>;
|
||||
private readonly independentUltracode: boolean;
|
||||
private query: Query | null = null;
|
||||
private readonly runtimeSafety = new ClaudeRuntimeSafety();
|
||||
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
|
||||
@@ -2444,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.logger = options.logger.child({ agentId: this.agentId });
|
||||
this.queryFactory = options.queryFactory;
|
||||
this.resolveBinary = options.resolveBinary;
|
||||
this.independentUltracode = options.independentUltracode;
|
||||
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
|
||||
this.contextUsage = new ClaudeContextUsageState(
|
||||
getClaudeContextWindowMaxTokens(this.config.model),
|
||||
@@ -2481,6 +2498,16 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.config.providerOptions = { ...config.providerOptions, fast_mode: false };
|
||||
this.openOptionsPatch = { fast_mode: false };
|
||||
}
|
||||
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
|
||||
// Direct adapter callers can still pass the combined choice.
|
||||
if (
|
||||
this.independentUltracode &&
|
||||
config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
|
||||
config.providerOptions.ultracode === undefined
|
||||
) {
|
||||
this.config.providerOptions = { ...config.providerOptions, ultracode: true };
|
||||
this.openOptionsPatch.ultracode = true;
|
||||
}
|
||||
}
|
||||
|
||||
get id(): string | null {
|
||||
@@ -2488,18 +2515,28 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
get controls(): AgentOptionControl[] {
|
||||
return buildClaudeControls(this.config.model);
|
||||
return buildClaudeControls(this.config.model, this.independentUltracode);
|
||||
}
|
||||
|
||||
async getRuntimeInfo(): Promise<AgentRuntimeInfo> {
|
||||
if (this.cachedRuntimeInfo) {
|
||||
return { ...this.cachedRuntimeInfo };
|
||||
}
|
||||
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
|
||||
const info: AgentRuntimeInfo = {
|
||||
provider: "claude",
|
||||
sessionId: this.claudeSessionId,
|
||||
model: this.lastOptionsModel ?? this.config.model ?? null,
|
||||
modeId: this.currentMode ?? null,
|
||||
...(this.independentUltracode &&
|
||||
this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
|
||||
? { thinkingOptionId: "xhigh" }
|
||||
: {}),
|
||||
...(!this.independentUltracode &&
|
||||
this.config.thinkingOptionId === "xhigh" &&
|
||||
this.config.providerOptions.ultracode === true
|
||||
? { thinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID }
|
||||
: {}),
|
||||
...(this.lastRuntimeModel
|
||||
? {
|
||||
extra: {
|
||||
@@ -2522,12 +2559,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
reduceFinalText: appendOrReplaceGrowingAssistantMessage,
|
||||
});
|
||||
|
||||
this.cachedRuntimeInfo = {
|
||||
provider: "claude",
|
||||
sessionId: this.claudeSessionId,
|
||||
model: this.lastOptionsModel,
|
||||
modeId: this.currentMode ?? null,
|
||||
};
|
||||
this.cachedRuntimeInfo = null;
|
||||
|
||||
if (!this.claudeSessionId) {
|
||||
throw new Error("Session ID not set after run completed");
|
||||
@@ -2816,9 +2848,14 @@ class ClaudeAgentSession implements AgentSession {
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId.trim() : null;
|
||||
const activeQuery = await this.ensureQuery();
|
||||
const previousUltracode = this.resolveUltracodeSetting();
|
||||
await activeQuery.setModel(normalizedModelId ?? undefined);
|
||||
this.config.model = normalizedModelId ?? undefined;
|
||||
this.reconcileThinkingOptionForModel(normalizedModelId);
|
||||
const ultracode = this.resolveUltracodeSetting();
|
||||
if (previousUltracode !== ultracode && this.config.providerOptions.ultracode !== undefined) {
|
||||
await activeQuery.applyFlagSettings({ ultracode: ultracode ?? false });
|
||||
}
|
||||
if (this.config.providerOptions.fast_mode) {
|
||||
const supported = claudeModelSupportsFastMode(this.config.model);
|
||||
await activeQuery.applyFlagSettings({ fastMode: supported });
|
||||
@@ -2877,9 +2914,26 @@ class ClaudeAgentSession implements AgentSession {
|
||||
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
|
||||
assertClaudeThinkingOptionSupported(this.config.model, normalizedThinkingOptionId);
|
||||
this.config.thinkingOptionId = normalizedThinkingOptionId;
|
||||
if (
|
||||
normalizedThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
|
||||
this.config.providerOptions.ultracode !== true
|
||||
) {
|
||||
this.config.providerOptions = { ...this.config.providerOptions, ultracode: true };
|
||||
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: true } });
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
|
||||
}
|
||||
this.cachedRuntimeInfo = null;
|
||||
if (
|
||||
!this.independentUltracode &&
|
||||
normalizedThinkingOptionId !== CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
|
||||
this.config.providerOptions.ultracode === true
|
||||
) {
|
||||
this.config.providerOptions = { ...this.config.providerOptions, ultracode: false };
|
||||
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: false } });
|
||||
this.queryRestartNeeded = true;
|
||||
}
|
||||
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
|
||||
this.queryRestartNeeded = true;
|
||||
}
|
||||
@@ -2896,12 +2950,20 @@ class ClaudeAgentSession implements AgentSession {
|
||||
previousThinkingOptionId: string | undefined,
|
||||
): Promise<boolean> {
|
||||
const effort = this.config.thinkingOptionId;
|
||||
const previousEffort =
|
||||
this.independentUltracode && previousThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
|
||||
? "xhigh"
|
||||
: previousThinkingOptionId;
|
||||
if (!this.query || this.queryRestartNeeded) return false;
|
||||
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
|
||||
if (!isClaudeThinkingEffort(previousEffort) || !isClaudeThinkingEffort(effort)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.query.applyFlagSettings({ effortLevel: effort });
|
||||
const ultracode = this.resolveUltracodeSetting();
|
||||
await this.query.applyFlagSettings({
|
||||
effortLevel: effort,
|
||||
...(ultracode === undefined ? {} : { ultracode }),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
|
||||
@@ -2910,14 +2972,13 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async applyOptions(options: ProviderOptions): Promise<void> {
|
||||
// Every option but Fast is read when the query is built, and replacing a started query would
|
||||
// end its background work, so once it exists only Fast can change.
|
||||
// Replacing a started query ends background work, so only flag settings can change live.
|
||||
if (this.query || this.queryStarting) {
|
||||
assertChangesAreLive({
|
||||
provider: "claude",
|
||||
patch: options,
|
||||
current: this.config.providerOptions,
|
||||
live: ["fast_mode"],
|
||||
live: ["fast_mode", "ultracode"],
|
||||
});
|
||||
}
|
||||
const providerOptions =
|
||||
@@ -2933,14 +2994,34 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
const fastModeChanged =
|
||||
(providerOptions.fast_mode === true) !== (this.config.providerOptions.fast_mode === true);
|
||||
if (fastModeChanged) {
|
||||
await this.query?.applyFlagSettings({ fastMode: providerOptions.fast_mode === true });
|
||||
const ultracodeChanged = providerOptions.ultracode !== this.config.providerOptions.ultracode;
|
||||
if (ultracodeChanged) this.assertUltracodeChangeSupported(providerOptions.ultracode);
|
||||
if (fastModeChanged || ultracodeChanged) {
|
||||
await this.query?.applyFlagSettings({
|
||||
...(fastModeChanged ? { fastMode: providerOptions.fast_mode === true } : {}),
|
||||
...(ultracodeChanged ? { ultracode: providerOptions.ultracode ?? false } : {}),
|
||||
});
|
||||
this.cachedRuntimeInfo = null;
|
||||
}
|
||||
// Held until the runtime accepts, so a rejected change is retried instead of skipped.
|
||||
this.config.providerOptions = providerOptions;
|
||||
}
|
||||
|
||||
private assertUltracodeChangeSupported(value: boolean | undefined): void {
|
||||
if (!this.independentUltracode) {
|
||||
throw new Error("The Ultracode toggle requires Claude Code 2.1.284 or later");
|
||||
}
|
||||
if (this.query && value === undefined) {
|
||||
// The SDK treats null as Off, so a running process cannot restore inherited settings.
|
||||
throw new Error("Close the agent to reset Ultracode to Claude's default");
|
||||
}
|
||||
if (value === true && !claudeManifestModelSupportsUltracode(this.config.model)) {
|
||||
throw new Error(
|
||||
`Claude Ultracode is not available for model '${this.config.model ?? "default"}'`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getPendingPermissions(): AgentPermissionRequest[] {
|
||||
return Array.from(this.pendingPermissions.values()).map((entry) => entry.request);
|
||||
}
|
||||
@@ -3670,8 +3751,12 @@ class ClaudeAgentSession implements AgentSession {
|
||||
);
|
||||
this.queryStarting = false;
|
||||
const fastMode = this.resolveFastModeSetting();
|
||||
if (fastMode !== null) {
|
||||
await this.query.applyFlagSettings({ fastMode });
|
||||
const ultracode = this.independentUltracode ? this.resolveUltracodeSetting() : undefined;
|
||||
if (fastMode !== null || ultracode !== undefined) {
|
||||
await this.query.applyFlagSettings({
|
||||
...(fastMode === null ? {} : { fastMode }),
|
||||
...(ultracode === undefined ? {} : { ultracode }),
|
||||
});
|
||||
}
|
||||
// Do not kick off background control-plane queries here. Methods like
|
||||
// supportedCommands()/setPermissionMode() may execute immediately after
|
||||
@@ -3729,7 +3814,6 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private resolveThinkingConfig(): {
|
||||
thinking: ClaudeOptions["thinking"];
|
||||
effort: ClaudeOptions["effort"];
|
||||
ultracode: boolean;
|
||||
} {
|
||||
const thinkingOptionId =
|
||||
this.config.thinkingOptionId && this.config.thinkingOptionId !== "default"
|
||||
@@ -3737,23 +3821,21 @@ class ClaudeAgentSession implements AgentSession {
|
||||
: undefined;
|
||||
assertClaudeThinkingOptionSupported(this.config.model, thinkingOptionId);
|
||||
if (thinkingOptionId === CLAUDE_DISABLED_THINKING_OPTION_ID) {
|
||||
return { thinking: { type: "disabled" }, effort: undefined, ultracode: false };
|
||||
return { thinking: { type: "disabled" }, effort: undefined };
|
||||
}
|
||||
if (thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) {
|
||||
return {
|
||||
thinking: { type: "adaptive", display: "summarized" },
|
||||
effort: "xhigh",
|
||||
ultracode: true,
|
||||
};
|
||||
}
|
||||
if (thinkingOptionId && isClaudeThinkingEffort(thinkingOptionId)) {
|
||||
return {
|
||||
thinking: { type: "adaptive", display: "summarized" },
|
||||
effort: thinkingOptionId,
|
||||
ultracode: false,
|
||||
};
|
||||
}
|
||||
return { thinking: undefined, effort: undefined, ultracode: false };
|
||||
return { thinking: undefined, effort: undefined };
|
||||
}
|
||||
|
||||
private buildAppendedSystemPrompt(): string {
|
||||
@@ -3790,12 +3872,15 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
private async buildOptions(permissionMode: PermissionMode): Promise<ClaudeOptions> {
|
||||
const { thinking, effort, ultracode } = this.resolveThinkingConfig();
|
||||
const { thinking, effort } = this.resolveThinkingConfig();
|
||||
const appendedSystemPrompt = this.buildAppendedSystemPrompt();
|
||||
// `fast_mode` is a composer control the provider applies through flag settings.
|
||||
const { fast_mode: _fastMode, ...sdkProviderOptions } = this.config.providerOptions;
|
||||
const {
|
||||
fast_mode: _fastMode,
|
||||
ultracode: _ultracode,
|
||||
...sdkProviderOptions
|
||||
} = this.config.providerOptions;
|
||||
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
|
||||
const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode });
|
||||
const settingsOptions = await this.buildSettingsOptions(providerOptions);
|
||||
const sdkEnv = this.harnessEnvironment;
|
||||
assertClaudeModeCanRun(permissionMode, sdkEnv);
|
||||
|
||||
@@ -3882,18 +3967,18 @@ class ClaudeAgentSession implements AgentSession {
|
||||
|
||||
private async buildSettingsOptions(
|
||||
providerOptions: ClaudeProviderOptions,
|
||||
input: { ultracode: boolean },
|
||||
): Promise<Pick<ClaudeOptions, "settings" | "extraArgs"> | Record<string, never>> {
|
||||
const fastMode = this.resolveFastModeSetting();
|
||||
const ultracode = this.resolveUltracodeSetting();
|
||||
// Internal agents do daemon work such as naming a branch, so the user's and
|
||||
// project's hooks must not run for them.
|
||||
const disableAllHooks = this.config.internal === true;
|
||||
if (fastMode === null && !input.ultracode && !disableAllHooks) {
|
||||
if (fastMode === null && ultracode === undefined && !disableAllHooks) {
|
||||
return {};
|
||||
}
|
||||
const updates = {
|
||||
...(fastMode === null ? {} : { fastMode }),
|
||||
...(input.ultracode ? { ultracode: true } : {}),
|
||||
...(ultracode === undefined ? {} : { ultracode }),
|
||||
...(disableAllHooks ? { disableAllHooks: true } : {}),
|
||||
};
|
||||
// The SDK replaces extraArgs.settings with Options.settings, so a user's
|
||||
@@ -3909,6 +3994,18 @@ class ClaudeAgentSession implements AgentSession {
|
||||
};
|
||||
}
|
||||
|
||||
private resolveUltracodeSetting(): boolean | undefined {
|
||||
const ultracode = this.config.providerOptions.ultracode;
|
||||
if (!this.independentUltracode) {
|
||||
return this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
|
||||
? true
|
||||
: ultracode && this.config.thinkingOptionId === "xhigh";
|
||||
}
|
||||
if (ultracode === undefined) return undefined;
|
||||
if (this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) return ultracode;
|
||||
return ultracode && claudeManifestModelSupportsUltracode(this.config.model);
|
||||
}
|
||||
|
||||
private resolveFastModeSetting(): boolean | null {
|
||||
if (!claudeModelSupportsFastMode(this.config.model)) {
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { AgentOptionControl, AgentOptionToggleControl } from "../../agent-sdk-types.js";
|
||||
import { claudeManifestModelSupportsFastMode } from "./model-manifest.js";
|
||||
import {
|
||||
claudeManifestModelSupportsFastMode,
|
||||
claudeManifestModelSupportsUltracode,
|
||||
} from "./model-manifest.js";
|
||||
|
||||
export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
|
||||
type: "toggle",
|
||||
@@ -10,10 +13,26 @@ export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
|
||||
icon: "zap",
|
||||
};
|
||||
|
||||
const CLAUDE_ULTRACODE_CONTROL: AgentOptionToggleControl = {
|
||||
type: "toggle",
|
||||
key: "ultracode",
|
||||
label: "Ultracode",
|
||||
description: "Let Claude plan workflows for substantive tasks",
|
||||
icon: "Workflow",
|
||||
};
|
||||
|
||||
export function claudeModelSupportsFastMode(modelId: string | null | undefined): boolean {
|
||||
return claudeManifestModelSupportsFastMode(modelId);
|
||||
}
|
||||
|
||||
export function buildClaudeControls(modelId: string | null | undefined): AgentOptionControl[] {
|
||||
return claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : [];
|
||||
export function buildClaudeControls(
|
||||
modelId: string | null | undefined,
|
||||
independentUltracode: boolean,
|
||||
): AgentOptionControl[] {
|
||||
return [
|
||||
...(claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : []),
|
||||
...(independentUltracode && claudeManifestModelSupportsUltracode(modelId)
|
||||
? [{ ...CLAUDE_ULTRACODE_CONTROL }]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -226,25 +226,27 @@ function buildThinkingOptions(
|
||||
effortLevels: readonly ClaudeEffortLevel[] | undefined,
|
||||
supportsThinkingDisabled: boolean,
|
||||
defaultThinkingOptionId: ClaudeEffortLevel,
|
||||
independentUltracode: boolean,
|
||||
): AgentSelectOption[] | undefined {
|
||||
if (!effortLevels) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const options: AgentSelectOption[] = [
|
||||
return [
|
||||
...(supportsThinkingDisabled ? [{ id: CLAUDE_DISABLED_THINKING_OPTION_ID, label: "Off" }] : []),
|
||||
...effortLevels.map((id) => ({
|
||||
id,
|
||||
label: CLAUDE_EFFORT_LABELS[id],
|
||||
...(id === defaultThinkingOptionId ? { isDefault: true } : {}),
|
||||
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
|
||||
...(independentUltracode && id === "xhigh"
|
||||
? { metadata: { replacesThinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID } }
|
||||
: {}),
|
||||
})),
|
||||
...(!independentUltracode && effortLevels.includes("xhigh")
|
||||
? [{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" }]
|
||||
: []),
|
||||
];
|
||||
|
||||
if (effortLevels.includes("xhigh")) {
|
||||
options.push({ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" });
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
export function getClaudeManifestModels(
|
||||
@@ -270,6 +272,7 @@ export function getClaudeManifestModels(
|
||||
model.effortLevels,
|
||||
model.supportsThinkingDisabled === true,
|
||||
getDefaultThinkingOptionId(model),
|
||||
supportsIndependentClaudeUltracode(claudeCodeVersion),
|
||||
);
|
||||
const definition: AgentModelDefinition = {
|
||||
provider: "claude",
|
||||
@@ -340,6 +343,10 @@ export function parseClaudeCodeVersion(value: string): [number, number, number]
|
||||
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
||||
}
|
||||
|
||||
export function supportsIndependentClaudeUltracode(version: string | undefined): boolean {
|
||||
return version === undefined || compareVersions(version, "2.1.284") >= 0;
|
||||
}
|
||||
|
||||
export interface ClaudeDisabledThinkingResolution {
|
||||
supported: boolean;
|
||||
fallbackThinkingOptionId: string | undefined;
|
||||
@@ -381,6 +388,14 @@ export function claudeManifestModelSupportsFastMode(modelId: string | null | und
|
||||
);
|
||||
}
|
||||
|
||||
export function claudeManifestModelSupportsUltracode(modelId: string | null | undefined): boolean {
|
||||
const normalized = normalizeClaudeRuntimeModelId(modelId);
|
||||
const model: ClaudeModelManifestEntry | undefined = CLAUDE_MODEL_MANIFEST.find(
|
||||
(candidate) => candidate.id === normalized,
|
||||
);
|
||||
return model?.effortLevels?.includes("xhigh") === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize first-party Claude model IDs for manifest capability checks. Provider-prefixed
|
||||
* runtime IDs intentionally use normalizeClaudeRuntimeModelId instead.
|
||||
|
||||
@@ -8,7 +8,6 @@ import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
import {
|
||||
CLAUDE_DISABLED_THINKING_OPTION_ID,
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
claudeManifestModelSupportsFastMode,
|
||||
normalizeClaudeManifestModelId,
|
||||
parseClaudeCodeVersion,
|
||||
@@ -190,7 +189,6 @@ describe("getClaudeModels", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(models.get("claude-sonnet-5")?.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
CLAUDE_DISABLED_THINKING_OPTION_ID,
|
||||
@@ -199,14 +197,7 @@ describe("getClaudeModels", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(
|
||||
models
|
||||
.get("claude-sonnet-5")
|
||||
?.thinkingOptions?.find((option) => option.id === CLAUDE_ULTRACODE_THINKING_OPTION_ID)
|
||||
?.label,
|
||||
).toBe("Ultra Code");
|
||||
expect(models.get("claude-sonnet-5")?.defaultThinkingOptionId).toBe("high");
|
||||
expect(models.get("claude-sonnet-5[1m]")?.thinkingOptions).toEqual(
|
||||
models.get("claude-sonnet-5")?.thinkingOptions,
|
||||
@@ -219,7 +210,6 @@ describe("getClaudeModels", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(models.get("claude-sonnet-4-6")?.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
CLAUDE_DISABLED_THINKING_OPTION_ID,
|
||||
@@ -420,9 +410,12 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
{ id: "xhigh", label: "Extra High" },
|
||||
{
|
||||
id: "xhigh",
|
||||
label: "Extra High",
|
||||
metadata: { replacesThinkingOptionId: "ultracode" },
|
||||
},
|
||||
{ id: "max", label: "Max" },
|
||||
{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" },
|
||||
];
|
||||
const configDir = await createClaudeConfigDir({
|
||||
model: "us.anthropic.claude-opus-4-7[1m]",
|
||||
@@ -845,7 +838,6 @@ describe("Claude Fable 5.2 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(claudeManifestModelSupportsFastMode("claude-fable-5-2")).toBe(true);
|
||||
});
|
||||
@@ -887,7 +879,6 @@ describe("Claude Opus 5.5 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(opus55?.defaultThinkingOptionId).toBe("medium");
|
||||
expect(
|
||||
@@ -922,7 +913,6 @@ describe("Claude Sonnet 5.5 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(sonnet55?.defaultThinkingOptionId).toBe("medium");
|
||||
expect(
|
||||
@@ -959,7 +949,6 @@ describe("Claude Haiku 5.5 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(haiku55?.defaultThinkingOptionId).toBe("medium");
|
||||
expect(
|
||||
@@ -1016,7 +1005,6 @@ describe("Claude Mythos 5.1 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(
|
||||
models[0].thinkingOptions?.filter((option) => option.isDefault).map((option) => option.id),
|
||||
@@ -1088,7 +1076,6 @@ describe("Claude Mythos 5.2 catalog", () => {
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(claudeManifestModelSupportsFastMode("claude-mythos-5-2")).toBe(true);
|
||||
});
|
||||
|
||||
@@ -45,8 +45,9 @@ const SandboxFilesystemSchema = z
|
||||
// Claude Agent SDK Options, maintained against @anthropic-ai/claude-agent-sdk 0.3.246.
|
||||
export const ClaudeProviderOptionsSchema = z
|
||||
.object({
|
||||
/** Composer control, not a Claude SDK option: the provider reads it and keeps it out of the SDK options. */
|
||||
/** Composer controls applied through Claude flag settings. */
|
||||
fast_mode: z.boolean().optional(),
|
||||
ultracode: z.boolean().optional(),
|
||||
allowedTools: z.array(z.string()).optional(),
|
||||
disallowedTools: z.array(z.string()).optional(),
|
||||
additionalDirectories: z.array(z.string()).optional(),
|
||||
|
||||
@@ -136,6 +136,94 @@ describe("OMP rpc-ui permission mapper", () => {
|
||||
).toEqual({ kind: "passthrough" });
|
||||
});
|
||||
|
||||
test("maps approvals that offer session and grant choices beside the one-call approval", () => {
|
||||
const session = classifyOmpRpcUiPermissionRequest({
|
||||
type: "extension_ui_request",
|
||||
id: "session-write",
|
||||
method: "select",
|
||||
title: "Allow tool: write\nPath: cap.txt\nContent:\nhello",
|
||||
options: ["Approve", "Approve write for this session", "Deny"],
|
||||
});
|
||||
if (session.kind !== "tool") throw new Error("Expected session approval to map as a tool");
|
||||
expect(
|
||||
session.request.actions?.map((action) => [action.id, action.label, action.behavior]),
|
||||
).toEqual([
|
||||
["deny", "Deny", "deny"],
|
||||
["approve", "Approve", "allow"],
|
||||
["approve-option-0", "Approve write for this session", "allow"],
|
||||
]);
|
||||
expect(buildOmpRpcUiPermissionResponse(session.request, { behavior: "allow" })).toEqual({
|
||||
value: "Approve",
|
||||
});
|
||||
expect(
|
||||
buildOmpRpcUiPermissionResponse(session.request, {
|
||||
behavior: "allow",
|
||||
selectedActionId: "approve-option-0",
|
||||
}),
|
||||
).toEqual({ value: "Approve write for this session" });
|
||||
expect(
|
||||
buildOmpRpcUiPermissionResponse(session.request, {
|
||||
behavior: "deny",
|
||||
selectedActionId: "approve-option-0",
|
||||
}),
|
||||
).toEqual({ value: "Deny" });
|
||||
|
||||
const grants = classifyOmpRpcUiPermissionRequest({
|
||||
type: "extension_ui_request",
|
||||
id: "grant-edit",
|
||||
method: "select",
|
||||
title: "Allow tool: edit\nFile: src/a.ts",
|
||||
options: ["Approve File", "Always Approve File", "Approve Once", "Deny"],
|
||||
});
|
||||
if (grants.kind !== "tool") throw new Error("Expected grant approval to map as a tool");
|
||||
expect(buildOmpRpcUiPermissionResponse(grants.request, { behavior: "allow" })).toEqual({
|
||||
value: "Approve Once",
|
||||
});
|
||||
expect(
|
||||
buildOmpRpcUiPermissionResponse(grants.request, {
|
||||
behavior: "allow",
|
||||
selectedActionId: "approve-option-1",
|
||||
}),
|
||||
).toEqual({ value: "Always Approve File" });
|
||||
});
|
||||
|
||||
test("allows one call when a grant is labeled Approve beside Approve Once", () => {
|
||||
// OMP names the one-call choice "Approve Once" whenever it offers grants. A grant for a
|
||||
// target that is not a file is then labeled "Approve", which remembers more than one call.
|
||||
const grants = classifyOmpRpcUiPermissionRequest({
|
||||
type: "extension_ui_request",
|
||||
id: "grant-target",
|
||||
method: "select",
|
||||
title: "Allow tool: edit\nFile: src/a.ts",
|
||||
options: ["Approve", "Always Approve", "Approve Once", "Deny"],
|
||||
});
|
||||
if (grants.kind !== "tool") throw new Error("Expected grant approval to map as a tool");
|
||||
expect(buildOmpRpcUiPermissionResponse(grants.request, { behavior: "allow" })).toEqual({
|
||||
value: "Approve Once",
|
||||
});
|
||||
});
|
||||
|
||||
test("passes through selects whose extra choices are not approvals", () => {
|
||||
expect(
|
||||
classifyOmpRpcUiPermissionRequest({
|
||||
type: "extension_ui_request",
|
||||
id: "odd-choice",
|
||||
method: "select",
|
||||
title: "Allow tool: bash\nCommand: echo hi",
|
||||
options: ["Approve", "Edit command", "Deny"],
|
||||
}),
|
||||
).toEqual({ kind: "passthrough" });
|
||||
expect(
|
||||
classifyOmpRpcUiPermissionRequest({
|
||||
type: "extension_ui_request",
|
||||
id: "deny-first",
|
||||
method: "select",
|
||||
title: "Allow tool: bash\nCommand: echo hi",
|
||||
options: ["Deny", "Approve"],
|
||||
}),
|
||||
).toEqual({ kind: "passthrough" });
|
||||
});
|
||||
|
||||
test("responds to tool approvals with exact select values", () => {
|
||||
const request = toolApproval("bash");
|
||||
|
||||
|
||||
@@ -10,8 +10,13 @@ import type { OmpRuntimeEvent } from "./rpc-types.js";
|
||||
const OMP_PROVIDER = "omp";
|
||||
const OMP_RPC_UI_TOOL_APPROVAL_METADATA = "omp_rpc_ui_tool_approval";
|
||||
const TOOL_APPROVAL_APPROVE_VALUE = "Approve";
|
||||
// OMP labels the approve-this-call choice "Approve Once" when it also offers grants that remember
|
||||
// more. A grant can then be labeled "Approve", so "Approve" is the one-call choice only without it.
|
||||
const TOOL_APPROVAL_ONCE_VALUE = "Approve Once";
|
||||
const TOOL_APPROVAL_DENY_VALUE = "Deny";
|
||||
const TOOL_APPROVAL_OPTIONS = [TOOL_APPROVAL_APPROVE_VALUE, TOOL_APPROVAL_DENY_VALUE] as const;
|
||||
// Session and grant choices OMP offers beside the one-call approval, e.g. "Approve write for this session".
|
||||
const TOOL_APPROVAL_EXTRA_CHOICE = /^(?:Always )?Approve\b/;
|
||||
const TOOL_APPROVAL_EXTRA_ACTION_PREFIX = "approve-option-";
|
||||
const TOOL_TITLE_PREFIX = "Allow tool: ";
|
||||
|
||||
export type OmpRpcUiPermissionClassification =
|
||||
@@ -25,6 +30,12 @@ interface ToolApprovalDescriptor {
|
||||
args: AgentMetadata;
|
||||
detail: ToolCallDetail;
|
||||
description?: string;
|
||||
choices: ToolApprovalChoices;
|
||||
}
|
||||
|
||||
interface ToolApprovalChoices {
|
||||
approveValue: string;
|
||||
extraValues: string[];
|
||||
}
|
||||
|
||||
export function classifyOmpRpcUiPermissionRequest(
|
||||
@@ -37,6 +48,13 @@ export function classifyOmpRpcUiPermissionRequest(
|
||||
}
|
||||
|
||||
const provider = options.provider ?? OMP_PROVIDER;
|
||||
const { approveValue, extraValues } = descriptor.choices;
|
||||
const extraActions = extraValues.map((value, index) => ({
|
||||
id: `${TOOL_APPROVAL_EXTRA_ACTION_PREFIX}${index}`,
|
||||
label: value,
|
||||
behavior: "allow" as const,
|
||||
variant: "secondary" as const,
|
||||
}));
|
||||
return {
|
||||
kind: "tool",
|
||||
request: {
|
||||
@@ -57,17 +75,18 @@ export function classifyOmpRpcUiPermissionRequest(
|
||||
},
|
||||
{
|
||||
id: "approve",
|
||||
label: TOOL_APPROVAL_APPROVE_VALUE,
|
||||
label: approveValue,
|
||||
behavior: "allow",
|
||||
variant: "primary",
|
||||
},
|
||||
...extraActions,
|
||||
],
|
||||
metadata: {
|
||||
extensionUiMethod: "select",
|
||||
toolApproval: OMP_RPC_UI_TOOL_APPROVAL_METADATA,
|
||||
toolName: descriptor.toolName,
|
||||
toolArgs: descriptor.args,
|
||||
approveValue: TOOL_APPROVAL_APPROVE_VALUE,
|
||||
approveValue,
|
||||
denyValue: TOOL_APPROVAL_DENY_VALUE,
|
||||
},
|
||||
},
|
||||
@@ -95,13 +114,23 @@ export function buildOmpRpcUiPermissionResponse(
|
||||
|
||||
const approveValue = readString(request.metadata.approveValue) ?? TOOL_APPROVAL_APPROVE_VALUE;
|
||||
const denyValue = readString(request.metadata.denyValue) ?? TOOL_APPROVAL_DENY_VALUE;
|
||||
return { value: response.behavior === "allow" ? approveValue : denyValue };
|
||||
if (response.behavior !== "allow") {
|
||||
return { value: denyValue };
|
||||
}
|
||||
// Each extra choice's action label is the exact select value OMP offered.
|
||||
const selectedExtraChoice = request.actions?.find(
|
||||
(action) =>
|
||||
action.id === response.selectedActionId &&
|
||||
action.id.startsWith(TOOL_APPROVAL_EXTRA_ACTION_PREFIX),
|
||||
);
|
||||
return { value: selectedExtraChoice?.label ?? approveValue };
|
||||
}
|
||||
|
||||
function parseToolApprovalDescriptor(
|
||||
event: ExtensionUiRequestEvent,
|
||||
): ToolApprovalDescriptor | null {
|
||||
if (event.method !== "select" || !hasExactToolApprovalOptions(event.options)) {
|
||||
const choices = event.method === "select" ? readToolApprovalChoices(event.options) : null;
|
||||
if (!choices) {
|
||||
return null;
|
||||
}
|
||||
const title = readString(event.title);
|
||||
@@ -118,6 +147,15 @@ function parseToolApprovalDescriptor(
|
||||
const body = firstLineBreak < 0 ? "" : title.slice(firstLineBreak).replace(/^\r?\n/, "");
|
||||
const bodyLines = body.split(/\r?\n/);
|
||||
|
||||
const parsed = parseToolApprovalBody(rawToolName, body, bodyLines);
|
||||
return parsed ? { ...parsed, choices } : null;
|
||||
}
|
||||
|
||||
function parseToolApprovalBody(
|
||||
rawToolName: string,
|
||||
body: string,
|
||||
bodyLines: string[],
|
||||
): Omit<ToolApprovalDescriptor, "choices"> | null {
|
||||
switch (rawToolName) {
|
||||
case "bash":
|
||||
return parseBashApproval(body);
|
||||
@@ -130,7 +168,7 @@ function parseToolApprovalDescriptor(
|
||||
}
|
||||
}
|
||||
|
||||
function parseBashApproval(body: string): ToolApprovalDescriptor | null {
|
||||
function parseBashApproval(body: string): Omit<ToolApprovalDescriptor, "choices"> | null {
|
||||
const match = /(?:^|\r?\n)[\t ]*Command:[\t ]?(.*)$/s.exec(body);
|
||||
const command = match?.[1];
|
||||
if (!command) {
|
||||
@@ -144,7 +182,7 @@ function parseBashApproval(body: string): ToolApprovalDescriptor | null {
|
||||
};
|
||||
}
|
||||
|
||||
function parseEditApproval(lines: string[]): ToolApprovalDescriptor | null {
|
||||
function parseEditApproval(lines: string[]): Omit<ToolApprovalDescriptor, "choices"> | null {
|
||||
const filePath = readPrefixedValue(lines, "File:");
|
||||
if (!filePath) {
|
||||
return null;
|
||||
@@ -157,7 +195,7 @@ function parseEditApproval(lines: string[]): ToolApprovalDescriptor | null {
|
||||
};
|
||||
}
|
||||
|
||||
function parseWriteApproval(lines: string[]): ToolApprovalDescriptor | null {
|
||||
function parseWriteApproval(lines: string[]): Omit<ToolApprovalDescriptor, "choices"> | null {
|
||||
const pathLineIndex = lines.findIndex((line) => line.trim().startsWith("Path:"));
|
||||
if (pathLineIndex < 0) {
|
||||
return null;
|
||||
@@ -182,12 +220,28 @@ function parseWriteApproval(lines: string[]): ToolApprovalDescriptor | null {
|
||||
};
|
||||
}
|
||||
|
||||
function hasExactToolApprovalOptions(options: unknown): boolean {
|
||||
return (
|
||||
Array.isArray(options) &&
|
||||
options.length === TOOL_APPROVAL_OPTIONS.length &&
|
||||
options.every((option, index) => option === TOOL_APPROVAL_OPTIONS[index])
|
||||
function readToolApprovalChoices(options: unknown): ToolApprovalChoices | null {
|
||||
if (!Array.isArray(options) || !options.every((option) => typeof option === "string")) {
|
||||
return null;
|
||||
}
|
||||
const labels = options as string[];
|
||||
if (
|
||||
labels.at(-1) !== TOOL_APPROVAL_DENY_VALUE ||
|
||||
labels.indexOf(TOOL_APPROVAL_DENY_VALUE) !== labels.length - 1
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const approveValue = [TOOL_APPROVAL_ONCE_VALUE, TOOL_APPROVAL_APPROVE_VALUE].find((value) =>
|
||||
labels.includes(value),
|
||||
);
|
||||
if (!approveValue) {
|
||||
return null;
|
||||
}
|
||||
const extraValues = labels.slice(0, -1).filter((label) => label !== approveValue);
|
||||
if (!extraValues.every((label) => TOOL_APPROVAL_EXTRA_CHOICE.test(label))) {
|
||||
return null;
|
||||
}
|
||||
return { approveValue, extraValues };
|
||||
}
|
||||
|
||||
function readPrefixedValue(lines: readonly string[], prefix: string): string | null {
|
||||
|
||||
@@ -800,7 +800,8 @@ describe("BrowserToolsBroker", () => {
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_timeout",
|
||||
message: "Browser automation timed out after 50ms.",
|
||||
message:
|
||||
"The browser host did not respond within 50ms. Try again or check the browser host.",
|
||||
retryable: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -422,7 +422,7 @@ export class BrowserToolsBroker {
|
||||
browserToolsFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_timeout",
|
||||
message: `Browser automation timed out after ${timeoutMs}ms.`,
|
||||
message: `The browser host did not respond within ${timeoutMs}ms. Try again or check the browser host.`,
|
||||
retryable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -481,14 +481,41 @@ const brokerErrorCases = [
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_timeout",
|
||||
message: "Browser automation timed out after 15000ms.",
|
||||
message:
|
||||
"The browser host did not respond within 15000ms. Try again or check the browser host.",
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "The browser did not respond before the timeout. Try again or check the browser host.",
|
||||
text: "The browser host did not respond within 15000ms. Try again or check the browser host.",
|
||||
},
|
||||
],
|
||||
context: {
|
||||
agentId: "agent-1",
|
||||
cwd: "/repo",
|
||||
workspaceId: "wks_workspace_a",
|
||||
browserId: BROWSER_ID,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "expired wait conditions",
|
||||
toolName: "browser_wait",
|
||||
input: { browserId: BROWSER_ID, text: "Example Domain" },
|
||||
payload: {
|
||||
requestId: "req-wait",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_timeout",
|
||||
message: "Timed out waiting for browser text: Example Domain",
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Timed out waiting for browser text: Example Domain",
|
||||
},
|
||||
],
|
||||
context: {
|
||||
@@ -897,7 +924,7 @@ describe("registerBrowserTools", () => {
|
||||
expect(response.content).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: 'The browser did not respond before the timeout. Try again or check the browser host.\nHandled browser dialog: dismissed beforeunload "Leave site?".',
|
||||
text: 'Timed out waiting for browser URL: /next\nHandled browser dialog: dismissed beforeunload "Leave site?".',
|
||||
},
|
||||
]);
|
||||
expect(response.structuredContent).toEqual({
|
||||
|
||||
@@ -1039,14 +1039,6 @@ function summarizeBrowserError(
|
||||
switch (error.code) {
|
||||
case "browser_disabled":
|
||||
return "Browser tools are disabled. Enable browser tools on the host, then try again.";
|
||||
case "browser_no_host":
|
||||
return error.message;
|
||||
case "browser_timeout":
|
||||
return "The browser did not respond before the timeout. Try again or check the browser host.";
|
||||
case "screenshot_no_frame":
|
||||
return error.message;
|
||||
case "browser_unsupported":
|
||||
return error.message;
|
||||
case "browser_stale_ref":
|
||||
return "That browser element reference is stale. Take a new browser snapshot and try again.";
|
||||
default:
|
||||
|
||||
@@ -50,7 +50,10 @@ export class CheckoutDiffManager {
|
||||
workspaceGitService: Pick<WorkspaceGitService, "requestWorkingTreeWatch">;
|
||||
workspaceRuntimeStore: WorkspaceRuntimeStore;
|
||||
}) {
|
||||
this.streams = new DiffSubscriptions(options.workspaceGitService);
|
||||
this.streams = new DiffSubscriptions(
|
||||
options.workspaceGitService,
|
||||
options.logger.child({ module: "checkout-diff" }),
|
||||
);
|
||||
this.paseoHome = options.paseoHome;
|
||||
}
|
||||
readCommitFile(input: CommitFileRead) {
|
||||
@@ -178,7 +181,7 @@ export class CheckoutDiffManager {
|
||||
checkoutDiffTargetCount: metrics.targets,
|
||||
checkoutDiffSubscriptionCount: metrics.subscriptions,
|
||||
checkoutDiffWatcherCount: metrics.metadataObservers,
|
||||
checkoutDiffFallbackRefreshTargetCount: 0,
|
||||
checkoutDiffFallbackRefreshTargetCount: metrics.fallbackTargets,
|
||||
};
|
||||
}
|
||||
async dispose(): Promise<void> {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "./persisted-config.js";
|
||||
import { ProviderOverrideSchema } from "./agent/provider-launch-config.js";
|
||||
import {
|
||||
convertLegacyClaudeUltracode,
|
||||
convertLegacyOptions,
|
||||
foldProfileFeatureValues,
|
||||
resolveAdapter,
|
||||
@@ -194,13 +195,21 @@ function foldConfigProfiles<T extends { agentProfiles?: AgentProfile[] }>(input:
|
||||
options,
|
||||
});
|
||||
const identity = (_provider: string, options: Record<string, unknown> | undefined) => options;
|
||||
const foldWith = (profile: AgentProfile, convertWith: typeof convert) =>
|
||||
foldProfileFeatureValues({
|
||||
const foldWith = (profile: AgentProfile, convertWith: typeof convert) => {
|
||||
const folded = foldProfileFeatureValues<
|
||||
Pick<AgentProfile, "provider" | "options" | "featureValues">
|
||||
>({
|
||||
profile,
|
||||
stored: held.find((candidate) => candidate.id === profile.id),
|
||||
source,
|
||||
convert: convertWith,
|
||||
});
|
||||
const { providerOptions, ...converted } = convertLegacyClaudeUltracode(
|
||||
{ ...folded, thinkingOptionId: profile.thinkingOptionId, providerOptions: folded.options },
|
||||
resolveAdapter({ provider: profile.provider, extendsOf: (id) => providers?.[id]?.extends }),
|
||||
);
|
||||
return { ...converted, options: providerOptions };
|
||||
};
|
||||
return {
|
||||
...config,
|
||||
agentProfiles: config.agentProfiles.map((profile) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { test, expect, beforeEach, afterEach } from "vitest";
|
||||
import { execSync } from "child_process";
|
||||
import { execFileSync, execSync } from "child_process";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import path from "path";
|
||||
@@ -164,3 +164,165 @@ test("keeps the socket usable after rejecting an oversized structured diff", asy
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 120000);
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"Changes opens and follows Git updates when metadata exceeds the watcher limit",
|
||||
async () => {
|
||||
const cwd = tmpCwd();
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
try {
|
||||
initGitRepo(cwd);
|
||||
commitFile(cwd, "tracked.txt", "base\n");
|
||||
const head = git("rev-parse", "HEAD");
|
||||
git("switch", "-c", "topic");
|
||||
commitFile(cwd, "next.txt", "next\n");
|
||||
const next = git("rev-parse", "HEAD");
|
||||
git("reset", "--hard", head);
|
||||
execFileSync("git", ["update-ref", "--stdin"], {
|
||||
cwd,
|
||||
input: Array.from(
|
||||
{ length: 5010 },
|
||||
(_, i) => `create refs/heads/overflow-${i}/branch ${head}\n`,
|
||||
).join(""),
|
||||
});
|
||||
writeFileSync(path.join(cwd, "tracked.txt"), "edit\n");
|
||||
|
||||
const changes = ctx.client.observeDiff({
|
||||
cwd,
|
||||
base: { kind: "rev", rev: "main" },
|
||||
head: { kind: "worktree" },
|
||||
mergeBase: true,
|
||||
});
|
||||
let current: import("@getpaseo/client").DiffState | undefined;
|
||||
const unsubscribe = changes.subscribe({
|
||||
snapshot: (state) => {
|
||||
current = state;
|
||||
},
|
||||
update: () => {},
|
||||
});
|
||||
try {
|
||||
await expect
|
||||
.poll(() => current, { timeout: 12000 })
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "tracked.txt" }],
|
||||
});
|
||||
const legacy = ctx.client.observeCheckoutDiff(cwd, { mode: "all", baseRef: "main" });
|
||||
try {
|
||||
expect(await legacy.ready).toMatchObject({
|
||||
error: null,
|
||||
files: [{ path: "tracked.txt" }],
|
||||
});
|
||||
} finally {
|
||||
await legacy.release();
|
||||
}
|
||||
expect(
|
||||
await ctx.client.getCheckoutDiff(cwd, { mode: "all", baseRef: "main" }),
|
||||
).toMatchObject({ error: null, files: [{ path: "tracked.txt" }] });
|
||||
|
||||
writeFileSync(path.join(cwd, "working.txt"), "untracked\n");
|
||||
await expect
|
||||
.poll(() => current, { timeout: 3000 })
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "tracked.txt" }, { path: "working.txt" }],
|
||||
});
|
||||
|
||||
const staged = ctx.client.observeDiff({
|
||||
cwd,
|
||||
base: { kind: "rev", rev: head },
|
||||
head: { kind: "index" },
|
||||
});
|
||||
const pinned = ctx.client.observeDiff({
|
||||
cwd,
|
||||
base: { kind: "empty" },
|
||||
head: { kind: "rev", rev: head },
|
||||
});
|
||||
const selected = ctx.client.observeDiff({
|
||||
cwd,
|
||||
base: { kind: "rev", rev: head },
|
||||
head: { kind: "rev", rev: "main" },
|
||||
});
|
||||
let stagedState: typeof current;
|
||||
let pinnedState: typeof current;
|
||||
let selectedState: typeof current;
|
||||
const stopStaged = staged.subscribe({
|
||||
snapshot: (state) => {
|
||||
stagedState = state;
|
||||
},
|
||||
update: () => {},
|
||||
});
|
||||
const stopPinned = pinned.subscribe({
|
||||
snapshot: (state) => {
|
||||
pinnedState = state;
|
||||
},
|
||||
update: () => {},
|
||||
});
|
||||
const stopSelected = selected.subscribe({
|
||||
snapshot: (state) => {
|
||||
selectedState = state;
|
||||
},
|
||||
update: () => {},
|
||||
});
|
||||
try {
|
||||
await expect.poll(() => stagedState).toMatchObject({ phase: "ready", files: [] });
|
||||
await expect
|
||||
.poll(() => pinnedState)
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "tracked.txt", status: "ok" }],
|
||||
});
|
||||
await expect.poll(() => selectedState).toMatchObject({ phase: "ready", files: [] });
|
||||
git("add", "tracked.txt");
|
||||
writeFileSync(path.join(cwd, ".git", "info", "attributes"), "tracked.txt -diff\n");
|
||||
git("update-ref", "refs/heads/main", next);
|
||||
await expect
|
||||
.poll(() => selectedState, { timeout: 17000 })
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "next.txt" }],
|
||||
resolved: { headSha: next },
|
||||
});
|
||||
await expect
|
||||
.poll(() => stagedState)
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "tracked.txt" }],
|
||||
});
|
||||
await expect
|
||||
.poll(() => pinnedState)
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
files: [{ path: "tracked.txt", status: "binary" }],
|
||||
});
|
||||
git("symbolic-ref", "HEAD", "refs/heads/main");
|
||||
await expect
|
||||
.poll(() => current, { timeout: 17000 })
|
||||
.toMatchObject({
|
||||
phase: "ready",
|
||||
resolved: { mergeBaseSha: next },
|
||||
files: [{ path: "next.txt" }, { path: "tracked.txt" }, { path: "working.txt" }],
|
||||
});
|
||||
expect(
|
||||
await ctx.client.readDiff({
|
||||
cwd,
|
||||
base: { kind: "rev", rev: "missing-branch" },
|
||||
head: { kind: "worktree" },
|
||||
}),
|
||||
).toMatchObject({ phase: "error", error: { code: "REF_NOT_FOUND" } });
|
||||
} finally {
|
||||
stopStaged();
|
||||
stopPinned();
|
||||
stopSelected();
|
||||
await Promise.all([staged.release(), pinned.release(), selected.release()]);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
await changes.release();
|
||||
}
|
||||
} finally {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
45000,
|
||||
);
|
||||
|
||||
@@ -1,91 +1,197 @@
|
||||
import { resolve, relative } from "node:path";
|
||||
import type { Logger } from "pino";
|
||||
import { runGitCommand } from "../../utils/run-git-command.js";
|
||||
import { createFileObserver, type FileObserverSubscription } from "../file-observer/index.js";
|
||||
import {
|
||||
affectsGitDiffInterpretation,
|
||||
classifyGitMetadataPath,
|
||||
type GitMetadataScope,
|
||||
} from "../git-metadata-event-rules.js";
|
||||
import { resolve } from "node:path";
|
||||
import { runGitCommand } from "../../utils/run-git-command.js";
|
||||
import type { WorkspaceGitService } from "../workspace-git-service.js";
|
||||
import { createFileObserver, type FileObserverSubscription } from "../file-observer/index.js";
|
||||
import type { RevisionWatch } from "./revision-probe.js";
|
||||
import { pollDiffMetadata } from "./metadata-poll.js";
|
||||
|
||||
export interface DiffDependencies {
|
||||
cwd: string;
|
||||
refs: string[];
|
||||
export interface DiffDependencies extends Omit<RevisionWatch, "changed" | "gitDirectory"> {
|
||||
movingRevision: boolean;
|
||||
index: boolean;
|
||||
worktree: boolean;
|
||||
}
|
||||
// Own metadata observations here; comparison managers declare inputs rather than watching paths.
|
||||
|
||||
type MetadataListener = (paths: string[] | null) => void;
|
||||
export interface DiffDependencySubscription {
|
||||
release(): Promise<void>;
|
||||
isPolling(): boolean;
|
||||
}
|
||||
|
||||
interface MetadataObservation {
|
||||
listeners: Set<MetadataListener>;
|
||||
revisions: Set<RevisionWatch>;
|
||||
ready: Promise<void>;
|
||||
watcher?: FileObserverSubscription;
|
||||
poll?: ReturnType<typeof pollDiffMetadata>;
|
||||
}
|
||||
|
||||
// Comparison managers declare inputs. This observer owns their shared Git metadata roots.
|
||||
export class DiffDependencyObserver {
|
||||
private observer = createFileObserver();
|
||||
constructor(private workspaceGit: Pick<WorkspaceGitService, "requestWorkingTreeWatch">) {}
|
||||
private roots = new Map<string, MetadataObservation>();
|
||||
|
||||
constructor(
|
||||
private workspaceGit: Pick<WorkspaceGitService, "requestWorkingTreeWatch">,
|
||||
private logger?: Pick<Logger, "warn">,
|
||||
) {}
|
||||
|
||||
async declareDependencies(
|
||||
input: DiffDependencies,
|
||||
changed: (kind: "endpoints" | "interpretation") => void,
|
||||
): Promise<() => Promise<void>> {
|
||||
const hasMutableEndpoints = input.refs.length > 0 || input.index || input.worktree;
|
||||
let polling: ReturnType<typeof setInterval> | null = null;
|
||||
const subscriptions: FileObserverSubscription[] = [];
|
||||
let workingTree: Awaited<ReturnType<WorkspaceGitService["requestWorkingTreeWatch"]>> | null =
|
||||
null;
|
||||
): Promise<DiffDependencySubscription> {
|
||||
const hasMutableEndpoints =
|
||||
input.movingRevision || input.checkoutBase !== undefined || input.index || input.worktree;
|
||||
const rootPaths = await runGitCommand(["rev-parse", "--absolute-git-dir", "--git-common-dir"], {
|
||||
cwd: input.cwd,
|
||||
});
|
||||
const [gitDir, commonDir] = rootPaths.stdout.split(/\r?\n/);
|
||||
if (!gitDir || !commonDir) throw new Error("Git returned incomplete metadata roots");
|
||||
const worktreeRoot = resolve(input.cwd, gitDir);
|
||||
const commonRoot = resolve(input.cwd, commonDir);
|
||||
const roots: [string, GitMetadataScope[]][] =
|
||||
commonRoot === worktreeRoot
|
||||
? [[worktreeRoot, ["worktree", "common"]]]
|
||||
: [
|
||||
[worktreeRoot, ["worktree"]],
|
||||
[commonRoot, ["common"]],
|
||||
];
|
||||
|
||||
const metadata: DiffDependencySubscription[] = [];
|
||||
const releaseMetadata = async () => {
|
||||
await Promise.all(metadata.map((subscription) => subscription.release()));
|
||||
};
|
||||
try {
|
||||
const paths = await runGitCommand(["rev-parse", "--absolute-git-dir", "--git-common-dir"], {
|
||||
cwd: input.cwd,
|
||||
});
|
||||
const [gitDir, commonDir] = paths.stdout.split(/\r?\n/);
|
||||
if (!gitDir || !commonDir) throw new Error("Git returned incomplete metadata roots");
|
||||
const roots = new Map<string, GitMetadataScope[]>();
|
||||
for (const [directory, scope] of [
|
||||
[gitDir, "worktree"],
|
||||
[commonDir, "common"],
|
||||
] as const) {
|
||||
const root = resolve(input.cwd, directory);
|
||||
const scopes = roots.get(root) ?? [];
|
||||
scopes.push(scope);
|
||||
roots.set(root, scopes);
|
||||
}
|
||||
for (const [root, scopes] of roots) {
|
||||
const subscription = await this.observer.subscribe(
|
||||
root,
|
||||
(error, events) => {
|
||||
if (error) {
|
||||
changed("endpoints");
|
||||
polling ??= setInterval(() => changed("endpoints"), 5000);
|
||||
return;
|
||||
}
|
||||
let interpretation = false;
|
||||
const endpoints = events.some((event) => {
|
||||
const path = event.path.slice(root.length + 1).replaceAll("\\", "/");
|
||||
if (scopes.some((scope) => affectsGitDiffInterpretation(scope, path)))
|
||||
interpretation = true;
|
||||
if (!hasMutableEndpoints) return false;
|
||||
if (path === "index") return input.index;
|
||||
return scopes.some((scope) => classifyGitMetadataPath(scope, path).kind !== "ignore");
|
||||
});
|
||||
if (endpoints) changed("endpoints");
|
||||
else if (interpretation) changed("interpretation");
|
||||
},
|
||||
{ ignore: [resolve(root, "objects"), resolve(root, "logs"), resolve(root, "hooks")] },
|
||||
const isWorktree = scopes.includes("worktree");
|
||||
metadata.push(
|
||||
await this.observeMetadata(
|
||||
root,
|
||||
root === commonRoot
|
||||
? { ...input, gitDirectory: worktreeRoot, changed: () => changed("endpoints") }
|
||||
: null,
|
||||
(paths) => {
|
||||
if (
|
||||
hasMutableEndpoints &&
|
||||
(paths === null ||
|
||||
paths.some((path) => {
|
||||
if (path === "index") return isWorktree && input.index;
|
||||
if (path === "HEAD") return isWorktree;
|
||||
return scopes.some(
|
||||
(scope) => classifyGitMetadataPath(scope, path).kind !== "ignore",
|
||||
);
|
||||
}))
|
||||
) {
|
||||
changed("endpoints");
|
||||
} else if (
|
||||
paths === null ||
|
||||
paths.some((path) =>
|
||||
scopes.some((scope) => affectsGitDiffInterpretation(scope, path)),
|
||||
)
|
||||
) {
|
||||
changed("interpretation");
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
subscriptions.push(subscription);
|
||||
}
|
||||
workingTree = await this.workspaceGit.requestWorkingTreeWatch(input.cwd, () =>
|
||||
const workingTree = await this.workspaceGit.requestWorkingTreeWatch(input.cwd, () =>
|
||||
changed(input.worktree ? "endpoints" : "interpretation"),
|
||||
);
|
||||
return async () => {
|
||||
if (polling) clearInterval(polling);
|
||||
await workingTree?.unsubscribe();
|
||||
await Promise.all(subscriptions.map((subscription) => subscription.unsubscribe()));
|
||||
return {
|
||||
isPolling: () => metadata.some((subscription) => subscription.isPolling()),
|
||||
async release() {
|
||||
try {
|
||||
workingTree.unsubscribe();
|
||||
} finally {
|
||||
await releaseMetadata();
|
||||
}
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (polling) clearInterval(polling);
|
||||
await workingTree?.unsubscribe();
|
||||
await Promise.all(subscriptions.map((subscription) => subscription.unsubscribe()));
|
||||
await releaseMetadata();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async observeMetadata(
|
||||
root: string,
|
||||
revisions: RevisionWatch | null,
|
||||
listener: MetadataListener,
|
||||
): Promise<DiffDependencySubscription> {
|
||||
let observation = this.roots.get(root);
|
||||
if (!observation) {
|
||||
observation = { listeners: new Set(), revisions: new Set(), ready: Promise.resolve() };
|
||||
this.roots.set(root, observation);
|
||||
observation.ready = this.openMetadata(root, observation);
|
||||
}
|
||||
const current = observation;
|
||||
current.listeners.add(listener);
|
||||
if (revisions) current.revisions.add(revisions);
|
||||
await current.ready;
|
||||
return {
|
||||
isPolling: () => current.poll !== undefined,
|
||||
release: async () => {
|
||||
if (!current.listeners.delete(listener)) return;
|
||||
if (revisions) current.revisions.delete(revisions);
|
||||
if (current.listeners.size) return;
|
||||
this.roots.delete(root);
|
||||
await Promise.all([current.watcher?.unsubscribe(), current.poll?.close()]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async openMetadata(root: string, observation: MetadataObservation) {
|
||||
const notify: MetadataListener = (paths) => {
|
||||
for (const listener of observation.listeners) listener(paths);
|
||||
};
|
||||
const startPoll = (error: unknown) => {
|
||||
if (!observation.poll) {
|
||||
this.logger?.warn(
|
||||
{ err: error, root },
|
||||
"Diff metadata watcher failed; using degraded polling",
|
||||
);
|
||||
let reported = false;
|
||||
observation.poll = pollDiffMetadata(root, observation.revisions, notify, (err, cwd) => {
|
||||
if (reported) return;
|
||||
reported = true;
|
||||
this.logger?.warn({ err, root, cwd }, "Failed to probe revisions for Changes");
|
||||
});
|
||||
}
|
||||
return observation.poll;
|
||||
};
|
||||
const recover = async (error: Error) => {
|
||||
// Resample the gap between the last watcher batch and the first poll.
|
||||
await startPoll(error).ready;
|
||||
notify(null);
|
||||
};
|
||||
|
||||
try {
|
||||
observation.watcher = await this.observer.subscribe(
|
||||
root,
|
||||
(error, events) => {
|
||||
if (error) {
|
||||
void recover(error);
|
||||
return;
|
||||
}
|
||||
notify(events.map((event) => relative(root, event.path).replaceAll("\\", "/")));
|
||||
},
|
||||
{ ignore: [resolve(root, "objects"), resolve(root, "logs"), resolve(root, "hooks")] },
|
||||
);
|
||||
} catch (error) {
|
||||
await startPoll(error).ready;
|
||||
}
|
||||
}
|
||||
|
||||
getObservationCount(): number {
|
||||
return this.observer.getDiagnostics().activeObservationCount;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.observer.close();
|
||||
}
|
||||
|
||||
@@ -21,6 +21,15 @@ import { parseDiff, highlightDiffWithFileContent } from "../utils/diff-highlight
|
||||
export type Compare = Omit<DiffSubscribeRequest, "type" | "requestId"> & {
|
||||
checkoutBase?: { compare: CheckoutDiffCompare; paseoHome: string };
|
||||
};
|
||||
export interface ComparisonRevisions {
|
||||
refs: Map<string, string | null>;
|
||||
checkoutBase?: string | null;
|
||||
}
|
||||
|
||||
export function isMovingRevision(rev: string): boolean {
|
||||
return !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(rev);
|
||||
}
|
||||
|
||||
export interface ListedFile {
|
||||
entry: DiffEntry;
|
||||
identity: string;
|
||||
@@ -90,6 +99,7 @@ async function resolveEndpoint(
|
||||
cwd: string,
|
||||
endpoint: DiffEndpoint,
|
||||
indexFile: string | null,
|
||||
revisions?: ComparisonRevisions,
|
||||
): Promise<string> {
|
||||
if (endpoint.kind === "empty") return EMPTY;
|
||||
if (endpoint.kind === "index") {
|
||||
@@ -108,7 +118,9 @@ async function resolveEndpoint(
|
||||
acceptExitCodes: [0, 128],
|
||||
},
|
||||
);
|
||||
if (result.exitCode === 0) return result.stdout.trim();
|
||||
const sha = result.exitCode === 0 ? result.stdout.trim() : null;
|
||||
if (isMovingRevision(ref)) revisions?.refs.set(ref, sha);
|
||||
if (sha !== null) return sha;
|
||||
if (ref === "HEAD") {
|
||||
const unborn = await runGitCommand(["rev-parse", "--verify", "HEAD"], {
|
||||
cwd,
|
||||
@@ -142,11 +154,16 @@ function parseStats(
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
export async function listComparison(compare: Compare): Promise<Comparison> {
|
||||
export async function listComparison(
|
||||
compare: Compare,
|
||||
revisions?: ComparisonRevisions,
|
||||
): Promise<Comparison> {
|
||||
if (compare.checkoutBase) {
|
||||
if (revisions) revisions.checkoutBase = null;
|
||||
const selected = await resolveCheckoutDiffBase(compare.cwd, compare.checkoutBase.compare, {
|
||||
paseoHome: compare.checkoutBase.paseoHome,
|
||||
});
|
||||
if (revisions) revisions.checkoutBase = selected;
|
||||
if (!selected) throw new DiffReadError("REF_NOT_FOUND", "Comparison base is unavailable");
|
||||
compare = { ...compare, base: { kind: "rev", rev: selected } };
|
||||
}
|
||||
@@ -157,14 +174,14 @@ export async function listComparison(compare: Compare): Promise<Comparison> {
|
||||
if (compare.base.kind === "index" || compare.head.kind === "index")
|
||||
privateIndex = await snapshotComparisonIndex(cwd);
|
||||
const indexFile = privateIndex ? privateIndex.indexFile : null;
|
||||
const baseSha = await resolveEndpoint(cwd, compare.base, indexFile);
|
||||
const headSha = await resolveEndpoint(cwd, compare.head, indexFile);
|
||||
const baseSha = await resolveEndpoint(cwd, compare.base, indexFile, revisions);
|
||||
const headSha = await resolveEndpoint(cwd, compare.head, indexFile, revisions);
|
||||
let mergeBaseSha = "";
|
||||
let comparisonBaseSha = baseSha;
|
||||
if (compare.mergeBase) {
|
||||
const headCommit =
|
||||
compare.head.kind === "index"
|
||||
? await resolveEndpoint(cwd, { kind: "rev", rev: "HEAD" }, indexFile)
|
||||
? await resolveEndpoint(cwd, { kind: "rev", rev: "HEAD" }, indexFile, revisions)
|
||||
: headSha;
|
||||
if (headCommit === EMPTY) comparisonBaseSha = EMPTY;
|
||||
else if (baseSha !== EMPTY) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Logger } from "pino";
|
||||
import { TOTAL_DIFF_MAX_BYTES } from "../../utils/checkout-git.js";
|
||||
import { DEFAULT_MAX_OUTPUT_BYTES, runGitCommand } from "../../utils/run-git-command.js";
|
||||
import { expandTilde, createRealpathAwarePathMatcher } from "../../utils/path.js";
|
||||
@@ -19,13 +20,15 @@ import type {
|
||||
import type { WorkspaceGitService } from "../workspace-git-service.js";
|
||||
import {
|
||||
listComparison,
|
||||
isMovingRevision,
|
||||
validateCompare,
|
||||
worktreeRoot,
|
||||
DiffReadError,
|
||||
type Compare,
|
||||
type Comparison,
|
||||
type ComparisonRevisions,
|
||||
} from "./git.js";
|
||||
import { DiffDependencyObserver } from "./dependencies.js";
|
||||
import { DiffDependencyObserver, type DiffDependencySubscription } from "./dependencies.js";
|
||||
|
||||
interface RecordCache {
|
||||
identity: string;
|
||||
@@ -42,6 +45,7 @@ interface Target {
|
||||
compare: Compare;
|
||||
listeners: Set<Listener>;
|
||||
revision: number;
|
||||
revisions: ComparisonRevisions | null;
|
||||
committed: number;
|
||||
cache: Map<string, RecordCache>;
|
||||
entries: DiffEntry[];
|
||||
@@ -53,7 +57,7 @@ interface Target {
|
||||
checkInterpretation: (() => Promise<boolean>) | null;
|
||||
interpretationCheck: Promise<void> | null;
|
||||
interpretationDirty: boolean;
|
||||
release: (() => Promise<void>) | null;
|
||||
dependencies: DiffDependencySubscription | null;
|
||||
opening: Promise<void> | null;
|
||||
closed: boolean;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
@@ -73,16 +77,18 @@ export class DiffSubscriptions {
|
||||
private dependencies: DiffDependencyObserver;
|
||||
private computations = 0;
|
||||
private highlightCalls = 0;
|
||||
constructor(workspaceGit: Pick<WorkspaceGitService, "requestWorkingTreeWatch">) {
|
||||
this.dependencies = new DiffDependencyObserver(workspaceGit);
|
||||
constructor(
|
||||
workspaceGit: Pick<WorkspaceGitService, "requestWorkingTreeWatch">,
|
||||
logger?: Pick<Logger, "warn">,
|
||||
) {
|
||||
this.dependencies = new DiffDependencyObserver(workspaceGit, logger);
|
||||
}
|
||||
getMetrics() {
|
||||
const targets = [...this.targets.values()];
|
||||
return {
|
||||
targets: this.targets.size,
|
||||
subscriptions: [...this.targets.values()].reduce(
|
||||
(sum, target) => sum + target.listeners.size,
|
||||
0,
|
||||
),
|
||||
targets: targets.length,
|
||||
subscriptions: targets.reduce((sum, target) => sum + target.listeners.size, 0),
|
||||
fallbackTargets: targets.filter((target) => target.dependencies?.isPolling()).length,
|
||||
computations: this.computations,
|
||||
highlightCalls: this.highlightCalls,
|
||||
metadataObservers: this.dependencies.getObservationCount(),
|
||||
@@ -141,6 +147,7 @@ export class DiffSubscriptions {
|
||||
compare,
|
||||
listeners: new Set(),
|
||||
revision: 0,
|
||||
revisions: null,
|
||||
committed: 0,
|
||||
cache: new Map(),
|
||||
entries: [],
|
||||
@@ -152,7 +159,7 @@ export class DiffSubscriptions {
|
||||
checkInterpretation: null,
|
||||
interpretationCheck: null,
|
||||
interpretationDirty: false,
|
||||
release: null,
|
||||
dependencies: null,
|
||||
opening: null,
|
||||
closed: false,
|
||||
timer: null,
|
||||
@@ -164,11 +171,11 @@ export class DiffSubscriptions {
|
||||
.declareDependencies(
|
||||
{
|
||||
cwd: compare.cwd,
|
||||
refs: [compare.base, compare.head].flatMap((endpoint) =>
|
||||
endpoint.kind === "rev" && !/^[a-f0-9]{40,64}$/.test(endpoint.rev)
|
||||
? [endpoint.rev]
|
||||
: [],
|
||||
movingRevision: [compare.base, compare.head].some(
|
||||
(endpoint) => endpoint.kind === "rev" && isMovingRevision(endpoint.rev),
|
||||
),
|
||||
checkoutBase: compare.checkoutBase,
|
||||
getRevisions: () => captured.revisions,
|
||||
index: compare.base.kind === "index" || compare.head.kind !== "rev",
|
||||
worktree: compare.head.kind === "worktree",
|
||||
},
|
||||
@@ -177,8 +184,8 @@ export class DiffSubscriptions {
|
||||
else this.invalidate(captured);
|
||||
},
|
||||
)
|
||||
.then((release) => {
|
||||
captured.release = release;
|
||||
.then((dependencies) => {
|
||||
captured.dependencies = dependencies;
|
||||
return undefined;
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -219,7 +226,7 @@ export class DiffSubscriptions {
|
||||
current.closed = true;
|
||||
if (current.timer) clearTimeout(current.timer);
|
||||
this.targets.delete(key);
|
||||
await current.release?.();
|
||||
await current.dependencies?.release();
|
||||
await current.refresh;
|
||||
await current.interpretationCheck;
|
||||
},
|
||||
@@ -329,7 +336,9 @@ export class DiffSubscriptions {
|
||||
let began = false;
|
||||
try {
|
||||
this.computations++;
|
||||
comparison = await listComparison(target.compare);
|
||||
const revisions: ComparisonRevisions = { refs: new Map() };
|
||||
target.revisions = revisions;
|
||||
comparison = await listComparison(target.compare, revisions);
|
||||
target.checkInterpretation = comparison.hasInterpretationChanged;
|
||||
const resolved = {
|
||||
baseSha: comparison.baseSha,
|
||||
@@ -450,7 +459,7 @@ export class DiffSubscriptions {
|
||||
target.closed = true;
|
||||
if (target.timer) clearTimeout(target.timer);
|
||||
await target.opening;
|
||||
await target.release?.();
|
||||
await target.dependencies?.release();
|
||||
await target.refresh;
|
||||
await target.interpretationCheck;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { GIT_METADATA_EVENT_RULES } from "../git-metadata-event-rules.js";
|
||||
import { checkDiffRevisions, type RevisionWatch } from "./revision-probe.js";
|
||||
|
||||
const FIRST_DELAY_MS = 5000;
|
||||
const MAX_DELAY_MS = 60000;
|
||||
const metadataFiles = [
|
||||
...new Set(
|
||||
GIT_METADATA_EVENT_RULES.filter(
|
||||
(rule) => rule.match === "exact" && rule.id !== "packed-refs",
|
||||
).map((rule) => rule.path),
|
||||
),
|
||||
];
|
||||
|
||||
async function fileIdentity(path: string): Promise<string> {
|
||||
try {
|
||||
const info = await stat(path, { bigint: true });
|
||||
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code ?? "unavailable";
|
||||
}
|
||||
}
|
||||
|
||||
export function pollDiffMetadata(
|
||||
root: string,
|
||||
revisions: ReadonlySet<RevisionWatch>,
|
||||
changed: (paths: string[]) => void,
|
||||
probeFailed: (error: unknown, cwd: string) => void,
|
||||
) {
|
||||
let closed = false;
|
||||
let delay = FIRST_DELAY_MS;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pending: Promise<void>;
|
||||
let previous: string[];
|
||||
|
||||
function schedule() {
|
||||
timer = setTimeout(() => {
|
||||
pending = sample();
|
||||
}, delay);
|
||||
timer.unref();
|
||||
}
|
||||
|
||||
function readFiles() {
|
||||
return Promise.all(metadataFiles.map((path) => fileIdentity(join(root, path))));
|
||||
}
|
||||
|
||||
async function sample() {
|
||||
const current = await readFiles();
|
||||
if (closed) return;
|
||||
const paths = metadataFiles.filter((_, index) => current[index] !== previous[index]);
|
||||
if (paths.length) changed(paths);
|
||||
previous = current;
|
||||
const refsChanged = await checkDiffRevisions(root, revisions, probeFailed);
|
||||
if (closed) return;
|
||||
delay = paths.length || refsChanged ? FIRST_DELAY_MS : Math.min(delay * 2, MAX_DELAY_MS);
|
||||
schedule();
|
||||
}
|
||||
|
||||
async function initialize() {
|
||||
previous = await readFiles();
|
||||
if (!closed) schedule();
|
||||
}
|
||||
|
||||
// File identities establish the event boundary before the first diff. The
|
||||
// comparison's own revision reads establish its ref baseline.
|
||||
const ready = (pending = initialize());
|
||||
return {
|
||||
ready,
|
||||
async close() {
|
||||
closed = true;
|
||||
clearTimeout(timer);
|
||||
await pending;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { resolveCheckoutDiffBase } from "../../utils/checkout-git.js";
|
||||
import { createRunGitCommand } from "../../utils/run-git-command.js";
|
||||
import type { Compare, ComparisonRevisions } from "./git.js";
|
||||
|
||||
const git = createRunGitCommand("diff-metadata-poll", { priority: "background" });
|
||||
const TIMEOUT_MS = 5000;
|
||||
const BATCH_SIZE = 128;
|
||||
|
||||
export interface RevisionWatch {
|
||||
cwd: string;
|
||||
gitDirectory: string;
|
||||
checkoutBase?: Compare["checkoutBase"];
|
||||
getRevisions(): ComparisonRevisions | null;
|
||||
changed(): void;
|
||||
}
|
||||
|
||||
function probeDirectory(root: string, watch: RevisionWatch, ref: string): string {
|
||||
const sharedRef = /^refs\/(?:heads|remotes|tags)\/[\w./-]+$/.test(ref);
|
||||
const mainHead = ref === "HEAD" && watch.gitDirectory === root;
|
||||
return sharedRef || mainHead ? root : watch.cwd;
|
||||
}
|
||||
|
||||
async function readRevisions(
|
||||
cwd: string,
|
||||
commonRoot: string,
|
||||
refs: Set<string>,
|
||||
failed: (error: unknown, cwd: string) => void,
|
||||
): Promise<Map<string, string | null>> {
|
||||
const result = new Map<string, string | null>();
|
||||
const options = {
|
||||
cwd,
|
||||
timeout: TIMEOUT_MS,
|
||||
envOverlay: cwd === commonRoot ? { GIT_DIR: "." } : undefined,
|
||||
};
|
||||
const names: string[] = [];
|
||||
for (const ref of refs) {
|
||||
if (!ref.includes("\n")) {
|
||||
names.push(ref);
|
||||
continue;
|
||||
}
|
||||
// Revision expressions can contain a newline even though ref names cannot.
|
||||
try {
|
||||
const output = await git(["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], {
|
||||
...options,
|
||||
acceptExitCodes: [0, 128],
|
||||
});
|
||||
result.set(ref, output.exitCode === 0 ? output.stdout.trim() : null);
|
||||
} catch (error) {
|
||||
failed(error, cwd);
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < names.length; index += BATCH_SIZE) {
|
||||
const batch = names.slice(index, index + BATCH_SIZE);
|
||||
const queries = batch.map((ref) => `${ref}^{commit}`);
|
||||
try {
|
||||
const output = await git(["cat-file", "--batch-check=%(objectname)"], {
|
||||
...options,
|
||||
input: queries.join("\n") + "\n",
|
||||
});
|
||||
const records = output.stdout.split("\n");
|
||||
if (output.truncated || records.length !== queries.length + 1) {
|
||||
throw new Error("Git returned incomplete diff revision records");
|
||||
}
|
||||
for (const [position, query] of queries.entries()) {
|
||||
const record = records[position];
|
||||
if (/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(record)) {
|
||||
result.set(batch[position], record);
|
||||
} else if (record === `${query} missing` || record === `${query} ambiguous`) {
|
||||
result.set(batch[position], null);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
failed(error, cwd);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function checkDiffRevisions(
|
||||
root: string,
|
||||
watches: ReadonlySet<RevisionWatch>,
|
||||
failed: (error: unknown, cwd: string) => void,
|
||||
): Promise<boolean> {
|
||||
const active = [...watches].flatMap((watch) => {
|
||||
const previous = watch.getRevisions();
|
||||
return previous ? [{ watch, previous }] : [];
|
||||
});
|
||||
const requests = new Map<string, Set<string>>();
|
||||
for (const { watch, previous } of active) {
|
||||
for (const ref of previous.refs.keys()) {
|
||||
const cwd = probeDirectory(root, watch, ref);
|
||||
const refs = requests.get(cwd) ?? new Set<string>();
|
||||
refs.add(ref);
|
||||
requests.set(cwd, refs);
|
||||
}
|
||||
}
|
||||
const reads = new Map(
|
||||
[...requests].map(([cwd, refs]) => [cwd, readRevisions(cwd, root, refs, failed)]),
|
||||
);
|
||||
const checkoutBases = new Map<string, Promise<string | null | undefined>>();
|
||||
async function readCheckoutBase(watch: RevisionWatch, observed: string | null) {
|
||||
const base = watch.checkoutBase;
|
||||
if (!base) return observed;
|
||||
// An explicit qualified selection is already checked by the revision batch.
|
||||
if (observed === base.compare.baseRef && /^refs\/(?:heads|remotes)\//.test(observed)) {
|
||||
return observed;
|
||||
}
|
||||
const key = JSON.stringify([watch.cwd, base]);
|
||||
let selected = checkoutBases.get(key);
|
||||
if (!selected) {
|
||||
selected = resolveCheckoutDiffBase(watch.cwd, base.compare, {
|
||||
paseoHome: base.paseoHome,
|
||||
runGitCommand: (args, options) => git(args, { ...options, timeout: TIMEOUT_MS }),
|
||||
}).catch(() => undefined);
|
||||
checkoutBases.set(key, selected);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
const changed = await Promise.all(
|
||||
active.map(async ({ watch, previous }) => {
|
||||
const base = previous.checkoutBase;
|
||||
const [selected, refs] = await Promise.all([
|
||||
base === undefined ? undefined : readCheckoutBase(watch, base),
|
||||
Promise.all(
|
||||
[...previous.refs].map(async ([ref, sha]) => {
|
||||
const current = (await reads.get(probeDirectory(root, watch, ref)))?.get(ref);
|
||||
return current !== undefined && current !== sha && previous.refs.get(ref) === sha;
|
||||
}),
|
||||
),
|
||||
]);
|
||||
if (
|
||||
((selected !== undefined && selected !== base && previous.checkoutBase === base) ||
|
||||
refs.some(Boolean)) &&
|
||||
watches.has(watch) &&
|
||||
watch.getRevisions() === previous
|
||||
) {
|
||||
watch.changed();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
);
|
||||
return changed.some(Boolean);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtemp, writeFile, rm, mkdir } from "node:fs/promises";
|
||||
import { mkdtemp, writeFile, rm, mkdir, rename } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, test } from "vitest";
|
||||
@@ -8,6 +8,9 @@ import { DiffSubscriptions } from "./index.js";
|
||||
import { createFileObserver } from "../file-observer/index.js";
|
||||
import {
|
||||
configureGitProcessPolicy,
|
||||
getGitCommandMetrics,
|
||||
startGitCommandMetrics,
|
||||
stopGitCommandMetrics,
|
||||
runGitCommand,
|
||||
runWithGitCommandPriority,
|
||||
} from "../../utils/run-git-command.js";
|
||||
@@ -170,6 +173,7 @@ test("shares computation, highlights only the changed file, recovers refs and re
|
||||
computations: before,
|
||||
highlightCalls: previousHighlightCalls,
|
||||
metadataObservers: 1,
|
||||
fallbackTargets: 0,
|
||||
});
|
||||
first.length = 0;
|
||||
second.length = 0;
|
||||
@@ -1259,3 +1263,231 @@ test.each(["pinned", "HEAD"] as const)(
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"overflow fallback opens before probing refs and refreshes only comparisons whose inputs move",
|
||||
async () => {
|
||||
const fixture = await createObservedWorktreeDiff("diff-overflow-");
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { cwd: fixture.cwd, encoding: "utf8" }).trim();
|
||||
const record = (frames: DiffFrame[]) => async (frame: DiffFrame) => {
|
||||
frames.push(frame);
|
||||
};
|
||||
const selectedFrames: DiffFrame[] = [];
|
||||
const pinnedFrames: DiffFrame[] = [];
|
||||
try {
|
||||
const head = git("rev-parse", "HEAD");
|
||||
const selectedRef = "refs/heads/selected";
|
||||
const empty = git("hash-object", "-t", "tree", "-w", "--stdin");
|
||||
const moved = git(
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit-tree",
|
||||
empty,
|
||||
"-p",
|
||||
head,
|
||||
"-m",
|
||||
"next",
|
||||
);
|
||||
execFileSync("git", ["update-ref", "--stdin"], {
|
||||
cwd: fixture.cwd,
|
||||
input: [
|
||||
`create ${selectedRef} ${head}`,
|
||||
...Array.from({ length: 5010 }, (_, i) => `create refs/heads/overflow-${i}/ref ${head}`),
|
||||
"",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
// The valid packed refs alone are larger than a full Git command's output budget.
|
||||
const packedPrefix = `refs/heads/${"p".repeat(180)}`;
|
||||
const packed = Array.from(
|
||||
{ length: 100000 },
|
||||
(_, i) => `${head} ${packedPrefix}/${String(i).padStart(6, "0")}\n`,
|
||||
);
|
||||
await writeFile(
|
||||
join(fixture.cwd, ".git", "packed-refs"),
|
||||
"# pack-refs with: peeled fully-peeled sorted \n" + packed.join(""),
|
||||
);
|
||||
expect(git("rev-parse", "--verify", `${packedPrefix}/099999`)).toBe(head);
|
||||
|
||||
startGitCommandMetrics();
|
||||
const selected = await fixture.subscriptions.subscribe(
|
||||
{ ...fixture.compare, base: { kind: "rev", rev: selectedRef }, highlight: false },
|
||||
record(selectedFrames),
|
||||
);
|
||||
const pinned = await fixture.subscriptions.subscribe(
|
||||
{ ...fixture.compare, base: { kind: "rev", rev: head }, highlight: false },
|
||||
record(pinnedFrames),
|
||||
);
|
||||
await Promise.all([selected.start(), pinned.start()]);
|
||||
expect(selectedFrames.find((frame) => frame.opcode === DiffOpcode.End)).toMatchObject({
|
||||
revision: 1,
|
||||
error: null,
|
||||
});
|
||||
expect(pinnedFrames.find((frame) => frame.opcode === DiffOpcode.End)).toMatchObject({
|
||||
revision: 1,
|
||||
error: null,
|
||||
});
|
||||
expect(
|
||||
getGitCommandMetrics().submissions.filter((command) => command.priority === "background"),
|
||||
).toEqual([]);
|
||||
|
||||
// Move the selected ref before the first poll. The pinned comparison shares the
|
||||
// same working tree and Git metadata, but the ref is unrelated to its inputs.
|
||||
git("update-ref", selectedRef, moved);
|
||||
await expect
|
||||
.poll(() => selectedFrames.findLast((frame) => frame.opcode === DiffOpcode.Begin), {
|
||||
timeout: 10000,
|
||||
})
|
||||
.toMatchObject({ revision: 2, baseSha: moved });
|
||||
await expect
|
||||
.poll(() => selectedFrames.findLast((frame) => frame.opcode === DiffOpcode.End))
|
||||
.toMatchObject({ revision: 2, error: null });
|
||||
expect(
|
||||
getGitCommandMetrics().submissions.filter((command) => command.priority === "background"),
|
||||
).toEqual([
|
||||
{
|
||||
args: ["cat-file", "--batch-check=%(objectname)"],
|
||||
cwd: join(fixture.cwd, ".git"),
|
||||
priority: "background",
|
||||
},
|
||||
]);
|
||||
await selected.release();
|
||||
await pinned.release();
|
||||
expect(pinnedFrames.filter((frame) => frame.opcode === DiffOpcode.Begin)).toHaveLength(1);
|
||||
expect(fixture.subscriptions.getMetrics().computations).toBe(3);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
stopGitCommandMetrics();
|
||||
}
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"a running comparison keeps following its ref after metadata observation overflows",
|
||||
async () => {
|
||||
const fixture = await createObservedWorktreeDiff("diff-runtime-overflow-");
|
||||
const overflow = await mkdtemp(join(tmpdir(), "diff-runtime-refs-"));
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { cwd: fixture.cwd, encoding: "utf8" }).trim();
|
||||
const frames: DiffFrame[] = [];
|
||||
try {
|
||||
git("branch", "selected");
|
||||
const empty = git("hash-object", "-t", "tree", "-w", "--stdin");
|
||||
const moved = git("-c", "commit.gpgsign=false", "commit-tree", empty, "-m", "next");
|
||||
// Move the populated directory into the metadata watch in a single event.
|
||||
for (let index = 0; index < 5010; index += 64) {
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(64, 5010 - index) }, (_, offset) =>
|
||||
mkdir(join(overflow, String(index + offset))),
|
||||
),
|
||||
);
|
||||
}
|
||||
const subscription = await fixture.subscriptions.subscribe(
|
||||
{ ...fixture.compare, base: { kind: "rev", rev: "refs/heads/selected" }, highlight: false },
|
||||
async (frame) => {
|
||||
frames.push(frame);
|
||||
},
|
||||
);
|
||||
await subscription.start();
|
||||
expect(fixture.subscriptions.getMetrics()).toMatchObject({
|
||||
metadataObservers: 1,
|
||||
fallbackTargets: 0,
|
||||
});
|
||||
|
||||
await rename(overflow, join(fixture.cwd, ".git", "refs", "heads", "overflow"));
|
||||
await expect
|
||||
.poll(() => fixture.subscriptions.getMetrics(), { timeout: 10000 })
|
||||
.toMatchObject({ metadataObservers: 0, fallbackTargets: 1 });
|
||||
await expect
|
||||
.poll(() => frames.findLast((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 })
|
||||
.toMatchObject({ revision: 2, error: null });
|
||||
|
||||
git("update-ref", "refs/heads/selected", moved);
|
||||
await expect
|
||||
.poll(() => frames.findLast((frame) => frame.opcode === DiffOpcode.Begin), {
|
||||
timeout: 12000,
|
||||
})
|
||||
.toMatchObject({ revision: 3, baseSha: moved });
|
||||
await subscription.release();
|
||||
expect(fixture.subscriptions.getMetrics()).toMatchObject({
|
||||
metadataObservers: 0,
|
||||
fallbackTargets: 0,
|
||||
});
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await rm(overflow, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
35000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"an unreachable worktree leaves shared revision probes available to other comparisons",
|
||||
async () => {
|
||||
const fixture = await createObservedWorktreeDiff("diff-shared-ref-");
|
||||
const removed = await mkdtemp(join(tmpdir(), "diff-removed-worktree-"));
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { cwd: fixture.cwd, encoding: "utf8" }).trim();
|
||||
const frames: DiffFrame[] = [];
|
||||
const ref = "refs/heads/selected";
|
||||
try {
|
||||
const head = git("rev-parse", "HEAD");
|
||||
const empty = git("hash-object", "-t", "tree", "-w", "--stdin");
|
||||
const moved = git(
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit-tree",
|
||||
empty,
|
||||
"-p",
|
||||
head,
|
||||
"-m",
|
||||
"next",
|
||||
);
|
||||
git("worktree", "add", "--detach", removed, head);
|
||||
execFileSync("git", ["update-ref", "--stdin"], {
|
||||
cwd: fixture.cwd,
|
||||
input: [
|
||||
`create ${ref} ${head}`,
|
||||
...Array.from({ length: 5010 }, (_, i) => `create refs/heads/overflow-${i}/ref ${head}`),
|
||||
"",
|
||||
].join("\n"),
|
||||
});
|
||||
const compare = {
|
||||
base: { kind: "empty" },
|
||||
head: { kind: "rev", rev: ref },
|
||||
highlight: false,
|
||||
} as const;
|
||||
const unavailable = await fixture.subscriptions.subscribe(
|
||||
{ ...compare, cwd: removed },
|
||||
async () => {},
|
||||
);
|
||||
const remaining = await fixture.subscriptions.subscribe(
|
||||
{ ...compare, cwd: fixture.cwd },
|
||||
async (frame) => {
|
||||
frames.push(frame);
|
||||
},
|
||||
);
|
||||
await Promise.all([unavailable.start(), remaining.start()]);
|
||||
expect(frames.find((frame) => frame.opcode === DiffOpcode.Begin)).toMatchObject({
|
||||
revision: 1,
|
||||
headSha: head,
|
||||
});
|
||||
|
||||
git("worktree", "remove", removed);
|
||||
git("update-ref", ref, moved);
|
||||
await expect
|
||||
.poll(() => frames.findLast((frame) => frame.opcode === DiffOpcode.Begin), {
|
||||
timeout: 12000,
|
||||
})
|
||||
.toMatchObject({ revision: 2, headSha: moved });
|
||||
await unavailable.release();
|
||||
await remaining.release();
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await rm(removed, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
35000,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { resolveDaemonVersion } from "../daemon-version.js";
|
||||
|
||||
const PROVIDER_ID = "closing-provider";
|
||||
const PLUGIN_ID = "closing-provider-plugin";
|
||||
|
||||
// How the provider ends the session that ran the first turn.
|
||||
type CloseMode =
|
||||
// The first turn completes, then the provider closes the session on its own.
|
||||
| "after-turn"
|
||||
// The first turn fails and the provider closes the session with the failure.
|
||||
| "after-failed-turn"
|
||||
// The provider answers the second prompt by closing the session.
|
||||
| "on-next-prompt";
|
||||
|
||||
async function createClosingProviderPlugin(root: string, mode: CloseMode): Promise<string> {
|
||||
const directory = path.join(root, "plugin");
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({
|
||||
id: PLUGIN_ID,
|
||||
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`import type {
|
||||
ProviderEvent,
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
|
||||
const CAPABILITIES = ["prompt.message", "session.persistence"];
|
||||
const MODE = ${JSON.stringify(mode)};
|
||||
|
||||
const provider: ProviderRegistration = {
|
||||
id: ${JSON.stringify(PROVIDER_ID)},
|
||||
label: "Closing provider",
|
||||
async connect() {
|
||||
let listener: ((event: ProviderEvent) => void) | null = null;
|
||||
const emit = (event: ProviderEvent) => listener?.(event);
|
||||
let turn = 0;
|
||||
const closed = new Set<string>();
|
||||
return {
|
||||
version: 1,
|
||||
capabilities: CAPABILITIES,
|
||||
async send(input: ProviderInput) {
|
||||
if (input.type === "catalog") {
|
||||
emit({
|
||||
type: "catalog",
|
||||
requestId: input.requestId,
|
||||
catalog: {
|
||||
models: [{ id: "closing-model", label: "Closing model" }],
|
||||
modes: [],
|
||||
thinkingOptions: [],
|
||||
defaultModel: "closing-model",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: CAPABILITIES,
|
||||
restoration: "core",
|
||||
persistence: { version: 1, data: { token: "root" } },
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
turn += 1;
|
||||
if (MODE === "on-next-prompt" && turn === 2) {
|
||||
closed.add(input.sessionId);
|
||||
emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
return;
|
||||
}
|
||||
const turnId = "turn-" + turn;
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
|
||||
if (MODE === "after-failed-turn" && turn === 1) {
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "failed", error: { message: "Provider turn failed" } });
|
||||
emit({ type: "session.closed", sessionId: input.sessionId, error: { message: "Provider turn failed" } });
|
||||
return;
|
||||
}
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "assistant_message", id: "answer-" + turn, text: "Done " + turn },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
|
||||
if (MODE === "after-turn" && turn === 1) {
|
||||
emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.close") {
|
||||
if (!closed.has(input.sessionId)) emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
}
|
||||
if ("requestId" in input) {
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
}
|
||||
},
|
||||
onEvent(next: (event: ProviderEvent) => void) {
|
||||
listener = next;
|
||||
return () => {
|
||||
if (listener === next) listener = null;
|
||||
};
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) {
|
||||
server.registerProvider(provider);
|
||||
return () => undefined;
|
||||
}`,
|
||||
);
|
||||
return directory;
|
||||
}
|
||||
|
||||
test.each<CloseMode>(["after-turn", "after-failed-turn", "on-next-prompt"])(
|
||||
"an agent whose provider session closed (%s) runs its next prompt",
|
||||
async (mode) => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-closed-session-"));
|
||||
onTestFinished(() =>
|
||||
rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
|
||||
);
|
||||
const pluginDirectory = await createClosingProviderPlugin(root, mode);
|
||||
const workspace = path.join(root, "workspace");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: path.join(root, "static"),
|
||||
pluginsEnabled: true,
|
||||
plugins: {
|
||||
[PLUGIN_ID]: { source: "directory", path: pluginDirectory, enabled: true },
|
||||
},
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.9.1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
});
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
|
||||
const agent = await client.createAgent({
|
||||
provider: PROVIDER_ID,
|
||||
model: "closing-model",
|
||||
cwd: workspace,
|
||||
title: "Closing provider agent",
|
||||
});
|
||||
await client.sendMessage(agent.id, "first");
|
||||
await client.waitForFinish(agent.id, 30_000);
|
||||
|
||||
// Before the fix, reopening tried to close the session the provider had already
|
||||
// closed, failed, and rejected this send with "Provider session <id> is stale".
|
||||
await client.sendMessage(agent.id, "second");
|
||||
expect((await client.waitForFinish(agent.id, 30_000)).status).toBe("idle");
|
||||
|
||||
const timeline = await client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 0,
|
||||
projection: "canonical",
|
||||
});
|
||||
const text = JSON.stringify(timeline.entries);
|
||||
// In on-next-prompt the provider closed the session on prompt 2, so the reopened
|
||||
// session answers the retried prompt as its third.
|
||||
expect(text).toContain(mode === "on-next-prompt" ? "Done 3" : "Done 2");
|
||||
expect(text).not.toMatch(/Provider session \S+ (closed|is stale)/);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
@@ -587,6 +587,29 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("a client reconnecting within the release grace reuses the warm target", async () => {
|
||||
const getCheckoutStatus = vi.fn(buildDefaultTestServiceDeps().getCheckoutStatus);
|
||||
const service = createService({ getCheckoutStatus });
|
||||
try {
|
||||
const first = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
|
||||
const snapshot = await service.getSnapshot(REPO_CWD);
|
||||
await waitForObservationToSettle(service, 1);
|
||||
first.unsubscribe();
|
||||
expect(service.getMetrics().workspaceTargetCount).toBe(1);
|
||||
const reads = getCheckoutStatus.mock.calls.length;
|
||||
|
||||
const second = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
|
||||
await expect(service.getSnapshot(REPO_CWD)).resolves.toEqual(snapshot);
|
||||
expect(getCheckoutStatus).toHaveBeenCalledTimes(reads);
|
||||
second.unsubscribe();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(90_000);
|
||||
expect(service.getMetrics().workspaceTargetCount).toBe(0);
|
||||
} finally {
|
||||
await service.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test("onSnapshotUpdated delivers without workspace subscribers and can unsubscribe", async () => {
|
||||
const service = createService();
|
||||
const snapshots: WorkspaceGitRuntimeSnapshot[] = [];
|
||||
@@ -623,6 +646,7 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: createLogger() as unknown as pino.Logger,
|
||||
paseoHome: "/tmp/paseo-test",
|
||||
releaseGraceMs: 0,
|
||||
deps: {
|
||||
...buildDefaultTestServiceDeps(),
|
||||
getPullRequestStatus: async () => {
|
||||
|
||||
@@ -81,6 +81,9 @@ import { checkoutLiteFromGitSnapshot } from "./workspace-registry-model.js";
|
||||
import { createWatcherLivenessCanary } from "./watcher-liveness-canary.js";
|
||||
|
||||
const WORKSPACE_GIT_WATCH_DEBOUNCE_MS = 1_000;
|
||||
// A target outlives its last listener this long, so a reconnecting client reuses its snapshot
|
||||
// and watchers instead of re-reading every checkout.
|
||||
const WORKSPACE_GIT_RELEASE_GRACE_MS = 90_000;
|
||||
export const BACKGROUND_GIT_FETCH_INTERVAL_MS = 180_000;
|
||||
const FETCH_METADATA_ECHO_TTL_MS = 5_000;
|
||||
export const WORKSPACE_GIT_OBSERVATION_REENSURE_INTERVAL_MS = 60_000;
|
||||
@@ -441,6 +444,8 @@ interface WorkspaceGitServiceOptions {
|
||||
worktreesRoot?: string;
|
||||
fileObserver?: FileObserver;
|
||||
deps?: Partial<WorkspaceGitServiceDependencies>;
|
||||
/** How long a workspace target outlives its last listener; 0 releases it immediately. */
|
||||
releaseGraceMs?: number;
|
||||
}
|
||||
|
||||
class WorkspaceGitServiceDisposedError extends Error {
|
||||
@@ -463,6 +468,7 @@ interface WorkspaceGitTarget {
|
||||
gitDirPaths: GitObservationPaths | null;
|
||||
cwd: string;
|
||||
listeners: Set<WorkspaceGitListener>;
|
||||
releaseTimer: NodeJS.Timeout | null;
|
||||
workingTreeWatchTarget: WorkingTreeWatchTarget | null;
|
||||
debounceTimer: NodeJS.Timeout | null;
|
||||
pendingDebounceRequest: WorkspaceGitRefreshRequest | null;
|
||||
@@ -657,6 +663,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly paseoHome: string;
|
||||
private readonly worktreesRoot: string | undefined;
|
||||
private readonly releaseGraceMs: number;
|
||||
private readonly fileObserver: FileObserver;
|
||||
private readonly deps: WorkspaceGitServiceDependencies;
|
||||
private readonly forgeResolver: ForgeResolver;
|
||||
@@ -710,6 +717,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
this.logger = options.logger.child({ module: "workspace-git-service" });
|
||||
this.paseoHome = options.paseoHome;
|
||||
this.worktreesRoot = options.worktreesRoot;
|
||||
this.releaseGraceMs = options.releaseGraceMs ?? WORKSPACE_GIT_RELEASE_GRACE_MS;
|
||||
this.fileObserver = options.fileObserver ?? createFileObserver();
|
||||
this.deps = resolveWorkspaceGitServiceDeps(
|
||||
this.fileObserver.subscribe.bind(this.fileObserver),
|
||||
@@ -733,6 +741,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
this.assertNotDisposed();
|
||||
const cwd = resolve(params.cwd);
|
||||
const target = this.ensureWorkspaceTarget(cwd);
|
||||
this.cancelWorkspaceRelease(target);
|
||||
target.listeners.add(listener);
|
||||
if (target.folderMissing) {
|
||||
void this.resumeWorkspaceIfFolderRestored(target);
|
||||
@@ -1318,6 +1327,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
gitDirPaths: null,
|
||||
cwd,
|
||||
listeners: new Set(),
|
||||
releaseTimer: null,
|
||||
workingTreeWatchTarget: null,
|
||||
debounceTimer: null,
|
||||
pendingDebounceRequest: null,
|
||||
@@ -3065,6 +3075,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
if (!target || target.closed || this.workspaceTargets.get(target.cwd) !== target) {
|
||||
return;
|
||||
}
|
||||
if (options.origin === "observation" && this.releaseChangedWarmTarget(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const request = this.buildScheduledRefreshRequest(options);
|
||||
target.pendingDebounceRequest = this.mergeRefreshRequests(
|
||||
@@ -3351,6 +3364,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
if (target.closed || this.workspaceTargets.get(target.cwd) !== target) {
|
||||
return;
|
||||
}
|
||||
if (request.origin === "observation" && this.releaseChangedWarmTarget(target)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.requestWorkspaceSnapshot(target, request);
|
||||
} catch (error) {
|
||||
@@ -4104,7 +4120,52 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.releaseGraceMs <= 0 || !this.isWorkspaceObservationEstablished(target)) {
|
||||
this.removeWorkspaceTarget(target);
|
||||
return;
|
||||
}
|
||||
// Keep the snapshot and watchers warm for a reconnecting client; stop forge polling now.
|
||||
this.stopForgePrStatusPollForTarget(target);
|
||||
this.cancelWorkspaceRelease(target);
|
||||
target.releaseTimer = setTimeout(() => {
|
||||
target.releaseTimer = null;
|
||||
if (
|
||||
!target.closed &&
|
||||
target.listeners.size === 0 &&
|
||||
this.workspaceTargets.get(target.cwd) === target
|
||||
) {
|
||||
this.removeWorkspaceTarget(target);
|
||||
}
|
||||
}, this.releaseGraceMs);
|
||||
target.releaseTimer.unref?.();
|
||||
}
|
||||
|
||||
/** Only a fully watched target stays warm; one still recovering a watcher is released now. */
|
||||
private isWorkspaceObservationEstablished(target: WorkspaceGitTarget): boolean {
|
||||
const repoTarget = target.repoGitRoot ? this.repoTargets.get(target.repoGitRoot) : undefined;
|
||||
return Boolean(
|
||||
target.latestSnapshot &&
|
||||
!target.folderMissing &&
|
||||
target.workingTreeWatchTarget?.subscription &&
|
||||
repoTarget?.subscription,
|
||||
);
|
||||
}
|
||||
|
||||
/** A change seen while nobody listens ends the grace: the next consumer re-reads, nobody pays now. */
|
||||
private releaseChangedWarmTarget(target: WorkspaceGitTarget): boolean {
|
||||
if (target.listeners.size > 0 || !target.releaseTimer) {
|
||||
return false;
|
||||
}
|
||||
this.cancelWorkspaceRelease(target);
|
||||
this.removeWorkspaceTarget(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
private cancelWorkspaceRelease(target: WorkspaceGitTarget): void {
|
||||
if (target.releaseTimer) {
|
||||
clearTimeout(target.releaseTimer);
|
||||
target.releaseTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private removeWorkspaceTarget(target: WorkspaceGitTarget): void {
|
||||
@@ -4171,6 +4232,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
|
||||
private closeWorkspaceTarget(target: WorkspaceGitTarget): void {
|
||||
target.closed = true;
|
||||
this.cancelWorkspaceRelease(target);
|
||||
this.stopWorkspaceObservation(target);
|
||||
target.listeners.clear();
|
||||
}
|
||||
|
||||
@@ -1687,10 +1687,10 @@ export async function resolveRepositoryDefaultBranch(
|
||||
// A stale origin/HEAD must fall through to the available local branches.
|
||||
}
|
||||
|
||||
const { stdout } = await getRunGitCommand(context)(["branch", "--format=%(refname:short)"], {
|
||||
cwd: repoRoot,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
const { stdout } = await getRunGitCommand(context)(
|
||||
["branch", "--list", "--format=%(refname:short)", "main", "master"],
|
||||
{ cwd: repoRoot, envOverlay: READ_ONLY_GIT_ENV },
|
||||
);
|
||||
const branches = new Set(
|
||||
stdout
|
||||
.split("\n")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -86,6 +86,12 @@ const patchedPackages = [
|
||||
nodeModulesPath: "node_modules/@mattermost/react-native-paste-input",
|
||||
patchPrefix: "@mattermost+react-native-paste-input+",
|
||||
},
|
||||
// Backport of https://github.com/mermaid-js/mermaid/pull/8459 (lexer half): a flowchart label
|
||||
// with an "@" parses. The patch header has the details. Remove when the app uses mermaid 12.
|
||||
{
|
||||
nodeModulesPath: "node_modules/mermaid",
|
||||
patchPrefix: "mermaid+",
|
||||
},
|
||||
{
|
||||
nodeModulesPath: "packages/server/node_modules/@opencode-ai/sdk",
|
||||
patchPrefix: "@opencode-ai+sdk+",
|
||||
|
||||
Reference in New Issue
Block a user