Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 47e13e0de0 fix(server): preserve the scheduled watcher retry deadline
The ordinary recovery delay can exceed the setup-timeout delay when a watcher reports an error before timing out. Retain the scheduled deadline so reopening waits the full interval.
2026-11-23 12:58:41 +00:00
paseo-bot[bot] ddd4248d0a fix(server): keep watcher retries on schedule after reconnect
A watcher that timed out lost its pending delay when its last observer disconnected. Keep the retry with the watched path so registering the same workspace again uses polling until the scheduled scan.
2026-11-23 12:51:16 +00:00
167 changed files with 1401 additions and 9552 deletions
+2
View File
@@ -422,6 +422,7 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -553,6 +554,7 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
-20
View File
@@ -1,25 +1,5 @@
# Changelog
## 0.17.4 - 2026-11-23
### Fixed
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android ([#10499](https://github.com/getpaseo/paseo/pull/10499))
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning ([#10586](https://github.com/getpaseo/paseo/pull/10586))
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system ([#10555](https://github.com/getpaseo/paseo/pull/10555) by [@yzim](https://github.com/yzim))
- Fixed interrupt and steer messages to archived agents being queued without starting a turn ([#10611](https://github.com/getpaseo/paseo/pull/10611) by [@thomasvan](https://github.com/thomasvan))
- Fixed Hermes Shell rows omitting part of the command ([#10614](https://github.com/getpaseo/paseo/pull/10614))
- Fixed OpenCode Go usage for logins stored in the OpenCode 2 database, including Console sign-ins and API keys ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
- Fixed existing OpenCode sessions failing to reopen after Paseo tool definitions change ([#10533](https://github.com/getpaseo/paseo/pull/10533) by [@Peanut-HZM](https://github.com/Peanut-HZM))
- Fixed Paseo tools missing from agents that use MCP protocol version `2026-07-28` ([#10558](https://github.com/getpaseo/paseo/pull/10558) by [@apple-ouyang](https://github.com/apple-ouyang))
- Fixed Codex MCP startup failures missing from daemon warning logs ([#10566](https://github.com/getpaseo/paseo/pull/10566))
- Fixed the daemon exiting when it closes a session after the plugin process has stopped ([#10585](https://github.com/getpaseo/paseo/pull/10585))
- Fixed Git commands selecting the wrong repository when a directory has the layout of a bare repository ([#10587](https://github.com/getpaseo/paseo/pull/10587))
- Fixed Claude Auto permission mode being unavailable on Bedrock and Vertex ([#6904](https://github.com/getpaseo/paseo/pull/6904))
- Fixed the sidebar host settings button requiring two clicks to open settings ([#10562](https://github.com/getpaseo/paseo/pull/10562) by [@ShalokShalom](https://github.com/ShalokShalom))
- Fixed the Changes pane not offering Push for a new branch that was never pushed in a regular checkout ([#10631](https://github.com/getpaseo/paseo/pull/10631))
- Fixed the daemon using the wrong model catalog when Hub sends a workspace directory for trigger validation ([#10582](https://github.com/getpaseo/paseo/pull/10582))
## 0.17.3 - 2026-11-22
### Fixed
-20
View File
@@ -1,25 +1,5 @@
# Changelog
## 0.17.4 - 2026-11-23
### 修复
- 修复 Android 上嵌套编号列表的编号与正文重叠,以及列表中的引用与后续消息重叠的问题 ([#10499](https://github.com/getpaseo/paseo/pull/10499))
- 修复 Android 终端输入,要求键盘不将输入内容用于个性化学习 ([#10586](https://github.com/getpaseo/paseo/pull/10586))
- 修复在不区分大小写的文件系统上,目录路径大小写不一致导致对话消失的问题 ([#10555](https://github.com/getpaseo/paseo/pull/10555),贡献者:[@yzim](https://github.com/yzim))
- 修复发给已归档 Agent 的中断和引导消息进入队列后未启动新轮次的问题 ([#10611](https://github.com/getpaseo/paseo/pull/10611),贡献者:[@thomasvan](https://github.com/thomasvan))
- 修复 Hermes 的 Shell 工具行只显示命令摘要的问题,现在会显示完整命令 ([#10614](https://github.com/getpaseo/paseo/pull/10614))
- 修复使用 OpenCode 2 数据库中保存的登录凭据时的 Go 用量显示,涵盖 Console 登录和 API 密钥 ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
- 修复 Paseo 工具定义变更后无法重新打开已有 OpenCode 会话的问题 ([#10533](https://github.com/getpaseo/paseo/pull/10533),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM))
- 修复使用 MCP 协议版本 `2026-07-28` 的 Agent 缺少 Paseo 工具的问题 ([#10558](https://github.com/getpaseo/paseo/pull/10558),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
- 修复 Codex MCP 启动失败时 daemon 未记录警告的问题 ([#10566](https://github.com/getpaseo/paseo/pull/10566))
- 修复插件进程停止后 daemon 在关闭会话时退出的问题 ([#10585](https://github.com/getpaseo/paseo/pull/10585))
- 修复目录结构与裸仓库相同时 Git 命令选错仓库的问题 ([#10587](https://github.com/getpaseo/paseo/pull/10587))
- 修复在 Bedrock 和 Vertex 上无法选择 Claude Auto 权限模式的问题 ([#6904](https://github.com/getpaseo/paseo/pull/6904))
- 修复侧边栏的主机设置按钮需要点击两次才能打开设置的问题 ([#10562](https://github.com/getpaseo/paseo/pull/10562),贡献者:[@ShalokShalom](https://github.com/ShalokShalom))
- 修复普通检出中从未推送过的新分支在“变更”面板中不显示“推送”的问题 ([#10631](https://github.com/getpaseo/paseo/pull/10631))
- 修复 Hub 在验证触发器时传入工作区目录后,daemon 使用错误模型目录的问题 ([#10582](https://github.com/getpaseo/paseo/pull/10582))
## 0.17.3 - 2026-11-22
### 修复
+33 -1
View File
@@ -514,7 +514,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st
ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout.
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Goose, Hermes, and Hoplite activate their [bundled providers](plugins.md#built-in-plugins) instead. An existing `extends: "acp"` entry for goose or Hermes migrates to the bundled provider on load and keeps a custom command. Hermes agents saved with the old adapter resume with their mode translated (`plugins/hermes-provider/server/legacy-modes.ts`).
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
### Adding a generic ACP provider
@@ -627,6 +627,32 @@ ACP probes use short timeouts and browser-suppression environment variables so a
Ref: [Gemini CLI ACP mode docs](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/acp-mode.md)
### Example: Hermes (Nous Research)
[Hermes](https://github.com/NousResearch/hermes-agent) is an open-source coding agent by Nous Research with persistent memory and multi-provider LLM support. It supports ACP via the `acp` subcommand.
1. Install: `curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash`
2. Install ACP support: `pip install -e '.[acp]'`
3. Configure Hermes credentials in `~/.hermes/`
4. Add to config.json:
```json
{
"agents": {
"providers": {
"hermes": {
"extends": "acp",
"label": "Hermes",
"description": "Nous Research self-improving AI agent",
"command": ["hermes", "acp"]
}
}
}
}
```
Ref: [Hermes ACP docs](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp)
### How ACP providers work in Paseo
When you launch an agent with an ACP provider:
@@ -827,6 +853,12 @@ A config.json with multiple custom providers:
"extends": "acp",
"label": "Google Gemini",
"command": ["gemini", "--acp"]
},
"hermes": {
"extends": "acp",
"label": "Hermes",
"command": ["hermes", "acp"]
}
}
}
+3 -7
View File
@@ -118,7 +118,7 @@ appear in the plugin catalog. Editing one in development requires a daemon resta
Directory, Git, and npm installs cannot use a built-in ID.
A provider registration with `requiresConfiguration: true` participates only while its ID exists
under `agents.providers`. Hoplite, fx, goose, and Hermes use this for catalog opt-in. Add writes `{ "enabled": true }`
under `agents.providers`. Hoplite and fx use this for catalog opt-in. Add writes `{ "enabled": true }`
without `extends`, so it selects the bundled adapter. Remove deletes the config entry; setting
`enabled: false` keeps the entry. The bundled JavaScript still loads at startup, but an absent
provider does not enter executable resolution or catalog discovery.
@@ -583,12 +583,8 @@ daemon launch from `connect` and the per-session env and MCP servers from `sessi
no provider reload input.
For an ACP command, register `runAcpProvider({ id, label, command })` from
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
whole provider event stream. A `toolCall` transformer sees the raw `input`, `output` and `content`, and a
`detail` it sets replaces the standard row. Parse vendor display text defensively and return the call
unchanged when the shape does not match, so an upstream format change falls back to the standard row
(`plugins/hermes-provider/server/terminal-command.ts`). The shim uses the resolved launch for every probe and session, overlaying
`@getpaseo/plugin/server/acp`. Its transformer hooks cover narrow vendor differences; do not translate the
whole provider event stream. The shim uses the resolved launch for every probe and session, overlaying
only the supplied per-session env for sessions. The direct and ACP examples live in
`plugin-examples/provider-direct`
and `plugin-examples/provider-acp-transformer`.
@@ -1,7 +0,0 @@
Fixed
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
Full notes: https://paseo.sh/changelog
@@ -1,7 +0,0 @@
Fixed
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
Full notes: https://paseo.sh/changelog
@@ -1,7 +0,0 @@
Fixed
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
Full notes: https://paseo.sh/changelog
@@ -1,7 +0,0 @@
Fixed
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
sha256-W725BRG14xajMsR4t8Y3NmxppMnJ8AUd7Kdb6F7LmMw=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.4",
"version": "0.17.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.4",
"version": "0.17.3",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37541,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.4",
"version": "0.17.3",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39694,13 +39694,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/server": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/server": "0.17.3",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39947,11 +39947,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39963,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40206,7 +40206,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.4",
"version": "0.17.3",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40252,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40282,7 +40282,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40290,8 +40290,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40301,8 +40301,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40324,7 +40324,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40351,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.17.4",
"version": "0.17.1",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40367,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40589,17 +40589,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.4",
"version": "0.17.3",
"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.17.4",
"@getpaseo/highlight": "0.17.4",
"@getpaseo/plugin": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/highlight": "0.17.3",
"@getpaseo/plugin": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -41549,7 +41549,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.4",
"version": "0.17.3",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43160,7 +43160,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.4",
"version": "0.17.3",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.4",
"version": "0.17.3",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -1,5 +1,4 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
@@ -472,83 +471,6 @@ test("All changes combines committed and pending edits and preserves an unfinish
});
});
test("Changes offers Push for a branch that was never pushed and the push sets its upstream", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("committing the edit makes Push the primary action", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Feature work");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
});
await test.step("Push sends the branch and sets its upstream", async () => {
await primary.click();
await expect
.poll(() => remoteBranchHead(workspace, "feature"), { timeout: 30_000 })
.toBe(localHead(workspace));
// git writes the upstream after the remote has the branch, so wait for it too.
await expect
.poll(() => branchUpstream(workspace, "feature"), { timeout: 30_000 })
.toBe("origin/feature");
await expect(primary).not.toHaveAccessibleName("Push", { timeout: 30_000 });
});
});
test("Changes pushes and pulls a branch whose only remote is not named origin", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Local work");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
await expectNoGitActionLeft(page);
});
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(localBranchSubjects(workspace)).toEqual(
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
);
await expectNoGitActionLeft(page);
});
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
commitAllWithGit(workspace.repoPath, "More local work");
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await page.getByTestId("changes-primary-cta-caret").click();
await page.getByTestId("changes-menu-pull-and-push").click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toEqual(
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
);
await expectNoGitActionLeft(page);
});
});
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
page,
}, testInfo) => {
@@ -2200,141 +2122,6 @@ async function createWorkspaceWithMountedTabDiff(
return { id: createdWorkspace.workspace.id, repoPath: repo.path };
}
interface RemoteWorkspace extends DirtyWorkspace {
remotePath: string;
}
// A regular checkout with a local bare remote and one uncommitted edit.
async function createWorkspaceWithRemote(
prepare: (repoPath: string) => void,
): Promise<RemoteWorkspace> {
const repo = await createTempGitRepo("changes-push-", {
withRemote: true,
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
});
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close();
await repo.cleanup();
},
});
// The helper keeps the bare remote inside the checkout; keep it out of the status.
await writeFile(path.join(repo.path, ".git/info/exclude"), "remote.git/\n");
prepare(repo.path);
await writeFile(path.join(repo.path, "tracked.ts"), "export const tracked = 2;\n");
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!created.workspace) {
throw new Error(created.error ?? `Failed to create workspace ${repo.path}`);
}
return {
id: created.workspace.id,
repoPath: repo.path,
remotePath: path.join(repo.path, "remote.git"),
};
}
// The app's Commit asks an agent provider for a message, and this harness has none.
function commitAllWithGit(repoPath: string, message: string): void {
execFileSync("git", ["commit", "-am", message], { cwd: repoPath, stdio: "ignore" });
}
function localHead(workspace: RemoteWorkspace): string {
return execFileSync("git", ["rev-parse", "HEAD"], {
cwd: workspace.repoPath,
encoding: "utf8",
}).trim();
}
function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string | null {
const line = execFileSync("git", ["ls-remote", "--heads", workspace.remotePath, branch], {
encoding: "utf8",
}).trim();
return line ? (line.split("\t")[0] ?? null) : null;
}
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
function trackingStatus(workspace: RemoteWorkspace): string {
const status = execFileSync("git", ["status", "-sb"], {
cwd: workspace.repoPath,
encoding: "utf8",
});
return status.split("\n")[0] ?? "";
}
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
await expect
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
return commitSubjects(workspace.repoPath, "HEAD");
}
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
return commitSubjects(workspace.remotePath, branch);
}
function commitSubjects(repoPath: string, revision: string): string[] {
const log = execFileSync("git", ["log", "--format=%s", revision], {
cwd: repoPath,
encoding: "utf8",
});
return log.trim().split("\n");
}
// Paseo fetches only origin in the background, so the checkout learns about another remote's
// commits when the user fetches it.
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
}
// Lands commits on the remote's main from a second clone, as a teammate's push does.
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
try {
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
for (const subject of subjects) {
execFileSync(
"git",
[
"-c",
"user.name=Teammate",
"-c",
"user.email=teammate@paseo.test",
"-c",
"commit.gpgsign=false",
"commit",
"--quiet",
"--allow-empty",
"-m",
subject,
],
{ cwd: clonePath },
);
}
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
} finally {
rmSync(clonePath, { recursive: true, force: true });
}
}
// Empty until the branch has an upstream.
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
return execFileSync(
"git",
["for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`],
{ cwd: workspace.repoPath, encoding: "utf8" },
).trim();
}
async function createWorkspaceWithNetDiff(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-net-", {
files: [{ path: "a-tracked.ts", content: "base\n" }],
@@ -4,7 +4,6 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -116,21 +115,12 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await test.step("preview a color and apply it to the sidebar badge", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -155,30 +145,3 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -65,7 +65,8 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostRowButton,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -191,16 +192,17 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await sidebarHostRowButton(page).click();
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -564,7 +566,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await sidebarHostRowButton(page).click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
+1 -10
View File
@@ -132,10 +132,7 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -198,12 +195,6 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
+14 -4
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,10 +32,20 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.4",
"version": "0.17.3",
"private": true,
"main": "index.ts",
"scripts": {
+133 -301
View File
@@ -1,28 +1,11 @@
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Check, Plus, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Plus, Server, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import {
getHostRuntimeStore,
useHostRuntimeConnectionStatus,
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -39,16 +22,7 @@ export {
};
const SEARCHABLE_THRESHOLD = 10;
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
const LEADING_RAIL_SIZE = 16;
const HOST_ROW_ICON_SIZE = 14;
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
const ThemedCheck = withUnistyles(Check);
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostPickerHost {
serverId: string;
label: string;
@@ -62,166 +36,122 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
);
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
// Socket/pipe transports have no host:port — their endpoint is a filesystem
// path, so they read as "Local". TCP and relay show the address being used.
function formatActiveConnectionLabel(connection: ActiveConnection): string {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return "Local";
}
return formatConnectionEndpoint(connection.endpoint);
}
export interface HostPickerOptionProps {
serverId: string;
label: string;
appearance: HostAppearance;
showActiveConnection: boolean;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
appearance,
showActiveConnection,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
const status = useHostRuntimeConnectionStatus(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const isOffline = status === "offline" || status === "error";
const { theme } = useUnistyles();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const connectionLabel =
showActiveConnection && activeConnection
? formatActiveConnectionLabel(activeConnection)
: undefined;
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
const handleSettingsPress = useCallback(() => {
onOpenHostSettings?.(serverId);
}, [onOpenHostSettings, serverId]);
const trailingAction = useMemo(() => {
if (!onOpenHostSettings) return undefined;
return (
<Pressable
onPress={handleSettingsPress}
style={styles.settingsAction}
accessibilityRole="button"
accessibilityLabel={`Open ${label} settings`}
>
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}, [
handleSettingsPress,
label,
onOpenHostSettings,
theme.colors.foregroundMuted,
theme.iconSize.sm,
]);
return (
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<HostStatusDot serverId={serverId} />
</View>
<View style={styles.hostBody}>
<View style={styles.hostHeaderRow}>
<HostIconGlyph
icon={resolvedIcon}
color={appearance.color}
size={HOST_ROW_ICON_SIZE}
style={styles.hostGlyph}
/>
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
{label}
</Text>
</View>
<HostConnectionLine serverId={serverId} />
</View>
<View style={styles.hostTrailing}>
<HostLatencyLabel serverId={serverId} />
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</View>
</PressHighlight>
</View>
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
function AllHostsOption({
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = t("sidebar.display.hostFilter.all");
return (
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</PressHighlight>
</View>
const { theme } = useUnistyles();
const Icon = kind === "add" ? Plus : Server;
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
const leadingSlot = useMemo(
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
);
}
function ActionOptionRow({
kind,
active,
showDivider,
onPress,
testID,
}: {
kind: "add" | "enableBuiltInDaemon";
active: boolean;
showDivider: boolean;
onPress: () => void;
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
return (
<View>
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
{kind === "add" ? (
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
) : (
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
)}
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
</PressHighlight>
</View>
</View>
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
@@ -238,6 +168,7 @@ export interface HostPickerProps {
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -259,85 +190,74 @@ export function HostPicker({
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
desktopMinWidth,
addHostTestID,
hostOptionTestID,
children,
}: HostPickerProps): ReactElement {
const { t } = useTranslation();
const localServerId = useLocalDaemonServerId();
const allHostProfiles = useHosts();
const orderedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
const appearanceByServerId = useMemo(() => {
const map = new Map<string, HostAppearance>();
for (const profile of allHostProfiles) {
map.set(profile.serverId, profile.appearance);
}
return map;
}, [allHostProfiles]);
useEffect(() => {
if (!open) return;
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
}, [open, orderedHosts]);
const options = useMemo(() => {
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
if (includeAllHost) {
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
if (includeEnableBuiltInDaemon)
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: t("settings.enableBuiltInDaemon"),
label: "Enable built-in daemon",
});
}
return hostOptions;
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
let firstActionOptionId: string | null = null;
if (includeAddHost) {
firstActionOptionId = ADD_HOST_OPTION_ID;
} else if (includeEnableBuiltInDaemon) {
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
}
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
const resolvedTitle = title ?? t("sidebar.actions.hosts");
const handleSelect = useCallback(
(id: string) => {
if (id === ADD_HOST_OPTION_ID) {
onOpenChange(false);
onAddHost?.();
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
return;
} else {
onSelect(id);
}
onSelect(id);
onOpenChange(false);
},
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
);
const handleOpenHostSettings = useCallback(
(serverId: string) => {
onOpenHostSettings?.(serverId);
onOpenChange(false);
},
[onOpenHostSettings, onOpenChange],
);
const renderOption = useCallback<RenderHostOption>(
({ option, selected, active, onPress }) => {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption
kind="add"
active={active}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ALL_HOSTS_OPTION_ID) {
return (
<AllHostsOption
<SystemHostPickerOption
kind="all"
active={active}
selected={selected}
onPress={onPress}
@@ -345,48 +265,30 @@ export function HostPicker({
/>
);
}
if (option.id === ADD_HOST_OPTION_ID) {
return (
<ActionOptionRow
kind="add"
active={active}
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
return (
<ActionOptionRow
kind="enableBuiltInDaemon"
active={active}
showDivider={
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
}
onPress={onPress}
/>
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
appearance={appearance}
showActiveConnection={showActiveConnection === true}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
orderedHosts.length,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
],
);
@@ -399,8 +301,8 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
@@ -412,86 +314,16 @@ export function HostPicker({
}
const styles = StyleSheet.create((theme) => ({
settingsAction: {
flex: 1,
justifyContent: "center",
paddingLeft: theme.spacing[1],
paddingRight: theme.spacing[3],
},
statusDotSlot: {
width: theme.iconSize.sm,
height: theme.iconSize.sm,
alignItems: "center",
justifyContent: "center",
},
rowEnvelope: {
position: "relative",
},
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
// centered 16px column aligned to the first line's 18px line-height.
leadingRailSlot: {
width: LEADING_RAIL_SIZE,
height: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
},
hostBody: {
flex: 1,
minWidth: 0,
gap: 2,
},
hostHeaderRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
hostGlyph: {
flexShrink: 0,
},
hostName: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
hostNameMuted: {
color: theme.colors.foregroundMuted,
},
hostTrailing: {
flexDirection: "row",
alignItems: "center",
height: 18,
gap: theme.spacing[2],
flexShrink: 0,
},
actionSectionDivider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
marginVertical: theme.spacing[1],
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
actionLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
}));
@@ -1,32 +0,0 @@
import Svg, { Circle } from "react-native-svg";
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
[3, 12, 21].map((cx, column) => ({
cx,
cy,
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
solid: row === 1 || (row === 2 && column === 1),
})),
);
export interface TailscaleIconProps {
size?: number;
color?: string;
}
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
{TAILSCALE_DOTS.map((dot) => (
<Circle
key={`${dot.cx}:${dot.cy}`}
cx={dot.cx}
cy={dot.cy}
r={3}
fill={color}
opacity={dot.solid ? 1 : 0.3}
/>
))}
</Svg>
);
}
+2 -2
View File
@@ -388,10 +388,10 @@ function SidebarHostPicker({
includeAddHost
onAddHost={onAddHost}
showActiveConnection
onOpenHostSettings={onOpenHostSettings}
searchable
title={label}
desktopPlacement="top-start"
desktopMinWidth={328}
desktopMinWidth={240}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
+14 -60
View File
@@ -73,9 +73,6 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
const IS_WEB = isWeb;
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
const FOOTER_DATASET = { comboboxFooter: true };
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
@@ -405,7 +402,6 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -413,27 +409,20 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
if (renderOption) {
return (
<View dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
}
return (
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
);
}
@@ -462,7 +451,6 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -964,9 +952,8 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// Consume the shortcut but keep the browser's default button activation when the user moved
// keyboard focus onto a trailing action or footer button inside the combobox.
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1140,12 +1127,7 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
[footer, footerStyle],
);
return (
@@ -1359,11 +1341,7 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1619,30 +1597,6 @@ export function Combobox({
setActiveIndex,
);
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
useEffect(() => {
if (!IS_WEB || !isOpen || isMobile) return;
const handleFocusIn = (event: FocusEvent) => {
const target = event.target;
if (!(target instanceof Element)) return;
const optionEl = target.closest("[data-combobox-option-index]");
if (!optionEl) return;
const nextIndex = Number.parseInt(
optionEl.getAttribute("data-combobox-option-index") ?? "",
10,
);
if (
Number.isInteger(nextIndex) &&
nextIndex >= 0 &&
nextIndex < orderedVisibleOptions.length
) {
setActiveIndex(nextIndex);
}
};
document.addEventListener("focusin", handleFocusIn);
return () => document.removeEventListener("focusin", handleFocusIn);
}, [isMobile, isOpen, orderedVisibleOptions.length]);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
@@ -244,7 +244,6 @@ const CATALOG_DATA = [
},
{
id: "hermes",
bundledProvider: { hostFeature: "hermesProvider" },
title: "Hermes",
description: "Nous Research self-improving AI agent",
version: "manual",
+2 -347
View File
@@ -7,8 +7,6 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability";
@@ -61,11 +59,9 @@ function githubStatus(overrides: Partial<GithubMergeFactsFixture> = {}): GithubM
function createInput(
overrides: Partial<Omit<BuildGitActionsInput, "mergeCapability">> & {
pullRequestGithub?: unknown;
// Shorthand for a branch that both Pull and Push have a remote for.
hasRemote?: boolean;
} = {},
): BuildGitActionsInput {
const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides;
const { pullRequestGithub = null, ...rest } = overrides;
return {
isGit: true,
githubFeaturesEnabled: true,
@@ -79,9 +75,7 @@ function createInput(
pullRequestIsMerged: false,
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasPullRemote: hasRemote,
hasPushRemote: hasRemote,
upstream: "tracked",
hasRemote: false,
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
canMergeLocally: true,
@@ -175,14 +169,6 @@ function createInput(
};
}
function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "push");
}
function pullAndPushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "pull-and-push");
}
describe("git-actions-policy", () => {
afterEach(async () => {
await i18n.changeLanguage("en");
@@ -360,7 +346,6 @@ describe("git-actions-policy", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: "none",
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
aheadCount: 1,
@@ -376,336 +361,6 @@ describe("git-actions-policy", () => {
});
});
it("re-publishes a Paseo worktree branch whose remote copy was deleted", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: "gone",
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
aheadCount: 2,
aheadOfOrigin: null,
behindOfOrigin: null,
shipDefault: "pr",
}),
);
const pushAction = actions.secondary.find((action) => action.id === "push");
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushAction).toMatchObject({ disabled: false, unavailableMessage: undefined });
});
describe("a never-pushed branch in a regular checkout", () => {
const neverPushed = {
hasRemote: true,
upstream: "none",
isOnBaseBranch: false,
aheadCount: 1,
aheadOfOrigin: null,
behindOfOrigin: null,
} as const;
it("offers Push first, ahead of Create PR", () => {
const actions = buildGitActions(createInput({ ...neverPushed, shipDefault: "pr" }));
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
});
it("offers Push first, ahead of Merge locally", () => {
const actions = buildGitActions(
createInput({ ...neverPushed, githubFeaturesEnabled: false, shipDefault: "merge" }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
});
it("does not offer Push when it has no commits of its own", () => {
const actions = buildGitActions(createInput({ ...neverPushed, aheadCount: 0 }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
expect(pushAction?.unavailableMessage).toBe(
"Push isn't available because there is nothing new to send",
);
});
it("does not offer Push when the repository has no origin", () => {
const actions = buildGitActions(createInput({ ...neverPushed, hasRemote: false }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
expect(pushAction?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
it("does not offer Push when Git pushes the branch to another remote", () => {
const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
expect(pushAction?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
});
// The daemon reports where Pull and Push go for the branch, so the remote's name never matters.
describe("a branch that tracks a remote other than origin", () => {
const tracksDorasMono = readSyncRemotes({
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("offers Push when the branch is ahead", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
});
it("offers Pull when the branch is behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
});
it("offers Pull first and Pull and push when the branch is ahead and behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available yet because there are newer changes to bring in first",
);
});
// `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote.
const pullOnly = readSyncRemotes({
hasRemote: false,
pullRemote: "upstream",
pushRemote: null,
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("does not offer Push when it would land on a differently named upstream branch", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary?.id).not.toBe("push");
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
it("still offers Pull for that branch, and not Pull and push", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe(
"Pull and push isn't available here because this branch is not connected to a remote yet",
);
});
});
describe("readSyncRemotes", () => {
it("uses the remotes the daemon reports", () => {
expect(
readSyncRemotes({
hasRemote: true,
pullRemote: null,
pushRemote: "origin",
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toEqual({ hasPullRemote: false, hasPushRemote: true });
});
// The rest covers a daemon that predates pullRemote and pushRemote.
const tracked = {
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
} as const;
const neverPushed = {
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
} as const;
it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => {
expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({
hasPullRemote: true,
hasPushRemote: true,
});
expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({
hasPullRemote: false,
hasPushRemote: false,
});
});
it("makes a regular checkout's first push only where an older daemon confirmed it", () => {
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }),
).toMatchObject({ hasPushRemote: true });
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }),
).toMatchObject({ hasPushRemote: false });
});
it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => {
expect(
readSyncRemotes({
...neverPushed,
hasRemote: true,
firstPushRemote: null,
isPaseoOwnedWorktree: true,
}),
).toMatchObject({ hasPushRemote: true });
});
});
it("does not offer a first push when the branch's remote copy was deleted", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: "gone",
isOnBaseBranch: false,
aheadCount: 2,
aheadOfOrigin: null,
behindOfOrigin: null,
shipDefault: "pr",
}),
);
const pushAction = actions.secondary.find((action) => action.id === "push");
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
expect(pushAction?.unavailableMessage).toBe(
"Push isn't available because the branch this one tracks no longer exists",
);
});
describe("a published branch whose upstream the daemon cannot read", () => {
const unreadableUpstream = {
hasRemote: true,
upstream: "unknown",
isOnBaseBranch: false,
aheadCount: 2,
aheadOfOrigin: null,
behindOfOrigin: null,
shipDefault: "pr",
} as const;
it("does not offer a first push in a regular checkout", () => {
const actions = buildGitActions(createInput(unreadableUpstream));
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
expect(pushActionOf(actions)?.unavailableMessage).toEqual(expect.any(String));
});
it("keeps offering Push in a Paseo worktree", () => {
const actions = buildGitActions(
createInput({ ...unreadableUpstream, isPaseoOwnedWorktree: true }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
});
});
describe("readUpstreamState", () => {
it("uses the upstream state the daemon reports", () => {
expect(
readUpstreamState({
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toBe("none");
expect(
readUpstreamState({
upstreamState: "gone",
aheadOfOrigin: null,
isPaseoOwnedWorktree: true,
}),
).toBe("gone");
});
it("keeps the old guess for daemons that predate upstream states", () => {
expect(
readUpstreamState({
upstreamState: undefined,
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
}),
).toBe("tracked");
expect(
readUpstreamState({
upstreamState: undefined,
aheadOfOrigin: null,
isPaseoOwnedWorktree: true,
}),
).toBe("none");
expect(
readUpstreamState({
upstreamState: undefined,
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toBe("unknown");
});
it("keeps an old daemon's never-pushed regular branch off Push", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: readUpstreamState({
upstreamState: undefined,
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
isOnBaseBranch: false,
aheadCount: 1,
aheadOfOrigin: null,
behindOfOrigin: null,
githubFeaturesEnabled: false,
shipDefault: "merge",
}),
);
const pushAction = pushActionOf(actions);
expect(actions.primary).toMatchObject({ id: "merge-branch" });
expect(pushAction?.unavailableMessage).toBe(
"Push isn't available because there is nothing new to send",
);
});
});
it("prioritizes push over pull request merge when local commits are unpushed", () => {
const actions = buildGitActions(
createInput({
+16 -84
View File
@@ -2,11 +2,7 @@ import type { ReactElement } from "react";
import type { ActionStatus } from "@/components/ui/dropdown-menu";
import { i18n } from "@/i18n/i18next";
import type {
CheckoutPrMergeMethod,
CheckoutStatusResponse,
PullRequestMergeable,
} from "@getpaseo/protocol/messages";
import type { CheckoutPrMergeMethod, PullRequestMergeable } from "@getpaseo/protocol/messages";
import type { MergeCapability } from "./merge-capability";
@@ -77,60 +73,7 @@ export function canMergeIntoLocalBase(
return currentBranch !== localTarget;
}
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
export function readUpstreamState(
status: Pick<CheckoutStatusPayload, "upstreamState" | "aheadOfOrigin" | "isPaseoOwnedWorktree">,
): GitUpstreamState {
if (status.upstreamState !== undefined) {
return status.upstreamState;
}
// COMPAT(checkoutUpstreamState): added in v0.17.4, remove after 2027-05-23 once the daemon
// floor reports upstreamState. Older daemons send a null upstream for both a never-pushed and
// a deleted remote branch. Only a Paseo worktree's null was trusted as never pushed.
if (status.aheadOfOrigin !== null) {
return "tracked";
}
return status.isPaseoOwnedWorktree ? "none" : "unknown";
}
export interface SyncRemotes {
/** Pull has a remote to fetch the branch from. Not limited to origin. */
hasPullRemote: boolean;
/** Push has a remote to send the branch to. Not limited to origin. */
hasPushRemote: boolean;
}
export function readSyncRemotes(
status: Pick<
CheckoutStatusPayload,
| "pullRemote"
| "pushRemote"
| "hasRemote"
| "firstPushRemote"
| "upstreamState"
| "aheadOfOrigin"
| "isPaseoOwnedWorktree"
>,
): SyncRemotes {
if (status.pullRemote !== undefined && status.pushRemote !== undefined) {
return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null };
}
// COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor
// reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have
// origin. They make a first push from a Paseo worktree, and from a regular checkout only where
// they report firstPushRemote.
const isFirstPush = readUpstreamState(status) === "none";
const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null;
return {
hasPullRemote: status.hasRemote,
hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush),
};
}
export interface BuildGitActionsInput extends SyncRemotes {
export interface BuildGitActionsInput {
isGit: boolean;
githubFeaturesEnabled: boolean;
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
@@ -145,7 +88,7 @@ export interface BuildGitActionsInput extends SyncRemotes {
pullRequestIsMerged: boolean;
pullRequestMergeable: PullRequestMergeable;
mergeCapability: MergeCapability | null;
upstream: GitUpstreamState;
hasRemote: boolean;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
canMergeLocally: boolean;
@@ -603,28 +546,20 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
}
function canPull(input: BuildGitActionsInput): boolean {
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
}
function canPush(input: BuildGitActionsInput): boolean {
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
}
function hasPushableCommits(input: BuildGitActionsInput): boolean {
switch (input.upstream) {
case "tracked":
return (input.aheadOfOrigin ?? 0) > 0;
case "none":
// A first push, which sets the upstream. The commits to send are the ones ahead of the base.
return input.aheadCount > 0;
case "gone":
case "unknown":
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
// left to send. Paseo worktrees publish whenever the branch is ahead of its base, for
// example after a merged PR. Regular checkouts do not: Push would re-create a branch that
// was deleted.
return input.isPaseoOwnedWorktree && input.aheadCount > 0;
if ((input.aheadOfOrigin ?? 0) > 0) {
return true;
}
// No-upstream Paseo worktrees are first-pushable: the daemon push sets upstream with `git push -u`.
// Do not fold this into aheadOfOrigin; null also covers deleted/pruned upstream branches.
return input.isPaseoOwnedWorktree && input.aheadOfOrigin === null && input.aheadCount > 0;
}
function canMergeFromBase(input: BuildGitActionsInput): boolean {
@@ -707,7 +642,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
}
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPullRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -723,23 +658,20 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
}
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
if ((input.behindOfOrigin ?? 0) > 0) {
return i18n.t("workspace.git.actions.unavailable.pushBehind");
}
if (hasPushableCommits(input)) {
return undefined;
if (!hasPushableCommits(input)) {
return i18n.t("workspace.git.actions.unavailable.pushNothing");
}
if (input.upstream === "gone") {
return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone");
}
return i18n.t("workspace.git.actions.unavailable.pushNothing");
return undefined;
}
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPullRemote || !input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
}
if (input.hasUncommittedChanges) {
+6 -19
View File
@@ -15,13 +15,9 @@ import {
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
type GitAction,
type GitActions,
type GitUpstreamState,
type SyncRemotes,
} from "@/git/policy";
import { deriveMergeCapability } from "@/git/merge-capability";
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
@@ -125,16 +121,14 @@ interface DeriveGitActionsStateArgs {
baseRef: string | undefined;
}
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
interface DerivedGitActionsState extends SyncRemotes {
interface DerivedGitActionsState {
actionsDisabled: boolean;
aheadCount: number;
behindBaseCount: number;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
hasPullRequest: boolean;
upstream: GitUpstreamState;
hasRemote: boolean;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
canMergeLocally: boolean;
@@ -185,8 +179,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
actionsDisabled,
...extractGitCommitCounts(gitStatus),
hasPullRequest: Boolean(prStatus?.url),
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
hasRemote: gitStatus?.hasRemote ?? false,
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
@@ -674,9 +667,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
aheadOfOrigin,
behindOfOrigin,
hasPullRequest,
hasPullRemote,
hasPushRemote,
upstream,
hasRemote,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -707,9 +698,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestIsMerged: prStatus?.isMerged ?? false,
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasPullRemote,
hasPushRemote,
upstream,
hasRemote,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -817,9 +806,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
};
}, [
isGit,
hasPullRemote,
hasPushRemote,
upstream,
hasRemote,
hasPullRequest,
prStatus?.url,
prStatus?.state,
@@ -151,26 +151,20 @@ describe("ACP provider catalog", () => {
});
});
it.each([
{ id: "goose", feature: "gooseProvider" },
{ id: "hermes", feature: "hermesProvider" },
] as const)(
"adds bundled $id on capable hosts and uses the ACP config on older hosts",
({ id, feature }) => {
const entry = findProvider(id);
expect(buildAcpProviderConfigPatch(entry, (supported) => supported === feature)).toEqual({
providers: { [id]: { enabled: true } },
});
expect(buildAcpProviderConfigPatch(entry)).toEqual({
providers: {
[id]: {
extends: "acp",
label: entry.title,
description: entry.description,
command: [id, "acp"],
env: {},
},
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
const goose = findProvider("goose");
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
providers: { goose: { enabled: true } },
});
expect(buildAcpProviderConfigPatch(goose)).toEqual({
providers: {
goose: {
extends: "acp",
label: "goose",
description: goose.description,
command: ["goose", "acp"],
env: {},
},
});
},
);
},
});
});
@@ -24,10 +24,9 @@ export function buildAcpProviderConfigPatch(
return { providers: { [entry.id]: { enabled: true } } };
}
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
if (feature !== "gooseProvider" && feature !== "hermesProvider") {
if (feature !== "gooseProvider") {
throw new Error(`Update the host to add ${entry.title}.`);
}
}
+7 -93
View File
@@ -4,7 +4,6 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -17,7 +16,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -25,82 +24,16 @@ describe("normalizeStoredHostAppearance", () => {
expect(normalizeStoredHostAppearance({})).toEqual(expected);
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
expect("icon" in defaultHostAppearance()).toBe(false);
});
it("preserves an unknown stored icon on disk while falling back at render time", () => {
const normalized = normalizeStoredHostAppearance({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(normalized).toEqual({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
"laptop",
);
});
it("keeps icon absent on stored entries that predate host icons", () => {
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
expect(normalized).toEqual({
color: "teal",
badgeDisplay: "icon",
});
expect("icon" in normalized).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
).toEqual({
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
color: "teal",
icon: "laptop",
badgeDisplay: "icon",
});
});
});
describe("resolveHostIcon", () => {
it("prefers an explicit user icon over daemon auto-detection", () => {
expect(
resolveHostIcon({
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
detectedMachineKind: "laptop",
}),
).toBe("workstation");
});
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "laptop",
}),
).toBe("laptop");
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "container",
}),
).toBe("container");
});
it("falls back to server when the detected machine kind is absent or unknown", () => {
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
).toBe("server");
});
});
describe("resolveHostBadgeDisplay", () => {
it("hides the badge for the local host until the user chooses", () => {
expect(
@@ -117,13 +50,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
appearance: { color: "none", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -139,7 +72,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -160,7 +93,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -171,14 +104,13 @@ describe("selectHostBadges", () => {
serverId: "beta",
label: "Beta",
color: "none",
icon: "server",
showLabel: true,
});
});
it("keeps an icon-only host in the map without its label", () => {
const badges = selectHostBadges({
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -186,7 +118,6 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -219,21 +150,4 @@ describe("selectHostBadges", () => {
});
expect(badges.size).toBe(0);
});
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha"),
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
],
localServerId: null,
detectedMachineKindByServerId: new Map([
["alpha", "laptop"],
["beta", "cloud"],
]),
enabled: true,
});
expect(badges.get("alpha")?.icon).toBe("laptop");
expect(badges.get("beta")?.icon).toBe("workstation");
});
});
+4 -65
View File
@@ -6,69 +6,25 @@ export type HostColor = "none" | IdentityColorName;
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
export const HOST_ICONS = [
"server",
"laptop",
"desktop",
"mini",
"workstation",
"cloud",
"container",
"board",
"terminal",
] as const;
export type HostIcon = (typeof HOST_ICONS)[number];
export const DEFAULT_HOST_ICON: HostIcon = "server";
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
const trimmed = value?.trim();
if (trimmed && HOST_ICON_SET.has(trimmed)) {
return trimmed as HostIcon;
}
return null;
}
export type HostBadgeDisplay = "name" | "icon" | "hidden";
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
/**
* Per-device host presentation.
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
* with older builds whose stored appearance schema is strict. An unknown icon string written by
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
* remote) without baking runtime facts at parse time.
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
* because the default differs by host (local hides, remote shows) and local-ness is only
* knowable from a desktop-only async query — never at parse time.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
const StoredHostAppearanceSchema = z.strictObject({
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
// added by a newer build survives read/write instead of being dropped or overwritten.
icon: z.string().nullable().optional(),
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
});
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
(value): HostAppearance => {
const icon = value.icon?.trim();
return {
color: value.color,
...(icon ? { icon } : {}),
badgeDisplay: value.badgeDisplay,
};
},
);
export function defaultHostAppearance(): HostAppearance {
return { color: "none", badgeDisplay: null };
}
@@ -78,17 +34,6 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
return result.success ? result.data : defaultHostAppearance();
}
export function resolveHostIcon(input: {
appearance: HostAppearance;
detectedMachineKind?: string | null;
}): HostIcon {
return (
normalizeDetectedHostIcon(input.appearance.icon) ??
normalizeDetectedHostIcon(input.detectedMachineKind) ??
DEFAULT_HOST_ICON
);
}
export function resolveHostBadgeDisplay(input: {
appearance: HostAppearance;
isLocalHost: boolean;
@@ -107,7 +52,6 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -122,7 +66,6 @@ export function selectHostBadges(input: {
hosts: readonly HostAppearanceSource[];
localServerId: string | null;
localHostResolutionPending?: boolean;
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
enabled: boolean;
}): ReadonlyMap<string, HostBadgeModel> {
const badges = new Map<string, HostBadgeModel>();
@@ -142,10 +85,6 @@ export function selectHostBadges(input: {
serverId: host.serverId,
label: host.label.trim() || host.serverId,
color: host.appearance.color,
icon: resolveHostIcon({
appearance: host.appearance,
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
}),
showLabel: display === "name",
});
}
@@ -1,134 +0,0 @@
import { describe, expect, it } from "vitest";
import {
describeActiveConnection,
describeHostConnection,
formatConnectionEndpoint,
isTailscaleEndpoint,
} from "./connection-display";
describe("isTailscaleEndpoint", () => {
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
});
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
});
it("does not misclassify LAN, localhost, or ordinary domains", () => {
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
});
});
describe("describeActiveConnection", () => {
it("describes local socket and pipe connections without exposing paths", () => {
expect(
describeActiveConnection({
type: "directSocket",
endpoint: "/tmp/paseo.sock",
display: "socket",
}),
).toEqual({ kind: "local" });
expect(
describeActiveConnection({
type: "directPipe",
endpoint: "\\\\.\\pipe\\paseo",
display: "pipe",
}),
).toEqual({ kind: "local" });
});
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
const loopback = {
type: "directTcp",
endpoint: "localhost:6767",
display: "localhost:6767",
} as const;
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
kind: "direct",
endpoint: "localhost:6767",
});
});
it("strips standard web ports on relay, tailscale, and direct connections", () => {
expect(
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "devbox.example.com:443",
display: "devbox.example.com:443",
}),
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
});
it("preserves SSH and routed targets", () => {
expect(
describeActiveConnection({
type: "remoteSsh",
endpoint: "mo@workstation",
display: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
expect(
describeActiveConnection({
type: "routed",
endpoint: "srv_origin",
display: "via srv_origin",
}),
).toEqual({ kind: "routed", endpoint: "srv_origin" });
});
it("strips default HTTP/HTTPS ports only", () => {
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
});
it("describes configured host connections before an active connection is online", () => {
expect(
describeHostConnection({
id: "direct:mac-mini.tail123.ts.net:6767",
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeHostConnection({
id: "relay:wss:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
useTls: true,
daemonPublicKeyB64: "key",
}),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeHostConnection({
id: "ssh:mo%40workstation::",
type: "remoteSsh",
host: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
});
});
@@ -1,120 +0,0 @@
import type { ActiveConnection } from "@/runtime/host-runtime";
import type { HostConnection } from "@/types/host-connection";
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
export interface HostConnectionDisplay {
kind: HostConnectionKind;
/** Address shown beside the connection kind. Omitted for local transports. */
endpoint?: string;
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
export function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
function extractEndpointHost(endpoint: string): string {
const trimmed = endpoint.trim().toLowerCase();
if (!trimmed) return "";
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
const authority = withoutScheme.split("/")[0] ?? "";
const hostPort = authority.includes("@")
? authority.slice(authority.lastIndexOf("@") + 1)
: authority;
if (hostPort.startsWith("[")) {
const closeBracket = hostPort.indexOf("]");
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
}
const firstColon = hostPort.indexOf(":");
const lastColon = hostPort.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) {
return hostPort.slice(0, firstColon);
}
return hostPort;
}
function isTailscaleIpv4(host: string): boolean {
const parts = host.split(".");
if (parts.length !== 4) return false;
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return false;
}
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
}
function isTailscaleIpv6(host: string): boolean {
return host.startsWith("fd7a:115c:a1e0:");
}
export function isTailscaleEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
if (!host) return false;
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
return true;
}
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
}
export function isLoopbackEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
export function describeActiveConnection(
connection: ActiveConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.endpoint };
case "routed":
return { kind: "routed", endpoint: connection.endpoint };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
export function describeHostConnection(
connection: HostConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.host };
case "routed":
return { kind: "routed", endpoint: connection.originServerId };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
+29 -8
View File
@@ -1,8 +1,9 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
/**
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
@@ -10,9 +11,30 @@ import { identityForeground } from "@/styles/identity-colors";
*/
export const HOST_BADGE_ICON_SIZE = 12;
const ThemedServer = withUnistyles(Server);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
//
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
// with an unrelated grey word beside it.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
/**
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
* and, when the host is configured to show one, its name — both in the host's identity color.
*
* A hostname is the least interesting thing on any line that carries it and the only one whose
* length nobody chose, so the badge yields space before its neighbours rather than alongside
@@ -25,11 +47,10 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<HostIconGlyph
icon={badge.icon}
color={badge.color}
<ThemedServer
size={HOST_BADGE_ICON_SIZE}
style={styles.icon}
uniProps={HOST_ICON_MAPPINGS[badge.color]}
/>
{badge.showLabel ? (
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
+27 -66
View File
@@ -7,16 +7,14 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Server } from "lucide-react-native";
import { create } from "zustand";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
import { isWeb } from "@/constants/platform";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useHosts } from "@/runtime/host-runtime";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -103,52 +101,36 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const { theme } = useUnistyles();
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active, hovered],
[active],
);
return (
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<View style={styles.rowHeader}>
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={14}
style={styles.rowGlyph}
/>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
</View>
<HostConnectionLine serverId={host.serverId} />
</View>
<View style={styles.rowTrailing}>
<HostLatencyLabel serverId={host.serverId} />
</View>
</Pressable>
</View>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDotSlot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
<Text style={styles.rowSubtitle} numberOfLines={1}>
{host.serverId}
</Text>
</View>
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}
@@ -179,7 +161,6 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -347,7 +328,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "flex-start",
alignItems: "center",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -356,39 +337,19 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 16,
height: 20,
width: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
rowText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
rowHeader: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
rowGlyph: {
flexShrink: 0,
},
rowTitle: {
flex: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
@@ -1,77 +0,0 @@
import type { ReactElement } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import {
Cloud,
Computer,
Container,
Cpu,
Laptop,
Monitor,
PcCase,
Server,
Terminal,
} from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
const ThemedServer = withUnistyles(Server);
const ThemedLaptop = withUnistyles(Laptop);
const ThemedMonitor = withUnistyles(Monitor);
const ThemedComputer = withUnistyles(Computer);
const ThemedPcCase = withUnistyles(PcCase);
const ThemedCloud = withUnistyles(Cloud);
const ThemedContainer = withUnistyles(Container);
const ThemedCpu = withUnistyles(Cpu);
const ThemedTerminal = withUnistyles(Terminal);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
// mapping keeps theme switches off React's render path.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
export function HostIconGlyph({
icon = DEFAULT_HOST_ICON,
color = "none",
size = 16,
style,
}: {
icon?: HostIcon;
color?: HostColor;
size?: number;
style?: StyleProp<ViewStyle>;
}): ReactElement {
const uniProps = HOST_ICON_MAPPINGS[color];
switch (icon) {
case "laptop":
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
case "desktop":
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
case "mini":
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
case "workstation":
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
case "cloud":
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
case "container":
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
case "board":
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
case "terminal":
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
case "server":
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
}
}
-215
View File
@@ -1,215 +0,0 @@
import { useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
import {
describeActiveConnection,
describeHostConnection,
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { HostProfile } from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
export { HostIconGlyph };
const CONNECTION_GLYPH_SIZE = 11;
const ThemedMonitor = withUnistyles(Monitor);
const ThemedTerminal = withUnistyles(Terminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedNetwork = withUnistyles(Network);
const ThemedWaypoints = withUnistyles(Waypoints);
const ThemedTailscale = withUnistyles(TailscaleIcon);
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
switch (kind) {
case "local":
return (
<ThemedMonitor
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "relay":
return (
<ThemedGlobe
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "tailscale":
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
case "ssh":
return (
<ThemedTerminal
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "routed":
return (
<ThemedWaypoints
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "direct":
return (
<ThemedNetwork
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
}
}
function resolvePreferredConnection(host: HostProfile | undefined) {
if (!host || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find(
(connection) => connection.id === host.preferredConnectionId,
);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const localServerId = useLocalDaemonServerId();
const hosts = useHosts();
const activeConnection = snapshot?.activeConnection ?? null;
const hostProfile = useMemo(
() => hosts.find((candidate) => candidate.serverId === serverId),
[hosts, serverId],
);
const fallbackConnection = useMemo(
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
[activeConnection, hostProfile],
);
const described = useMemo(() => {
const options = { isLocalHost: serverId === localServerId };
if (activeConnection) {
return describeActiveConnection(activeConnection, options);
}
if (fallbackConnection) {
return describeHostConnection(fallbackConnection, options);
}
return null;
}, [activeConnection, fallbackConnection, localServerId, serverId]);
if (!described) {
return null;
}
const endpoint =
described.kind === "routed" && described.endpoint
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
: described.endpoint;
return (
<View style={styles.connectionRow}>
<View style={styles.linkIconSlot}>
<ConnectionKindGlyph kind={described.kind} />
</View>
<Text style={styles.connectionKind} numberOfLines={1}>
{t(`settings.host.connectionKinds.${described.kind}`)}
</Text>
{endpoint ? (
<Text style={styles.connectionEndpoint} numberOfLines={1}>
{endpoint}
</Text>
) : null}
</View>
);
}
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const status = snapshot?.connectionStatus;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
if (latencyMs !== null) {
return (
<Text style={styles.latency} numberOfLines={1}>
{formatLatency(latencyMs)}
</Text>
);
}
if (status === "offline" || status === "error") {
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
</Text>
);
}
return null;
}
const styles = StyleSheet.create((theme) => ({
connectionRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
linkIconSlot: {
width: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
linkIcon: {
flexShrink: 0,
},
connectionKind: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
connectionEndpoint: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 1,
minWidth: 0,
},
latency: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
flexShrink: 0,
},
statusText: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 0,
},
}));
+11 -24
View File
@@ -1,13 +1,11 @@
import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useHosts } from "@/runtime/host-runtime";
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
import { useSessionStore } from "@/stores/session-store";
/**
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* Every host's badge, resolved from the three things that decide one: the host registry, which
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* that has its own reason to hide badges passes false rather than filtering the result, so the
* per-host setting stays the only thing that decides name vs icon vs hidden.
*/
@@ -19,25 +17,14 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKinds = useSessionStore(
useShallow((state) => {
const result: Record<string, string | null> = {};
for (const host of hosts) {
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
}
return result;
}),
return useMemo(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
);
return useMemo(() => {
const detectedMachineKindByServerId = new Map<string, string | null>(
Object.entries(detectedMachineKinds),
);
return selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
detectedMachineKindByServerId,
enabled,
});
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
}
-26
View File
@@ -912,7 +912,6 @@ export const ar: TranslationResources = {
pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً",
pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله",
pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا",
pullAndPushNoRemote:
"السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pullAndPushDirty:
@@ -2841,23 +2840,6 @@ export const ar: TranslationResources = {
name: {
label: "الاسم",
},
icon: {
label: "الأيقونة",
accessibilityLabel: "الأيقونة، {{value}}",
auto: "تلقائي",
autoDetected: "تلقائي ({{icon}})",
options: {
server: "خادم",
laptop: "حاسوب محمول",
desktop: "حاسوب مكتبي",
mini: "حاسوب مصغّر",
workstation: "محطة عمل",
cloud: "سحابي",
container: "حاوية",
board: "حاسوب أحادي اللوحة",
terminal: "طرفية",
},
},
color: {
label: "اللون",
accessibilityLabel: "اللون، {{value}}",
@@ -2894,14 +2876,6 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
-27
View File
@@ -913,8 +913,6 @@ export const en = {
"Push isn't available here because this branch is not connected to a remote yet",
pushBehind: "Push isn't available yet because there are newer changes to bring in first",
pushNothing: "Push isn't available because there is nothing new to send",
pushUpstreamGone:
"Push isn't available because the branch this one tracks no longer exists",
pullAndPushNoRemote:
"Pull and push isn't available here because this branch is not connected to a remote yet",
pullAndPushDirty:
@@ -2936,23 +2934,6 @@ export const en = {
name: {
label: "Name",
},
icon: {
label: "Icon",
accessibilityLabel: "Icon, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Server",
laptop: "Laptop",
desktop: "Desktop",
mini: "Mini",
workstation: "Workstation",
cloud: "Cloud",
container: "Container",
board: "Single-board PC",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2989,14 +2970,6 @@ export const en = {
local: "Local",
remoteSsh: "Remote SSH",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connections",
removeTitle: "Remove connection",
-27
View File
@@ -925,8 +925,6 @@ export const es: TranslationResources = {
pushBehind:
"Push aún no está disponible porque hay cambios más nuevos que implementar primero",
pushNothing: "Push no está disponible porque no hay nada nuevo que enviar",
pushUpstreamGone:
"Push no está disponible porque la rama que sigue esta rama ya no existe",
pullAndPushNoRemote:
"Tirar y empujar no está disponible aquí porque esta rama aún no está conectada a un control remoto",
pullAndPushDirty:
@@ -2865,23 +2863,6 @@ export const es: TranslationResources = {
name: {
label: "Nombre",
},
icon: {
label: "Icono",
accessibilityLabel: "Icono, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Portátil",
desktop: "Escritorio",
mini: "Mini",
workstation: "Estación de trabajo",
cloud: "Nube",
container: "Contenedor",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2918,14 +2899,6 @@ export const es: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relé",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Directo",
routed: "Vía",
},
connections: {
title: "Conexiones",
removeTitle: "Quitar conexión",
-26
View File
@@ -926,7 +926,6 @@ export const fr: TranslationResources = {
pushBehind:
"Push indisponible pour l’instant : des modifications plus récentes doivent d’abord être récupérées",
pushNothing: "Push indisponible : il n’y a rien de nouveau à pousser",
pushUpstreamGone: "Push indisponible : la branche suivie par cette branche n’existe plus",
pullAndPushNoRemote:
"Pull et push indisponibles : cette branche n’est pas encore liée à un dépôt distant",
pullAndPushDirty:
@@ -2867,23 +2866,6 @@ export const fr: TranslationResources = {
name: {
label: "Nom",
},
icon: {
label: "Icône",
accessibilityLabel: "Icône, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Serveur",
laptop: "Portable",
desktop: "Bureau",
mini: "Mini",
workstation: "Station de travail",
cloud: "Cloud",
container: "Conteneur",
board: "Ordinateur monocarte",
terminal: "Terminal",
},
},
color: {
label: "Couleur",
accessibilityLabel: "Couleur, {{value}}",
@@ -2920,14 +2902,6 @@ export const fr: TranslationResources = {
local: "Local",
remoteSsh: "SSH distant",
},
connectionKinds: {
local: "Local",
relay: "Relais",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connexions",
removeTitle: "Supprimer la connexion",
-27
View File
@@ -919,8 +919,6 @@ export const ja: TranslationResources = {
"このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません",
pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません",
pushNothing: "プッシュする変更がないため、プッシュは利用できません",
pushUpstreamGone:
"このブランチが追跡しているブランチが存在しないため、プッシュは利用できません",
pullAndPushNoRemote:
"このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません",
pullAndPushDirty:
@@ -2833,23 +2831,6 @@ export const ja: TranslationResources = {
name: {
label: "名前",
},
icon: {
label: "アイコン",
accessibilityLabel: "アイコン、{{value}}",
auto: "自動",
autoDetected: "自動 ({{icon}})",
options: {
server: "サーバー",
laptop: "ノート PC",
desktop: "デスクトップ",
mini: "ミニ PC",
workstation: "ワークステーション",
cloud: "クラウド",
container: "コンテナ",
board: "シングルボード PC",
terminal: "ターミナル",
},
},
color: {
label: "色",
accessibilityLabel: "色、{{value}}",
@@ -2886,14 +2867,6 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
-26
View File
@@ -913,7 +913,6 @@ export const ko: TranslationResources = {
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다",
pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다",
pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다",
pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다",
pullAndPushNoRemote:
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다",
pullAndPushDirty:
@@ -2819,23 +2818,6 @@ export const ko: TranslationResources = {
name: {
label: "이름",
},
icon: {
label: "아이콘",
accessibilityLabel: "아이콘, {{value}}",
auto: "자동",
autoDetected: "자동 ({{icon}})",
options: {
server: "서버",
laptop: "노트북",
desktop: "데스크톱",
mini: "미니",
workstation: "워크스테이션",
cloud: "클라우드",
container: "컨테이너",
board: "싱글보드 PC",
terminal: "터미널",
},
},
color: {
label: "색상",
accessibilityLabel: "색상, {{value}}",
@@ -2872,14 +2854,6 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
-27
View File
@@ -921,8 +921,6 @@ export const ptBR: TranslationResources = {
pushBehind:
"Push ainda não está disponível porque há alterações mais recentes para trazer primeiro",
pushNothing: "Push não está disponível porque não há nada novo para enviar",
pushUpstreamGone:
"Push não está disponível porque a branch que esta branch acompanha não existe mais",
pullAndPushNoRemote:
"Pull e push não estão disponíveis aqui porque esta branch ainda não está conectada a um remoto",
pullAndPushDirty:
@@ -2846,23 +2844,6 @@ export const ptBR: TranslationResources = {
name: {
label: "Nome",
},
icon: {
label: "Ícone",
accessibilityLabel: "Ícone, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Notebook",
desktop: "Desktop",
mini: "Mini",
workstation: "Estação de trabalho",
cloud: "Nuvem",
container: "Contêiner",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Cor",
accessibilityLabel: "Cor, {{value}}",
@@ -2899,14 +2880,6 @@ export const ptBR: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direto",
routed: "Via",
},
connections: {
title: "Conexões",
removeTitle: "Remover conexão",
-27
View File
@@ -924,8 +924,6 @@ export const ru: TranslationResources = {
"Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.",
pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.",
pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.",
pushUpstreamGone:
"Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.",
pullAndPushNoRemote:
"Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.",
pullAndPushDirty:
@@ -2854,23 +2852,6 @@ export const ru: TranslationResources = {
name: {
label: "Имя",
},
icon: {
label: "Значок",
accessibilityLabel: "Значок, {{value}}",
auto: "Авто",
autoDetected: "Авто ({{icon}})",
options: {
server: "Сервер",
laptop: "Ноутбук",
desktop: "Компьютер",
mini: "Мини-ПК",
workstation: "Рабочая станция",
cloud: "Облако",
container: "Контейнер",
board: "Одноплатный ПК",
terminal: "Терминал",
},
},
color: {
label: "Цвет",
accessibilityLabel: "Цвет, {{value}}",
@@ -2907,14 +2888,6 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
-26
View File
@@ -908,7 +908,6 @@ export const zhCN: TranslationResources = {
pushNoRemote: "此处无法 push,因为此分支尚未连接到 remote",
pushBehind: "暂时无法 push,因为需要先拉取更新的变更",
pushNothing: "无法 push,因为没有新的内容可发送",
pushUpstreamGone: "无法 push,因为此分支跟踪的分支已不存在",
pullAndPushNoRemote: "此处无法 pull 并 push,因为此分支尚未连接到 remote",
pullAndPushDirty: "有本地变更时无法 pull 并 push,请先 commit 或 stash",
pullAndPushNoIncoming: "无法 pull 并 push,因为没有需要先 pull 的传入变更",
@@ -2775,23 +2774,6 @@ export const zhCN: TranslationResources = {
name: {
label: "名称",
},
icon: {
label: "图标",
accessibilityLabel: "图标,{{value}}",
auto: "自动",
autoDetected: "自动 ({{icon}})",
options: {
server: "服务器",
laptop: "笔记本电脑",
desktop: "台式机",
mini: "迷你主机",
workstation: "工作站",
cloud: "云端",
container: "容器",
board: "单板机",
terminal: "终端",
},
},
color: {
label: "颜色",
accessibilityLabel: "颜色,{{value}}",
@@ -2828,14 +2810,6 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
+6 -175
View File
@@ -1114,106 +1114,6 @@ describe("HostRuntimeController", () => {
expect(activeClient.latencyMeasurements()).toEqual([]);
});
it("measures active latency on demand when an online host has no sample yet", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const controller = new HostRuntimeController({
host: makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
preferredConnectionId: "direct:lan:6767",
}),
deps: makeDeps({ "direct:lan:6767": 14 }, []),
});
await controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "pending",
latencyMs: null,
});
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
});
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const relayProbeStarted = createDeferred<void>();
const slowRelayProbe = createDeferred<{
client: DaemonClient;
serverId: string;
hostname: string | null;
}>();
const relayClient = new FakeDaemonClient();
relayClient.setConnectionState({ status: "connected" });
relayClient.ping = async () => ({ rttMs: 90 });
const controller = new HostRuntimeController({
host: makeHost(),
deps: {
...makeDeps({}, []),
connectToDaemon: async ({ host, connection }) => {
if (connection.id === "relay:relay.paseo.sh:443") {
relayProbeStarted.resolve();
return slowRelayProbe.promise;
}
return {
client: initialClient as unknown as DaemonClient,
serverId: host.serverId,
hostname: null,
};
},
},
});
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
// flight, then measure active latency on demand before the relay probe resolves.
const startPromise = controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
await relayProbeStarted.promise;
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
slowRelayProbe.resolve({
client: relayClient as unknown as DaemonClient,
serverId: "srv_test",
hostname: null,
});
await startPromise;
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
status: "available",
latencyMs: 90,
});
});
it.each([12, null])(
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
async (heartbeatRtt) => {
@@ -3466,11 +3366,7 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
store.syncHosts([]);
});
@@ -3495,7 +3391,6 @@ describe("HostRuntimeStore", () => {
const updated = store.getHosts()[0];
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
expect("icon" in (updated?.appearance ?? {})).toBe(false);
expect(updated?.updatedAt).not.toBe(host.updatedAt);
const persisted = await storage.getItem("@paseo:daemon-registry");
@@ -3507,60 +3402,10 @@ describe("HostRuntimeStore", () => {
store.syncHosts([]);
});
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "violet", badgeDisplay: "icon" },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
await storage.setItem("@paseo:e2e", "1");
const store = createAppearanceStore(storage);
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
const hostListChanged = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === "laptop",
);
await store.setHostIcon("srv_appearance", "laptop");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const resetToAuto = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === undefined,
);
await store.setHostIcon("srv_appearance", null);
await resetToAuto;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
badgeDisplay: "icon",
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
it("records a chosen badge display without disturbing the color", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "amber", icon: "server", badgeDisplay: null },
appearance: { color: "amber", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3578,16 +3423,11 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3636,25 +3476,16 @@ describe("HostRuntimeStore", () => {
};
const color = store.setHostColor("srv_appearance", "teal");
const icon = store.setHostIcon("srv_appearance", "mini");
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
await Promise.resolve();
expect(writeCount).toBe(1);
firstWrite.resolve();
await Promise.all([color, icon, display]);
await Promise.all([color, display]);
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
store.syncHosts([]);
});
+15 -91
View File
@@ -28,12 +28,7 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -950,56 +945,6 @@ export class HostRuntimeController {
await this.switchToConnection(input);
}
/**
* Measures the active connection's round-trip time when the host is online and no sample has
* landed yet (for example right after connecting, before the first heartbeat interval fires).
*/
async refreshActiveLatency(): Promise<void> {
const activeConnectionId = this.snapshot.activeConnectionId;
const activeClient = this.snapshot.client;
if (
this.snapshot.connectionStatus !== "online" ||
!activeConnectionId ||
!activeClient ||
activeClient.getConnectionState().status !== "connected"
) {
return;
}
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
if (existing?.status === "available") {
return;
}
const existingRtt = activeClient.getLastLivenessRttMs();
if (existingRtt !== null) {
this.recordActiveLatencySample(activeConnectionId, existingRtt);
return;
}
try {
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
if (
this.snapshot.activeConnectionId !== activeConnectionId ||
this.snapshot.client !== activeClient ||
this.snapshot.connectionStatus !== "online"
) {
return;
}
this.recordActiveLatencySample(activeConnectionId, rttMs);
} catch {
// A latency probe never drives teardown; the heartbeat owns liveness.
}
}
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
probeByConnectionId.set(connectionId, probe);
this.updateSnapshot({ probeByConnectionId });
}
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
this.recordActiveRttSample(rttMs, performance.now());
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
}
async runProbeCycleNow(): Promise<void> {
if (this.probeCycleInFlight) {
return this.probeCycleInFlight;
@@ -1056,32 +1001,30 @@ export class HostRuntimeController {
return;
}
const initialProbes = new Map(this.snapshot.probeByConnectionId);
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = initialProbes.get(connection.id);
const existingProbe = probeByConnectionId.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
initialProbes.set(connection.id, {
probeByConnectionId.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: initialProbes });
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
// Merge each connection result into the live snapshot map so a slow probe on another
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
const publishProbeState = (): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.setConnectionProbe(connectionId, probe);
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
};
const maybeActivateFirstAvailable = async (
@@ -1110,7 +1053,6 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1266,10 +1208,11 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1278,10 +1221,11 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1291,10 +1235,11 @@ export class HostRuntimeController {
return;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1302,10 +1247,11 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2490,16 +2436,6 @@ export class HostRuntimeStore {
}));
}
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
await this.updateHostAppearance(serverId, (host) => {
const { icon: _previousIcon, ...rest } = host.appearance;
return {
...host,
appearance: icon ? { ...rest, icon } : rest,
};
});
}
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
await this.updateHostAppearance(serverId, (host) => ({
...host,
@@ -2507,16 +2443,6 @@ export class HostRuntimeStore {
}));
}
refreshActiveLatencies(serverIds?: readonly string[]): void {
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
for (const serverId of targets) {
const controller = this.controllers.get(serverId);
if (controller) {
void controller.refreshActiveLatency();
}
}
}
private updateHostAppearance(
serverId: string,
apply: (host: HostProfile) => HostProfile,
@@ -3370,7 +3296,6 @@ export interface HostMutations {
beginLinkPairing: () => LinkPairing;
renameHost: (serverId: string, label: string) => Promise<void>;
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
removeHost: (serverId: string) => Promise<void>;
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
@@ -3386,7 +3311,6 @@ export function useHostMutations(): HostMutations {
beginLinkPairing: () => store.beginLinkPairing(),
renameHost: (serverId, label) => store.renameHost(serverId, label),
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
setHostBadgeDisplay: (serverId, badgeDisplay) =>
store.setHostBadgeDisplay(serverId, badgeDisplay),
removeHost: (serverId) => store.removeHost(serverId),
@@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={320}
desktopMinWidth={200}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
+1 -1
View File
@@ -907,7 +907,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={328}
desktopMinWidth={240}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -4,12 +4,7 @@ import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Pencil } from "lucide-react-native";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { AdaptiveRenameModal } from "@/components/rename-modal";
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
@@ -18,18 +13,12 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
import {
HOST_BADGE_DISPLAYS,
HOST_COLORS,
HOST_ICONS,
normalizeDetectedHostIcon,
resolveHostBadgeDisplay,
resolveHostIcon,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { useHostMutations } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { identityColor } from "@/styles/identity-colors";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
@@ -87,112 +76,10 @@ function colorLabel(t: TFunction, color: HostColor): string {
return t(`settings.host.appearance.color.options.${color}`);
}
function iconLabel(t: TFunction, icon: HostIcon): string {
return t(`settings.host.appearance.icon.options.${icon}`);
}
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
if (detectedIcon) {
return t("settings.host.appearance.icon.autoDetected", {
icon: iconLabel(t, detectedIcon),
});
}
return t("settings.host.appearance.icon.auto");
}
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
return t(`settings.host.appearance.badge.options.${display}`);
}
function IconMenuItem({
icon,
color,
selected,
onChange,
}: {
icon: HostIcon;
color: HostColor;
selected: boolean;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
const leading = useMemo(
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
[color, icon],
);
return (
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
{iconLabel(t, icon)}
</DropdownMenuItem>
);
}
function IconRow({
icon,
detectedIcon,
resolvedIcon,
color,
onChange,
}: {
icon: HostIcon | null;
detectedIcon: HostIcon | null;
resolvedIcon: HostIcon;
color: HostColor;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const autoLabel = autoIconLabel(t, detectedIcon);
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
const triggerLeading = useMemo(
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
[color, resolvedIcon],
);
const autoLeading = useMemo(
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
[color, detectedIcon],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
</View>
<DropdownMenu>
<DropdownTrigger
testID="host-appearance-icon"
accessibilityRole="button"
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
value: selectedLabel,
})}
leading={triggerLeading}
>
{selectedLabel}
</DropdownTrigger>
<DropdownMenuContent side="bottom" align="end" width={220}>
<DropdownMenuItem
selected={icon === null}
onSelect={handleSelectAuto}
leading={autoLeading}
>
{autoLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
{HOST_ICONS.map((option) => (
<IconMenuItem
key={option}
icon={option}
color={color}
selected={option === icon}
onChange={onChange}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
</View>
);
}
function ColorSwatch({ color }: { color: HostColor }) {
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
@@ -318,11 +205,9 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -334,10 +219,9 @@ function BadgePreview({
serverId: host.serverId,
label: host.label,
color: host.appearance.color,
icon: resolvedIcon,
showLabel: badgeDisplay === "name",
},
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
[badgeDisplay, host.serverId, host.label, host.appearance.color],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -360,14 +244,8 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
const badgeDisplay = resolveHostBadgeDisplay({
appearance: host.appearance,
@@ -385,16 +263,6 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
},
[host.serverId, setHostColor, t, toast],
);
const handleIconChange = useCallback(
async (icon: HostIcon | null) => {
try {
await setHostIcon(host.serverId, icon);
} catch {
toast.error(t("errors.unableToSave"));
}
},
[host.serverId, setHostIcon, t, toast],
);
const handleBadgeDisplayChange = useCallback(
async (next: HostBadgeDisplay) => {
try {
@@ -420,18 +288,11 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
<HostRenameButton host={host} />
</View>
</View>
<IconRow
icon={selectedIcon}
detectedIcon={detectedIcon}
resolvedIcon={resolvedIcon}
color={host.appearance.color}
onChange={handleIconChange}
/>
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
{badgeDisplay === null ? null : (
<>
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
</>
)}
</View>
-9
View File
@@ -293,7 +293,6 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -304,7 +303,6 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
serverId: serverInfo.serverId,
hostname: serverInfo.hostname ?? null,
version: serverInfo.version ?? null,
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
@@ -788,7 +786,6 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo: SessionState["serverInfo"] | undefined;
nextHostname: string | null;
nextVersion: string | null;
nextMachineKind: string | null;
nextDesktopManaged: boolean | undefined;
nextCapabilities: ServerCapabilities | undefined;
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
@@ -798,19 +795,16 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
} = input;
const prevHostname = currentServerInfo?.hostname?.trim() || null;
const prevVersion = currentServerInfo?.version?.trim() || null;
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
return (
currentServerInfo?.serverId === input.nextServerId &&
prevHostname === nextHostname &&
prevVersion === nextVersion &&
prevMachineKind === nextMachineKind &&
currentServerInfo?.desktopManaged === nextDesktopManaged &&
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
@@ -948,7 +942,6 @@ export const useSessionStore = create<SessionStore>()(
const nextHostname = info.hostname?.trim() || null;
const nextVersion = info.version?.trim() || null;
const nextMachineKind = info.machineKind?.trim() || null;
const nextDesktopManaged = info.desktopManaged;
const nextCapabilities = info.capabilities;
const nextFeatures = info.features;
@@ -958,7 +951,6 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -978,7 +970,6 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
+5 -27
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
it("gives a host stored before appearance existed the default appearance", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,35 +161,18 @@ describe("normalizeStoredHostProfile", () => {
});
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(profile && "icon" in profile.appearance).toBe(false);
});
it("loads a stored appearance the user chose", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_new",
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
appearance: { color: "teal", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
});
it("preserves an unknown stored icon intact without dropping the saved host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_future_icon",
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({
color: "violet",
icon: "future-device",
badgeDisplay: "name",
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -357,13 +340,12 @@ describe("upsertHostConnectionInProfiles", () => {
});
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
expect("icon" in profile.appearance).toBe(false);
});
it("keeps the appearance the user chose when the host reconnects", () => {
const existing: HostProfile = {
...makeHost("srv_known"),
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
appearance: { color: "amber", badgeDisplay: "hidden" },
connections: [],
};
@@ -373,11 +355,7 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
});
it("replaces a direct connection when its settings change", () => {
@@ -143,11 +143,3 @@ export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
export const Cloud = StubIcon;
export const Computer = StubIcon;
export const Container = StubIcon;
export const Cpu = StubIcon;
export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.17.4",
"version": "0.17.3",
"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.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/server": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/server": "0.17.3",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.17.4",
"version": "0.17.3",
"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.17.4",
"@getpaseo/relay": "0.17.4",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -14
View File
@@ -754,14 +754,13 @@ class DaemonClientSession {
private readonly daemon = new FakeDaemon();
private readonly client: DaemonClient;
constructor(options: { livenessHeartbeat?: boolean } = {}) {
constructor() {
this.client = new DaemonClient({
url: "ws://test",
clientId: "clsk_heartbeat_test",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => this.daemon.transport,
...options,
});
clients.push(this.client);
}
@@ -3396,18 +3395,6 @@ test("starts pinging one interval after connecting and holds the cadence", async
expect(session.pingTimestamps()).toEqual(["10s", "20s", "30s"]);
});
test("a client with the liveness heartbeat off never pings on its own", async () => {
useHeartbeatClock();
const session = new DaemonClientSession({ livenessHeartbeat: false });
session.daemonAnswersPingsAfter("fast");
await session.connect();
await session.advance(60_000);
expect(session.state()).toEqual({ status: "connected" });
expect(session.pingTimestamps()).toEqual([]);
});
test("stops pinging once the connection is gone", async () => {
useHeartbeatClock();
const session = new DaemonClientSession();
+1 -12
View File
@@ -473,13 +473,6 @@ export interface DaemonClientConfig {
runtimeMetricsWindowMs?: number;
trace?: DaemonClientTrace;
capabilities?: Partial<Record<ClientCapability, unknown>>;
/**
* Ping the daemon every 10 s and reconnect after missed replies (default true). Turn it off
* only where the transport reports its own loss (a plugin's IPC channel, an in-process
* channel): there a ping cannot find a dead link the channel would not, and it costs both
* processes a wakeup per client every 10 s.
*/
livenessHeartbeat?: boolean;
}
export interface DaemonClientTrace {
@@ -2749,11 +2742,7 @@ export class DaemonClient {
}
private scheduleNextLivenessHeartbeat(): void {
if (
this.config.livenessHeartbeat === false ||
this.connectionState.status !== "connected" ||
this.livenessHeartbeatTimer
) {
if (this.connectionState.status !== "connected" || this.livenessHeartbeatTimer) {
return;
}
this.livenessHeartbeatTimer = setTimeout(() => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.17.4",
"version": "0.17.3",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.4",
"version": "0.17.3",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.17.4",
"version": "0.17.3",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.17.4",
"version": "0.17.3",
"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.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@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.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -13,15 +13,14 @@ import {
type RequestPermissionRequest,
type RequestPermissionResponse,
type SessionConfigOption,
type SessionInfo,
type SessionNotification,
type SessionUpdate,
type ToolCall,
type ToolCallContent,
type ToolCallUpdate,
type Stream,
} from "@agentclientprotocol/sdk";
import { z } from "zod";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type {
AcpConfigAccess,
AcpConfigChange,
@@ -32,7 +31,6 @@ import type {
AcpVendorUpdate,
RunAcpProviderOptions,
} from "../acp.js";
import { standardToolCallDetail } from "./tool-call-detail.js";
import {
PROVIDER_PROTOCOL_VERSION,
ProviderEventSchema,
@@ -50,7 +48,6 @@ import {
type ProviderLaunch,
type ProviderModel,
type ProviderPermissionResponse,
type ProviderToolCallDetail,
type ProviderPersistence,
type ProviderSessionConfig,
type ProviderSetting,
@@ -299,7 +296,8 @@ async function listSessions(
emit: state.emit,
});
try {
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
const response = await runtime.listSessions(input.cwd);
const selected = input.limit ? response.sessions.slice(0, input.limit) : response.sessions;
state.emit({
type: "sessions",
requestId: input.requestId,
@@ -410,14 +408,14 @@ interface ActivePrompt {
}
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
const SESSION_SCAN_LIMIT = 500;
// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves
// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider.
const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept";
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
type AcpToolCallSource = AcpToolCallSnapshot & {
diff?: Extract<ToolCallContent, { type: "diff" }>;
};
interface AcpToolCallState {
source: AcpToolCallSnapshot;
source: AcpToolCallSource;
presentation: AcpToolCallSnapshot;
}
@@ -918,17 +916,8 @@ class AcpRuntime {
return true;
}
/** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */
async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise<SessionInfo[]> {
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
const sessions: SessionInfo[] = [];
let cursor: string | undefined;
do {
const page = await this.call(this.connection.listSessions({ cwd, cursor }));
sessions.push(...page.sessions);
cursor = page.nextCursor ?? undefined;
} while (cursor && sessions.length < wanted);
return sessions.slice(0, wanted);
listSessions(cwd?: string) {
return this.call(this.connection.listSessions({ cwd }));
}
async drainNotifications(): Promise<void> {
@@ -1083,41 +1072,17 @@ class AcpRuntime {
const requested: AcpConfigChange[] = [];
if (config.model) requested.push({ target: "model", value: config.model });
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
const { settings, legacyAutoAccept } = this.withoutLegacyAutoAccept(config.settings);
// The toggle stays saved after a mode is chosen here, so it counts only while the saved mode
// is one the generic adapter wrote.
const mode =
legacyAutoAccept && autoAcceptMode && !this.offersMode(config.mode)
? autoAcceptMode.mode.id
: (config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined));
const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined);
if (mode) requested.push({ target: "mode", value: mode });
if (config.thinkingOption) {
requested.push({ target: "thinking", value: config.thinkingOption });
}
for (const [id, value] of Object.entries(settings)) {
for (const [id, value] of Object.entries(config.settings)) {
requested.push({ target: "setting", id, value });
}
for (const change of this.inAgentOrder(requested)) await this.applyConfigChange(change);
}
private offersMode(mode: string | undefined): boolean {
if (mode === undefined) return false;
if (mode === this.options.options.acpOptions?.autoAcceptMode?.mode.id) return true;
return toProviderCatalog(this.modes, this.configOptions).modes.some(({ id }) => id === mode);
}
/** Reads the generic ACP adapter's saved Auto Accept toggle unless the agent has such a setting. */
private withoutLegacyAutoAccept(settings: Readonly<Record<string, JsonValue>>): {
settings: Readonly<Record<string, JsonValue>>;
legacyAutoAccept: boolean;
} {
if (this.configOptions.some((option) => option.id === LEGACY_AUTO_ACCEPT_SETTING)) {
return { settings, legacyAutoAccept: false };
}
const { [LEGACY_AUTO_ACCEPT_SETTING]: saved, ...rest } = settings;
return { settings: rest, legacyAutoAccept: saved === true };
}
// One option can reset another: choosing an fx provider also selects that provider's saved
// model, so a model applied first would be lost. Agents list the option that decides first.
private inAgentOrder(changes: readonly AcpConfigChange[]): AcpConfigChange[] {
@@ -1317,7 +1282,6 @@ class AcpRuntime {
}
}
const permissionId = `permission:${request.toolCall.toolCallId}`;
const { presentation } = this.presentToolCall(request.toolCall);
return new Promise((resolve) => {
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
@@ -1330,7 +1294,6 @@ class AcpRuntime {
kind: "tool",
title: request.toolCall.title ?? undefined,
input: jsonRecord(request.toolCall.rawInput),
detail: toolCallDetail(presentation),
actions: request.options.map((option) => ({
id: option.optionId,
label: option.name,
@@ -1599,21 +1562,6 @@ class AcpRuntime {
this.pendingCompactions.clear();
}
/** Merges an update into the call's earlier updates and runs it through the transformers. */
private presentToolCall(update: ToolCall | ToolCallUpdate): AcpToolCallState {
const tool = this.toolCalls.get(update.toolCallId);
const source = mergeToolCallSnapshot(update, tool?.source);
const context = {
sessionId: this.options.boundarySessionId,
mcpServerNames: this.mcpServerNames,
previous: tool?.presentation,
};
let presentation: AcpToolCallSnapshot = source;
for (const transformer of this.transformers)
presentation = transformer.toolCall?.(presentation, context) ?? presentation;
return { source, presentation };
}
private reduceToolCall(
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
wireSeq: number,
@@ -1633,7 +1581,25 @@ class AcpRuntime {
current !== undefined &&
this.liveOpenToolIds.has(current.id) &&
this.toolKeepsTurnOpen(current);
const { source, presentation: snapshot } = this.presentToolCall(update);
const source = mergeToolCallSnapshot(update, tool?.source);
let snapshot: AcpToolCallSnapshot = source;
const context = {
sessionId: this.options.boundarySessionId,
mcpServerNames: this.mcpServerNames,
};
for (const transformer of this.transformers)
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
snapshot = {
...snapshot,
detail: {
type: "edit",
filePath: source.diff.path,
oldString: source.diff.oldText ?? undefined,
newString: source.diff.newText,
},
};
}
this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
if (this.replayWindow === null) {
@@ -2213,8 +2179,8 @@ function ownConnectorStream(source: Stream): {
function mergeToolCallSnapshot(
update: ToolCall | ToolCallUpdate,
current: AcpToolCallSnapshot | undefined,
): AcpToolCallSnapshot {
current: AcpToolCallSource | undefined,
): AcpToolCallSource {
return {
id: update.toolCallId,
name: firstText(update.name, current?.name),
@@ -2224,7 +2190,10 @@ function mergeToolCallSnapshot(
input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
content: update.content === undefined ? current?.content : jsonValue(update.content),
diff:
update.content === undefined
? current?.diff
: update.content?.find((item) => item.type === "diff"),
};
}
@@ -2398,12 +2367,21 @@ function configValues(
type ToolCallTimelineItem = Extract<ProviderTimelineItem, { type: "tool_call" }>;
function toolCallDetail(snapshot: AcpToolCallSnapshot): ProviderToolCallDetail {
return snapshot.detail ?? standardToolCallDetail(snapshot);
}
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem {
const detail = toolCallDetail(snapshot);
const input = jsonRecord(snapshot.input);
const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
const detail =
snapshot.detail ??
(isEdit
? {
type: "edit" as const,
filePath:
typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""),
oldString: typeof input.oldString === "string" ? input.oldString : undefined,
newString: typeof input.newString === "string" ? input.newString : undefined,
unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined,
}
: { type: "unknown" as const, input: snapshot.input, output: snapshot.output });
const status =
snapshot.status === "in_progress" || snapshot.status === "pending"
? "running"
@@ -2438,7 +2416,6 @@ function jsonValue(value: unknown) {
}
function jsonRecord(value: unknown): Record<string, ReturnType<typeof jsonValue>> {
if (value === undefined) return {};
const parsed = jsonValue(value);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
return parsed;
@@ -1,164 +0,0 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { AcpToolCallSnapshot } from "../acp.js";
import type { ProviderToolCallDetail } from "../provider.js";
type JsonRecord = Readonly<Record<string, JsonValue>>;
interface ToolCallParts {
call: AcpToolCallSnapshot;
input: JsonRecord;
output: JsonRecord;
text: string | undefined;
}
type KindDetail = (parts: ToolCallParts) => ProviderToolCallDetail;
const KIND_DETAILS = new Map<string, KindDetail>(
Object.entries({
read: ({ call, input, output, text }) => ({
type: "read",
filePath: call.locations[0] ?? string(input, "path", "filePath", "file") ?? call.title,
content: text ?? string(output, "content", "text"),
offset: number(input, "offset", "line"),
limit: number(input, "limit"),
}),
edit: editDetail,
delete: editDetail,
search: ({ call, input, output, text }) => ({
type: "search",
query: string(input, "query", "pattern") ?? call.title,
toolName: "search",
content: text ?? string(output, "content", "text"),
filePaths: call.locations.length > 0 ? [...call.locations] : undefined,
}),
execute: ({ call, input, output, text }) => ({
type: "shell",
command: shellCommand(input) ?? call.title,
cwd: string(input, "cwd"),
output: text ?? string(output, "output", "text"),
exitCode: number(output, "exitCode"),
}),
fetch: ({ call, input, output, text }) => ({
type: "fetch",
url: string(input, "url") ?? call.title,
prompt: string(input, "prompt"),
result: text ?? string(output, "result", "text", "content"),
code: number(output, "status", "code"),
}),
think: ({ call, text }) => ({ type: "plain_text", label: call.title, icon: "brain", text }),
switch_mode: ({ call, text }) => ({
type: "plain_text",
label: call.title,
icon: "sparkles",
text,
}),
} satisfies Record<string, KindDetail>),
);
/**
* The row for a tool call whose transformers set no detail, read from the call's ACP `kind`,
* `rawInput`, `rawOutput`, `content` and `locations` the way the ACP spec defines them.
*/
export function standardToolCallDetail(call: AcpToolCallSnapshot): ProviderToolCallDetail {
const parts: ToolCallParts = {
call,
input: record(call.input),
output: record(call.output),
text: contentText(call.content),
};
const kindDetail = call.kind === undefined ? undefined : KIND_DETAILS.get(call.kind);
if (kindDetail) return kindDetail(parts);
if (call.name?.toLowerCase().includes("edit")) return editDetail(parts);
// Raw input or output is the most a client can show for a tool it does not know.
if (parts.text !== undefined && call.input === null && call.output === null) {
return { type: "plain_text", label: call.title, icon: "wrench", text: parts.text };
}
return { type: "unknown", input: call.input, output: call.output };
}
function editDetail({ call, input, text }: ToolCallParts): ProviderToolCallDetail {
const diff = contentDiff(call.content);
const filePath =
diff?.path ?? string(input, "filePath", "path", "file") ?? call.locations[0] ?? "";
if (call.kind === "delete") {
return {
type: "edit",
filePath,
oldString: diff?.oldText ?? fileText(input, "oldText"),
newString: "",
unifiedDiff: text,
};
}
return {
type: "edit",
filePath,
oldString: diff?.oldText ?? fileText(input, "oldString", "oldText"),
newString: diff?.newText ?? fileText(input, "newString", "newText"),
unifiedDiff: string(input, "unifiedDiff") ?? text,
};
}
function shellCommand(input: JsonRecord): string | undefined {
const command = string(input, "command");
if (!command) return undefined;
const args = Array.isArray(input.args)
? input.args.filter((arg): arg is string => typeof arg === "string")
: [];
return args.length > 0 ? `${command} ${args.join(" ")}` : command;
}
function contentText(content: JsonValue | undefined): string | undefined {
const parts = contentBlocks(content).flatMap((block) => {
if (block.type !== "content") return [];
const body = record(block.content ?? null);
return body.type === "text" && typeof body.text === "string" && body.text.length > 0
? [body.text]
: [];
});
return parts.length > 0 ? parts.join("\n") : undefined;
}
function contentDiff(
content: JsonValue | undefined,
): { path?: string; oldText?: string; newText?: string } | undefined {
const diff = contentBlocks(content).find((block) => block.type === "diff");
if (!diff) return undefined;
return {
path: string(diff, "path"),
oldText: typeof diff.oldText === "string" ? diff.oldText : undefined,
newText: typeof diff.newText === "string" ? diff.newText : undefined,
};
}
function contentBlocks(content: JsonValue | undefined): JsonRecord[] {
return Array.isArray(content) ? content.map((block) => record(block)) : [];
}
function record(value: JsonValue): JsonRecord {
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
}
function string(value: JsonRecord, ...keys: string[]): string | undefined {
for (const key of keys) {
const entry = value[key];
if (typeof entry === "string" && entry.trim().length > 0) return entry;
}
return undefined;
}
/** File text is kept as written: whitespace or an empty string is the edit itself. */
function fileText(value: JsonRecord, ...keys: string[]): string | undefined {
for (const key of keys) {
const entry = value[key];
if (typeof entry === "string") return entry;
}
return undefined;
}
function number(value: JsonRecord, ...keys: string[]): number | undefined {
for (const key of keys) {
const entry = value[key];
if (typeof entry === "number" && Number.isFinite(entry)) return entry;
}
return undefined;
}
-401
View File
@@ -9,7 +9,6 @@ import {
} from "@agentclientprotocol/sdk";
import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js";
import { afterEach, describe, expect, it } from "vitest";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
import { runAcpProvider, type AcpStreamMessage } from "./acp.js";
@@ -6725,403 +6724,3 @@ describe("deferTurnOnRunningTools", () => {
await connection.close();
});
});
describe("ACP tool call rows", () => {
function jsonRecord(value: JsonValue | undefined): Readonly<Record<string, JsonValue>> {
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
}
function text(value: string) {
return [{ type: "content", content: { type: "text", text: value } }];
}
async function toolRows(
updates: unknown[],
transformers?: Parameters<typeof runAcpProvider>[0]["transformers"],
) {
const harness = connectorHarness({ promptUpdates: () => updates });
const registration = runAcpProvider({
id: "tool-rows-acp",
label: "Tool rows ACP",
connector: harness.connector,
transformers,
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "first",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "Use a tool" }] },
},
});
await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === "completed",
);
const rows = events.flatMap((event) =>
event.type === "timeline.item" && event.item.type === "tool_call" ? [event.item] : [],
);
for (const row of rows) {
expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true);
}
return rows;
} finally {
await connection.close();
}
}
it.each([
{
kind: "execute",
start: { title: "Run tests", rawInput: { command: "npm", args: ["test"], cwd: "/repo" } },
end: { content: text("passed"), rawOutput: { exitCode: 0 } },
detail: { type: "shell", command: "npm test", cwd: "/repo", output: "passed", exitCode: 0 },
},
{
kind: "execute",
start: { title: "Run tests" },
end: { content: text("passed") },
detail: { type: "shell", command: "Run tests", output: "passed" },
},
{
kind: "read",
start: { title: "Read a.ts", locations: [{ path: "/repo/a.ts" }], rawInput: { offset: 3 } },
end: { content: text("const a = 1;") },
detail: { type: "read", filePath: "/repo/a.ts", content: "const a = 1;", offset: 3 },
},
{
kind: "search",
start: { title: "Search TODO", rawInput: { pattern: "TODO" } },
end: { content: text("a.ts:1"), locations: [{ path: "/repo/a.ts" }] },
detail: {
type: "search",
query: "TODO",
toolName: "search",
content: "a.ts:1",
filePaths: ["/repo/a.ts"],
},
},
{
kind: "fetch",
start: { title: "Fetch example", rawInput: { url: "https://example.com" } },
end: { content: text("Example Domain") },
detail: { type: "fetch", url: "https://example.com", result: "Example Domain" },
},
{
kind: "edit",
start: {
title: "Edit a.ts",
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
},
end: {},
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
},
{
kind: "edit",
start: { title: "Edit a.ts", locations: [{ path: "/repo/a.ts" }] },
end: { content: text("Replaced 1 occurrence") },
detail: { type: "edit", filePath: "/repo/a.ts", unifiedDiff: "Replaced 1 occurrence" },
},
{
kind: "edit",
start: {
title: "Edit a.ts",
rawInput: { filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
},
end: {},
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
},
{
kind: "delete",
start: { title: "Delete a.ts", locations: [{ path: "/repo/a.ts" }] },
end: {},
detail: { type: "edit", filePath: "/repo/a.ts", newString: "" },
},
{
kind: "think",
start: { title: "Plan" },
end: { content: text("First read the tests") },
detail: { type: "plain_text", label: "Plan", icon: "brain", text: "First read the tests" },
},
{
kind: "other",
start: { title: "Update todos" },
end: { content: text("2 open") },
detail: { type: "plain_text", label: "Update todos", icon: "wrench", text: "2 open" },
},
{
kind: "other",
start: { title: "Custom tool", rawInput: { value: 1 } },
end: { content: text("done"), rawOutput: { ok: true } },
detail: { type: "unknown", input: { value: 1 }, output: { ok: true } },
},
])("presents a completed $kind call as its standard row ($start.title)", async (example) => {
const rows = await toolRows([
{
sessionUpdate: "tool_call",
toolCallId: "tool-1",
kind: example.kind,
status: "in_progress",
...example.start,
},
{
sessionUpdate: "tool_call_update",
toolCallId: "tool-1",
status: "completed",
...example.end,
},
]);
expect(rows.at(-1)?.detail).toEqual(example.detail);
});
it("gives transformers the call's content and the call as it was last presented", async () => {
const commandFromStart: NonNullable<
NonNullable<Parameters<typeof runAcpProvider>[0]["transformers"]>[number]["toolCall"]
> = (call, { previous }) => {
const first = Array.isArray(call.content) ? call.content[0] : undefined;
const startText = jsonRecord(jsonRecord(first).content).text;
if (typeof startText === "string" && startText.startsWith("$ ")) {
return { ...call, input: { command: startText.slice(2) } };
}
const command = jsonRecord(previous?.input).command;
return typeof command === "string" ? { ...call, input: { command } } : call;
};
const rows = await toolRows(
[
{
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "git status + 1 command",
kind: "execute",
status: "in_progress",
content: text("$ git status && git diff"),
},
{
sessionUpdate: "tool_call_update",
toolCallId: "tool-1",
status: "completed",
content: text("clean"),
},
],
[{ toolCall: commandFromStart }],
);
expect(rows.map((row) => row.detail)).toEqual([
{ type: "shell", command: "git status && git diff", output: "$ git status && git diff" },
{ type: "shell", command: "git status && git diff", output: "clean" },
]);
});
it("keeps a transformer's own detail over the standard row", async () => {
const rows = await toolRows(
[
{
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Run tests",
kind: "execute",
status: "completed",
rawInput: { command: "npm test" },
},
],
[
{
toolCall: (call) => ({
...call,
detail: { type: "unknown", input: call.input, output: null },
}),
},
],
);
expect(rows.at(-1)?.detail).toEqual({
type: "unknown",
input: { command: "npm test" },
output: null,
});
});
it("shows the call's row on its approval", async () => {
const harness = connectorHarness({
handleRequest(runtime, request) {
if (request.method !== "session/prompt") return false;
void runtime.request("session/request_permission", {
sessionId: "connector-session",
toolCall: {
toolCallId: "edit-1",
title: "Edit a.ts",
kind: "edit",
status: "pending",
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
},
options: [
{ optionId: "allow", name: "Allow edit", kind: "allow_once" },
{ optionId: "deny", name: "Deny", kind: "reject_once" },
],
});
return true;
},
});
const connection = await runAcpProvider({
id: "approval-rows",
label: "Approval rows",
connector: harness.connector,
}).connect({ versions: [1], capabilities: ["prompt.message", "permission"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "edit",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "Edit a.ts" }] },
},
});
expect(
await waitForEvent(events, (event) => event.type === "session.permission"),
).toMatchObject({
request: {
id: "permission:edit-1",
title: "Edit a.ts",
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
},
});
} finally {
await connection.close();
}
});
it("lists sessions across every page the agent returns", async () => {
const pages: Record<string, { sessions: unknown[]; nextCursor?: string }> = {
first: {
sessions: [{ sessionId: "s1", cwd: "/repo", title: "One" }],
nextCursor: "second",
},
second: { sessions: [{ sessionId: "s2", cwd: "/repo", title: "Two" }] },
};
const harness = connectorHarness({
capabilities: { sessionCapabilities: { list: {} } },
handleRequest(runtime, request) {
if (request.method !== "session/list") return false;
const { cursor } = request.params as { cursor?: string };
runtime.respond(request, pages[cursor ?? "first"]);
return true;
},
});
const connection = await runAcpProvider({
id: "paged-sessions",
label: "Paged sessions",
connector: harness.connector,
}).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({ type: "sessions", requestId: "list" });
const listed = await waitForEvent(events, (event) => event.type === "sessions");
expect(listed.type === "sessions" && listed.sessions.map((session) => session.title)).toEqual(
["One", "Two"],
);
} finally {
await connection.close();
}
});
it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => {
const harness = connectorHarness({
configOptions: [
{
id: "edit_approval_policy",
name: "Edits",
category: "mode",
type: "select",
currentValue: "ask",
options: [
{ value: "ask", name: "Default" },
{ value: "session", name: "Don't Ask" },
],
},
],
});
const connection = await runAcpProvider({
id: "former-generic",
label: "Former generic",
connector: harness.connector,
acpOptions: {
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
},
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
const input = openInput();
input.config.settings = { auto_accept: true };
await connection.send(input);
await waitForEvent(events, (event) => event.type === "session.ready");
const configs = events.flatMap((event) =>
event.type === "session.config" ? [event.config.mode] : [],
);
expect(configs.at(-1)).toBe("full-access");
const sentOptions = harness.instances
.flatMap((instance) => instance.requests)
.filter((request) => request.method === "session/set_config_option")
.map((request) => (request.params as { configId: string }).configId);
expect(sentOptions).not.toContain("auto_accept");
expect(events.some((event) => event.type === "request.failed")).toBe(false);
} finally {
await connection.close();
}
});
it("keeps a mode chosen after the generic ACP adapter's Auto Accept toggle was saved", async () => {
const harness = connectorHarness({
configOptions: [
{
id: "edit_approval_policy",
name: "Edits",
category: "mode",
type: "select",
currentValue: "session",
options: [
{ value: "ask", name: "Default" },
{ value: "session", name: "Don't Ask" },
],
},
],
});
const connection = await runAcpProvider({
id: "former-generic",
label: "Former generic",
connector: harness.connector,
acpOptions: {
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
},
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
const input = openInput();
input.config.mode = "ask";
input.config.settings = { auto_accept: true };
await connection.send(input);
await waitForEvent(events, (event) => event.type === "session.ready");
const configs = events.flatMap((event) =>
event.type === "session.config" ? [event.config.mode] : [],
);
expect(configs.at(-1)).toBe("ask");
} finally {
await connection.close();
}
});
});
+1 -11
View File
@@ -117,14 +117,9 @@ export interface AcpToolCallSnapshot {
title: string;
kind?: string;
status: "pending" | "in_progress" | "completed" | "failed";
/** The call's ACP `rawInput`. */
input: JsonValue;
/** The call's ACP `rawOutput`. */
output: JsonValue;
/** The call's ACP `content` blocks. An update that sends `content` replaces them. */
content?: JsonValue;
locations: readonly string[];
/** The row Paseo shows. Without it, Paseo builds the standard row for the call's ACP `kind`. */
detail?: ProviderToolCallDetail;
}
@@ -155,14 +150,9 @@ export interface AcpTransformer {
notification: { method: string; params: JsonValue },
context: AcpContext,
): AcpVendorUpdate | readonly AcpVendorUpdate[] | null;
/** Rewrites each update of a tool call, merged with the call's earlier updates. */
toolCall?(
toolCall: AcpToolCallSnapshot,
context: AcpContext & {
mcpServerNames?: readonly string[];
/** The call as Paseo last presented it, after every transformer. Absent on its first update. */
previous?: AcpToolCallSnapshot;
},
context: AcpContext & { mcpServerNames?: readonly string[] },
): AcpToolCallSnapshot;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.17.4",
"version": "0.17.3",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
@@ -814,7 +814,7 @@ describe("checkout PR schemas", () => {
});
test.each(
["hopliteProvider", "fxProvider", "gooseProvider", "hermesProvider"].flatMap((name) =>
["hopliteProvider", "fxProvider", "gooseProvider"].flatMap((name) =>
[undefined, false, true].map((value) => [name, value] as const),
),
)("accepts optional bundled provider capability (%s: %s)", (name, value) => {
-26
View File
@@ -3970,9 +3970,6 @@ export const ServerInfoStatusPayloadSchema = z
serverId: z.string().trim().min(1),
hostname: ServerInfoHostnameSchema.optional(),
version: ServerInfoVersionSchema.optional(),
// Best-effort machine kind detected by the daemon (e.g. "laptop", "mini", "cloud").
// Loose string so unknown future kinds stay parseable across versions.
machineKind: z.string().nullable().optional(),
// Authenticated producer for host registration ownership, separate from admission authority.
sourceId: z.string().optional(),
// COMPAT(sessionPermissions): optional while clients support older daemons.
@@ -4171,8 +4168,6 @@ export const ServerInfoStatusPayloadSchema = z
fxProvider: z.boolean().optional(),
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
gooseProvider: z.boolean().optional(),
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
hermesProvider: z.boolean().optional(),
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
importSessionWorkspaceTarget: z.boolean().optional(),
// COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02.
@@ -5821,27 +5816,6 @@ const CheckoutStatusCommonSchema = z.object({
// upstream branch name is not necessarily currentBranch, so composing one is wrong.
// aheadOfOrigin/behindOfOrigin are measured against exactly this ref.
upstreamRef: z.string().nullable().optional(),
// How currentBranch relates to its upstream: "tracked" (upstreamRef and the counts are set),
// "none" (never pushed; Push does a first push), "gone" (the upstream's remote-tracking ref no
// longer exists, as after the remote branch is deleted), or "unknown" (the daemon cannot tell,
// as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that
// predate it, which report all but "tracked" as a null upstreamRef.
upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(),
// The remote Pull fetches currentBranch from, as git names it: the remote of the branch's
// configured upstream, which is not necessarily origin, or "." when the upstream is a local
// branch. Null when the branch has no upstream. Absent from daemons that predate it, which
// pull only in checkouts that have origin (hasRemote).
pullRemote: z.string().nullable().optional(),
// The remote Push sends currentBranch to, resolved as the daemon's push resolves it. It is not
// necessarily origin. Null when Push has nowhere to send the branch, as when it has no upstream
// and origin is missing, or git is set to push it to another remote (branch.<name>.pushRemote,
// remote.pushDefault). Absent from daemons that predate it, which push only in checkouts that
// have origin (hasRemote).
pushRemote: z.string().nullable().optional(),
// "origin" when Push sends currentBranch to origin, and null otherwise. Clients that predate
// pushRemote read it to offer a first push; newer clients read pushRemote instead. Absent from
// daemons that predate it.
firstPushRemote: z.string().nullable().optional(),
forgeWeb: ForgeWebSchema.optional(),
});
@@ -72,41 +72,6 @@ test("base selection RPCs are correlated while older checkout and branch message
expect(WorkspaceBaseBranchSetResponseSchema.parse(response)).toEqual(response);
});
test("checkout status stays valid without pull and push remotes and retains them when sent", () => {
const olderDaemonPayload = {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
currentBranch: "main",
isDirty: false,
baseRef: "main",
aheadBehind: null,
aheadOfOrigin: 1,
behindOfOrigin: 2,
hasRemote: false,
remoteUrl: null,
upstreamRef: "refs/remotes/doras-mono/main",
upstreamState: "tracked",
firstPushRemote: null,
};
const parse = (payload: Record<string, unknown>) =>
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload;
const older = parse(olderDaemonPayload);
expect(older.pullRemote).toBeUndefined();
expect(older.pushRemote).toBeUndefined();
expect(
parse({ ...olderDaemonPayload, pullRemote: "doras-mono", pushRemote: "doras-mono" }),
).toMatchObject({ pullRemote: "doras-mono", pushRemote: "doras-mono" });
expect(parse({ ...olderDaemonPayload, pullRemote: "upstream", pushRemote: null })).toMatchObject({
pullRemote: "upstream",
pushRemote: null,
});
});
test("terminal listings accept older rows and retain new per-terminal directories", () => {
const response = {
type: "list_terminals_response",
@@ -236,34 +201,6 @@ describe("wire schema compatibility", () => {
});
});
test("server info accepts optional machineKind and older clients drop it cleanly", () => {
const legacyServerInfo = z.object({
status: z.literal("server_info"),
serverId: z.string().trim().min(1),
hostname: z.string().nullable().optional(),
version: z.string().nullable().optional(),
});
const withKind = {
status: "server_info",
serverId: "macbook-server",
hostname: "mbp.local",
version: "0.9.5",
machineKind: "laptop",
};
expect(ServerInfoStatusPayloadSchema.parse(withKind).machineKind).toBe("laptop");
expect(
ServerInfoStatusPayloadSchema.parse({ ...withKind, machineKind: null }).machineKind,
).toBeNull();
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "older-server",
}).machineKind,
).toBeUndefined();
expect(legacyServerInfo.parse(withKind)).not.toHaveProperty("machineKind");
});
test("assistant timeline message ids are optional on the wire", () => {
expect(
AgentTimelineItemPayloadSchema.parse({
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.17.4",
"version": "0.17.1",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.17.4",
"version": "0.17.3",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.17.4",
"version": "0.17.3",
"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.17.4",
"@getpaseo/highlight": "0.17.4",
"@getpaseo/plugin": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"@getpaseo/client": "0.17.3",
"@getpaseo/highlight": "0.17.3",
"@getpaseo/plugin": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -74,19 +74,6 @@ describe("findExecutable", () => {
await expect(findExecutable("foo")).resolves.toBe(executable);
});
test("ignores relative PATH entries when resolving a bare command name", async () => {
const dir = makeTempDir();
const previousCwd = process.cwd();
writeExecutable(path.join(dir, "rel-only-cmd"), "#!/bin/sh\necho 0.1\n");
process.chdir(dir);
try {
process.env.PATH = [".", originalEnv.PATH].filter(Boolean).join(path.delimiter);
await expect(findExecutable("rel-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
describe.runIf(isPlatform("win32"))("Windows", () => {
@@ -155,21 +142,6 @@ describe("findExecutable", () => {
process.env.LOCALAPPDATA = originalLocalAppData;
}
});
test("ignores commands in the current working directory when not explicitly on PATH", async () => {
const repoDir = makeTempDir();
const emptyPathDir = makeTempDir();
const previousCwd = process.cwd();
process.env.PATHEXT = [".EXE", ".CMD"].join(path.delimiter);
writeExecutable(path.join(repoDir, "cwd-only-cmd.cmd"), "@echo off\r\necho 0.1\r\n");
process.chdir(repoDir);
try {
process.env.PATH = emptyPathDir;
await expect(findExecutable("cwd-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
test("returns an invokable absolute path", async () => {
@@ -1,5 +1,5 @@
import { existsSync } from "node:fs";
import { delimiter, dirname, isAbsolute, resolve } from "node:path";
import { delimiter, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import which from "which";
@@ -11,46 +11,11 @@ function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
function stripWindowsPathQuotes(entry: string): string {
return process.platform === "win32" &&
entry.length >= 2 &&
entry.startsWith('"') &&
entry.endsWith('"')
? entry.slice(1, -1)
: entry;
}
function normalizeDirectory(dir: string): string {
const resolved = resolve(dir);
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}
function extractAbsolutePathDirs(rawPath: string | undefined): string[] {
if (!rawPath) {
return [];
}
return rawPath
.split(delimiter)
.map(stripWindowsPathQuotes)
.filter((entry) => entry.length > 0 && isAbsolute(entry));
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
const rawPath = env?.PATH !== undefined ? env.PATH : process.env.PATH;
const absolutePathDirs = extractAbsolutePathDirs(rawPath);
if (absolutePathDirs.length === 0) {
return [];
if (process.platform !== "win32" && existsSync("/usr/bin/which")) {
return enumerateCandidatesViaSystemWhich(name, env);
}
const filteredEnv: ProcessEnvRecord = {
...(env ?? process.env),
PATH: absolutePathDirs.join(delimiter),
};
const allowedDirs = new Set(absolutePathDirs.map(normalizeDirectory));
const candidates =
process.platform !== "win32" && existsSync("/usr/bin/which")
? await enumerateCandidatesViaSystemWhich(name, filteredEnv)
: await enumerateCandidatesViaLibrary(name, filteredEnv);
return candidates.filter((candidate) => allowedDirs.has(normalizeDirectory(dirname(candidate))));
return enumerateCandidatesViaLibrary(name, env);
}
async function enumerateCandidatesViaSystemWhich(
@@ -237,20 +237,6 @@ second line'`,
expect(result).toBe('[paseo__create_agent] {"cwd":"/tmp/repo","initialPrompt":"do the thing"}');
});
it("summarizes a typed row by its detail when its name looks external", () => {
const timeline: AgentTimelineItem[] = [
toolCallItem({
callId: "hermes-terminal",
name: 'terminal: echo "whoami: $(whoami)" + 1 command',
detail: { type: "shell", command: 'echo "whoami: $(whoami)" && uname -s' },
}),
];
const result = curateAgentActivity(timeline);
expect(result).toBe('[Shell] echo "whoami: $(whoami)" && uname -s');
});
it("collapses repeated tool updates by callId", () => {
const timeline: AgentTimelineItem[] = [
toolCallItem({
@@ -84,7 +84,7 @@ function formatToolSummary(summary: string | undefined): string | null {
function inputFromUnknownDetail(
detail: Extract<AgentTimelineItem, { type: "tool_call" }>["detail"],
): unknown {
return detail.type === "unknown" ? detail.input : undefined;
return detail.type === "unknown" ? detail.input : null;
}
function projectForCuration(items: readonly AgentTimelineItem[]): AgentTimelineItem[] {
@@ -3168,8 +3168,15 @@ export class AgentManager {
options?: AgentRunOptions,
onAccepted?: () => void,
): Promise<boolean> {
const agent = await this.findOutOfBandRecipient(agentId);
if (!agent) return false;
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
await this.waitForAgentClose(agentId);
await ensureAgentLoaded(agentId, {
agentManager: this,
agentStorage: this.requireRegistry(),
logger: this.logger,
});
}
const agent = await this.ensureInteractiveSession(agentId);
// Providers parse slash commands from the raw text, so a command another agent sent
// must reach them without its sender envelope.
const agentMessage = typeof prompt === "string" ? parseAgentMessage(prompt) : null;
@@ -3215,31 +3222,6 @@ export class AgentManager {
return true;
}
private async findOutOfBandRecipient(agentId: string): Promise<ActiveManagedAgent | null> {
const live = this.agents.get(agentId);
const collecting = this.collectingRuntimes.has(agentId);
if (live?.session && !collecting && !this.historySessions.has(live.session)) {
return live;
}
if (collecting || !live) {
await this.waitForAgentClose(agentId);
const storage = this.requireRegistry();
// Normal dispatch owns unarchiving. Decline without loading archived history.
if ((await storage.get(agentId))?.archivedAt) return null;
await ensureAgentLoaded(agentId, {
agentManager: this,
agentStorage: storage,
logger: this.logger,
});
}
return this.runLifecycleMutation(agentId, async () => {
const record = await this.registry?.get(agentId);
// Restore closes any history session. Normal dispatch can reopen the stored agent.
if (record && (record.archivedAt || !this.agents.get(agentId)?.session)) return null;
return this.upgradeHistorySessionUnlocked(this.requireSessionAgent(agentId));
});
}
async appendTimelineItem(
agentId: string,
item: AgentTimelineItem,
@@ -3363,22 +3345,13 @@ export class AgentManager {
/** Inside the agent's lane: a history session is upgraded before anything is applied to it. */
private async ensureInteractiveSessionUnlocked(agentId: string): Promise<ActiveManagedAgent> {
const agent = this.requireSessionAgent(agentId);
if (
this.historySessions.has(agent.session) &&
(await this.registry?.get(agentId))?.archivedAt
) {
throw new Error(`Agent is archived: ${agentId}`);
if (this.historySessions.has(agent.session)) {
const record = await this.registry?.get(agentId);
if (record?.archivedAt) throw new Error(`Agent is archived: ${agentId}`);
// Reload validates the directory before releasing readable history.
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
}
return this.upgradeHistorySessionUnlocked(agent);
}
private async upgradeHistorySessionUnlocked(
agent: ActiveManagedAgent,
): Promise<ActiveManagedAgent> {
if (!this.historySessions.has(agent.session)) return agent;
// Reload validates the directory before releasing readable history.
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agent.id));
return this.requireSessionAgent(agent.id);
return this.requireSessionAgent(agentId);
}
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
@@ -1,29 +1,7 @@
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import { expect, test } from "vitest";
import type { ForgeService } from "../../services/forge-service.js";
import { createWorktree } from "../../utils/worktree.js";
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
import type { WorkspaceGitService } from "../workspace-git-service.js";
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import {
CreateAgentLifecycleDispatch,
registerAgentAutoArchive,
} from "./create-agent-lifecycle-dispatch.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
class AgentLifecycleEvents {
private readonly listeners = new Set<AgentSubscriber>();
@@ -47,109 +25,6 @@ class AgentLifecycleEvents {
}
}
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const paseoHome = path.join(tempDir, ".paseo");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
const worktree = await createWorktree({
cwd: repoDir,
worktreeSlug: slug,
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
paseoHome,
});
const workspace: PersistedWorkspaceRecord = {
workspaceId: `ws-${slug}`,
projectId: "proj-1",
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
};
const blockedSource = {
kind: "change_request" as const,
forge: "github",
number: 99,
headRepository: "contributor/paseo",
};
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
if (id === workspace.workspaceId) {
throw new WorkspaceAutomationBlockedError(blockedSource);
}
});
const activeWorkspaces = [workspace];
const archived = new Set<string>();
const events = new AgentLifecycleEvents();
const agentManager = {
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
listAgents: () => [],
getAgent: () => null,
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
archiveSnapshot: vi.fn(async () => ({})),
} as unknown as AgentManager;
const dispatch = new CreateAgentLifecycleDispatch({
paseoHome,
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: async () => false,
agentManager,
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
github: { invalidate: () => {} } as unknown as ForgeService,
workspaceGitService: {
getSnapshot: vi.fn(async () => null),
invalidateWorktrees: () => {},
} as unknown as WorkspaceGitService,
createPaseoWorktreeWorkflow: vi.fn(),
archiveAgentForClose: vi.fn(async () => undefined),
findWorkspaceIdForCwd: async () => workspace.workspaceId,
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
archiveWorkspaceRecord: async (id) => {
archived.add(id);
},
emit: vi.fn(),
emitAgentRemove: vi.fn(async () => undefined),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => undefined),
logger: pino({ level: "silent" }),
});
return {
dispatch,
events,
marker: path.join(repoDir, markerName),
createdWorktree: { worktree, workspace },
archived,
assertWorkspaceAutomationAllowed,
};
}
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
const agents = new AgentLifecycleEvents();
@@ -170,41 +45,3 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
expect(archiveCount).toBe(1);
expect(agents.listenerCount()).toBe(0);
});
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
createdWorktree,
createdAgentId: null,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
const agentId = "agent-auto-archive-untrusted";
const registration = dispatch.registerAutoArchiveIfRequested({
autoArchive: true,
agentId,
createdWorktree,
});
events.completeTurn(agentId);
await registration.cancel();
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
@@ -29,8 +29,7 @@ interface CreateAgentLifecycleDispatchDependencies {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -202,7 +201,6 @@ export class CreateAgentLifecycleDispatch {
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
@@ -25,7 +25,6 @@ import { z } from "zod";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js";
import { createMcpHandler } from "@modelcontextprotocol/server";
import { ensureAgentLoaded } from "./agent-loading.js";
import { AgentManager, type ManagedAgent } from "./agent-manager.js";
import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
@@ -2527,8 +2526,6 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds,
markWorkspaceArchiving,
clearWorkspaceArchiving,
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2645,8 +2642,6 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2679,117 +2674,6 @@ describe("create_agent MCP tool", () => {
}
});
it("skips teardown commands when archiving a worktree with blocked repository automation", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
await mkdtemp(join(tmpdir(), "paseo-mcp-archive-worktree-blocked-")),
);
const repoDir = join(tempDir, "repo");
const paseoHome = join(tempDir, ".paseo");
const markerName = "mcp-blocked-teardown.log";
const markerPath = join(repoDir, markerName);
try {
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@example.com"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "commit.gpgsign", "false"], {
cwd: repoDir,
stdio: "pipe",
});
await writeFile(
join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["branch", "-M", "main"], { cwd: repoDir, stdio: "pipe" });
const workspaceGitService = {
getSnapshot: vi.fn(async () => null),
listWorktrees: vi.fn(async () => []),
resolveRepoRoot: vi.fn(async () => repoDir),
invalidateWorktrees: vi.fn(),
};
const archivedWorkspaceIds: string[] = [];
const activeWorkspaces: Array<{
workspaceId: string;
cwd: string;
kind: "worktree" | "local_checkout" | "directory";
}> = [];
const listActiveWorkspaces = vi.fn(async () => activeWorkspaces);
const archiveWorkspaceRecord = createArchiveWorkspaceRecordMutator(
activeWorkspaces,
archivedWorkspaceIds,
);
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
paseoHome,
createPaseoWorktree: createPaseoWorktreeForMcpTest({ paseoHome, broadcasts: [] }),
workspaceGitService: workspaceGitService as unknown as Pick<
WorkspaceGitService,
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>,
findWorkspaceIdForCwd: vi.fn(async () => "ws-mcp-blocked"),
listActiveWorkspaces,
archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 77,
headRepository: "contributor/repo",
});
},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
const createTool = registeredTool(server, "create_workspace");
const archiveTool = registeredTool(server, "archive_workspace");
const created = await createTool.handler({
isolation: "worktree",
path: repoDir,
worktreeSlug: "archive-blocked-worktree",
baseBranch: "main",
});
const worktreePath = z.string().parse(created.structuredContent.cwd);
activeWorkspaces.push({
workspaceId: "ws-mcp-blocked",
cwd: worktreePath,
kind: "worktree",
});
const archived = await archiveTool.handler({
workspaceId: "ws-mcp-blocked",
});
expect(archived.structuredContent).toMatchObject({
workspaceId: "ws-mcp-blocked",
removedDirectory: true,
});
await expect(access(worktreePath)).rejects.toThrow();
await expect(access(markerPath)).rejects.toThrow();
} finally {
await removeTempDir(tempDir);
}
});
it("does not expose worktree path or slug operations", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
@@ -3626,7 +3510,6 @@ class HeldTurnAgentSession implements AgentSession {
private turnStartGate: Promise<void> | null = null;
private cancelHeldStart: (() => void) | null = null;
private interruptGate: Promise<void> | null = null;
private closeGate?: { signalStart: () => void; waitForRelease: Promise<void> };
private nextStartError: Error | null = null;
constructor(
@@ -3818,19 +3701,7 @@ class HeldTurnAgentSession implements AgentSession {
});
}
holdClose(): { started: Promise<void>; release: () => void } {
const started = Promise.withResolvers<void>();
const released = Promise.withResolvers<void>();
this.closeGate = { signalStart: started.resolve, waitForRelease: released.promise };
return { started: started.promise, release: released.resolve };
}
async close(): Promise<void> {
if (this.closeGate) {
this.closeGate.signalStart();
await this.closeGate.waitForRelease;
}
}
async close(): Promise<void> {}
}
class HeldTurnAgentClient implements AgentClient {
@@ -3989,91 +3860,6 @@ describe("send_agent_prompt MCP tool", () => {
},
);
it.each([
{ activeTurnBehavior: "interrupt", history: "closed" },
{ activeTurnBehavior: "steer", history: "closed" },
{ activeTurnBehavior: "queue", history: "closed" },
{ activeTurnBehavior: "interrupt", history: "open" },
{ activeTurnBehavior: "interrupt", history: "restoring" },
] as const)(
"an agent-scoped $activeTurnBehavior send starts a turn on an archived agent (history: $history)",
async ({ activeTurnBehavior, history }) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-archived-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
let mcpClient: Client | undefined;
let restore: Promise<boolean> | undefined;
let releaseHistoryClose: (() => void) | undefined;
try {
const sender = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{ workspaceId: "wks_parent" },
);
const recipient = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{ workspaceId: "wks_parent" },
);
await manager.archiveAgent(recipient.id);
if (history !== "closed") {
await ensureAgentLoaded(recipient.id, {
agentManager: manager,
agentStorage: storage,
logger,
});
}
const openedSessions = client.sessions.length;
const server = await createAgentMcpServer({
agentManager: manager,
agentStorage: storage,
callerAgentId: sender.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
mcpClient = await connectInMemoryMcpClient(server);
if (history === "restoring") {
const closing = client.sessions.at(-1)!.holdClose();
releaseHistoryClose = closing.release;
restore = manager.unarchiveSnapshot(recipient.id);
await closing.started;
}
const response = await mcpClient.callTool({
name: "send_agent_prompt",
arguments: {
agentId: recipient.id,
prompt: "Start work",
notifyOnFinish: false,
activeTurnBehavior,
},
});
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
activeTurnBehavior,
});
const dispatch = serverDeliveries
.get(server)!
.waitForDispatch(recipient.id, AbortSignal.timeout(5_000));
releaseHistoryClose?.();
await Promise.all([restore, dispatch]);
expect((await storage.get(recipient.id))?.archivedAt).toBeNull();
expect(manager.getAgent(recipient.id)?.lifecycle).toBe("running");
expect(client.sessions).toHaveLength(openedSessions + 1);
expect(client.sessions.at(-1)?.prompts.map(parseAgentMessage)).toEqual([
expect.objectContaining({ text: "Start work" }),
]);
} finally {
releaseHistoryClose?.();
await restore?.catch(() => undefined);
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
}
},
);
it("tells an agent caller that an idle recipient starts a turn with its queued message", async () => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-idle-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -3063,34 +3063,31 @@ test("plugin provider import keeps the stats the plugin reported with its histor
}
});
test.each(["goose", "hermes"])(
"resumes a %s session saved by the generic ACP provider",
async (provider) => {
const logger = createTestLogger();
const harness = createProviderHarness();
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([{ ...harness.registration, id: provider }]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const client = registry[provider].createClient(logger);
test("resumes a goose session saved by the generic ACP provider", async () => {
const logger = createTestLogger();
const harness = createProviderHarness();
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([{ ...harness.registration, id: "goose" }]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const client = registry.goose.createClient(logger);
try {
const session = await client.resumeSession(
{
provider,
sessionId: "native-session",
nativeHandle: "native-session",
},
{ provider, cwd: "/tmp" },
);
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
persistence: { version: 1, data: { sessionId: "native-session" } },
});
await session.close();
} finally {
await plugins.shutdown();
}
},
);
try {
const session = await client.resumeSession(
{
provider: "goose",
sessionId: "native-goose-session",
nativeHandle: "native-goose-session",
},
{ provider: "goose", cwd: "/tmp" },
);
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
persistence: { version: 1, data: { sessionId: "native-goose-session" } },
});
await session.close();
} finally {
await plugins.shutdown();
}
});
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
const logger = createTestLogger();
@@ -2245,20 +2245,13 @@ function encodePersistence(persistence: ProviderPersistence): string {
return `plugin:${JSON.stringify(persistence)}`;
}
// Providers whose agents were saved by the generic ACP provider before they became plugins.
const FORMER_ACP_PROVIDERS = new Set<string>([
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
"goose",
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once legacy handles have migrated.
"hermes",
]);
function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence {
const fromMetadata = handle.metadata?.pluginProviderPersistence;
if (fromMetadata !== undefined) {
return ProviderPersistenceSchema.parse(fromMetadata);
}
if (FORMER_ACP_PROVIDERS.has(handle.provider) && !handle.sessionId.startsWith("plugin:")) {
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) {
return { version: 1, data: { sessionId: handle.sessionId } };
}
return decodePersistenceId(handle.sessionId);
@@ -1,12 +1,9 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import type { ChildProcess } from "node:child_process";
import {
query as sdkQuery,
type Options,
type Query,
type SpawnOptions as ClaudeSpawnOptions,
type SpawnedProcess,
import type {
Options,
Query,
SpawnOptions as ClaudeSpawnOptions,
} from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, test, vi } from "vitest";
@@ -105,72 +102,4 @@ describe("Claude spawn override", () => {
const spawnOptions = claudeSpawnCall?.[2];
expect(spawnOptions?.shell).toBe(false);
});
test("keeps the Paseo MCP bearer token off the Claude Code command line", async () => {
let capturedOptions: Options | undefined;
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.326",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
await session.close();
if (!capturedOptions) {
throw new Error("Claude query options were not captured");
}
// Feed Paseo's options to the real SDK and record the argv it would launch with.
let launchArgs: string[] | undefined;
let stdinText = "";
const stdin = new PassThrough();
stdin.on("data", (chunk: Buffer) => {
stdinText += chunk.toString("utf8");
});
const abortController = new AbortController();
const sdk = sdkQuery({
prompt: "hello",
options: {
...capturedOptions,
abortController,
spawnClaudeCodeProcess: (spawnOptions: ClaudeSpawnOptions): SpawnedProcess => {
launchArgs = spawnOptions.args;
const child = new EventEmitter() as EventEmitter & SpawnedProcess;
Object.assign(child, {
stdin,
stdout: new PassThrough(),
killed: false,
exitCode: null,
kill: () => true,
});
return child;
},
},
});
// The fake process never answers, so the first message never arrives; only the launch matters.
void sdk.next().catch(() => undefined);
await vi.waitFor(() => {
expect(stdinText).toContain("secret-token");
});
abortController.abort();
expect(launchArgs).toBeDefined();
expect(launchArgs?.join(" ")).not.toContain("secret-token");
expect(launchArgs).not.toContain("--mcp-config");
});
});
@@ -449,12 +449,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
describe("a background subagent", () => {
// Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result,
// and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn.
function backgroundLaunch({ toolUseId = TOOL_USE_ID, agentId = AGENT_ID } = {}): string[] {
function backgroundLaunch(): string[] {
return [
parentEntry([
{
type: "tool_use",
id: toolUseId,
id: TOOL_USE_ID,
name: "Agent",
input: {
subagent_type: "general-purpose",
@@ -472,17 +472,17 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
content: [
{
type: "tool_result",
tool_use_id: toolUseId,
tool_use_id: TOOL_USE_ID,
content: [
{
type: "text",
text: `Async agent launched successfully.\nagentId: ${agentId}`,
text: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
},
],
},
],
},
toolUseResult: { isAsync: true, status: "async_launched", agentId },
toolUseResult: { isAsync: true, status: "async_launched", agentId: AGENT_ID },
}),
];
}
@@ -607,35 +607,17 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
expect(statuses).toContain("running");
});
function taskNotification({
status,
form = "user",
includeToolUseId = true,
taskIds = [AGENT_ID],
quoted = false,
}: {
status: string;
form?: string;
includeToolUseId?: boolean;
taskIds?: string[];
quoted?: boolean;
}): string {
const toolUseTag = includeToolUseId ? `<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n` : "";
const taskTags = taskIds.map((id) => `<task-id>${id}</task-id>`).join("\n");
const notification = `<task-notification>\n${taskTags}\n${toolUseTag}<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
const text = quoted ? `Explain this log.\n${notification}` : notification;
function taskNotification(status: string, form = "user"): string {
const text = `<task-notification>\n<task-id>${AGENT_ID}</task-id>\n<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
const records = {
user: {
...(quoted ? {} : { origin: { kind: "task-notification" } }),
message: { role: "user", content: [{ type: "text", text }] },
},
user: { message: { role: "user", content: [{ type: "text", text }] } },
system: {
subtype: "task_notification",
task_id: AGENT_ID,
...(includeToolUseId ? { tool_use_id: TOOL_USE_ID } : {}),
tool_use_id: TOOL_USE_ID,
status,
},
"queue-operation": { operation: quoted ? "remove" : "enqueue", content: text },
"queue-operation": { operation: "enqueue", content: text },
};
return JSON.stringify({
type: form,
@@ -654,7 +636,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
`restores a %s task notification from ${form} when the child stop_reason is null`,
async (status, expected) => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status, form })],
parentLines: [...backgroundLaunch(), taskNotification(status, form)],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -666,160 +648,9 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
);
}
for (const form of ["user", "system", "queue-operation"]) {
test.each([
["completed", "completed"],
["failed", "failed"],
["stopped", "canceled"],
["unknown", "running"],
])(`restores a task-id-only %s notification from ${form}`, async (status, expected) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status, form, includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: expected,
});
});
}
test.each([
["user", false, "canceled"],
["queue-operation", false, "canceled"],
["user", true, "running"],
])(
"restores a shared %s notification with explicit tool-use ID present = %s",
async (form, includeToolUseId, secondStatus) => {
const secondAgentId = "a2222222222222222";
const secondToolUseId = "toolu_second";
const subagentDir = writeParentSession([
...backgroundLaunch(),
...backgroundLaunch({ agentId: secondAgentId, toolUseId: secondToolUseId }),
taskNotification({
status: "stopped",
form,
includeToolUseId,
taskIds: [AGENT_ID, "unrelated-task", secondAgentId],
}),
]);
writeSubagent({
subagentDir,
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
writeSubagent({
subagentDir,
agentId: secondAgentId,
sidechainLines: [sidechainEntry({ agentId: secondAgentId, stopReason: "tool_use" })],
});
const statuses = new Map();
for (const { id, status } of upserts(await replayDescriptors())) {
statuses.set(id, status);
}
expect(statuses).toEqual(
new Map([
[TOOL_USE_ID, "canceled"],
[secondToolUseId, secondStatus],
]),
);
},
);
test("keeps the latest outcome across task-only and tool-linked notifications", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "queue-operation", includeToolUseId: false }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
taskNotification({ status: "completed" }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
});
test("honors a later task-only stopped notification after a tool-linked completion", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "canceled" });
});
test.each(["user", "queue-operation"])(
"keeps a completed child when a later %s record quotes a stopped notification",
async (form) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form, includeToolUseId: false, quoted: true }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
},
);
test("does not apply an unrelated task's stopped outcome to a child", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }).replace(
AGENT_ID,
"unrelated-task",
),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "running" });
});
test("restores a stopped child after a Bash result echoes its launch log", async () => {
const bashToolUseId = "toolu_bash";
writeSession({
parentLines: [
...backgroundLaunch(),
parentEntry([{ type: "tool_use", id: bashToolUseId, name: "Bash", input: {} }]),
JSON.stringify({
type: "user",
message: {
content: [
{
type: "tool_result",
tool_use_id: bashToolUseId,
content: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
},
],
},
}),
taskNotification({ status: "stopped", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: "canceled",
});
});
test("prefers a stopped notification over the child's end_turn", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status: "stopped" })],
parentLines: [...backgroundLaunch(), taskNotification("stopped")],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "end_turn" })],
});
@@ -828,7 +659,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
test("does not invent an outcome for an unknown notification status", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status: "unknown" })],
parentLines: [...backgroundLaunch(), taskNotification("unknown")],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -1094,153 +1094,6 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test.each([
{ claudeCodeVersion: "2.1.326", expected: "initialize" },
{ claudeCodeVersion: "2.2.0", expected: "initialize" },
{ claudeCodeVersion: "2.1.325", expected: "argv" },
{ claudeCodeVersion: undefined, expected: "argv" },
])(
"delivers MCP servers by $expected for Claude Code $claudeCodeVersion",
async ({ claudeCodeVersion, expected }) => {
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => {
if (claudeCodeVersion === undefined) {
throw new Error("Unable to parse Claude Code version from --version output");
}
return claudeCodeVersion;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
expect(queryFactory.mock.calls[0]?.[0].options.mcpServersDelivery).toBe(expected);
await session.close();
},
);
test("probes the configured Claude command in the workspace with the session environment", async () => {
const { queryFactory, launches } = createQueryMock();
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "claude-mcp-workspace-"));
const versionProbe = `
const workspace = process.cwd().endsWith(${JSON.stringify(path.basename(cwd))});
const selected = workspace && process.env.TEST_CLAUDE_WORKSPACE_VERSION;
console.log((selected || "2.1.326") + " (Claude Code)");
`;
const client = new ClaudeAgentClient({
logger,
queryFactory,
runtimeSettings: {
command: { mode: "replace", argv: [process.execPath, "-e", versionProbe, "--"] },
},
});
try {
const session = await client.createSession(
{
provider: "claude",
cwd,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
},
{ env: { TEST_CLAUDE_WORKSPACE_VERSION: "2.1.325" } },
);
try {
await session.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
} finally {
await session.close();
}
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
test("uses stdin on new launches and relaunches after Claude Code upgrades", async () => {
const { queryFactory, launches } = createQueryMock();
let version = "2.1.325";
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => version,
});
const config = {
provider: "claude",
cwd: process.cwd(),
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
const existing = await client.createSession(config);
try {
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
version = "2.1.326";
const fresh = await client.createSession(config);
try {
await fresh.setModel?.("claude-sonnet-4-6");
await existing.setThinkingOption?.("high");
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual([
"argv",
"initialize",
"initialize",
]);
} finally {
await fresh.close();
}
} finally {
await existing.close();
}
});
test("warns about argv delivery only on launches with MCP servers", async () => {
const messages: string[] = [];
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger: pino({}, { write: (message: string) => messages.push(JSON.parse(message).msg) }),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.325",
});
const warnings = () => messages.filter((message) => message.includes("MCP server headers"));
const config = { provider: "claude", cwd: process.cwd() } as const;
const launch = async (sessionConfig: Parameters<typeof client.createSession>[0]) => {
const session = await client.createSession(sessionConfig);
try {
await session.setModel?.("claude-sonnet-4-6");
} finally {
await session.close();
}
};
await launch(config);
await launch({ ...config, mcpServers: {} });
expect(warnings()).toEqual([]);
const withMcp = {
...config,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
await launch(withMcp);
await launch(withMcp);
expect(warnings()).toEqual([
"Claude Code is too old or reports no version; MCP server headers go on its command line",
]);
});
test("passes extra Claude Code CLI arguments to the SDK", async () => {
const { queryFactory, launches } = createQueryMock();
const client = new ClaudeAgentClient({
@@ -39,7 +39,7 @@ import {
mapTaskNotificationSystemRecordToToolCall,
mapTaskNotificationUserContentToToolCall,
readTaskNotificationToolUseIdFromHistoryRecord,
readTaskNotificationOutcomeFromHistoryRecord,
readTaskNotificationFromHistoryRecord,
} from "./task-notification-tool-call.js";
import { isClaudeInterruptPlaceholderText } from "./interrupt-placeholder.js";
import {
@@ -54,7 +54,6 @@ import {
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
resolveClaudeDisabledThinkingForModel,
supportsClaudeMcpServersViaInitialize,
supportsIndependentClaudeUltracode,
} from "./model-manifest.js";
import { expandTilde } from "../../../../utils/path.js";
@@ -89,13 +88,7 @@ import {
} from "./options.js";
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js";
import {
claudeQuery,
probeClaudeLaunchVersion,
type ClaudeLaunchVersionProbe,
type ClaudeOptions,
type ClaudeQueryFactory,
} from "./query.js";
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
import {
findSteeredMessageParent,
realClaudeRewindSdk,
@@ -520,14 +513,9 @@ interface ClaudeAgentSessionOptions {
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
resolveMcpServersDelivery: (
launch: ClaudeLaunchVersionProbe,
) => Promise<ClaudeMcpServersDelivery>;
rewindSdk?: ClaudeRewindSdk;
}
type ClaudeMcpServersDelivery = NonNullable<ClaudeOptions["mcpServersDelivery"]>;
type ClaudeThinkingEffort = "low" | "medium" | "high" | "xhigh" | "max";
type ClaudeThinkingOption =
| ClaudeThinkingEffort
@@ -1658,11 +1646,7 @@ export class ClaudeAgentClient implements AgentClient {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
private readonly resolveLaunchVersion: (
launch: ClaudeLaunchVersionProbe,
) => Promise<string | null>;
private version: Promise<string | undefined> | undefined;
private warnedMcpServersOnArgv = false;
private readonly lookupLatestRelease: LatestReleaseLookup;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
@@ -1685,9 +1669,6 @@ export class ClaudeAgentClient implements AgentClient {
this.resolveVersion =
options.resolveVersion ??
((signal) => resolveClaudeCodeVersion(this.runtimeSettings, signal));
this.resolveLaunchVersion = options.resolveVersion
? () => this.resolveVersion()
: async (launch) => parseReportedClaudeVersion(await probeClaudeLaunchVersion(launch));
this.lookupLatestRelease =
options.lookupLatestRelease ??
((input) =>
@@ -1718,7 +1699,6 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
}
@@ -1749,7 +1729,6 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1847,25 +1826,6 @@ export class ClaudeAgentClient implements AgentClient {
return supportsIndependentClaudeUltracode(await this.version);
}
private async resolveMcpServersDelivery(
launch: ClaudeLaunchVersionProbe,
): Promise<ClaudeMcpServersDelivery> {
// The installed version can change between SDK launches in the same session.
const version = (await this.resolveLaunchVersion(launch).catch(() => null)) ?? undefined;
if (supportsClaudeMcpServersViaInitialize(version)) {
return "initialize";
}
if (this.warnedMcpServersOnArgv) {
return "argv";
}
this.warnedMcpServersOnArgv = true;
this.logger.warn(
{ claudeCodeVersion: version ?? null },
"Claude Code is too old or reports no version; MCP server headers go on its command line",
);
return "argv";
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
@@ -2099,23 +2059,22 @@ async function readClaudeCodeVersion(
const installed = await resolveInstalledClaude(runtimeSettings);
if (!installed) return { status: "not_installed" };
const { executable } = installed;
const output = await execCommand(executable, [...installed.args, "--version"], {
const { stdout, stderr } = await execCommand(executable, [...installed.args, "--version"], {
...createProviderEnvSpec({ runtimeSettings }),
timeout: 5_000,
signal,
});
return { status: "installed", version: parseReportedClaudeVersion(output) };
}
function parseReportedClaudeVersion({ stdout, stderr }: { stdout: string; stderr: string }) {
// A wrapper command (the `command` provider setting) may print its own version here
// A wrapper command (the `command` provider setting) prints its own version here
// instead of Claude Code's. Only trust output that identifies itself as Claude Code,
// so a wrapper's version can't mis-gate models behind a minimumClaudeCodeVersion.
const rawVersionOutput = `${stdout}\n${stderr}`;
const version = /\d+\.\d+\.\d+\s+\(Claude Code\)/i.test(rawVersionOutput)
? parseClaudeCodeVersion(rawVersionOutput)
: null;
return version ? version.join(".") : null;
return {
status: "installed",
version: version ? version.join(".") : null,
};
}
async function resolveClaudeAuth(
@@ -2465,7 +2424,6 @@ class ClaudeAgentSession implements AgentSession {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private readonly resolveMcpServersDelivery: ClaudeAgentSessionOptions["resolveMcpServersDelivery"];
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2605,7 +2563,6 @@ class ClaudeAgentSession implements AgentSession {
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.resolveMcpServersDelivery = options.resolveMcpServersDelivery;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -4091,15 +4048,6 @@ class ClaudeAgentSession implements AgentSession {
if (this.config.mcpServers) {
base.mcpServers = this.normalizeMcpServers(this.config.mcpServers);
if (Object.keys(base.mcpServers).length > 0) {
base.mcpServersDelivery = await this.resolveMcpServersDelivery({
executable: claudeBinary,
cwd: this.config.cwd,
env: sdkEnv,
runtimeSettings: this.runtimeSettings,
launchEnv: this.launchEnv,
});
}
}
if (this.config.model) {
@@ -6821,8 +6769,10 @@ async function readClaudeReplayParentFacts(
const linksByAgentId = new Map<string, { toolCallId: string }>();
const outcomes: Map<string, { status: ProviderSubagentStatus }> = new Map();
for await (const entry of entries) {
for (const notificationOutcome of readClaudeReplayNotificationOutcomes(entry, linksByAgentId)) {
outcomes.set(notificationOutcome.toolCallId, { status: notificationOutcome.status });
const notification = readTaskNotificationFromHistoryRecord(entry);
const status = mapTaskStatus(notification?.status ?? undefined);
if (notification?.toolUseId && status) {
outcomes.set(notification.toolUseId, { status });
}
const content = toObjectRecord(entry.message)?.content;
if (!Array.isArray(content)) continue;
@@ -6840,7 +6790,6 @@ async function readClaudeReplayParentFacts(
outcomes.set(block.tool_use_id, {
status: block.is_error === true ? "failed" : "completed",
});
if (!toolCalls.has(block.tool_use_id)) continue;
const agentId = readLegacyClaudeSubagentId(block.content);
if (agentId)
linksByAgentId.set(agentId, {
@@ -6855,26 +6804,6 @@ async function readClaudeReplayParentFacts(
};
}
function* readClaudeReplayNotificationOutcomes(
entry: ClaudeHistoryEntry,
linksByAgentId: ReadonlyMap<string, { toolCallId: string }>,
): Generator<{ toolCallId: string; status: ProviderSubagentStatus }> {
const notification = readTaskNotificationOutcomeFromHistoryRecord(entry);
if (!notification) return;
const status = mapTaskStatus(notification.status ?? undefined);
if (!status) return;
if (notification.toolUseId) {
yield { toolCallId: notification.toolUseId, status };
return;
}
// Stopped tasks can omit tool-use-id; their launch results already link the native IDs.
for (const taskId of notification.taskIds) {
const link = linksByAgentId.get(taskId);
if (link) yield { toolCallId: link.toolCallId, status };
}
}
function readClaudeReplayTaskDeclaration(
entryType: unknown,
block: Record<string, unknown> | undefined,
@@ -347,27 +347,6 @@ export function supportsIndependentClaudeUltracode(version: string | undefined):
return version === undefined || compareVersions(version, "2.1.284") >= 0;
}
/**
* The Claude Code version bundled with the Agent SDK release that documents
* `mcpServersDelivery: "initialize"`. The SDK only guarantees that delivery for
* the bundled Claude Code or newer: an older binary exits on an unknown flag or
* has its session ended by the SDK.
*/
export const CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION = "2.1.326";
/**
* Whether MCP servers can reach Claude Code over stdin instead of `--mcp-config`
* on its command line, where any local user can read their headers and env.
* An unknown version (a wrapper command) stays on the command line so the
* session still starts.
*/
export function supportsClaudeMcpServersViaInitialize(version: string | undefined): boolean {
return (
version !== undefined &&
compareVersions(version, CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION) >= 0
);
}
export interface ClaudeDisabledThinkingResolution {
supported: boolean;
fallbackThinkingOptionId: string | undefined;
@@ -6,7 +6,7 @@ import {
type ProviderRuntimeSettings,
} from "../../provider-launch-config.js";
import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js";
import { execCommand, spawnProcess } from "../../../../utils/spawn.js";
import { spawnProcess } from "../../../../utils/spawn.js";
// Keep the raw SDK query import in this module only. Claude process launch behavior
// must stay shared between production and tests so Windows .cmd/.bat handling cannot
@@ -29,7 +29,7 @@ function isChildProcessWithStreams(child: ChildProcess): child is ChildProcessWi
}
function resolveClaudeSpawnCommand(
spawnOptions: Pick<SpawnOptions, "command" | "args">,
spawnOptions: SpawnOptions,
runtimeSettings?: ProviderRuntimeSettings,
): { command: string; args: string[] } {
const commandConfig = runtimeSettings?.command;
@@ -53,44 +53,11 @@ function resolveClaudeSpawnCommand(
};
}
type ClaudeLaunchEnvironment = Pick<ClaudeQueryContext, "runtimeSettings" | "launchEnv">;
function createClaudeSpawnEnvSpec(
baseEnv: SpawnOptions["env"],
{ runtimeSettings, launchEnv }: ClaudeLaunchEnvironment,
) {
const spec = createProviderEnvSpec({ baseEnv, runtimeSettings, overlays: [launchEnv] });
// Session-open hooks may supply a client identity. Clear inherited SDK/parent identities.
spec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
return spec;
}
export interface ClaudeLaunchVersionProbe extends ClaudeLaunchEnvironment {
executable: string;
cwd: string;
env: SpawnOptions["env"];
}
export function probeClaudeLaunchVersion(
launch: ClaudeLaunchVersionProbe,
): Promise<{ stdout: string; stderr: string }> {
const { command, args } = resolveClaudeSpawnCommand(
{ command: launch.executable, args: ["--version"] },
launch.runtimeSettings,
);
return execCommand(command, args, {
...createClaudeSpawnEnvSpec(launch.env, launch),
cwd: launch.cwd,
shell: false,
timeout: 5_000,
});
}
function applyRuntimeSettingsToClaudeOptions(
options: ClaudeOptions,
context: ClaudeQueryContext,
): ClaudeOptions {
const { runtimeSettings, onChildProcess } = context;
const { runtimeSettings, launchEnv, onChildProcess } = context;
return {
...options,
spawnClaudeCodeProcess: (spawnOptions) => {
@@ -101,7 +68,14 @@ function applyRuntimeSettingsToClaudeOptions(
// When the SDK passes a native binary path (from pathToClaudeCodeExecutable)
// or the user overrides the command via runtime settings, use that directly.
const isDefaultRuntime = resolved.command === "node" || resolved.command === "bun";
const providerEnvSpec = createClaudeSpawnEnvSpec(spawnOptions.env, context);
const providerEnvSpec = createProviderEnvSpec({
baseEnv: spawnOptions.env,
runtimeSettings,
overlays: [launchEnv],
});
// Session-open hooks may explicitly supply a client identity. Keep inherited
// SDK/parent identities cleared while honoring this launch-only contribution.
providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay);
const selfNodeCommand = isDefaultRuntime
? buildSelfNodeCommand(resolved.args, providerEnv)
@@ -14,7 +14,7 @@ const OptionalNonEmptyTrimmedStringSchema = z.preprocess(
const TaskNotificationEnvelopeSchema = z.object({
notificationId: z.string().optional(),
messageId: z.string().nullable(),
taskIds: z.array(z.string()),
taskId: z.string().nullable(),
toolUseId: z.string().nullable(),
status: z.string().nullable(),
summary: z.string().nullable(),
@@ -44,10 +44,6 @@ const TaskNotificationHistoryRecordSchema = z
message_id: z.string().optional(),
task_id: z.string().optional(),
tool_use_id: z.string().optional(),
origin: z
.object({ kind: z.literal("task-notification") })
.optional()
.catch(undefined),
status: z.string().optional(),
summary: z.string().optional(),
output_file: z.string().optional(),
@@ -149,19 +145,6 @@ function readTaskNotificationTagValue(input: ReadTaskNotificationTagInput): stri
return toNonEmptyString(match[1]);
}
function readTaskNotificationTaskIds(rawText: string | null, structuredTaskId?: string): string[] {
const taskIds = [];
const taskId = toNonEmptyString(structuredTaskId);
if (taskId) taskIds.push(taskId);
if (rawText) {
for (const match of rawText.matchAll(/<task-id>([\s\S]*?)<\/task-id>/gi)) {
const taggedTaskId = toNonEmptyString(match[1]);
if (taggedTaskId) taskIds.push(taggedTaskId);
}
}
return [...new Set(taskIds)];
}
function parseTaskNotificationFromUserContent(
input: MapTaskNotificationUserContentToToolCallInput,
): TaskNotificationEnvelope | null {
@@ -178,7 +161,7 @@ function parseTaskNotificationFromUserContent(
return TaskNotificationEnvelopeSchema.parse({
notificationId: parsedInput.data.notificationId,
messageId: toNonEmptyString(parsedInput.data.messageId),
taskIds: readTaskNotificationTaskIds(rawText),
taskId: readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }),
toolUseId:
readTaskNotificationTagValue({ text: rawText, tagName: "tool-use-id" }) ??
readTaskNotificationTagValue({ text: rawText, tagName: "tool_use_id" }),
@@ -210,7 +193,9 @@ function parseTaskNotificationFromSystemRecord(record: unknown): TaskNotificatio
return TaskNotificationEnvelopeSchema.parse({
notificationId: systemRecord.notificationId,
messageId: toNonEmptyString(systemRecord.uuid) ?? toNonEmptyString(systemRecord.message_id),
taskIds: readTaskNotificationTaskIds(rawText, systemRecord.task_id),
taskId:
toNonEmptyString(systemRecord.task_id) ??
(rawText ? readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }) : null),
toolUseId:
toNonEmptyString(systemRecord.tool_use_id) ??
(rawText
@@ -251,7 +236,7 @@ export async function* assignTaskNotificationReplayIds<T>(
data.type === "user"
? parseTaskNotificationFromUserContent({ content: data.message?.content })
: parseTaskNotificationFromSystemRecord(data);
if (!envelope?.taskIds.length || !data.type) {
if (!envelope?.taskId || !data.type) {
yield entry;
continue;
}
@@ -278,7 +263,7 @@ function taskNotificationReplaySignature(envelope: TaskNotificationEnvelope): st
return createHash("sha1")
.update(
JSON.stringify([
envelope.taskIds.length > 1 ? envelope.taskIds : (envelope.taskIds[0] ?? null),
envelope.taskId,
envelope.toolUseId,
envelope.status,
envelope.summary,
@@ -301,8 +286,9 @@ function buildTaskNotificationCallId(envelope: TaskNotificationEnvelope): string
: null;
if (messageSegment) return `task_notification_${messageSegment}`;
const [taskId] = envelope.taskIds;
const taskSegment = taskId ? normalizeTaskNotificationCallIdSegment(taskId) : null;
const taskSegment = envelope.taskId
? normalizeTaskNotificationCallIdSegment(envelope.taskId)
: null;
if (taskSegment) return `task_notification_${taskSegment}`;
const seed =
@@ -348,11 +334,10 @@ function toTaskNotificationToolCall(
});
const label = buildTaskNotificationLabel(envelope);
const detailText = envelope.rawText ?? envelope.summary ?? undefined;
const [taskId] = envelope.taskIds;
const metadata: Record<string, unknown> = {
synthetic: true,
source: "claude_task_notification",
...(taskId ? { taskId } : {}),
...(envelope.taskId ? { taskId: envelope.taskId } : {}),
...(envelope.toolUseId ? { toolUseId: envelope.toolUseId } : {}),
...(envelope.status ? { status: envelope.status } : {}),
...(envelope.outputFile ? { outputFile: envelope.outputFile } : {}),
@@ -422,38 +407,18 @@ export function mapTaskNotificationSystemRecordToToolCall(
}
export function readTaskNotificationToolUseIdFromHistoryRecord(record: unknown): string | null {
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
return parsedRecord.success
? (parseTaskNotificationHistoryRecord(parsedRecord.data)?.toolUseId ?? null)
: null;
return readTaskNotificationFromHistoryRecord(record)?.toolUseId ?? null;
}
export function readTaskNotificationOutcomeFromHistoryRecord(
export function readTaskNotificationFromHistoryRecord(
record: unknown,
): TaskNotificationEnvelope | null {
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
if (!parsedRecord.success) return null;
const entry = parsedRecord.data;
if (entry.type === "user" && entry.origin?.kind !== "task-notification") return null;
if (entry.type === "queue-operation") {
const content = entry.content?.trim();
if (
!content?.startsWith(TASK_NOTIFICATION_MARKER) ||
!content.endsWith("</task-notification>")
) {
return null;
}
}
return parseTaskNotificationHistoryRecord(entry);
}
function parseTaskNotificationHistoryRecord(
record: TaskNotificationHistoryRecord,
): TaskNotificationEnvelope | null {
if (record.type === "user" && record.message) {
if (parsedRecord.data.type === "user" && parsedRecord.data.message) {
return parseTaskNotificationFromUserContent({
content: record.message.content,
messageId: record.uuid ?? record.message_id,
content: parsedRecord.data.message.content,
messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id,
});
}
return parseTaskNotificationFromSystemRecord(record);
@@ -477,12 +442,11 @@ export function coerceTaskNotificationHistoryRecordToSystemMessage(
status = "completed";
}
const [taskId] = parsed.taskIds;
return {
type: "system",
subtype: "task_notification",
...(parsed.messageId ? { uuid: parsed.messageId } : {}),
...(taskId ? { task_id: taskId } : {}),
...(parsed.taskId ? { task_id: parsed.taskId } : {}),
status,
...(parsed.summary ? { summary: parsed.summary } : {}),
...(parsed.outputFile ? { output_file: parsed.outputFile } : {}),
@@ -185,39 +185,29 @@ test("repeated content is reused without rewriting the attachment", async () =>
test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => {
const bytes = Buffer.alloc(64 * 1024 * 1024, 37);
const data = bytes.toString("base64");
const materializing = new AsyncLocalStorage<boolean>();
let loopAdvanced = false;
let yieldedBeforeFilesystem: boolean | undefined;
const hook = createHook({
init(_id, type) {
// The first filesystem request follows hashing. A later turn could
// come from filesystem I/O even if hashing blocked the event loop.
if (
type === "FSREQPROMISE" &&
materializing.getStore() &&
yieldedBeforeFilesystem === undefined
) {
yieldedBeforeFilesystem = loopAdvanced;
}
},
});
const probe = setImmediate(() => {
loopAdvanced = true;
});
hook.enable();
// Main-thread CPU time between ticks bounds the decode and hash work done on the loop;
// wall-clock gaps on shared CI runners also count preemption and timer granularity.
// File writes stay on fs/promises, so they never block the loop.
const threadCpuMs = () => {
const { user, system } = process.threadCpuUsage();
return (user + system) / 1000;
};
let previous = threadCpuMs();
let longest = 0;
const probe = setInterval(() => {
const now = threadCpuMs();
longest = Math.max(longest, now - previous);
previous = now;
}, 1);
try {
const result = await materializing.run(true, () =>
materializeProviderImage({ data, mimeType: "image/png" }),
);
try {
expect(yieldedBeforeFilesystem).toBe(true);
expect(readFileSync(result.path).equals(bytes)).toBe(true);
} finally {
rmSync(result.path, { force: true });
}
const result = await materializeProviderImage({ data, mimeType: "image/png" });
await new Promise((resolve) => setTimeout(resolve, 5));
console.log(`64 MiB attachment longest blocking stretch: ${longest.toFixed(2)} ms CPU`);
expect(longest).toBeLessThan(50);
expect(readFileSync(result.path).equals(bytes)).toBe(true);
rmSync(result.path, { force: true });
} finally {
hook.disable();
clearImmediate(probe);
clearInterval(probe);
}
});
@@ -145,7 +145,6 @@ export interface PaseoToolHostDependencies {
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
@@ -3428,18 +3427,11 @@ function archiveWorktreeDependencies(
if (!options.clearWorkspaceArchiving) {
throw new Error("Workspace archiving clearer is required to archive worktrees");
}
if (!options.assertWorkspaceAutomationAllowed) {
throw new Error("Workspace automation gate is required to archive worktrees");
}
if (!options.isCheckoutUntrusted) {
throw new Error("Checkout trust lookup is required to archive worktrees");
}
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
github: options.github,
workspaceGitService: options.workspaceGitService,
@@ -111,8 +111,6 @@ function createHarness(overrides?: {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
assertWorkspaceAutomationAllowed: vi.fn(async () => undefined),
isCheckoutUntrusted: vi.fn(async () => false),
};
const archiveByScope = vi.fn(
overrides?.archiveByScope ??
@@ -330,8 +328,6 @@ function createRealOutcomeHarness(input: {
},
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
};
@@ -632,68 +628,4 @@ describe("archiveIfSafe", () => {
expect(archivedWorkspaceIds.has(workspace.workspaceId)).toBe(false);
expect(existsSync(worktree.worktreePath)).toBe(true);
});
test("real outcome: skips teardown commands for an unapproved cross-repository checkout", async () => {
const { tempDir, repoDir } = createGitRepo();
const markerName = "auto-archive-merge-teardown.log";
const marker = path.join(repoDir, markerName);
const fs = await import("node:fs");
fs.writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "teardown"], {
cwd: repoDir,
stdio: "pipe",
});
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "merged-untrusted");
const workspaceId = "ws-merged-untrusted";
const archivedWorkspaceIds = new Set<string>();
const harness = createRealOutcomeHarness({
paseoHome,
repoDir,
worktreePath: worktree.worktreePath,
activeWorkspaces: [
{
workspaceId,
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
],
archivedWorkspaceIds,
});
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const assertWorkspaceAutomationAllowed = vi.fn(async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 123,
headRepository: "contributor/repo",
});
});
harness.options.assertWorkspaceAutomationAllowed = assertWorkspaceAutomationAllowed;
await archiveIfSafe({
workspaceId,
snapshot: { ...createSnapshot(), cwd: worktree.worktreePath },
options: harness.options,
log: harness.log,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(workspaceId);
expect(archivedWorkspaceIds.has(workspaceId)).toBe(true);
expect(existsSync(worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
});
@@ -25,8 +25,7 @@ export interface AutoArchiveArchiveOptions {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -114,7 +113,6 @@ export async function archiveIfSafe(input: {
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
+1 -26
View File
@@ -16,7 +16,6 @@ import { createServer as createHTTPServer, type IncomingMessage, type ServerResp
import { constants, existsSync, unlinkSync } from "fs";
import { open, rm, stat } from "fs/promises";
import { randomUUID } from "node:crypto";
import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import path from "node:path";
import { createMcpHandler } from "@modelcontextprotocol/server";
@@ -637,9 +636,6 @@ export async function createPaseoDaemon(
rootLogger: Logger,
dependencies: PaseoDaemonDependencies = {},
): Promise<PaseoDaemon> {
// Start hardware detection at the beginning of bootstrap so it overlaps with disk/registry init
// and does not hold up the listener when probes are slow.
const hostMachineKindReady = primeHostMachineKind();
configureGitProcessPolicy(config.git ?? resolveGitProcessPolicy({ env: process.env }));
const logger = rootLogger.child({ module: "bootstrap" });
const obsoleteTimelineDirectory = path.join(config.paseoHome, "agent-timelines");
@@ -878,13 +874,11 @@ export async function createPaseoDaemon(
});
app.get("/api/status", (_req, res) => {
const machineKind = getCachedHostMachineKind();
res.json({
status: "server_info",
serverId,
hostname: getHostName(),
version: daemonVersion,
...(machineKind ? { machineKind } : {}),
listen: formatListenTarget(boundListenTarget ?? listenTarget),
});
});
@@ -1252,8 +1246,6 @@ export async function createPaseoDaemon(
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
@@ -1366,8 +1358,6 @@ export async function createPaseoDaemon(
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
@@ -1621,8 +1611,6 @@ export async function createPaseoDaemon(
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
@@ -1815,20 +1803,7 @@ export async function createPaseoDaemon(
const start = async () => {
let mainStarted = false;
try {
let machineKindTimeout: ReturnType<typeof setTimeout> | null = null;
const [nextLocalCredential] = await Promise.all([
writeLocalCredential(config.paseoHome),
Promise.race([
hostMachineKindReady,
new Promise<void>((resolve) => {
machineKindTimeout = setTimeout(resolve, 150);
machineKindTimeout.unref();
}),
]).finally(() => {
if (machineKindTimeout) clearTimeout(machineKindTimeout);
}),
]);
localCredential = nextLocalCredential;
localCredential = await writeLocalCredential(config.paseoHome);
if (serviceProxyListenTarget) {
const boundServiceProxyTarget = await serviceProxy.startStandalone({
listenTarget: serviceProxyListenTarget,
@@ -67,11 +67,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({
upstreamRef: snapshot.git.upstreamRef ?? null,
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
isPaseoOwnedWorktree: true,
@@ -94,11 +90,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({
upstreamRef: snapshot.git.upstreamRef ?? null,
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
isPaseoOwnedWorktree: false,
@@ -314,8 +314,6 @@ test("streams whole-file batches and answers a same-socket ping before the revis
).join("\n") + "\n";
writeFileSync(join(cwd, `${file}.ts`), content);
}
// Stage the fixture so Git reads the added files in bulk. They are still new relative to HEAD.
git(cwd, "add", ".");
expect(ctx.client.getLastServerInfoMessage()).toMatchObject({
features: { diffSubscription: true },
});
@@ -13,6 +13,7 @@ const identityIo = pLimit(2);
export class GitObservationPaths {
private constructor(
private readonly root: string,
readonly identity: string,
private readonly aliases: string[],
private readonly windows: boolean,
) {}
@@ -23,11 +24,15 @@ export class GitObservationPaths {
windows
? normalizePathPreservingCase(value, true).replaceAll("\\", "/").toLowerCase()
: normalizePathPreservingCase(value, false);
const aliases = new Set([normalizePath(root)]);
const lexicalRoot = normalizePath(root);
const aliases = new Set([lexicalRoot]);
let identity: string | undefined;
// Sequential: foreign paths must not fan out into the shared libuv pool.
for (const resolve of [nativeRealpath, jsRealpath]) {
try {
aliases.add(normalizePath(await identityIo(() => resolve(root))));
const alias = normalizePath(await identityIo(() => resolve(root)));
identity ??= alias;
aliases.add(alias);
} catch {
/* Missing roots retain lexical identity. */
}
@@ -48,7 +53,7 @@ export class GitObservationPaths {
break;
}
}
return new GitObservationPaths(root, [...aliases], windows);
return new GitObservationPaths(root, identity ?? lexicalRoot, [...aliases], windows);
}
relative(candidate: string): string | null {
@@ -1,94 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyLinuxMachine,
classifyMacModel,
parseMacIoregProductName,
type LinuxMachineProbeInput,
} from "./host-machine-kind";
function linuxProbe(overrides: Partial<LinuxMachineProbeInput> = {}): LinuxMachineProbeInput {
return {
hasContainerMarker: false,
procVersion: null,
deviceTreeModel: null,
sysVendor: null,
productName: null,
biosVendor: null,
boardVendor: null,
chassisType: null,
...overrides,
};
}
describe("classifyMacModel", () => {
it.each([
["MacBookPro18,3", "laptop"],
["MacBookAir10,1", "laptop"],
["Macmini9,1", "mini"],
["iMac21,1", "desktop"],
["MacStudio1,1", "workstation"],
["MacPro7,1", "workstation"],
["Mac15,6", null],
["", null],
[null, null],
] as const)("maps %s to %s", (model, expected) => {
expect(classifyMacModel(model)).toBe(expected);
});
it("extracts Apple Silicon product-name from ioreg output", () => {
const ioreg = `
"model" = <"Mac15,6">
"product-name" = <"MacBook Pro">
`;
expect(classifyMacModel(parseMacIoregProductName(ioreg))).toBe("laptop");
});
});
describe("classifyLinuxMachine", () => {
it("detects containers before VM or chassis markers", () => {
expect(
classifyLinuxMachine(
linuxProbe({ hasContainerMarker: true, sysVendor: "Hetzner", chassisType: "17" }),
),
).toBe("container");
});
it("detects WSL as desktop", () => {
expect(
classifyLinuxMachine(
linuxProbe({ procVersion: "Linux version 5.15.153.1-microsoft-standard-WSL2" }),
),
).toBe("desktop");
});
it("detects single-board PCs from device-tree model", () => {
expect(
classifyLinuxMachine(linuxProbe({ deviceTreeModel: "Raspberry Pi 5 Model B Rev 1.0" })),
).toBe("board");
});
it("detects cloud VMs and hypervisors from DMI metadata", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Hetzner", productName: "vServer" }))).toBe(
"cloud",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Amazon EC2" }))).toBe("cloud");
expect(classifyLinuxMachine(linuxProbe({ biosVendor: "QEMU" }))).toBe("cloud");
});
it("classifies bare-metal Linux machines by SMBIOS chassis type", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "LENOVO", chassisType: "10" }))).toBe(
"laptop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "ASUS", chassisType: "35" }))).toBe("mini");
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Dell Inc.", chassisType: "3" }))).toBe(
"desktop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Supermicro", chassisType: "23" }))).toBe(
"server",
);
});
it("returns null when no marker matches", () => {
expect(classifyLinuxMachine(linuxProbe())).toBeNull();
});
});
@@ -1,251 +0,0 @@
import { execFile } from "node:child_process";
import { access, readFile } from "node:fs/promises";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export type HostMachineKind =
| "laptop"
| "desktop"
| "mini"
| "workstation"
| "cloud"
| "container"
| "board"
| "server";
const PROBE_TIMEOUT_MS = 1_500;
export function classifyMacModel(model: string | null | undefined): HostMachineKind | null {
const normalized = model?.trim().toLowerCase() ?? "";
if (!normalized) return null;
if (normalized.includes("macbook")) return "laptop";
if (normalized.includes("macmini") || normalized.includes("mac mini")) return "mini";
if (normalized.includes("imac")) return "desktop";
if (
normalized.includes("macstudio") ||
normalized.includes("mac studio") ||
normalized.includes("macpro") ||
normalized.includes("mac pro")
) {
return "workstation";
}
return null;
}
export interface LinuxMachineProbeInput {
hasContainerMarker: boolean;
procVersion: string | null;
deviceTreeModel: string | null;
sysVendor: string | null;
productName: string | null;
biosVendor: string | null;
boardVendor: string | null;
chassisType: string | null;
}
const BOARD_PATTERNS = [
"raspberry pi",
"orange pi",
"banana pi",
"rock pi",
"jetson",
"beaglebone",
"odroid",
"pine64",
"radxa",
] as const;
const CLOUD_OR_VM_MARKERS = [
"amazon",
"aws",
"ec2",
"google",
"gce",
"digitalocean",
"hetzner",
"linode",
"akamai",
"vultr",
"ovh",
"scaleway",
"oracle",
"qemu",
"kvm",
"vmware",
"virtualbox",
"xen",
"bochs",
"parallels",
"proxmox",
"hyper-v",
"virtual machine",
"openstack",
"upcloud",
"fly.io",
] as const;
const LAPTOP_CHASSIS_TYPES = new Set([8, 9, 10, 11, 14, 30, 31, 32]);
const DESKTOP_CHASSIS_TYPES = new Set([3, 4, 5, 6, 7, 13, 15, 16]);
const SERVER_CHASSIS_TYPES = new Set([17, 23, 25, 28, 29]);
export function classifyLinuxMachine(input: LinuxMachineProbeInput): HostMachineKind | null {
if (input.hasContainerMarker) {
return "container";
}
const procVersion = input.procVersion?.toLowerCase() ?? "";
if (procVersion.includes("microsoft") || procVersion.includes("wsl")) {
return "desktop";
}
const deviceTree = input.deviceTreeModel?.toLowerCase() ?? "";
if (deviceTree && BOARD_PATTERNS.some((pattern) => deviceTree.includes(pattern))) {
return "board";
}
const dmiText = [input.sysVendor, input.productName, input.biosVendor, input.boardVendor]
.filter((value): value is string => Boolean(value))
.join(" ")
.toLowerCase();
if (dmiText && CLOUD_OR_VM_MARKERS.some((marker) => dmiText.includes(marker))) {
return "cloud";
}
const chassis = Number.parseInt(input.chassisType?.trim() ?? "", 10);
if (Number.isInteger(chassis)) {
if (LAPTOP_CHASSIS_TYPES.has(chassis)) return "laptop";
if (chassis === 35) return "mini";
if (DESKTOP_CHASSIS_TYPES.has(chassis)) return "desktop";
if (SERVER_CHASSIS_TYPES.has(chassis)) return "server";
}
return null;
}
async function fileExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
async function readTrimmedFile(path: string): Promise<string | null> {
try {
const content = (await readFile(path, "utf8")).replaceAll("\u0000", "").trim();
return content.length > 0 ? content : null;
} catch {
return null;
}
}
export function parseMacIoregProductName(output: string): string | null {
const productMatch = output.match(/"product-name"\s*=\s*<"([^"]+)">/i);
if (productMatch?.[1]?.trim()) {
return productMatch[1].trim();
}
const modelMatch = output.match(/"model"\s*=\s*<"([^"]+)">/i);
return modelMatch?.[1]?.trim() ?? null;
}
async function readMacModel(): Promise<string | null> {
// Apple Silicon Macs report generic "Mac15,6" in sysctl hw.model, while IOPlatformExpertDevice
// exposes the human product name ("MacBook Pro", "Mac mini", "Mac Studio", etc.).
try {
const { stdout } = await execFileAsync(
"/usr/sbin/ioreg",
["-rd1", "-c", "IOPlatformExpertDevice"],
{
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
},
);
const parsed = parseMacIoregProductName(stdout);
if (parsed && classifyMacModel(parsed)) {
return parsed;
}
} catch {
// Fall back to sysctl below.
}
try {
const { stdout } = await execFileAsync("/usr/sbin/sysctl", ["-n", "hw.model"], {
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
});
const trimmed = stdout.trim();
return trimmed || null;
} catch {
return null;
}
}
export async function detectHostMachineKind(
platform: NodeJS.Platform = process.platform,
): Promise<HostMachineKind | null> {
if (platform === "darwin") {
return classifyMacModel(await readMacModel());
}
if (platform === "linux") {
const [
hasDockerEnv,
hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
] = await Promise.all([
fileExists("/.dockerenv"),
fileExists("/run/.containerenv"),
readTrimmedFile("/proc/version"),
readTrimmedFile("/proc/device-tree/model"),
readTrimmedFile("/sys/class/dmi/id/sys_vendor"),
readTrimmedFile("/sys/class/dmi/id/product_name"),
readTrimmedFile("/sys/class/dmi/id/bios_vendor"),
readTrimmedFile("/sys/class/dmi/id/board_vendor"),
readTrimmedFile("/sys/class/dmi/id/chassis_type"),
]);
return classifyLinuxMachine({
hasContainerMarker: hasDockerEnv || hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
});
}
return null;
}
let cachedMachineKind: HostMachineKind | null | undefined;
let pendingMachineKind: Promise<HostMachineKind | null> | null = null;
export function primeHostMachineKind(): Promise<HostMachineKind | null> {
if (cachedMachineKind !== undefined) {
return Promise.resolve(cachedMachineKind);
}
if (!pendingMachineKind) {
pendingMachineKind = detectHostMachineKind()
.then((kind) => {
cachedMachineKind = kind;
return kind;
})
.catch(() => {
cachedMachineKind = null;
return null;
});
}
return pendingMachineKind;
}
export function getCachedHostMachineKind(): HostMachineKind | null {
return cachedMachineKind ?? null;
}

Some files were not shown because too many files have changed in this diff Show More