mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-03 21:56:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9a803be52 | ||
|
|
e7f2913109 | ||
|
|
6e071b60f2 | ||
|
|
8a8bc76cc6 | ||
|
|
a246b931ed | ||
|
|
8c2c5d5103 | ||
|
|
b1ce00192d |
@@ -89,9 +89,8 @@ relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins and the plugin runtime included, so their changes run it too.
|
||||
# plugins included, so daemon changes run it too.
|
||||
cli:
|
||||
- "packages/cli/**"
|
||||
- "packages/server/**"
|
||||
- "packages/plugin/**"
|
||||
- "plugins/**"
|
||||
|
||||
+21
-21
@@ -32,15 +32,6 @@
|
||||
- Paseo CLI and daemon now require Node.js 22.16.0 or later ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- Relay connections now require [protected end-to-end encryption](https://paseo.sh/docs/security) by default, so apps older than 0.13.0 cannot connect through the relay ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### Security
|
||||
|
||||
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### Added
|
||||
|
||||
- Added Antigravity quota to Usage, refreshed only when you select Refresh ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
@@ -74,18 +65,6 @@
|
||||
- Changed Cmd/Ctrl+click on a sidebar workspace to open it instead of entering select mode ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- Changed agents that already reported to their caller with `send_agent_prompt` to skip the extra finished notice ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
|
||||
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed thinking level, mode and model changes on a running agent snapping back to the old value ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
@@ -184,6 +163,27 @@
|
||||
- Fixed `paseo daemon status` leaving out unconfirmed terminal cleanup ([#11658](https://github.com/getpaseo/paseo/pull/11658) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed CLI archive, detach and reload scanning all agent history for a full agent ID ([#11617](https://github.com/getpaseo/paseo/pull/11617) by [@maci0](https://github.com/maci0))
|
||||
|
||||
### Security
|
||||
|
||||
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
|
||||
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **Redesigned model picker:** Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings. ([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
|
||||
+21
-21
@@ -32,15 +32,6 @@
|
||||
- Paseo CLI 和 daemon 现在需要 Node.js 22.16.0 或更高版本 ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- 中继连接现在默认要求[受保护的端到端加密](https://paseo.sh/zh-CN/docs/security),因此 0.13.0 之前的应用无法再通过中继连接 ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### 安全
|
||||
|
||||
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### 新增
|
||||
|
||||
- 在用量中新增 Antigravity 配额,仅在选择 **刷新** 时更新 ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
@@ -74,18 +65,6 @@
|
||||
- 在侧边栏中 Cmd/Ctrl+点击工作区改为打开该工作区,而不再进入选择模式 ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- 已通过 `send_agent_prompt` 向调用方汇报的 Agent 不再额外发送完成通知 ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
|
||||
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复更改运行中 Agent 的思考强度、模式和模型后又跳回旧值的问题 ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
@@ -184,6 +163,27 @@
|
||||
- 修复 `paseo daemon status` 遗漏未确认的终端清理的问题 ([#11658](https://github.com/getpaseo/paseo/pull/11658),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 CLI 归档、分离和重新加载时为匹配完整 Agent ID 而扫描全部 Agent 历史记录的问题 ([#11617](https://github.com/getpaseo/paseo/pull/11617),贡献者:[@maci0](https://github.com/maci0))
|
||||
|
||||
### 安全
|
||||
|
||||
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
|
||||
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **重新设计的模型选择器**:桌面端采用支持跨 Provider 搜索的双栏视图,手机端合并为带思考强度滑块的单层抽屉,并支持在设置中按 Provider 筛选常用模型。([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
|
||||
@@ -10,7 +10,7 @@ Two contracts follow from it.
|
||||
|
||||
A schema change must not break parsing in either direction. An old app still parses messages from a new daemon. A new daemon still parses messages from an old app.
|
||||
|
||||
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes a refusal close only when the client sent `hello.auth` or advertised `hello_rejection` or `evolvable_hello_rejection`; older clients receive only the WebSocket close code and reason so their validator does not reject an unknown top-level envelope. Clients advertising `evolvable_hello_rejection` accept open `reason`, optional `accepts`, and optional `message` fields and halt reconnects on any refusal. Reserve `hello.rejected` for refusals that require user or client-version action; transient restarts and temporary unavailability close the socket without `hello.rejected` so clients reconnect automatically. For `hello_rejection`-only clients, the daemon downgrades unknown reasons to `password_required` (when `accepts` includes `"password"`) or `incompatible_protocol`, restricts `accepts` to `["password"]` or `[]`, and omits `message`.
|
||||
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes an auth close only when the client sent `hello.auth` or advertised `hello_rejection`; older clients receive the existing WebSocket close code and reason. This avoids sending them a new top-level message their validator does not recognize.
|
||||
|
||||
- New fields are `.optional()` with a sensible default.
|
||||
- Never flip optional to required, remove a field, or narrow a type. `string` to `enum` and nullable to non-null are both narrowing.
|
||||
|
||||
@@ -971,8 +971,6 @@ question.
|
||||
you got wrong, rank every highlight again, and then edit the file. Moving only the named item
|
||||
leaves the same mistake in the others.
|
||||
|
||||
Order sections as `Breaking`, `Security`, `Added`, `Improved`, `Changed`, `Plugins`, `Fixed` (omitting empty sections) so `Security` and `Plugins` stay visible above a long `Fixed` list.
|
||||
|
||||
Bullets within each section (Added, Changed, Fixed) follow this order:
|
||||
|
||||
1. **User-facing features and changes first** — things users will notice, want to try, or that change their workflow.
|
||||
|
||||
@@ -97,19 +97,13 @@ Two more reasons the stylesheet route does not work here:
|
||||
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
|
||||
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
|
||||
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the step
|
||||
grid's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
|
||||
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
cycle wherever and whenever it mounted. `phase: "own"` starts the loop at the beginning of the
|
||||
current grid step, so its steps still turn over with the shared loops. A stepped animation sets its easing on the keyframes:
|
||||
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
|
||||
even steps. The compositor then draws a frame when a step changes and none in between.
|
||||
|
||||
The grid's origin is 2.5 µs after the document timeline's, not at it. Browsers stamp frames on
|
||||
whole microseconds, and each loop computes a step boundary from its own duration. A boundary that
|
||||
falls exactly on a frame's stamp can then round to before that frame for the ring and after it for
|
||||
the shimmer, so they turn over on consecutive frames. With the origin at 0, every third boundary is
|
||||
a whole millisecond and lands on a stamp. Off by 2.5 µs, no boundary does.
|
||||
|
||||
## Native
|
||||
|
||||
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-xt1xi8llKklgr6gn21Ae+Jmdke4bjMZ0F+CnR1bh8UE=
|
||||
sha256-oBd6CQ8+BhzMHhrpRIwzojuFPUwqXpgc3ZAPqKPs5QQ=
|
||||
|
||||
@@ -20,9 +20,6 @@ import {
|
||||
readTerminalProcessIds,
|
||||
} from "../support/helpers/daemon-lifecycle";
|
||||
|
||||
// Page setup takes up to 30 s, then a restart can take DAEMON_RESTART_TIMEOUT_MS to confirm.
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
test("settings restart waits for a replacement worker while retaining the supervisor", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -131,11 +131,6 @@ test.describe("Running indicators", () => {
|
||||
test.setTimeout(180_000);
|
||||
const scene = await openIdleChatBesideRunningAgent(page);
|
||||
try {
|
||||
// Once the chat has settled, nothing but rings is moving, so every frame drawn is a ring's.
|
||||
// A 200 ms border-colour transition in the composer can still be running as the chat opens.
|
||||
await expect
|
||||
.poll(async () => new Set(await readAnimatingTargets(page)))
|
||||
.toEqual(new Set(["status-ring"]));
|
||||
const animating = await readAnimatingTargets(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
@@ -148,6 +143,8 @@ test.describe("Running indicators", () => {
|
||||
JSON.stringify({ animating, activity, angles }, null, 2),
|
||||
);
|
||||
|
||||
// Nothing but rings is moving, so every frame drawn is a ring's.
|
||||
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
|
||||
expect
|
||||
.soft(activity.compositorFramesPerSecond)
|
||||
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
|
||||
|
||||
@@ -33,13 +33,9 @@ import {
|
||||
expectHostPageVisible,
|
||||
seedSavedSettingsHosts,
|
||||
selectSettingsHost,
|
||||
expectNoHostRefusalSheet,
|
||||
expectHostRefusalSheet,
|
||||
dismissHostRefusalSheet,
|
||||
expectHostPasswordRefusalInline,
|
||||
reopenHostPasswordRefusalSheet,
|
||||
submitHostRefusalPassword,
|
||||
expectHostRefusalPasswordError,
|
||||
expectHostRejectedWithReAddGuidance,
|
||||
expectNoHostPasswordControls,
|
||||
removeHostFromHostPage,
|
||||
addDirectHostFromSettings,
|
||||
expectAddHostFieldDrawnAsInput,
|
||||
selectHostConnectionType,
|
||||
@@ -115,7 +111,7 @@ test.describe("Settings host page", () => {
|
||||
await expect(updateButton).toBeEnabled();
|
||||
});
|
||||
|
||||
test("a saved host rejected for its password reconnects in place from its settings page", async ({
|
||||
test("a host rejected for its password reconnects after being removed and added again with it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e host password";
|
||||
@@ -137,29 +133,16 @@ test.describe("Settings host page", () => {
|
||||
]);
|
||||
await page.reload();
|
||||
await openSettings(page);
|
||||
await openClientHostSettings(page, daemon.serverId);
|
||||
|
||||
await test.step("background refusal stays quiet until the host page is opened", async () => {
|
||||
await expectNoHostRefusalSheet(page);
|
||||
await openClientHostSettings(page, daemon.serverId);
|
||||
await expectHostRefusalSheet(page, {
|
||||
title: "Password required",
|
||||
hostLabel: "Password host",
|
||||
});
|
||||
await test.step("the host page shows the reason and the re-add guidance, with no password UI", async () => {
|
||||
await expectHostRejectedWithReAddGuidance(page, "Password required");
|
||||
await expectNoHostPasswordControls(page);
|
||||
});
|
||||
|
||||
await test.step("dismissing leaves an inline password prompt that reopens the sheet", async () => {
|
||||
await dismissHostRefusalSheet(page);
|
||||
await expectHostPasswordRefusalInline(page, "Password required");
|
||||
await reopenHostPasswordRefusalSheet(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password stays inline and the right password brings the host online", async () => {
|
||||
await submitHostRefusalPassword(page, "wrong password");
|
||||
await expectHostRefusalPasswordError(page, "Incorrect password");
|
||||
await submitHostRefusalPassword(page, password);
|
||||
await expectNoHostRefusalSheet(page);
|
||||
await expect(page.getByTestId("host-connection-error")).toHaveCount(0);
|
||||
await selectSettingsHost(page, daemon.serverId);
|
||||
await test.step("removing the host and adding it again with the password brings it online", async () => {
|
||||
await removeHostFromHostPage(page, daemon.serverId);
|
||||
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port, password });
|
||||
await openHostSection(page, daemon.serverId, "daemon");
|
||||
await expectHostOnlineWithoutError(page);
|
||||
});
|
||||
@@ -354,20 +337,6 @@ test("Add host draws its text fields as bordered inputs", async ({ page }) => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Space toggles the focused Use SSL checkbox in the direct host form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSidebarAddHost(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
const checkbox = page.getByRole("checkbox", { name: "Use SSL", exact: true });
|
||||
const initial = await checkbox.isChecked();
|
||||
await checkbox.focus();
|
||||
await checkbox.press("Space");
|
||||
await expect(checkbox).toBeChecked({ checked: !initial });
|
||||
await expect(checkbox).toBeFocused();
|
||||
await checkbox.press("Space");
|
||||
await expect(checkbox).toBeChecked({ checked: initial });
|
||||
});
|
||||
|
||||
test("sidebar Add host completes without navigating", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await expect(page).toHaveURL(/\/open-project$/);
|
||||
|
||||
@@ -33,20 +33,16 @@ export async function restartDaemonInSettings(
|
||||
await expect(page.getByRole("button", { name: "Restarting...", exact: true })).toBeDisabled();
|
||||
}
|
||||
|
||||
// The app reads the replacement worker only after it reconnects. Reconnect attempts back off
|
||||
// (1.5 s doubling to a 30 s cap), so the result can trail a ready worker by up to 30 s.
|
||||
export const DAEMON_RESTART_TIMEOUT_MS = 75_000;
|
||||
|
||||
export async function expectDaemonRestartFailed(page: Page, text: string) {
|
||||
const error = page.getByTestId("host-page-restart-error");
|
||||
await expect(error).toBeVisible({ timeout: DAEMON_RESTART_TIMEOUT_MS });
|
||||
await expect(error).toBeVisible({ timeout: 30_000 });
|
||||
await expect(error).toContainText(text);
|
||||
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled();
|
||||
}
|
||||
|
||||
export async function expectDaemonRestartComplete(page: Page) {
|
||||
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled({
|
||||
timeout: DAEMON_RESTART_TIMEOUT_MS,
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -712,47 +712,27 @@ export async function expectLocalHostEntryFirst(page: Page, _serverId: string):
|
||||
await expect(picker.getByText(TEST_HOST_LABEL, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectNoHostRefusalSheet(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectHostRefusalSheet(
|
||||
export async function expectHostRejectedWithReAddGuidance(
|
||||
page: Page,
|
||||
expected: { title: string; hostLabel: string },
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
const sheet = page.getByTestId("host-refusal-sheet");
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(sheet.getByTestId("host-refusal-sheet-title")).toHaveText(expected.title);
|
||||
await expect(sheet.getByTestId("host-refusal-sheet-host")).toHaveText(expected.hostLabel);
|
||||
}
|
||||
|
||||
export async function dismissHostRefusalSheet(page: Page): Promise<void> {
|
||||
await page.getByTestId("host-refusal-sheet-dismiss").click();
|
||||
await expectNoHostRefusalSheet(page);
|
||||
}
|
||||
|
||||
export async function expectHostPasswordRefusalInline(page: Page, reason: string): Promise<void> {
|
||||
const error = page.getByTestId("host-connection-error");
|
||||
await expect(error).toContainText(reason);
|
||||
await expect(error.getByRole("button", { name: "Enter password", exact: true })).toBeVisible();
|
||||
await expect(error).toContainText(
|
||||
"Remove this host and add it again with the password this daemon asks for.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function reopenHostPasswordRefusalSheet(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("host-connection-error")
|
||||
.getByRole("button", { name: "Enter password", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
|
||||
export async function expectNoHostPasswordControls(page: Page): Promise<void> {
|
||||
await expect(page.getByText("Password", { exact: true })).toHaveCount(0);
|
||||
await expect(page.locator('input[type="password"]')).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: /password/i })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function submitHostRefusalPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByTestId("host-password-input").fill(password);
|
||||
await page.getByTestId("host-refusal-sheet-submit").click();
|
||||
}
|
||||
|
||||
export async function expectHostRefusalPasswordError(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("host-password-field")).toContainText(message);
|
||||
export async function removeHostFromHostPage(page: Page, serverId: string): Promise<void> {
|
||||
await page.getByTestId("host-page-remove-host-button").click();
|
||||
await page.getByTestId("remove-host-confirm").click();
|
||||
await expect(page).not.toHaveURL(new RegExp(`/settings/(hosts|device-hosts)/${serverId}`));
|
||||
}
|
||||
|
||||
export async function expectHostOnlineWithoutError(page: Page): Promise<void> {
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
resolveDesktopDivisionLayout,
|
||||
} from "@/window-layout";
|
||||
import { AddHostProvider, AddHostFlowHost } from "@/hosts/add-host";
|
||||
import { HostRefusalSheetHost } from "@/hosts/host-refusal-sheet";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useIsExplorerSidebarOpen } from "@/workspace-tabs/explorer-sidebar";
|
||||
@@ -532,7 +531,6 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<HostRefusalSheetHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { useLocalSearchParams, useRouter, type Href } from "expo-router";
|
||||
import { useIsFocused } from "expo-router/react-navigation";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { resolveAgentRoute, type AgentRouteLookup } from "@/navigation/agent-route-resolution";
|
||||
import { AgentRouteResolutionView } from "@/navigation/agent-route-resolution-view";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useHasHydratedWorkspaces } from "@/stores/session-store-hooks";
|
||||
import { useDirectoryDemand } from "@/hooks/use-directory-demand";
|
||||
import { useWorkspaceLayoutStoreHydrated } from "@/stores/workspace-layout-store";
|
||||
@@ -25,14 +23,13 @@ export default function HostAgentReadyRoute() {
|
||||
|
||||
function HostAgentReadyRouteContent() {
|
||||
const router = useRouter();
|
||||
const isRouteFocused = useIsFocused();
|
||||
const params = useLocalSearchParams<{
|
||||
serverId?: string;
|
||||
agentId?: string;
|
||||
}>();
|
||||
const handledNavigationRef = useRef<string | null>(null);
|
||||
const serverId = readStringParam(params.serverId);
|
||||
const agentId = readStringParam(params.agentId);
|
||||
const serverId = typeof params.serverId === "string" ? params.serverId : "";
|
||||
const agentId = typeof params.agentId === "string" ? params.agentId : "";
|
||||
const hosts = useHosts();
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const client = runtimeSnapshot?.client ?? null;
|
||||
@@ -50,13 +47,9 @@ function HostAgentReadyRouteContent() {
|
||||
.prepareAgentRoute(serverId, agentId)
|
||||
.catch(() => undefined);
|
||||
}, [agentId, agentWorkspaceId, serverId]);
|
||||
const shouldLookupAgent = canLookupAgentRoute({
|
||||
serverId,
|
||||
agentId,
|
||||
hasClient: client !== null,
|
||||
connectionStatus,
|
||||
agentWorkspaceId,
|
||||
});
|
||||
const shouldLookupAgent = Boolean(
|
||||
serverId && agentId && client && connectionStatus === "online" && !agentWorkspaceId,
|
||||
);
|
||||
const lookupQuery = useFetchQuery({
|
||||
queryKey: ["agentRouteResolution", serverId, agentId, runtimeSnapshot?.clientGeneration ?? 0],
|
||||
queryFn: async () => {
|
||||
@@ -105,10 +98,16 @@ function HostAgentReadyRouteContent() {
|
||||
connectionStatus,
|
||||
lookup,
|
||||
});
|
||||
useActiveRefusalHost(serverId, isRouteFocused && isVisibleAgentRouteResolution(resolution));
|
||||
|
||||
useEffect(() => {
|
||||
const navigationKey = resolveAgentRouteNavigationKey(resolution);
|
||||
let navigationKey: string | null = null;
|
||||
if (resolution.kind === "invalid") {
|
||||
navigationKey = "invalid";
|
||||
} else if (resolution.kind === "resolved") {
|
||||
navigationKey = `workspace:${resolution.workspaceId}`;
|
||||
} else if (resolution.kind === "notFound") {
|
||||
navigationKey = "not-found";
|
||||
}
|
||||
if (!navigationKey || handledNavigationRef.current === navigationKey) {
|
||||
return;
|
||||
}
|
||||
@@ -127,7 +126,7 @@ function HostAgentReadyRouteContent() {
|
||||
return;
|
||||
}
|
||||
if (serverId) {
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId);
|
||||
}
|
||||
}, [lookupQuery, resolution.kind, serverId]);
|
||||
const handleManageHost = useCallback(() => {
|
||||
@@ -143,16 +142,18 @@ function HostAgentReadyRouteContent() {
|
||||
router.replace(serverId ? buildHostRootRoute(serverId) : ("/" as Href));
|
||||
}, [router, serverId]);
|
||||
|
||||
if (isVisibleAgentRouteResolution(resolution)) {
|
||||
if (
|
||||
resolution.kind === "waitingForHost" ||
|
||||
resolution.kind === "fetchingAgent" ||
|
||||
resolution.kind === "lookupError"
|
||||
) {
|
||||
// Agent URLs intentionally omit workspaceId. Keep this route mounted while the target host
|
||||
// reconnects, then resolve the workspace from the authoritative agent record.
|
||||
return (
|
||||
<AgentRouteResolutionView
|
||||
serverId={serverId}
|
||||
resolution={resolution}
|
||||
hostName={hostName}
|
||||
lastHostError={runtimeSnapshot?.lastError ?? null}
|
||||
helloRejection={runtimeSnapshot?.helloRejection ?? null}
|
||||
onRetry={handleRetry}
|
||||
onManageHost={handleManageHost}
|
||||
onBack={handleBack}
|
||||
@@ -162,45 +163,3 @@ function HostAgentReadyRouteContent() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readStringParam(value: string | undefined): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function canLookupAgentRoute(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
hasClient: boolean;
|
||||
connectionStatus: string;
|
||||
agentWorkspaceId: string | null;
|
||||
}): boolean {
|
||||
return Boolean(
|
||||
input.serverId &&
|
||||
input.agentId &&
|
||||
input.hasClient &&
|
||||
input.connectionStatus === "online" &&
|
||||
!input.agentWorkspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveAgentRouteNavigationKey(
|
||||
resolution: ReturnType<typeof resolveAgentRoute>,
|
||||
): string | null {
|
||||
if (resolution.kind === "invalid") return "invalid";
|
||||
if (resolution.kind === "resolved") return `workspace:${resolution.workspaceId}`;
|
||||
if (resolution.kind === "notFound") return "not-found";
|
||||
return null;
|
||||
}
|
||||
|
||||
function isVisibleAgentRouteResolution(
|
||||
resolution: ReturnType<typeof resolveAgentRoute>,
|
||||
): resolution is Extract<
|
||||
ReturnType<typeof resolveAgentRoute>,
|
||||
{ kind: "waitingForHost" | "fetchingAgent" | "lookupError" }
|
||||
> {
|
||||
return (
|
||||
resolution.kind === "waitingForHost" ||
|
||||
resolution.kind === "fetchingAgent" ||
|
||||
resolution.kind === "lookupError"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,19 +84,4 @@ describe("direct connection failure copy", () => {
|
||||
}),
|
||||
).toMatchObject({ detail: message, raw: message });
|
||||
});
|
||||
|
||||
it("preserves non-password hello rejections without falling back to generic unableToConnect", () => {
|
||||
const message = "Incompatible protocol version";
|
||||
expect(
|
||||
buildConnectionFailureCopy({
|
||||
endpoint: "example.test:6767",
|
||||
error: new DaemonConnectionTestError(message, {
|
||||
reason: message,
|
||||
lastError: message,
|
||||
helloRejection: { reason: "incompatible_protocol", accepts: [] },
|
||||
}),
|
||||
labels,
|
||||
}),
|
||||
).toMatchObject({ detail: message, raw: message });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
DaemonConnectionTestError,
|
||||
getConnectionHelloRejection,
|
||||
getConnectionAuthFailureReason,
|
||||
} from "@/utils/test-daemon-connection";
|
||||
|
||||
interface ConnectionFailureLabels {
|
||||
@@ -73,7 +73,7 @@ export function buildConnectionFailureCopy(input: {
|
||||
const rawLower = raw?.toLowerCase() ?? "";
|
||||
let detail: string | null = null;
|
||||
|
||||
if (getConnectionHelloRejection(error)) {
|
||||
if (getConnectionAuthFailureReason(error)) {
|
||||
detail = error instanceof Error ? error.message : raw;
|
||||
} else if (rawLower.includes("timed out")) {
|
||||
detail = labels.timedOut;
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { View } from "react-native";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "./loop.web";
|
||||
import { INDICATOR_STEP_MS } from "./steps";
|
||||
|
||||
// A ring and a shimmer: two stepped loops of different lengths on the step grid, one counted from
|
||||
// the timeline's origin and one from the step it started in.
|
||||
const RING: IndicatorLoop = {
|
||||
keyframes: [
|
||||
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
|
||||
{ transform: "rotate(360deg)" },
|
||||
],
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
phase: "shared",
|
||||
};
|
||||
const SHIMMER_STEPS = 42;
|
||||
const SHIMMER: IndicatorLoop = {
|
||||
keyframes: [
|
||||
{ transform: "translateX(-100px)", easing: `steps(${SHIMMER_STEPS})` },
|
||||
{ transform: "translateX(300px)" },
|
||||
],
|
||||
durationMs: SHIMMER_STEPS * INDICATOR_STEP_MS,
|
||||
phase: "own",
|
||||
};
|
||||
|
||||
function Indicators() {
|
||||
const ringRef = useIndicatorLoop(RING);
|
||||
const shimmerRef = useIndicatorLoop(SHIMMER);
|
||||
return (
|
||||
<>
|
||||
<View ref={ringRef} testID="ring" />
|
||||
<View ref={shimmerRef} testID="shimmer" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mountIndicators(): { ring: Animation; shimmer: Animation } {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root!.render(<Indicators />));
|
||||
const animationOf = (testId: string) => {
|
||||
const element = container.querySelector(`[data-testid="${testId}"]`);
|
||||
const animation = element?.getAnimations()[0];
|
||||
if (!animation) throw new Error(`${testId} is not animating`);
|
||||
return animation;
|
||||
};
|
||||
return { ring: animationOf("ring"), shimmer: animationOf("shimmer") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps through every timeline time, on the microsecond marks a browser stamps frames at, around
|
||||
* each of the grid's next `boundaries` step boundaries. Reports how often each loop turned over and
|
||||
* the times at which one of the two turned over and the other did not.
|
||||
*/
|
||||
function sweepBoundaries(
|
||||
loops: { ring: Animation; shimmer: Animation },
|
||||
boundaries: number,
|
||||
): { ringTurnovers: number; shimmerTurnovers: number; turningOneLoop: number[] } {
|
||||
const elements = {
|
||||
ring: loops.ring.effect as KeyframeEffect,
|
||||
shimmer: loops.shimmer.effect as KeyframeEffect,
|
||||
};
|
||||
const startTimes = {
|
||||
ring: Number(loops.ring.startTime),
|
||||
shimmer: Number(loops.shimmer.startTime),
|
||||
};
|
||||
loops.ring.pause();
|
||||
loops.shimmer.pause();
|
||||
const showAt = (timelineMs: number) => {
|
||||
loops.ring.currentTime = timelineMs - startTimes.ring;
|
||||
loops.shimmer.currentTime = timelineMs - startTimes.shimmer;
|
||||
return {
|
||||
ring: getComputedStyle(elements.ring.target!).transform,
|
||||
shimmer: getComputedStyle(elements.shimmer.target!).transform,
|
||||
};
|
||||
};
|
||||
|
||||
const firstStep = Math.ceil(startTimes.shimmer / INDICATOR_STEP_MS) + 1;
|
||||
const turnovers = { ringTurnovers: 0, shimmerTurnovers: 0, turningOneLoop: [] as number[] };
|
||||
for (let step = firstStep; step < firstStep + boundaries; step += 1) {
|
||||
const boundaryUs = Math.round(step * INDICATOR_STEP_MS * 1000);
|
||||
let previous = showAt((boundaryUs - 20) / 1000);
|
||||
for (let frameUs = boundaryUs - 19; frameUs <= boundaryUs + 20; frameUs += 1) {
|
||||
const current = showAt(frameUs / 1000);
|
||||
const ringTurned = current.ring !== previous.ring;
|
||||
const shimmerTurned = current.shimmer !== previous.shimmer;
|
||||
if (ringTurned) turnovers.ringTurnovers += 1;
|
||||
if (shimmerTurned) turnovers.shimmerTurnovers += 1;
|
||||
if (ringTurned !== shimmerTurned) {
|
||||
turnovers.turningOneLoop.push(frameUs / 1000);
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
return turnovers;
|
||||
}
|
||||
|
||||
it("turns loops of different lengths over on the same frame, whenever the frame is stamped", () => {
|
||||
const loops = mountIndicators();
|
||||
|
||||
// Each loop turns over once at every boundary, and never on a frame without the other.
|
||||
expect(sweepBoundaries(loops, 300)).toEqual({
|
||||
ringTurnovers: 300,
|
||||
shimmerTurnovers: 300,
|
||||
turningOneLoop: [],
|
||||
});
|
||||
});
|
||||
@@ -2,14 +2,7 @@ import { useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { INDICATOR_STEP_MS } from "./steps";
|
||||
|
||||
// Where the step grid starts on the document timeline. Browsers stamp a frame at a whole number of
|
||||
// microseconds, often coarsened to 5 or 100. Each loop works out a step boundary from its own
|
||||
// duration, so floating-point rounding can put a boundary that falls exactly on a frame's stamp
|
||||
// before that frame for one loop and after it for another: the two then turn over on consecutive
|
||||
// frames, and the window draws one more. Every third boundary of a grid from 0 is a whole number of
|
||||
// milliseconds and so falls on a stamp. Starting the grid 2.5 µs in keeps every boundary at least
|
||||
// a sixth of a microsecond from any stamp, far beyond the rounding.
|
||||
const STEP_GRID_ORIGIN_MS = 0.0025;
|
||||
const TIMELINE_ORIGIN_MS = 0;
|
||||
|
||||
export interface IndicatorLoop {
|
||||
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
|
||||
@@ -17,7 +10,7 @@ export interface IndicatorLoop {
|
||||
durationMs: number;
|
||||
/**
|
||||
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
|
||||
* the loop counts from the step grid's origin instead of from its own start. `own` starts
|
||||
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
|
||||
* the cycle at the step of the indicator step grid the loop starts in, so a stepped loop turns
|
||||
* over with every other; see `steps.ts`.
|
||||
*/
|
||||
@@ -26,8 +19,8 @@ export interface IndicatorLoop {
|
||||
|
||||
// The start of the step of the indicator step grid the document timeline is in now.
|
||||
function currentStepStartMs(): number {
|
||||
const sinceOrigin = Number(document.timeline.currentTime ?? 0) - STEP_GRID_ORIGIN_MS;
|
||||
return STEP_GRID_ORIGIN_MS + Math.floor(sinceOrigin / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
|
||||
const now = Number(document.timeline.currentTime ?? 0);
|
||||
return Math.floor(now / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,7 +47,7 @@ export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | n
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
// An explicit start also keeps loops that start in the same commit exactly together.
|
||||
animation.startTime = loop.phase === "shared" ? STEP_GRID_ORIGIN_MS : currentStepStartMs();
|
||||
animation.startTime = loop.phase === "shared" ? TIMELINE_ORIGIN_MS : currentStepStartMs();
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
|
||||
@@ -497,30 +497,6 @@ it("recognizes forge references in prose but not in code, links or paths", async
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["见 src/app/main.ts,还有", ["src/app/main.ts"]],
|
||||
["改了 src/a/b/c,然后", ["src/a/b/c"]],
|
||||
["src/foo.ts、src/bar.ts", ["src/foo.ts", "src/bar.ts"]],
|
||||
["查看:docs/说明.md:12。", ["docs/说明.md:12"]],
|
||||
["see src/app/main.ts, ok", ["src/app/main.ts"]],
|
||||
])("recognizes bare file paths next to sentence punctuation: %s", async (source, expected) => {
|
||||
const prepared = prepareMarkdownSource(source, "/repo");
|
||||
const tree = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), { latexMath: false }),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const parts = tree.children?.[0]?.children ?? [];
|
||||
expect(parts.map((node) => node.content ?? node.children?.[0]?.content).join("")).toBe(source);
|
||||
expect(parts.filter((node) => node.type === "Link").map((node) => node.attributes?.url)).toEqual(
|
||||
expected,
|
||||
);
|
||||
expect(toNativeLinkRecognition(prepared.linkRecognition).text).toMatchObject({
|
||||
isDisabled: false,
|
||||
isDefault: false,
|
||||
});
|
||||
});
|
||||
|
||||
describe("bare URL sentence punctuation", () => {
|
||||
it.each([".", ",", ";", ":", "!", "?", ")", ").", "...", "?!"])(
|
||||
"leaves %s outside the link and preserves the rendered sentence",
|
||||
@@ -1251,18 +1227,6 @@ it.each([
|
||||
).toEqual([token]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["更正此前的进度说明:A/B/C/D 主实验", ["A/B/C/D"]],
|
||||
["修改:src/index.ts,然后提交。", ["src/index.ts"]],
|
||||
["见(docs/说明.md)。", ["docs/说明.md"]],
|
||||
["参考「src/index.ts:12」、「README.md」", ["src/index.ts:12", "README.md"]],
|
||||
["“./scripts/run”…", ["./scripts/run"]],
|
||||
["文档在 docs/说明.md 里", ["docs/说明.md"]],
|
||||
])("ends prose paths at CJK and typographic punctuation: %s", (source, expected) => {
|
||||
const { linkRecognition } = prepareMarkdownSource(source, "/repo");
|
||||
expect([...source.matchAll(linkRecognition.text)].map(([text]) => text)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"before/after",
|
||||
"and/or",
|
||||
|
||||
@@ -9,56 +9,11 @@ import { decodeString } from "micromark-util-decode-string";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import type { Link, Nodes, Paragraph, PhrasingContent, Root } from "mdast";
|
||||
|
||||
// CJK, fullwidth and typographic punctuation (、。,:()【】「」“”…) ends bare URLs and prose
|
||||
// paths; CJK letters do not.
|
||||
const PUNCTUATION_BOUNDARY_RANGES: readonly (readonly [number, number])[] = [
|
||||
[0x2018, 0x2019],
|
||||
[0x201c, 0x201d],
|
||||
[0x2026, 0x2026],
|
||||
[0x3000, 0x3003],
|
||||
[0x3008, 0x3011],
|
||||
[0x3014, 0x301f],
|
||||
[0xff01, 0xff0f],
|
||||
[0xff1a, 0xff20],
|
||||
[0xff3b, 0xff40],
|
||||
[0xff5b, 0xff65],
|
||||
];
|
||||
|
||||
function formatCharacterRanges(ranges: readonly (readonly [number, number])[]): string {
|
||||
const escape = (codePoint: number) =>
|
||||
`\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
|
||||
return ranges
|
||||
.map(([start, end]) => (start === end ? escape(start) : `${escape(start)}-${escape(end)}`))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** The parts of `from`..`to` that no excluded range covers. */
|
||||
function subtractCharacterRanges(
|
||||
from: number,
|
||||
to: number,
|
||||
excluded: readonly (readonly [number, number])[],
|
||||
): [number, number][] {
|
||||
const kept: [number, number][] = [];
|
||||
let next = from;
|
||||
for (const [start, end] of excluded) {
|
||||
if (start > next) kept.push([next, start - 1]);
|
||||
next = end + 1;
|
||||
}
|
||||
if (next <= to) kept.push([next, to]);
|
||||
return kept;
|
||||
}
|
||||
|
||||
const URL_BOUNDARY = formatCharacterRanges(PUNCTUATION_BOUNDARY_RANGES);
|
||||
// Non-ASCII characters a path can contain: everything from U+0080 except boundary punctuation.
|
||||
const PATH_NON_ASCII = formatCharacterRanges(
|
||||
subtractCharacterRanges(0x80, 0xffff, PUNCTUATION_BOUNDARY_RANGES),
|
||||
);
|
||||
|
||||
// Keep this regex in the syntax shared by JavaScript, ICU and java.util.regex.
|
||||
// The Unicode flag makes Metro expand it to escapes rejected by native engines.
|
||||
const PATH_CHARACTER = String.raw`[a-zA-Z0-9${PATH_NON_ASCII}_@.%+-]`;
|
||||
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\uFFFF_@.%+-]`;
|
||||
const PATH_LETTER = String.raw`[a-zA-Z]`;
|
||||
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9${PATH_NON_ASCII}_@%+-]`;
|
||||
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\uFFFF_@%+-]`;
|
||||
const LINE_SUFFIX = String.raw`(?::\d+(?::\d+)?(?:-\d+(?::\d+)?)?)?`;
|
||||
const FILE_EXTENSIONS = [...ASSISTANT_FILE_EXTENSIONS]
|
||||
.map((extension) => extension.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`))
|
||||
@@ -75,13 +30,16 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp
|
||||
const forgeReference = forgeReferencePattern ? `|${forgeReferencePattern}` : "";
|
||||
// The native adapter mistakes a literal + in lookbehind for a quantifier; use its hex escape.
|
||||
return new RegExp(
|
||||
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9${PATH_NON_ASCII}_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9${PATH_NON_ASCII}_@%+:/\\-]|\.${PATH_CHARACTER}))`,
|
||||
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
|
||||
"g",
|
||||
);
|
||||
}
|
||||
|
||||
// Matches bare URLs that MD4C does not autolink, like single-label or bracketed hosts.
|
||||
// Quotes and unbalanced closing parentheses end the URL. Trailing sentence punctuation stays outside.
|
||||
// CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) also ends it; CJK letters do not.
|
||||
const URL_BOUNDARY =
|
||||
"\\u2018\\u2019\\u201C\\u201D\\u2026\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65";
|
||||
const URL_CHARACTER = String.raw`[^\s<>()"'\x60${URL_BOUNDARY}]`;
|
||||
const URL_GROUP = String.raw`\(${URL_CHARACTER}*\)`;
|
||||
const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?${URL_BOUNDARY}]|${URL_GROUP})`;
|
||||
|
||||
@@ -18,21 +18,6 @@ export function Checkbox({ checked }: { checked: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** React Native Web checkboxes need an explicit Space handler when built on Pressable. */
|
||||
export function useCheckboxSpaceKey(onToggle: () => void, disabled: boolean) {
|
||||
return useMemo(() => {
|
||||
if (!isWeb || disabled) return {};
|
||||
return {
|
||||
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
onToggle();
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [disabled, onToggle]);
|
||||
}
|
||||
|
||||
interface HoverState {
|
||||
hovered?: boolean;
|
||||
}
|
||||
@@ -63,7 +48,18 @@ export function CheckboxRow({
|
||||
({ hovered }: HoverState) => [style, hovered && !disabled ? styles.hovered : null],
|
||||
[disabled, style],
|
||||
);
|
||||
const keyProps = useCheckboxSpaceKey(onToggle, disabled);
|
||||
const keyProps = useMemo(() => {
|
||||
if (!isWeb || disabled) return {};
|
||||
return {
|
||||
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
onToggle();
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [disabled, onToggle]);
|
||||
|
||||
return (
|
||||
<PressHighlight
|
||||
|
||||
@@ -2,9 +2,8 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createJSONStorage, type StateStorage } from "zustand/middleware";
|
||||
import { mountBrowserAutomationHandler, type BrowserAutomationHandlerOptions } from "./handler";
|
||||
import type { DesktopAutomationExecutionContext, DesktopHostBridge } from "@/desktop/host";
|
||||
import type { DesktopHostBridge } from "@/desktop/host";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { findPaneById } from "@/stores/workspace-layout-actions";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
@@ -73,11 +72,9 @@ class FakeDaemonClient {
|
||||
|
||||
class FakeBrowserBridge {
|
||||
public readonly executedRequests: BrowserAutomationExecuteRequest[] = [];
|
||||
public readonly executedContexts: DesktopAutomationExecutionContext[] = [];
|
||||
public readonly unregisteredWorkspaceBrowsers: string[] = [];
|
||||
public readonly activeWorkspaceBrowsers: Array<{
|
||||
browserId: string | null;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}> = [];
|
||||
public response: BrowserAutomationResponsePayload | null = null;
|
||||
@@ -85,10 +82,8 @@ class FakeBrowserBridge {
|
||||
|
||||
public executeAutomationCommand = async (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
): Promise<BrowserAutomationResponsePayload> => {
|
||||
this.executedRequests.push(request);
|
||||
this.executedContexts.push(context);
|
||||
if (this.thrownError) {
|
||||
throw this.thrownError;
|
||||
}
|
||||
@@ -101,7 +96,6 @@ class FakeBrowserBridge {
|
||||
|
||||
public setWorkspaceActiveBrowser = async (input: {
|
||||
browserId: string | null;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): Promise<void> => {
|
||||
this.activeWorkspaceBrowsers.push(input);
|
||||
@@ -111,7 +105,6 @@ class FakeBrowserBridge {
|
||||
class FakeResidentBrowser {
|
||||
public readonly ensuredWebviews: Array<{
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -119,7 +112,6 @@ class FakeResidentBrowser {
|
||||
|
||||
public ensure = (input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -139,22 +131,20 @@ class BrowserAutomationHandlerHarness {
|
||||
input: {
|
||||
serverId?: string;
|
||||
host?: DesktopHostBridge | null;
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"] | null;
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"];
|
||||
prepareHostBrowserPartition?: BrowserAutomationHandlerOptions["prepareHostBrowserPartition"];
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
} = {},
|
||||
): void {
|
||||
const readHostBrowserRouting =
|
||||
input.readHostBrowserRouting === null
|
||||
? undefined
|
||||
: (input.readHostBrowserRouting ?? (() => ({ kind: "local" as const })));
|
||||
this.unsubscribe = mountBrowserAutomationHandler({
|
||||
client: this.client,
|
||||
...(input.serverId ? { serverId: input.serverId } : {}),
|
||||
getHost: () => (input.host === undefined ? { browser: this.browser } : input.host),
|
||||
ensureResidentBrowserWebview: this.resident.ensure,
|
||||
...(readHostBrowserRouting ? { readHostBrowserRouting } : {}),
|
||||
...(input.readHostBrowserRouting
|
||||
? { readHostBrowserRouting: input.readHostBrowserRouting }
|
||||
: {}),
|
||||
...(input.prepareHostBrowserPartition
|
||||
? { prepareHostBrowserPartition: input.prepareHostBrowserPartition }
|
||||
: {}),
|
||||
@@ -177,14 +167,10 @@ class BrowserAutomationHandlerHarness {
|
||||
}
|
||||
}
|
||||
|
||||
function browserAutomationRequest(input?: {
|
||||
workspaceId?: string;
|
||||
}): BrowserAutomationExecuteRequest {
|
||||
const workspaceId = input && "workspaceId" in input ? input.workspaceId : "wks_workspace_a";
|
||||
function browserAutomationRequest(): BrowserAutomationExecuteRequest {
|
||||
return {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-1",
|
||||
...(workspaceId ? { workspaceId } : {}),
|
||||
command: { command: "list_tabs", args: {} },
|
||||
};
|
||||
}
|
||||
@@ -308,7 +294,6 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
browserAutomationStorage.clear();
|
||||
useBrowserStore.setState({ browsersById: {} });
|
||||
useWorkspaceLayoutStore.setState({ layoutByWorkspace: {} });
|
||||
useSessionStore.setState({ sessions: {} });
|
||||
});
|
||||
|
||||
test("browser_new_tab creates a workspace browser tab without stealing focus", async () => {
|
||||
@@ -353,7 +338,6 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
serverId: "server-1",
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "https://example.com",
|
||||
},
|
||||
@@ -559,14 +543,13 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
ok: true,
|
||||
result: { command: "list_tabs", tabs: [] },
|
||||
};
|
||||
browser.mount({ serverId: "server-1" });
|
||||
browser.mount();
|
||||
const request = browserAutomationRequest();
|
||||
|
||||
browser.receive(request);
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.browser.executedRequests).toEqual([request]);
|
||||
expect(browser.browser.executedContexts).toEqual([{ serverId: "server-1", uploadRoot: null }]);
|
||||
expect(browser.client.sentResponses).toEqual([
|
||||
{
|
||||
type: "browser.automation.execute.response",
|
||||
@@ -581,7 +564,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
|
||||
test("missing desktop bridge sends browser_unsupported", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1", host: null });
|
||||
browser.mount({ host: null });
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -609,7 +592,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
message: "Browser tab browser-1 was not found.",
|
||||
retryable: false,
|
||||
};
|
||||
browser.mount({ serverId: "server-1" });
|
||||
browser.mount();
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -635,7 +618,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
browser.browser.thrownError = new Error(
|
||||
'No handler registered for "paseo:browser:execute-automation-command"',
|
||||
);
|
||||
browser.mount({ serverId: "server-1" });
|
||||
browser.mount();
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -658,7 +641,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
|
||||
test("unsubscribe stops handling browser automation requests", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
browser.mount();
|
||||
|
||||
browser.unmount();
|
||||
browser.receive(browserAutomationRequest());
|
||||
@@ -697,7 +680,6 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
serverId: "remote-1",
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "http://localhost:5173",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
@@ -705,165 +687,6 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("browser_resize fails closed when workspaceId is omitted", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserNewTabRequest());
|
||||
await vi.waitFor(() => expect(browser.client.sentResponses).toHaveLength(1));
|
||||
const result = newTabResultFrom(browser.client.payloadAt(0));
|
||||
|
||||
browser.receive({
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-resize-no-ws",
|
||||
agentId: "agent-1",
|
||||
command: {
|
||||
command: "resize",
|
||||
args: { browserId: result.browserId, width: 800, height: 600 },
|
||||
},
|
||||
});
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.client.payloadAt(1)).toEqual({
|
||||
requestId: "req-resize-no-ws",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_denied",
|
||||
message: expect.stringMatching(/workspace/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(useBrowserStore.getState().browsersById[result.browserId]?.viewport).toEqual({
|
||||
mode: "responsive",
|
||||
});
|
||||
});
|
||||
|
||||
test("forwarded commands fail closed when workspaceId is omitted", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserAutomationRequest({ workspaceId: "" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.browser.executedRequests).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toEqual({
|
||||
requestId: "req-1",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_denied",
|
||||
message: expect.stringMatching(/workspace/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("passes uploadRoot from session-store for local hosts and null for remote hosts", async () => {
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession("local-1", null);
|
||||
store.mergeWorkspaces("local-1", [
|
||||
{
|
||||
id: "wks_workspace_a",
|
||||
projectId: "proj-1",
|
||||
projectDisplayName: "Project",
|
||||
projectRootPath: "/Users/dev/project",
|
||||
workspaceDirectory: "/Users/dev/project",
|
||||
projectKind: "git",
|
||||
workspaceKind: "directory",
|
||||
name: "Project",
|
||||
title: "Project",
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
},
|
||||
]);
|
||||
store.initializeSession("remote-1", null);
|
||||
store.mergeWorkspaces("remote-1", [
|
||||
{
|
||||
id: "wks_workspace_a",
|
||||
projectId: "proj-2",
|
||||
projectDisplayName: "Remote Project",
|
||||
projectRootPath: "/home/remote/project",
|
||||
workspaceDirectory: "/home/remote/project",
|
||||
projectKind: "git",
|
||||
workspaceKind: "directory",
|
||||
name: "Remote Project",
|
||||
title: "Remote Project",
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const uploadRequest: BrowserAutomationExecuteRequest = {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-upload",
|
||||
workspaceId: "wks_workspace_a",
|
||||
cwd: "/Users/dev/project",
|
||||
command: {
|
||||
command: "upload",
|
||||
args: {
|
||||
browserId: "11111111-1111-4111-8111-111111111111",
|
||||
ref: "@e1",
|
||||
filePaths: ["a.txt"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const localHarness = new BrowserAutomationHandlerHarness();
|
||||
localHarness.mount({
|
||||
serverId: "local-1",
|
||||
readHostBrowserRouting: () => ({ kind: "local" }),
|
||||
});
|
||||
localHarness.receive(uploadRequest);
|
||||
await flushAsyncWork();
|
||||
expect(localHarness.browser.executedContexts).toEqual([
|
||||
{ serverId: "local-1", uploadRoot: "/Users/dev/project" },
|
||||
]);
|
||||
|
||||
const remoteHarness = new BrowserAutomationHandlerHarness();
|
||||
remoteHarness.mount({
|
||||
serverId: "remote-1",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
}),
|
||||
});
|
||||
remoteHarness.receive(uploadRequest);
|
||||
await flushAsyncWork();
|
||||
expect(remoteHarness.browser.executedContexts).toEqual([
|
||||
{ serverId: "remote-1", uploadRoot: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test("browser_new_tab on an unhydrated host fails closed without opening a local webview", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
serverId: "unhydrated-host-id",
|
||||
readHostBrowserRouting: null,
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.resident.ensuredWebviews).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toMatchObject({
|
||||
requestId: "req-new",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab fails closed without creating a webview when host proxy cannot prepare", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
getDesktopHost,
|
||||
type DesktopAutomationExecutionContext,
|
||||
type DesktopHostBridge,
|
||||
} from "@/desktop/host";
|
||||
import { getDesktopHost, type DesktopHostBridge } from "@/desktop/host";
|
||||
import {
|
||||
ensureResidentBrowserWebview as ensureResidentBrowserWebviewDefault,
|
||||
removeResidentBrowserWebview,
|
||||
@@ -24,7 +20,6 @@ import {
|
||||
useBrowserStore,
|
||||
waitForBrowserHydration,
|
||||
} from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
|
||||
@@ -218,70 +213,17 @@ async function handleBrowserAutomationRequest(params: {
|
||||
return;
|
||||
}
|
||||
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: await forwardAutomationRequest({
|
||||
request,
|
||||
serverId,
|
||||
executeAutomationCommand,
|
||||
readHostBrowserRouting,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveWorkspaceUploadRoot(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
}): string | null {
|
||||
if (input.readHostBrowserRouting(input.serverId).kind !== "local") {
|
||||
return null;
|
||||
}
|
||||
const directory = useSessionStore
|
||||
.getState()
|
||||
.sessions[input.serverId]?.workspaces.get(input.workspaceId)
|
||||
?.workspaceDirectory?.trim();
|
||||
return directory || null;
|
||||
}
|
||||
|
||||
async function forwardAutomationRequest(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
serverId?: string;
|
||||
executeAutomationCommand: NonNullable<DesktopHostBridge["browser"]>["executeAutomationCommand"];
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
}): Promise<BrowserAutomationResponsePayload> {
|
||||
const { request, serverId, executeAutomationCommand, readHostBrowserRouting } = params;
|
||||
const normalizedServerId = serverId?.trim();
|
||||
const normalizedWorkspaceId = request.workspaceId?.trim();
|
||||
if (!normalizedServerId || !normalizedWorkspaceId) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_denied",
|
||||
message: "Browser automation requires a server and workspace context.",
|
||||
});
|
||||
}
|
||||
if (!executeAutomationCommand) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_unsupported",
|
||||
message: "Browser automation is not available in this app runtime.",
|
||||
});
|
||||
}
|
||||
|
||||
const uploadRoot = resolveWorkspaceUploadRoot({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
readHostBrowserRouting,
|
||||
});
|
||||
|
||||
try {
|
||||
const payload = await executeAutomationCommand(request, {
|
||||
serverId: normalizedServerId,
|
||||
uploadRoot,
|
||||
const payload = await executeAutomationCommand(request);
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: normalizeBridgePayload(request.requestId, payload),
|
||||
});
|
||||
return normalizeBridgePayload(request.requestId, payload);
|
||||
} catch (error) {
|
||||
return normalizeThrownBridgeError(request.requestId, error);
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: normalizeThrownBridgeError(request.requestId, error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,24 +237,16 @@ function resizeBrowserTabForRequest(params: {
|
||||
{ command: "resize" }
|
||||
>;
|
||||
const browserId = command.args.browserId;
|
||||
const normalizedServerId = serverId?.trim();
|
||||
const normalizedWorkspaceId = request.workspaceId?.trim();
|
||||
if (!normalizedServerId || !normalizedWorkspaceId) {
|
||||
if (!getBrowserRecord(browserId)) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_denied",
|
||||
message: "Cannot resize a browser tab without a workspace context.",
|
||||
code: "browser_tab_not_found",
|
||||
message: `No browser tab found for ID: ${browserId}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!findWorkspaceBrowserTab({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
browserId,
|
||||
}) ||
|
||||
!getBrowserRecord(browserId)
|
||||
) {
|
||||
const workspaceId = request.workspaceId;
|
||||
if (serverId && workspaceId && !findWorkspaceBrowserTab({ serverId, workspaceId, browserId })) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_tab_not_found",
|
||||
@@ -500,7 +434,6 @@ async function openBrowserTabForRequest(params: {
|
||||
try {
|
||||
ensureResidentBrowserWebview({
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
url: normalizedUrl,
|
||||
...(targetPartition ? { partition: targetPartition } : {}),
|
||||
@@ -508,7 +441,6 @@ async function openBrowserTabForRequest(params: {
|
||||
registered = await waitForBrowserRegistration({
|
||||
request,
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
executeAutomationCommand: browserHost.executeAutomationCommand,
|
||||
...(registrationWaitTimeoutMs !== undefined
|
||||
@@ -541,31 +473,23 @@ async function openBrowserTabForRequest(params: {
|
||||
async function waitForBrowserRegistration(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
executeAutomationCommand: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
) => Promise<BrowserAutomationResponsePayload>;
|
||||
timeoutMs?: number;
|
||||
pollIntervalMs?: number;
|
||||
}): Promise<boolean> {
|
||||
const deadline = Date.now() + (params.timeoutMs ?? 5_000);
|
||||
while (Date.now() < deadline) {
|
||||
const payload = await params.executeAutomationCommand(
|
||||
{
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: `${params.request.requestId}:list_tabs`,
|
||||
agentId: params.request.agentId,
|
||||
cwd: params.request.cwd,
|
||||
workspaceId: params.workspaceId,
|
||||
command: { command: "list_tabs", args: {} },
|
||||
},
|
||||
{
|
||||
serverId: params.serverId,
|
||||
uploadRoot: null,
|
||||
},
|
||||
);
|
||||
const payload = await params.executeAutomationCommand({
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: `${params.request.requestId}:list_tabs`,
|
||||
agentId: params.request.agentId,
|
||||
cwd: params.request.cwd,
|
||||
workspaceId: params.workspaceId,
|
||||
command: { command: "list_tabs", args: {} },
|
||||
});
|
||||
if (payload.ok && payload.result.command === "list_tabs") {
|
||||
if (payload.result.tabs.some((tab) => tab.browserId === params.browserId)) {
|
||||
return true;
|
||||
|
||||
@@ -774,7 +774,6 @@ function deviceSizeIdForViewport(viewport: BrowserViewport): DeviceSizeId | null
|
||||
|
||||
function acquirePartitionedWebview(input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
initialUrl: string;
|
||||
@@ -792,7 +791,6 @@ function acquirePartitionedWebview(input: {
|
||||
const webview = document.createElement("webview") as ElectronWebview;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId: input.browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.initialUrl,
|
||||
partition: input.partition,
|
||||
@@ -987,7 +985,6 @@ export function BrowserPane({
|
||||
);
|
||||
const webview = acquirePartitionedWebview({
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
partition: activePartition,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : currentUrl,
|
||||
|
||||
@@ -173,27 +173,6 @@ describe("classifyHostBrowserRouting", () => {
|
||||
).toEqual({ kind: "remote", support: "host_connecting" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["idle", "host_connecting"],
|
||||
["connecting", "host_connecting"],
|
||||
["offline", "host_offline"],
|
||||
] as const)(
|
||||
"fails closed when host profile has no saved connections and is %s",
|
||||
(connectionStatus, expectedSupport) => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "unhydrated-host",
|
||||
connections: [],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus,
|
||||
features: null,
|
||||
origin: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: expectedSupport });
|
||||
},
|
||||
);
|
||||
|
||||
it("routes only loopback URLs on supported remote hosts in Electron to a proxied browser tab", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
|
||||
@@ -216,9 +216,9 @@ export function classifyHostBrowserRouting(
|
||||
if (originServerId) {
|
||||
return classifyRoutedHost(host, originServerId, origin);
|
||||
}
|
||||
} else if (connections.some(isLocalHostConnection)) {
|
||||
// No active connection yet (connecting/offline). Classify as local only when saved
|
||||
// connections positively identify a local host; unhydrated or unknown hosts fail closed.
|
||||
} else if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
// No active connection yet (connecting/offline). Distinguish local hosts from remote
|
||||
// hosts using saved connection definitions so remote tabs fail closed during startup.
|
||||
return { kind: "local" };
|
||||
}
|
||||
|
||||
|
||||
@@ -21,9 +21,7 @@ import {
|
||||
const RESIDENT_HOST_ID = "paseo-browser-resident-webviews";
|
||||
const attachedBrowsers: Array<{
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
webContentsId: number;
|
||||
}> = [];
|
||||
const profileHost: BrowserWebviewProfileHost = {
|
||||
@@ -34,13 +32,11 @@ const profileHost: BrowserWebviewProfileHost = {
|
||||
|
||||
function ensureTestBrowser(input: {
|
||||
browserId: string;
|
||||
serverId?: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
}): HTMLElement | null {
|
||||
return ensureResidentBrowserWebview({
|
||||
partition: "persist:paseo-browser",
|
||||
serverId: "server-a",
|
||||
...input,
|
||||
profileHost,
|
||||
});
|
||||
@@ -48,14 +44,9 @@ function ensureTestBrowser(input: {
|
||||
|
||||
function prepareTestBrowser(
|
||||
webview: HTMLElement,
|
||||
input: { browserId: string; serverId?: string; workspaceId: string; initialUrl?: string | null },
|
||||
input: { browserId: string; workspaceId: string; initialUrl?: string | null },
|
||||
): void {
|
||||
prepareBrowserWebview(webview, {
|
||||
partition: "persist:paseo-browser",
|
||||
serverId: "server-a",
|
||||
...input,
|
||||
profileHost,
|
||||
});
|
||||
prepareBrowserWebview(webview, { partition: "persist:paseo-browser", ...input, profileHost });
|
||||
}
|
||||
|
||||
function residentHost(): HTMLElement {
|
||||
@@ -239,13 +230,7 @@ describe("resident browser webviews", () => {
|
||||
});
|
||||
|
||||
it("reuses a resident browser on the same partition and replaces it when the partition changes", () => {
|
||||
const input = {
|
||||
browserId: "first",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace",
|
||||
url: "about:blank",
|
||||
profileHost,
|
||||
};
|
||||
const input = { browserId: "first", workspaceId: "workspace", url: "about:blank", profileHost };
|
||||
const first = ensureTestBrowser(input);
|
||||
expect(ensureResidentBrowserWebview({ ...input, partition: "persist:paseo-browser" })).toBe(
|
||||
first,
|
||||
@@ -290,14 +275,12 @@ describe("resident browser webviews", () => {
|
||||
expect(attachedBrowsers).toEqual([
|
||||
{
|
||||
browserId: "browser-first",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace-a",
|
||||
partition: "persist:paseo-browser",
|
||||
webContentsId: 101,
|
||||
},
|
||||
{
|
||||
browserId: "browser-second",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace-b",
|
||||
partition: "persist:paseo-browser",
|
||||
webContentsId: 202,
|
||||
|
||||
@@ -25,7 +25,6 @@ interface BrowserWebviewElement extends HTMLElement {
|
||||
interface BrowserWebviewIdentity {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
@@ -81,7 +80,6 @@ function registerBrowserWhenAttached(
|
||||
await browser.registerAttachedBrowser({
|
||||
partition: identity.partition,
|
||||
browserId: identity.browserId,
|
||||
serverId: identity.serverId,
|
||||
workspaceId: identity.workspaceId,
|
||||
webContentsId,
|
||||
});
|
||||
@@ -329,7 +327,6 @@ export function prepareBrowserWebview(
|
||||
webview: HTMLElement,
|
||||
input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
initialUrl?: string | null;
|
||||
partition?: string;
|
||||
@@ -351,7 +348,6 @@ export function prepareBrowserWebview(
|
||||
{
|
||||
partition: targetPartition,
|
||||
browserId: input.browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
},
|
||||
browser,
|
||||
@@ -364,7 +360,6 @@ export function getResidentBrowserWebviewPartition(webview: HTMLElement): string
|
||||
|
||||
export function ensureResidentBrowserWebview(input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -405,7 +400,6 @@ export function ensureResidentBrowserWebview(input: {
|
||||
const webview = ownerDocument.createElement("webview") as BrowserWebviewElement;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.url,
|
||||
partition: desiredPartition,
|
||||
|
||||
@@ -145,16 +145,10 @@ export interface DesktopBrowserNewTabRequestEvent {
|
||||
export interface DesktopAttachedBrowserRegistration {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
webContentsId: number;
|
||||
}
|
||||
|
||||
export interface DesktopAutomationExecutionContext {
|
||||
serverId: string;
|
||||
uploadRoot: string | null;
|
||||
}
|
||||
|
||||
export type BrowserProfileColor = IdentityColorName;
|
||||
|
||||
export interface BrowserProfileEntry {
|
||||
@@ -212,7 +206,6 @@ export interface DesktopBrowserBridge {
|
||||
registerAttachedBrowser?: (input: DesktopAttachedBrowserRegistration) => Promise<void>;
|
||||
unregisterWorkspaceBrowser?: (browserId: string) => Promise<void>;
|
||||
setWorkspaceActiveBrowser?: (input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
browserId: string | null;
|
||||
}) => Promise<void>;
|
||||
@@ -239,7 +232,6 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
executeAutomationCommand?: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
) => Promise<BrowserAutomationExecuteResponse["payload"]>;
|
||||
acknowledgeFocusGuard?: (input: { token: string; composing: boolean }) => void;
|
||||
/** Capture a PNG screenshot of the guest viewport cropped to `rect`. */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -14,15 +14,13 @@ import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsDetailRow,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
} from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
import { DaemonPasswordSheet } from "./daemon-password-sheet";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
|
||||
@@ -492,74 +490,6 @@ function ConnectedClientsCardBody({
|
||||
);
|
||||
}
|
||||
|
||||
function DevicesAccessSection({
|
||||
serverId,
|
||||
isOnline,
|
||||
serverInfo,
|
||||
}: {
|
||||
serverId: string;
|
||||
isOnline: boolean;
|
||||
serverInfo: DaemonServerInfo | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [passwordSheetMode, setPasswordSheetMode] = useState<"set" | "change" | null>(null);
|
||||
const passwordConfigured = serverInfo?.passwordConfigured === true;
|
||||
const passwordManagedByEnv = serverInfo?.passwordManagedByEnv === true;
|
||||
const handleOpenPasswordSheet = useCallback(() => {
|
||||
setPasswordSheetMode(passwordConfigured ? "change" : "set");
|
||||
}, [passwordConfigured]);
|
||||
const handleClosePasswordSheet = useCallback(() => {
|
||||
setPasswordSheetMode(null);
|
||||
}, []);
|
||||
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
const supportsPasswordManagement = serverInfo?.features?.daemonPasswordManagement === true;
|
||||
const canManagePassword =
|
||||
!serverInfo?.permissions ||
|
||||
(serverInfo.permissions.includes("daemon.manage") &&
|
||||
serverInfo.permissions.includes("access.manage"));
|
||||
|
||||
if (!isOnline || !supportsPasswordManagement || !canManagePassword) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let passwordSummary: string;
|
||||
let passwordHint: string;
|
||||
if (passwordManagedByEnv) {
|
||||
passwordSummary = t("devices.access.passwordEnvSummary");
|
||||
passwordHint = t("devices.access.passwordEnvHint");
|
||||
} else if (passwordConfigured) {
|
||||
passwordSummary = t("devices.access.passwordSetSummary");
|
||||
passwordHint = t("devices.access.passwordSetHint");
|
||||
} else {
|
||||
passwordSummary = t("devices.access.passwordNotSetSummary");
|
||||
passwordHint = t("devices.access.passwordNotSetHint");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title={t("devices.access.title")}>
|
||||
<SettingsCard testID="devices-access-card">
|
||||
<SettingsDetailRow
|
||||
label={t("devices.access.passwordLabel")}
|
||||
summary={passwordSummary}
|
||||
hint={passwordHint}
|
||||
disabled={passwordManagedByEnv}
|
||||
onPress={handleOpenPasswordSheet}
|
||||
testID="devices-password-row"
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
<DaemonPasswordSheet
|
||||
serverId={serverId}
|
||||
visible={passwordSheetMode !== null}
|
||||
initialMode={passwordSheetMode ?? "set"}
|
||||
onClose={handleClosePasswordSheet}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
@@ -608,8 +538,6 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
|
||||
return (
|
||||
<View>
|
||||
<DevicesAccessSection serverId={serverId} isOnline={isOnline} serverInfo={serverInfo} />
|
||||
|
||||
<SettingsSection title={t("devices.connected.title")}>
|
||||
<SettingsCard testID="devices-connected-clients-card">
|
||||
<ConnectedClientsCardBody
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
DAEMON_PASSWORD_MAX_BYTES,
|
||||
DAEMON_PASSWORD_MIN_CHARS,
|
||||
openDaemonPasswordForm,
|
||||
shouldSyncHostProfilePassword,
|
||||
} from "./daemon-password-form-model";
|
||||
|
||||
describe("daemon password form model", () => {
|
||||
test("set mode validates min 8 chars, max 72 UTF-8 bytes, and confirmation match", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "set",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
expect(form.getState()).toMatchObject({
|
||||
step: "set",
|
||||
isLocalCredential: false,
|
||||
submitting: false,
|
||||
});
|
||||
|
||||
// 7 chars fails min length.
|
||||
form.setNewPassword("1234567");
|
||||
form.setConfirmPassword("1234567");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBe("too_short");
|
||||
|
||||
// 8 chars with mismatch fails confirm.
|
||||
form.setNewPassword("12345678");
|
||||
form.setConfirmPassword("87654321");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBeNull();
|
||||
expect(form.getState().fieldErrors.confirmPassword).toBe("mismatch");
|
||||
|
||||
// 73 UTF-8 bytes fails (including multibyte UTF-8 under 72 chars).
|
||||
const over72Bytes = "🔐".repeat(19); // 76 UTF-8 bytes
|
||||
expect(over72Bytes.length).toBeLessThan(DAEMON_PASSWORD_MAX_BYTES);
|
||||
form.setNewPassword(over72Bytes);
|
||||
form.setConfirmPassword(over72Bytes);
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBe("too_long");
|
||||
|
||||
// Exact 72 UTF-8 bytes succeeds.
|
||||
const exact72 = "a".repeat(DAEMON_PASSWORD_MAX_BYTES);
|
||||
form.setNewPassword(exact72);
|
||||
form.setConfirmPassword(exact72);
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: exact72 },
|
||||
});
|
||||
expect(form.getState().submitting).toBe(true);
|
||||
form.finishSubmitSuccess();
|
||||
expect(form.getState().submitting).toBe(false);
|
||||
|
||||
// Exact 8 chars succeeds.
|
||||
const exact8 = "a".repeat(DAEMON_PASSWORD_MIN_CHARS);
|
||||
form.setNewPassword(exact8);
|
||||
form.setConfirmPassword(exact8);
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: exact8 },
|
||||
});
|
||||
});
|
||||
|
||||
test("change mode requires current password on remote sessions and maps server incorrect_password to field error", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
|
||||
form.setNewPassword("new-secret-123");
|
||||
form.setConfirmPassword("new-secret-123");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("current_password_required");
|
||||
|
||||
form.setCurrentPassword("wrong-current");
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: "new-secret-123", currentPassword: "wrong-current" },
|
||||
});
|
||||
|
||||
form.finishSubmitError({
|
||||
code: "incorrect_password",
|
||||
message: "Current password is incorrect",
|
||||
});
|
||||
expect(form.getState().submitting).toBe(false);
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
|
||||
expect(form.getState().submitError).toBeNull();
|
||||
// Preserves inputs so the user does not retype.
|
||||
expect(form.getState().newPassword).toBe("new-secret-123");
|
||||
expect(form.getState().confirmPassword).toBe("new-secret-123");
|
||||
|
||||
// Network/generic error goes to submitError.
|
||||
form.finishSubmitError({ message: "Network timeout" });
|
||||
expect(form.getState().submitError).toBe("Network timeout");
|
||||
});
|
||||
|
||||
test("change mode omits currentPassword on local-credential sessions", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: true,
|
||||
});
|
||||
|
||||
form.setNewPassword("recovered-secret");
|
||||
form.setConfirmPassword("recovered-secret");
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: "recovered-secret" },
|
||||
});
|
||||
});
|
||||
|
||||
test("remote remove step seeds currentPassword from change step and submits password=null", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
form.setCurrentPassword("my-current-pw");
|
||||
form.enterRemoveStep();
|
||||
expect(form.getState().step).toBe("remove");
|
||||
expect(form.getState().currentPassword).toBe("my-current-pw");
|
||||
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: null, currentPassword: "my-current-pw" },
|
||||
});
|
||||
|
||||
form.finishSubmitError({
|
||||
code: "incorrect_password",
|
||||
message: "Current password is incorrect",
|
||||
});
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
|
||||
|
||||
form.backToChangeStep();
|
||||
expect(form.getState().step).toBe("change");
|
||||
});
|
||||
|
||||
test("shouldSyncHostProfilePassword skips persisting password on local-only profiles when using localCredentialAuth", () => {
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
],
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
],
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
// Local desktop profile that also has a relay or remote route DOES sync so remote routes stay usable.
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
{
|
||||
id: "relay:relay.paseo.sh:443",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "pk",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
// Non-local browser session always syncs even on localhost so reload stays authenticated.
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: false,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,269 +0,0 @@
|
||||
import { isLoopbackEndpoint } from "@/hosts/connection-display";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
export const DAEMON_PASSWORD_MIN_CHARS = 8;
|
||||
export const DAEMON_PASSWORD_MAX_BYTES = 72;
|
||||
|
||||
export type DaemonPasswordFormStep = "set" | "change" | "remove";
|
||||
|
||||
export type DaemonPasswordFieldErrorCode =
|
||||
| "current_password_required"
|
||||
| "incorrect_password"
|
||||
| "too_short"
|
||||
| "too_long"
|
||||
| "mismatch"
|
||||
| "invalid_password";
|
||||
|
||||
export interface DaemonPasswordFormFieldErrors {
|
||||
currentPassword: DaemonPasswordFieldErrorCode | null;
|
||||
newPassword: DaemonPasswordFieldErrorCode | null;
|
||||
confirmPassword: DaemonPasswordFieldErrorCode | null;
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormState {
|
||||
step: DaemonPasswordFormStep;
|
||||
isLocalCredential: boolean;
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
showCurrentPassword: boolean;
|
||||
showNewPassword: boolean;
|
||||
showConfirmPassword: boolean;
|
||||
submitting: boolean;
|
||||
fieldErrors: DaemonPasswordFormFieldErrors;
|
||||
submitError: string | null;
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormSnapshot {
|
||||
mode: "set" | "change";
|
||||
isLocalCredential: boolean;
|
||||
}
|
||||
|
||||
export type DaemonPasswordSubmitResult =
|
||||
| { valid: false }
|
||||
| { valid: true; payload: { password: string | null; currentPassword?: string } };
|
||||
|
||||
export interface DaemonPasswordFormModel {
|
||||
getState(): DaemonPasswordFormState;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setCurrentPassword(value: string): void;
|
||||
setNewPassword(value: string): void;
|
||||
setConfirmPassword(value: string): void;
|
||||
toggleShowCurrentPassword(): void;
|
||||
toggleShowNewPassword(): void;
|
||||
toggleShowConfirmPassword(): void;
|
||||
enterRemoveStep(): void;
|
||||
backToChangeStep(): void;
|
||||
beginSubmit(): DaemonPasswordSubmitResult;
|
||||
finishSubmitSuccess(): void;
|
||||
finishSubmitError(error: { code?: string; message: string }): void;
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
export function utf8ByteLength(value: string): number {
|
||||
return textEncoder.encode(value).byteLength;
|
||||
}
|
||||
|
||||
export function isLocalOnlyHostConnection(connection: HostConnection): boolean {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return true;
|
||||
}
|
||||
if (connection.type === "directTcp") {
|
||||
return isLoopbackEndpoint(connection.endpoint);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function shouldSyncHostProfilePassword(input: {
|
||||
localCredentialAuth: boolean;
|
||||
connections: readonly HostConnection[];
|
||||
}): boolean {
|
||||
if (!input.localCredentialAuth) {
|
||||
return true;
|
||||
}
|
||||
return input.connections.some((connection) => !isLocalOnlyHostConnection(connection));
|
||||
}
|
||||
|
||||
const EMPTY_FIELD_ERRORS: DaemonPasswordFormFieldErrors = {
|
||||
currentPassword: null,
|
||||
newPassword: null,
|
||||
confirmPassword: null,
|
||||
};
|
||||
|
||||
export function openDaemonPasswordForm(
|
||||
snapshot: DaemonPasswordFormSnapshot,
|
||||
): DaemonPasswordFormModel {
|
||||
const listeners = new Set<() => void>();
|
||||
let state: DaemonPasswordFormState = {
|
||||
step: snapshot.mode,
|
||||
isLocalCredential: snapshot.isLocalCredential,
|
||||
currentPassword: "",
|
||||
newPassword: "",
|
||||
confirmPassword: "",
|
||||
showCurrentPassword: false,
|
||||
showNewPassword: false,
|
||||
showConfirmPassword: false,
|
||||
submitting: false,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
};
|
||||
|
||||
const publish = (next: DaemonPasswordFormState) => {
|
||||
state = next;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
|
||||
setCurrentPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
currentPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, currentPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
setNewPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
newPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, newPassword: null, confirmPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
setConfirmPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
confirmPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, confirmPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
toggleShowCurrentPassword() {
|
||||
publish({ ...state, showCurrentPassword: !state.showCurrentPassword });
|
||||
},
|
||||
|
||||
toggleShowNewPassword() {
|
||||
publish({ ...state, showNewPassword: !state.showNewPassword });
|
||||
},
|
||||
|
||||
toggleShowConfirmPassword() {
|
||||
publish({ ...state, showConfirmPassword: !state.showConfirmPassword });
|
||||
},
|
||||
|
||||
enterRemoveStep() {
|
||||
if (state.step !== "change" || state.submitting) return;
|
||||
publish({
|
||||
...state,
|
||||
step: "remove",
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
backToChangeStep() {
|
||||
if (state.step !== "remove" || state.submitting) return;
|
||||
publish({
|
||||
...state,
|
||||
step: "change",
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
beginSubmit() {
|
||||
if (state.submitting) {
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
|
||||
const needsCurrentPassword =
|
||||
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
|
||||
|
||||
if (needsCurrentPassword && state.currentPassword.length === 0) {
|
||||
fieldErrors.currentPassword = "current_password_required";
|
||||
}
|
||||
|
||||
if (state.step !== "remove") {
|
||||
if (state.newPassword.length < DAEMON_PASSWORD_MIN_CHARS) {
|
||||
fieldErrors.newPassword = "too_short";
|
||||
} else if (utf8ByteLength(state.newPassword) > DAEMON_PASSWORD_MAX_BYTES) {
|
||||
fieldErrors.newPassword = "too_long";
|
||||
} else if (state.confirmPassword !== state.newPassword) {
|
||||
fieldErrors.confirmPassword = "mismatch";
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
fieldErrors.currentPassword !== null ||
|
||||
fieldErrors.newPassword !== null ||
|
||||
fieldErrors.confirmPassword !== null
|
||||
) {
|
||||
publish({
|
||||
...state,
|
||||
fieldErrors,
|
||||
submitError: null,
|
||||
});
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
publish({
|
||||
...state,
|
||||
submitting: true,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
payload: {
|
||||
password: state.step === "remove" ? null : state.newPassword,
|
||||
...(needsCurrentPassword ? { currentPassword: state.currentPassword } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
finishSubmitSuccess() {
|
||||
publish({
|
||||
...state,
|
||||
submitting: false,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
finishSubmitError(error) {
|
||||
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
|
||||
let submitError: string | null = null;
|
||||
if (error.code === "incorrect_password") {
|
||||
fieldErrors.currentPassword = "incorrect_password";
|
||||
} else if (error.code === "current_password_required") {
|
||||
fieldErrors.currentPassword = "current_password_required";
|
||||
} else if (error.code === "invalid_password") {
|
||||
fieldErrors.newPassword = "invalid_password";
|
||||
} else {
|
||||
submitError = error.message;
|
||||
}
|
||||
publish({
|
||||
...state,
|
||||
submitting: false,
|
||||
fieldErrors,
|
||||
submitError,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,532 +0,0 @@
|
||||
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Eye, EyeOff } from "lucide-react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { DaemonRpcError } from "@getpaseo/client";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useHostMutations, useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import {
|
||||
openDaemonPasswordForm,
|
||||
shouldSyncHostProfilePassword,
|
||||
type DaemonPasswordFieldErrorCode,
|
||||
type DaemonPasswordFormModel,
|
||||
} from "./daemon-password-form-model";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
|
||||
function translateFieldError(
|
||||
code: DaemonPasswordFieldErrorCode | null,
|
||||
t: TFunction,
|
||||
): string | null {
|
||||
switch (code) {
|
||||
case "current_password_required":
|
||||
return t("devices.password.errors.currentRequired");
|
||||
case "incorrect_password":
|
||||
return t("devices.password.errors.currentIncorrect");
|
||||
case "too_short":
|
||||
return t("devices.password.errors.tooShort");
|
||||
case "too_long":
|
||||
case "invalid_password":
|
||||
return t("devices.password.errors.tooLong");
|
||||
case "mismatch":
|
||||
return t("devices.password.errors.mismatch");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatSuccessToast(
|
||||
action: "set" | "change" | "remove",
|
||||
disconnectedSessionCount: number,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (action === "remove") {
|
||||
return t("devices.password.toast.removed");
|
||||
}
|
||||
if (action === "set") {
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return t("devices.password.toast.setDisconnectedOne");
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return t("devices.password.toast.setDisconnectedOther", { count: disconnectedSessionCount });
|
||||
}
|
||||
return t("devices.password.toast.set");
|
||||
}
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return t("devices.password.toast.updatedDisconnectedOne");
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return t("devices.password.toast.updatedDisconnectedOther", {
|
||||
count: disconnectedSessionCount,
|
||||
});
|
||||
}
|
||||
return t("devices.password.toast.updated");
|
||||
}
|
||||
|
||||
function extractRpcError(
|
||||
error: unknown,
|
||||
fallbackMessage: string,
|
||||
): {
|
||||
code?: string;
|
||||
message: string;
|
||||
} {
|
||||
if (error instanceof DaemonRpcError) {
|
||||
return { code: error.code, message: error.userMessage || error.message };
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return { message: error.message || fallbackMessage };
|
||||
}
|
||||
return { message: fallbackMessage };
|
||||
}
|
||||
|
||||
function resolvePrimaryButtonLabel(
|
||||
step: "set" | "change" | "remove",
|
||||
submitting: boolean,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (step === "set") {
|
||||
return submitting ? t("devices.password.setting") : t("devices.password.setAction");
|
||||
}
|
||||
if (step === "change") {
|
||||
return submitting ? t("devices.password.saving") : t("devices.password.saveAction");
|
||||
}
|
||||
return submitting ? t("devices.password.removing") : t("devices.password.removeAction");
|
||||
}
|
||||
|
||||
function DaemonPasswordStepBanner({
|
||||
step,
|
||||
t,
|
||||
}: {
|
||||
step: "set" | "change" | "remove";
|
||||
t: TFunction;
|
||||
}) {
|
||||
if (step === "remove") {
|
||||
return (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
description={t("devices.password.removeWarning")}
|
||||
testID="daemon-password-remove-warning"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="info"
|
||||
description={
|
||||
step === "set" ? t("devices.password.setInfo") : t("devices.password.changeInfo")
|
||||
}
|
||||
testID="daemon-password-info"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface PasswordInputFieldProps {
|
||||
label: string;
|
||||
initialValue: string;
|
||||
showPassword: boolean;
|
||||
onChangeText: (value: string) => void;
|
||||
onToggleShow: () => void;
|
||||
onSubmitEditing?: () => void;
|
||||
error: string | null;
|
||||
disabled: boolean;
|
||||
autoFocus?: boolean;
|
||||
size: "sm" | "md";
|
||||
returnKeyType?: "next" | "done";
|
||||
testID: string;
|
||||
}
|
||||
|
||||
function PasswordInputField({
|
||||
label,
|
||||
initialValue,
|
||||
showPassword,
|
||||
onChangeText,
|
||||
onToggleShow,
|
||||
onSubmitEditing,
|
||||
error,
|
||||
disabled,
|
||||
autoFocus,
|
||||
size,
|
||||
returnKeyType = "next",
|
||||
testID,
|
||||
}: PasswordInputFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Field label={label} error={error} testID={`${testID}-field`}>
|
||||
<View style={styles.passwordRow}>
|
||||
<View style={styles.passwordInputWrap}>
|
||||
<FormTextInput
|
||||
initialValue={initialValue}
|
||||
onChangeText={onChangeText}
|
||||
onSubmitEditing={onSubmitEditing}
|
||||
secureTextEntry={!showPassword}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="off"
|
||||
autoFocus={autoFocus}
|
||||
editable={!disabled}
|
||||
invalid={Boolean(error)}
|
||||
size={size}
|
||||
returnKeyType={returnKeyType}
|
||||
testID={testID}
|
||||
/>
|
||||
</View>
|
||||
<Button
|
||||
variant="outline"
|
||||
size={size}
|
||||
leftIcon={showPassword ? EyeOff : Eye}
|
||||
onPress={onToggleShow}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={
|
||||
showPassword ? t("devices.password.hide") : t("devices.password.show")
|
||||
}
|
||||
testID={`${testID}-toggle`}
|
||||
/>
|
||||
</View>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormContentProps {
|
||||
serverId: string;
|
||||
initialMode: "set" | "change";
|
||||
model?: DaemonPasswordFormModel;
|
||||
onCancel: () => void;
|
||||
onCompleted: () => void;
|
||||
}
|
||||
|
||||
export function DaemonPasswordFormContent({
|
||||
serverId,
|
||||
initialMode,
|
||||
model: externalModel,
|
||||
onCancel,
|
||||
onCompleted,
|
||||
}: DaemonPasswordFormContentProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const fieldSize = isCompact ? "md" : "sm";
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const hosts = useHosts();
|
||||
const { setHostPassword } = useHostMutations();
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
const host = useMemo(
|
||||
() => hosts.find((item) => item.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const isLocalCredential = serverInfo?.localCredentialAuth === true;
|
||||
|
||||
const [internalModel] = useState(() =>
|
||||
openDaemonPasswordForm({
|
||||
mode: initialMode,
|
||||
isLocalCredential,
|
||||
}),
|
||||
);
|
||||
const model = externalModel ?? internalModel;
|
||||
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
|
||||
const syncProfilePasswordIfNeeded = useCallback(
|
||||
async (nextPassword: string | null) => {
|
||||
if (
|
||||
!shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: serverInfo?.localCredentialAuth === true,
|
||||
connections: host?.connections ?? [],
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await setHostPassword(serverId, nextPassword ?? "");
|
||||
},
|
||||
[host?.connections, serverId, serverInfo?.localCredentialAuth, setHostPassword],
|
||||
);
|
||||
|
||||
const executeMutation = useCallback(
|
||||
async (
|
||||
action: "set" | "change" | "remove",
|
||||
payload: {
|
||||
password: string | null;
|
||||
currentPassword?: string;
|
||||
},
|
||||
) => {
|
||||
if (!client) {
|
||||
model.finishSubmitError({ message: t("workspace.terminal.hostDisconnected") });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await client.setDaemonPassword(payload);
|
||||
await syncProfilePasswordIfNeeded(payload.password);
|
||||
model.finishSubmitSuccess();
|
||||
toast.show(formatSuccessToast(action, result.disconnectedSessionCount, t), {
|
||||
variant: "success",
|
||||
});
|
||||
onCompleted();
|
||||
} catch (error) {
|
||||
model.finishSubmitError(extractRpcError(error, t("errors.unableToSave")));
|
||||
}
|
||||
},
|
||||
[client, model, onCompleted, syncProfilePasswordIfNeeded, t, toast],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
const attempt = model.beginSubmit();
|
||||
if (!attempt.valid) return;
|
||||
void executeMutation(state.step, attempt.payload);
|
||||
}, [executeMutation, model, state.step]);
|
||||
|
||||
const handleRequestRemove = useCallback(() => {
|
||||
if (state.submitting) return;
|
||||
if (!state.isLocalCredential) {
|
||||
model.enterRemoveStep();
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("devices.password.removeTitle"),
|
||||
message: t("devices.password.removeWarning"),
|
||||
confirmLabel: t("devices.password.removeAction"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
model.enterRemoveStep();
|
||||
const attempt = model.beginSubmit();
|
||||
if (!attempt.valid) return;
|
||||
await executeMutation("remove", attempt.payload);
|
||||
})();
|
||||
}, [executeMutation, model, state.isLocalCredential, state.submitting, t]);
|
||||
|
||||
const showCurrentPassword =
|
||||
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
|
||||
const primaryLabel = resolvePrimaryButtonLabel(state.step, state.submitting, t);
|
||||
|
||||
return (
|
||||
<View style={styles.form} testID={`daemon-password-form-${state.step}`}>
|
||||
<DaemonPasswordStepBanner step={state.step} t={t} />
|
||||
|
||||
{showCurrentPassword ? (
|
||||
<PasswordInputField
|
||||
key={`current-${state.step}`}
|
||||
label={t("devices.password.fields.current")}
|
||||
initialValue={state.currentPassword}
|
||||
showPassword={state.showCurrentPassword}
|
||||
onChangeText={model.setCurrentPassword}
|
||||
onToggleShow={model.toggleShowCurrentPassword}
|
||||
onSubmitEditing={state.step === "remove" ? handleSubmit : undefined}
|
||||
error={translateFieldError(state.fieldErrors.currentPassword, t)}
|
||||
disabled={state.submitting}
|
||||
autoFocus
|
||||
size={fieldSize}
|
||||
returnKeyType={state.step === "remove" ? "done" : "next"}
|
||||
testID="daemon-password-current-input"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.step !== "remove" ? (
|
||||
<>
|
||||
<PasswordInputField
|
||||
key={`new-${state.step}`}
|
||||
label={t("devices.password.fields.new")}
|
||||
initialValue={state.newPassword}
|
||||
showPassword={state.showNewPassword}
|
||||
onChangeText={model.setNewPassword}
|
||||
onToggleShow={model.toggleShowNewPassword}
|
||||
error={translateFieldError(state.fieldErrors.newPassword, t)}
|
||||
disabled={state.submitting}
|
||||
autoFocus={!showCurrentPassword}
|
||||
size={fieldSize}
|
||||
testID="daemon-password-new-input"
|
||||
/>
|
||||
<PasswordInputField
|
||||
key={`confirm-${state.step}`}
|
||||
label={
|
||||
state.step === "set"
|
||||
? t("devices.password.fields.confirm")
|
||||
: t("devices.password.fields.confirmNew")
|
||||
}
|
||||
initialValue={state.confirmPassword}
|
||||
showPassword={state.showConfirmPassword}
|
||||
onChangeText={model.setConfirmPassword}
|
||||
onToggleShow={model.toggleShowConfirmPassword}
|
||||
onSubmitEditing={handleSubmit}
|
||||
error={translateFieldError(state.fieldErrors.confirmPassword, t)}
|
||||
disabled={state.submitting}
|
||||
size={fieldSize}
|
||||
returnKeyType="done"
|
||||
testID="daemon-password-confirm-input"
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{state.submitError ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="error"
|
||||
description={state.submitError}
|
||||
testID="daemon-password-submit-error"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={FLEX_ONE_STYLE}
|
||||
onPress={state.step === "remove" ? model.backToChangeStep : onCancel}
|
||||
disabled={state.submitting}
|
||||
testID="daemon-password-cancel-button"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant={state.step === "remove" ? "destructive" : "default"}
|
||||
style={FLEX_ONE_STYLE}
|
||||
loading={state.submitting}
|
||||
disabled={state.submitting}
|
||||
onPress={handleSubmit}
|
||||
testID="daemon-password-submit-button"
|
||||
>
|
||||
{primaryLabel}
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
{state.step === "change" ? (
|
||||
<View style={styles.removeSection}>
|
||||
<View style={styles.divider} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
onPress={handleRequestRemove}
|
||||
disabled={state.submitting}
|
||||
textStyle={styles.removeButtonText}
|
||||
testID="daemon-password-remove-trigger"
|
||||
>
|
||||
{t("devices.password.removeAction")}
|
||||
</Button>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export interface DaemonPasswordSheetProps {
|
||||
serverId: string;
|
||||
visible: boolean;
|
||||
initialMode: "set" | "change";
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function DaemonPasswordSheet({
|
||||
serverId,
|
||||
visible,
|
||||
initialMode,
|
||||
onClose,
|
||||
}: DaemonPasswordSheetProps) {
|
||||
if (!visible) return null;
|
||||
return (
|
||||
<DaemonPasswordSheetOpen
|
||||
key={`${serverId}:${initialMode}`}
|
||||
serverId={serverId}
|
||||
initialMode={initialMode}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DaemonPasswordSheetOpen({
|
||||
serverId,
|
||||
initialMode,
|
||||
onClose,
|
||||
}: Omit<DaemonPasswordSheetProps, "visible">) {
|
||||
const { t } = useTranslation();
|
||||
const isLocalCredential = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.localCredentialAuth === true,
|
||||
);
|
||||
const [model] = useState(() =>
|
||||
openDaemonPasswordForm({
|
||||
mode: initialMode,
|
||||
isLocalCredential,
|
||||
}),
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
if (state.submitting) return;
|
||||
onClose();
|
||||
}, [onClose, state.submitting]);
|
||||
|
||||
const header = useMemo<SheetHeader>(() => {
|
||||
if (state.step === "remove") {
|
||||
return {
|
||||
title: t("devices.password.removeTitle"),
|
||||
back: {
|
||||
onPress: model.backToChangeStep,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
title:
|
||||
state.step === "set" ? t("devices.password.setTitle") : t("devices.password.changeTitle"),
|
||||
};
|
||||
}, [model.backToChangeStep, state.step, t]);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible
|
||||
onClose={handleClose}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={440}
|
||||
testID="daemon-password-sheet"
|
||||
>
|
||||
<DaemonPasswordFormContent
|
||||
serverId={serverId}
|
||||
initialMode={initialMode}
|
||||
model={model}
|
||||
onCancel={handleClose}
|
||||
onCompleted={onClose}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
form: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
passwordRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
passwordInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
removeSection: {
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
divider: {
|
||||
height: theme.borderWidth[1],
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
removeButtonText: {
|
||||
color: theme.colors.destructive,
|
||||
},
|
||||
}));
|
||||
@@ -6,10 +6,9 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { PairDeviceSection } from "./pair-device-section";
|
||||
import { DaemonPasswordFormContent } from "./daemon-password-sheet";
|
||||
import { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
const SNAP_POINTS: string[] = ["80%", "92%"];
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const iconProps = (theme: Theme) => ({
|
||||
size: theme.iconSize.sm,
|
||||
@@ -17,7 +16,7 @@ const iconProps = (theme: Theme) => ({
|
||||
});
|
||||
const plusIcon = <ThemedPlus uniProps={iconProps} />;
|
||||
|
||||
type PairStep = "ways" | "relay" | "password";
|
||||
type PairStep = "ways" | "relay";
|
||||
|
||||
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -36,59 +35,22 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
}, []);
|
||||
const handleOpenRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleBackToWays = useCallback(() => setStep("ways"), []);
|
||||
const handleOpenPassword = useCallback(() => setStep("password"), []);
|
||||
const handleBackToRelay = useCallback(() => setStep("relay"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(() => {
|
||||
if (step === "password") {
|
||||
return {
|
||||
title: t("devices.password.setTitle"),
|
||||
back: {
|
||||
onPress: handleBackToRelay,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (step === "relay") {
|
||||
return {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
};
|
||||
}, [handleBackToRelay, handleBackToWays, step, t]);
|
||||
|
||||
let sheetTestID = "devices-pair-sheet";
|
||||
if (step === "relay") sheetTestID = "devices-relay-pairing";
|
||||
else if (step === "password") sheetTestID = "devices-pair-password-step";
|
||||
|
||||
let sheetContent: React.ReactNode;
|
||||
if (step === "password") {
|
||||
sheetContent = (
|
||||
<DaemonPasswordFormContent
|
||||
key={`${serverId}:pair-password`}
|
||||
serverId={serverId}
|
||||
initialMode="set"
|
||||
onCancel={handleBackToRelay}
|
||||
onCompleted={handleBackToRelay}
|
||||
/>
|
||||
);
|
||||
} else if (step === "relay") {
|
||||
sheetContent = (
|
||||
<PairDeviceSection
|
||||
serverId={serverId}
|
||||
onClose={handleClose}
|
||||
onOpenPassword={handleOpenPassword}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
sheetContent = <WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />;
|
||||
}
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
step === "relay"
|
||||
? {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
},
|
||||
[handleBackToWays, step, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -107,10 +69,14 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
desktopHeight={560}
|
||||
testID={sheetTestID}
|
||||
desktopHeight={520}
|
||||
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
|
||||
>
|
||||
{sheetContent}
|
||||
{step === "relay" ? (
|
||||
<PairDeviceSection serverId={serverId} onClose={handleClose} />
|
||||
) : (
|
||||
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { PairDeviceSection } from "@/devices/pair-device-section";
|
||||
import { DaemonPasswordFormContent } from "@/devices/daemon-password-sheet";
|
||||
|
||||
export interface PairDeviceModalProps {
|
||||
serverId: string;
|
||||
@@ -11,28 +10,13 @@ export interface PairDeviceModalProps {
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
const SNAP_POINTS: string[] = ["80%", "92%"];
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
|
||||
export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDeviceModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [step, setStep] = useState<"relay" | "password">("relay");
|
||||
|
||||
const handleOpenPassword = useCallback(() => setStep("password"), []);
|
||||
const handleBackToRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleDismiss = useCallback(() => setStep("relay"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
step === "password"
|
||||
? {
|
||||
title: t("devices.password.setTitle"),
|
||||
back: {
|
||||
onPress: handleBackToRelay,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: { title: t("settings.host.pairDevices.rowTitle") },
|
||||
[handleBackToRelay, step, t],
|
||||
() => ({ title: t("settings.host.pairDevices.rowTitle") }),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -40,26 +24,11 @@ export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDevi
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
testID={testID}
|
||||
>
|
||||
{step === "password" ? (
|
||||
<DaemonPasswordFormContent
|
||||
key={`${serverId}:modal-password`}
|
||||
serverId={serverId}
|
||||
initialMode="set"
|
||||
onCancel={handleBackToRelay}
|
||||
onCompleted={handleBackToRelay}
|
||||
/>
|
||||
) : (
|
||||
<PairDeviceSection
|
||||
serverId={serverId}
|
||||
onClose={onClose}
|
||||
onOpenPassword={handleOpenPassword}
|
||||
/>
|
||||
)}
|
||||
<PairDeviceSection serverId={serverId} onClose={onClose} />
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import { useFetchQuery } from "@/data/query";
|
||||
import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
@@ -34,42 +33,24 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
const accentBrightColorMapping = (theme: Theme) => ({ color: theme.colors.accentBright });
|
||||
|
||||
function canOfferSetPassword(
|
||||
serverInfo: DaemonServerInfo | null,
|
||||
serverFeatures: DaemonServerInfo["features"] | undefined,
|
||||
onOpenPassword: (() => void) | undefined,
|
||||
): boolean {
|
||||
if (!onOpenPassword) return false;
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
if (serverFeatures?.daemonPasswordManagement !== true) return false;
|
||||
if (serverInfo?.passwordManagedByEnv === true) return false;
|
||||
const permissions = serverInfo?.permissions;
|
||||
if (!permissions) return true;
|
||||
return permissions.includes("daemon.manage") && permissions.includes("access.manage");
|
||||
}
|
||||
|
||||
export interface PairDeviceSectionProps {
|
||||
serverId: string;
|
||||
onClose: () => void;
|
||||
onOpenPassword?: () => void;
|
||||
}
|
||||
|
||||
export function PairDeviceSection({ serverId, onClose, onOpenPassword }: PairDeviceSectionProps) {
|
||||
export function PairDeviceSection({ serverId, onClose }: PairDeviceSectionProps) {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
const isConnected = runtimeSnapshot?.connectionStatus === "online";
|
||||
const isDisconnected =
|
||||
runtimeSnapshot?.connectionStatus === "offline" ||
|
||||
runtimeSnapshot?.connectionStatus === "error";
|
||||
const { patchConfig } = useDaemonConfig(serverId);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const serverFeatures = serverInfo?.features ?? client?.getLastServerInfoMessage()?.features;
|
||||
const serverFeatures = client?.getLastServerInfoMessage()?.features;
|
||||
const supportsPairingRpc = serverFeatures?.daemonStatusRpc === true;
|
||||
const canConfigureRelay = supportsPairingRpc && serverFeatures?.relayConfig === true;
|
||||
const passwordConfigured = serverInfo?.passwordConfigured === true;
|
||||
const canSetPassword = canOfferSetPassword(serverInfo, serverFeatures, onOpenPassword);
|
||||
|
||||
const pairingQuery = useFetchQuery({
|
||||
queryKey: daemonPairingOfferQueryKey(serverId),
|
||||
@@ -142,9 +123,6 @@ export function PairDeviceSection({ serverId, onClose, onOpenPassword }: PairDev
|
||||
onEnableRelay={handleEnableRelay}
|
||||
onClose={onClose}
|
||||
onCopy={handleCopyPress}
|
||||
passwordConfigured={passwordConfigured}
|
||||
canSetPassword={canSetPassword}
|
||||
onOpenPassword={onOpenPassword}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
@@ -165,9 +143,6 @@ interface PairDeviceBodyProps {
|
||||
onEnableRelay: () => void;
|
||||
onClose: () => void;
|
||||
onCopy: () => void;
|
||||
passwordConfigured: boolean;
|
||||
canSetPassword: boolean;
|
||||
onOpenPassword?: () => void;
|
||||
}
|
||||
|
||||
function PairDeviceBody(props: PairDeviceBodyProps) {
|
||||
@@ -292,32 +267,7 @@ function PairingOffer(props: PairDeviceBodyProps & { offer: { url: string } }) {
|
||||
{props.copied ? t("pairing.device.copied") : t("pairing.device.copy")}
|
||||
</Button>
|
||||
</View>
|
||||
{props.passwordConfigured ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="info"
|
||||
description={t("pairing.device.passwordProtected")}
|
||||
testID="pairing-password-protected-alert"
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
description={t("pairing.device.securityWarning")}
|
||||
testID="pairing-no-password-alert"
|
||||
>
|
||||
{props.canSetPassword && props.onOpenPassword ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={props.onOpenPassword}
|
||||
testID="pairing-set-password-button"
|
||||
>
|
||||
{t("devices.password.setAction")}
|
||||
</Button>
|
||||
) : null}
|
||||
</Alert>
|
||||
)}
|
||||
<Alert size="sm" variant="warning" description={t("pairing.device.securityWarning")} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -403,7 +353,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
lineHeight: theme.fontSize.sm * 1.5,
|
||||
},
|
||||
offer: {
|
||||
gap: theme.spacing[3],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
offerHint: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
@@ -414,7 +364,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignSelf: "center",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 224,
|
||||
width: 304,
|
||||
maxWidth: "100%",
|
||||
aspectRatio: 1,
|
||||
padding: theme.spacing[3],
|
||||
|
||||
@@ -733,23 +733,4 @@ describe("deriveAgentScreenViewState", () => {
|
||||
expect(ready.source).toBe("authoritative");
|
||||
expect(ready.sync).toEqual({ status: "catching_up", ui: "overlay" });
|
||||
});
|
||||
|
||||
it("stays idle instead of reconnecting when the host connection was refused", () => {
|
||||
const result = deriveAgentScreenViewState({
|
||||
input: {
|
||||
...createBaseInput(),
|
||||
agent: createAgent("agent-1"),
|
||||
isConnected: false,
|
||||
isConnectionRefused: true,
|
||||
hasHydratedHistoryBefore: true,
|
||||
},
|
||||
memory: createBaseMemory({
|
||||
hasRenderedReady: true,
|
||||
lastReadyAgent: createAgent("agent-1"),
|
||||
}),
|
||||
});
|
||||
|
||||
const ready = expectReadyState(result.state);
|
||||
expect(ready.sync).toEqual({ status: "idle" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ export interface AgentScreenMachineInput {
|
||||
isArchived: boolean;
|
||||
missingAgentState: AgentScreenMissingState;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused?: boolean;
|
||||
isArchivingCurrentAgent: boolean;
|
||||
isHistorySyncing: boolean;
|
||||
needsAuthoritativeSync: boolean;
|
||||
@@ -182,9 +181,6 @@ function resolveAgentScreenSync(args: {
|
||||
) {
|
||||
return { status: "idle" };
|
||||
}
|
||||
if (input.isConnectionRefused) {
|
||||
return { status: "idle" };
|
||||
}
|
||||
// A reconnected chat is not back until the daemon answers whether it is current.
|
||||
if (
|
||||
(!input.isConnected || input.visibilityCatchUpStatus === "reattaching") &&
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -16,15 +15,8 @@ import {
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalPresentation,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
@@ -35,7 +27,6 @@ import {
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
uriHostLabel,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
type DirectConnectionMode,
|
||||
@@ -177,9 +168,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
// Switching modes mounts the other mode's fields. They take focus when the user was typing
|
||||
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
|
||||
const [focusModeBody, setFocusModeBody] = useState(false);
|
||||
@@ -237,7 +225,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
if (next.mode !== input.mode) {
|
||||
setFocusModeBody(keyboardPresent || fieldFocused.current);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}
|
||||
setInput(next);
|
||||
},
|
||||
@@ -297,7 +284,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
const result = await connect(connection);
|
||||
if (!result) return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
@@ -305,29 +291,13 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
const targetHostName =
|
||||
connection.kind === "relay"
|
||||
? (uriHostLabel(connection.link) ?? "host")
|
||||
: connection.endpoint;
|
||||
setRefusalPresentation(
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: targetHostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
);
|
||||
// URI mode has no Password field, so a password refusal asks for it here.
|
||||
if (input.mode === "uri" && isPasswordRefusal(rejection)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const message = describeFailure(connection, error);
|
||||
setErrorMessage(message);
|
||||
// URI mode has no Password field, so a rejected password is asked for here.
|
||||
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
return;
|
||||
}
|
||||
if (connection.kind === "direct" && !isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
|
||||
}
|
||||
@@ -447,9 +417,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
)}
|
||||
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="direct-host-refusal" />
|
||||
) : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
@@ -503,7 +470,6 @@ function DirectFormFields({
|
||||
if (isSaving) return;
|
||||
onChange(editForm(input, { useTls: !input.useTls }));
|
||||
}, [input, isSaving, onChange]);
|
||||
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
}, []);
|
||||
@@ -564,7 +530,6 @@ function DirectFormFields({
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={input.useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
{...tlsCheckboxKeyProps}
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
{input.useTls ? (
|
||||
|
||||
@@ -21,13 +21,7 @@ import {
|
||||
resolveControlInteractionStyles,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { resolveHostRefusal, type HostRefusalPresentation } from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import {
|
||||
DaemonConnectionTestError,
|
||||
getConnectionHelloRejection,
|
||||
} from "@/utils/test-daemon-connection";
|
||||
import { DaemonConnectionTestError } from "@/utils/test-daemon-connection";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
@@ -111,9 +105,6 @@ export function AddRemoteSshHostModal({
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.remoteSsh.title") }), [t]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
@@ -123,7 +114,6 @@ export function AddRemoteSshHostModal({
|
||||
passwordInputRef.current?.replaceText("");
|
||||
setIsPasswordVisible(false);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}, []);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
@@ -158,25 +148,11 @@ export function AddRemoteSshHostModal({
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
result = await probeAndUpsertRemoteSshConnection({
|
||||
...target,
|
||||
password: passwordRef.current === "" ? undefined : passwordRef.current,
|
||||
});
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
setRefusalPresentation(
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: target.host,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const message =
|
||||
error instanceof DaemonConnectionTestError
|
||||
? t("pairing.remoteSsh.errors.failedToConnect", { detail: error.message })
|
||||
@@ -288,9 +264,6 @@ export function AddRemoteSshHostModal({
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</Field>
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="remote-ssh-refusal" />
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
uriHostLabel,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
} from "./direct-connection";
|
||||
@@ -268,11 +267,4 @@ describe("resolving the connection", () => {
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts a short host label from pairing links without exposing query credentials", () => {
|
||||
const relayWithPassword = `${RELAY_LINK}&password=top-secret`;
|
||||
expect(uriHostLabel(relayWithPassword)).toBe("srv_abc");
|
||||
expect(uriHostLabel(OFFER_LINK)).toBe("srv_offer");
|
||||
expect(uriHostLabel("relay://invalid?password=top-secret")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -163,7 +163,7 @@ function uriToForm(uri: string): DirectConnectionForm {
|
||||
};
|
||||
}
|
||||
|
||||
export function uriHostLabel(uri: string): string | null {
|
||||
function uriHostLabel(uri: string): string | null {
|
||||
const trimmed = uri.trim();
|
||||
if (isPairingLink(trimmed)) {
|
||||
try {
|
||||
|
||||
@@ -6,20 +6,14 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { Link } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations, type PasswordRequiredPairing } from "@/runtime/host-runtime";
|
||||
import { uriHostLabel } from "./direct-connection";
|
||||
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
AdaptiveTextInput,
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalPresentation,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { PairingTargetTracker } from "@/components/pair-link-credentials";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
@@ -27,7 +21,14 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
function parsedHostLabel(input: string): string {
|
||||
return uriHostLabel(input) ?? "host";
|
||||
try {
|
||||
if (input.startsWith("relay://") || input.includes("#connect=")) {
|
||||
return parseRelayConnectionUri(input).offer.serverId;
|
||||
}
|
||||
return parseConnectionOfferFromUrl(input)?.serverId ?? "host";
|
||||
} catch {
|
||||
return "host";
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
@@ -115,9 +116,6 @@ function PairLinkModalContent({
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
const [password, setPassword] = useState("");
|
||||
const [needsPassword, setNeedsPassword] = useState(passwordRequired !== undefined);
|
||||
const [passwordResetKey, resetPasswordInput] = useReducer((key: number) => key + 1, 0);
|
||||
@@ -128,7 +126,6 @@ function PairLinkModalContent({
|
||||
inputRef.current?.replaceText("");
|
||||
setPassword("");
|
||||
setNeedsPassword(false);
|
||||
setRefusalPresentation(null);
|
||||
resetPasswordInput();
|
||||
}, []);
|
||||
|
||||
@@ -164,7 +161,6 @@ function PairLinkModalContent({
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
const result = await pairing.submit(raw, password || undefined);
|
||||
if (result.status === "cancelled") return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
@@ -172,22 +168,13 @@ function PairLinkModalContent({
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: parsedHostLabel(raw),
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
setRefusalPresentation(presentation);
|
||||
setNeedsPassword(isPasswordRefusal(rejection));
|
||||
return;
|
||||
}
|
||||
const message =
|
||||
error instanceof Error ? error.message : t("pairing.link.errors.unableToPair");
|
||||
setErrorMessage(message);
|
||||
if (getConnectionAuthFailureReason(error)) {
|
||||
setNeedsPassword(true);
|
||||
return;
|
||||
}
|
||||
if (!isMobile) {
|
||||
Alert.alert(t("pairing.link.alert.failedTitle"), message);
|
||||
}
|
||||
@@ -204,7 +191,6 @@ function PairLinkModalContent({
|
||||
setNeedsPassword(false);
|
||||
resetPasswordInput();
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}
|
||||
offerUrlRef.current = next;
|
||||
}, []);
|
||||
@@ -241,9 +227,6 @@ function PairLinkModalContent({
|
||||
keyboardType="url"
|
||||
/>
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="pair-link-refusal" />
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{needsPassword ? (
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DaemonHelloRejectedError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ConnectionLinkImport, LinkPairing } from "@/runtime/host-runtime";
|
||||
import { openPairScan, type PairScanModel } from "./pair-scan-model";
|
||||
|
||||
@@ -92,35 +91,10 @@ describe("openPairScan", () => {
|
||||
await settled(scan);
|
||||
scan.scan(LINK);
|
||||
|
||||
expect(scan.getState()).toEqual({
|
||||
status: "stopped",
|
||||
error: "Server disconnected",
|
||||
helloRejection: null,
|
||||
hostName: "host",
|
||||
});
|
||||
expect(scan.getState()).toEqual({ status: "stopped", error: "Server disconnected" });
|
||||
expect(imports).toEqual([LINK]);
|
||||
});
|
||||
|
||||
it("stops with structured helloRejection for non-password refusals", async () => {
|
||||
const rejection = {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Re-pair device",
|
||||
};
|
||||
const { scan, imports } = createScanner([new DaemonHelloRejectedError(rejection)]);
|
||||
|
||||
scan.scan("relay://relay.example:443/srv_alpha?key=AAAA");
|
||||
await settled(scan);
|
||||
|
||||
expect(scan.getState()).toEqual({
|
||||
status: "stopped",
|
||||
error: "Connection refused (pairing_required)",
|
||||
helloRejection: rejection,
|
||||
hostName: "srv_alpha",
|
||||
});
|
||||
expect(imports).toEqual(["relay://relay.example:443/srv_alpha?key=AAAA"]);
|
||||
});
|
||||
|
||||
it("does not navigate for an attempt that finishes after the screen closed", async () => {
|
||||
let finish: (outcome: ConnectionLinkImport) => void = () => {};
|
||||
const connected: string[] = [];
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import type { ConnectionLinkImport, PasswordRequiredPairing } from "@/runtime/host-runtime";
|
||||
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
|
||||
/**
|
||||
* One visit to the QR scan screen. The camera reports every frame that shows
|
||||
@@ -15,12 +11,7 @@ export type PairScanState =
|
||||
| { status: "scanning" }
|
||||
| { status: "pairing" }
|
||||
| { status: "passwordRequired"; passwordRequired: PasswordRequiredPairing }
|
||||
| {
|
||||
status: "stopped";
|
||||
error: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
hostName?: string;
|
||||
}
|
||||
| { status: "stopped"; error: string | null }
|
||||
| { status: "connected" };
|
||||
|
||||
export interface PairScanModel {
|
||||
@@ -70,13 +61,7 @@ export function openPairScan(deps: PairScanDependencies): PairScanModel {
|
||||
}
|
||||
publish({ status: "stopped", error: null });
|
||||
} catch (error) {
|
||||
const helloRejection = getConnectionHelloRejection(error);
|
||||
publish({
|
||||
status: "stopped",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
helloRejection,
|
||||
hostName: hostNameFromLink(link),
|
||||
});
|
||||
publish({ status: "stopped", error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,14 +101,3 @@ function pairingLinkFromScan(data: string): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function hostNameFromLink(link: string): string {
|
||||
try {
|
||||
if (link.startsWith("relay://") || link.includes("#connect=")) {
|
||||
return parseRelayConnectionUri(link).offer.serverId;
|
||||
}
|
||||
return parseConnectionOfferFromUrl(link)?.serverId ?? "host";
|
||||
} catch {
|
||||
return "host";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,8 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import type { BarcodeScanningResult, BarcodeSettings } from "expo-camera";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { openPairScan, type PairScanState } from "./pair-scan-model";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { HostRefusalBody } from "@/hosts/host-refusal-body";
|
||||
import { openPairScan } from "./pair-scan-model";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { PairLinkModal } from "./pair-link-modal";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -83,12 +81,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
textAlign: "center",
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
refusalBox: {
|
||||
marginTop: theme.spacing[4],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
permissionCard: {
|
||||
marginTop: theme.spacing[6],
|
||||
padding: theme.spacing[6],
|
||||
@@ -210,7 +202,9 @@ export function PairScanContent({
|
||||
{scanState.status === "pairing" ? (
|
||||
<Text style={styles.helperText}>{t("pairing.scan.pairing")}</Text>
|
||||
) : null}
|
||||
<PairScanStoppedError scanState={scanState} />
|
||||
{scanState.status === "stopped" && scanState.error ? (
|
||||
<Text style={styles.helperText}>{scanState.error}</Text>
|
||||
) : null}
|
||||
{scanState.status === "stopped" ? (
|
||||
<Button
|
||||
style={styles.scanAgainButton}
|
||||
@@ -237,34 +231,3 @@ export function PairScanContent({
|
||||
}
|
||||
|
||||
const BARCODE_SCANNER_SETTINGS: BarcodeSettings = { barcodeTypes: ["qr"] };
|
||||
|
||||
function PairScanStoppedError({ scanState }: { scanState: PairScanState }) {
|
||||
const { t } = useTranslation();
|
||||
if (scanState.status !== "stopped") return null;
|
||||
if (scanState.helloRejection) {
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection: scanState.helloRejection,
|
||||
hostName: scanState.hostName ?? "host",
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
return (
|
||||
<View style={styles.refusalBox} testID="pair-scan-refusal">
|
||||
<Text style={styles.helperText}>{presentation.title}</Text>
|
||||
<HostRefusalBody
|
||||
presentation={presentation}
|
||||
centered
|
||||
numberOfLines={3}
|
||||
testIDPrefix="pair-scan-refusal"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (!scanState.error) return null;
|
||||
return (
|
||||
<Text style={styles.helperText} dataDetectorType="none">
|
||||
{scanState.error}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
type HostConnectionKind,
|
||||
} from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
@@ -161,16 +160,9 @@ export function HostLatencyLabel({ serverId }: { serverId: string }): ReactEleme
|
||||
}
|
||||
|
||||
if (status === "offline" || status === "error") {
|
||||
const label = snapshot?.helloRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: snapshot.helloRejection,
|
||||
hostName: serverId,
|
||||
t,
|
||||
}).shortStatus
|
||||
: t("common.connectionStatus.offline");
|
||||
return (
|
||||
<Text style={styles.statusText} numberOfLines={1}>
|
||||
{label}
|
||||
{t("common.connectionStatus.offline")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useRouter, type Href } from "expo-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { Settings } from "lucide-react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { openHostRefusalSheet } from "@/hosts/host-refusal-sheet-state";
|
||||
import {
|
||||
getHostRefusalActionLabel,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalAction,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalBody, HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { buildSettingsSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
export { HostRefusalBody, HostRefusalInlineAlert };
|
||||
|
||||
export function useHostRefusalAction(serverId: string): (action: HostRefusalAction) => void {
|
||||
const router = useRouter();
|
||||
const openPairLink = useAddHost({ method: "link" });
|
||||
const openScanQr = useAddHost({ method: "scan" });
|
||||
|
||||
return useCallback(
|
||||
(action: HostRefusalAction) => {
|
||||
switch (action.kind) {
|
||||
case "enter_password":
|
||||
if (serverId) openHostRefusalSheet(serverId);
|
||||
return;
|
||||
case "pair_link":
|
||||
openPairLink();
|
||||
return;
|
||||
case "scan_qr":
|
||||
openScanQr();
|
||||
return;
|
||||
case "update_app":
|
||||
router.push(buildSettingsSectionRoute("about") as Href);
|
||||
return;
|
||||
case "retry":
|
||||
if (serverId) {
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
},
|
||||
[openPairLink, openScanQr, router, serverId],
|
||||
);
|
||||
}
|
||||
|
||||
function useHostRefusalBindings(
|
||||
serverId: string,
|
||||
hostName: string,
|
||||
rejection: DaemonHelloRejection,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const runAction = useHostRefusalAction(serverId);
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
[hostName, rejection, t],
|
||||
);
|
||||
|
||||
const handlePrimary = useCallback(() => {
|
||||
runAction(presentation.primaryAction);
|
||||
}, [presentation.primaryAction, runAction]);
|
||||
|
||||
const handleSecondary = useCallback(() => {
|
||||
if (presentation.secondaryAction) {
|
||||
runAction(presentation.secondaryAction);
|
||||
}
|
||||
}, [presentation.secondaryAction, runAction]);
|
||||
|
||||
return { t, presentation, handlePrimary, handleSecondary };
|
||||
}
|
||||
|
||||
export function HostRefusalAlert({
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
testID,
|
||||
}: {
|
||||
serverId: string;
|
||||
hostName: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
testID?: string;
|
||||
}) {
|
||||
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
);
|
||||
|
||||
const description = useMemo(
|
||||
() =>
|
||||
presentation.description || presentation.hostMessage ? (
|
||||
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
|
||||
) : undefined,
|
||||
[presentation, testID],
|
||||
);
|
||||
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={presentation.title}
|
||||
description={description}
|
||||
testID={testID}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onPress={handlePrimary}
|
||||
testID={testID ? `${testID}-primary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.primaryAction, t)}
|
||||
</Button>
|
||||
{presentation.secondaryAction ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onPress={handleSecondary}
|
||||
testID={testID ? `${testID}-secondary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
</InlineAlert>
|
||||
);
|
||||
}
|
||||
|
||||
/** Centered full-view refusal state shared by unreachable workspace and agent routes. */
|
||||
export function HostRefusalEmptyState({
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
onManageHost,
|
||||
testID,
|
||||
testIDPrefix,
|
||||
}: {
|
||||
serverId: string;
|
||||
hostName: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
onManageHost: () => void;
|
||||
testID?: string;
|
||||
testIDPrefix?: string;
|
||||
}) {
|
||||
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.emptyState} testID={testID}>
|
||||
<View style={styles.textStack}>
|
||||
<Text style={styles.title}>{presentation.title}</Text>
|
||||
<HostRefusalBody presentation={presentation} centered testIDPrefix={testIDPrefix} />
|
||||
</View>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handlePrimary}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-primary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.primaryAction, t)}
|
||||
</Button>
|
||||
{presentation.secondaryAction ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={handleSecondary}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-secondary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="outline" leftIcon={Settings} onPress={onManageHost}>
|
||||
{t("workspace.route.manageHost")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
emptyState: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 420,
|
||||
},
|
||||
title: {
|
||||
fontSize: theme.fontSize.lg,
|
||||
fontWeight: theme.fontWeight.semibold,
|
||||
color: theme.colors.foreground,
|
||||
textAlign: "center",
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import type { HostRefusalPresentation } from "@/hosts/host-refusal";
|
||||
|
||||
export function HostRefusalBody({
|
||||
presentation,
|
||||
centered = false,
|
||||
numberOfLines,
|
||||
testIDPrefix,
|
||||
}: {
|
||||
presentation: HostRefusalPresentation;
|
||||
centered?: boolean;
|
||||
numberOfLines?: number;
|
||||
testIDPrefix?: string;
|
||||
}) {
|
||||
if (!presentation.description && !presentation.hostMessage) return null;
|
||||
|
||||
return (
|
||||
<View style={[styles.body, centered && styles.bodyCentered]}>
|
||||
{presentation.description ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
numberOfLines={numberOfLines}
|
||||
style={[styles.description, centered && styles.textCentered]}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-description` : undefined}
|
||||
>
|
||||
{presentation.description}
|
||||
</Text>
|
||||
) : null}
|
||||
{presentation.hostMessage ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
numberOfLines={numberOfLines}
|
||||
style={[styles.hostMessage, centered && styles.textCentered]}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-host-message` : undefined}
|
||||
>
|
||||
{presentation.hostMessage}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Inline refusal alert without action buttons (used in pairing sheets). */
|
||||
export function HostRefusalInlineAlert({
|
||||
presentation,
|
||||
testID,
|
||||
}: {
|
||||
presentation: HostRefusalPresentation;
|
||||
testID?: string;
|
||||
}) {
|
||||
const description = useMemo(
|
||||
() =>
|
||||
presentation.description || presentation.hostMessage ? (
|
||||
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
|
||||
) : undefined,
|
||||
[presentation, testID],
|
||||
);
|
||||
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={presentation.title}
|
||||
description={description}
|
||||
testID={testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
bodyCentered: {
|
||||
alignItems: "center",
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.4),
|
||||
},
|
||||
hostMessage: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.4),
|
||||
},
|
||||
textCentered: {
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
@@ -1,286 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
dismissHostRefusalSheet,
|
||||
getActiveRefusalHostServerId,
|
||||
openHostRefusalSheet,
|
||||
registerActiveRefusalHost,
|
||||
resetHostRefusalSheetState,
|
||||
resolveHostRefusalSheetTarget,
|
||||
setHostRefusalFailed,
|
||||
setHostRefusalSubmitting,
|
||||
useHostRefusalSheetStore,
|
||||
type HostRefusalSnapshotSummary,
|
||||
} from "./host-refusal-sheet-state";
|
||||
|
||||
const PASSWORD_REJECTION: DaemonHelloRejection = {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
};
|
||||
|
||||
const EMPTY_SNAPSHOT: HostRefusalSnapshotSummary = {
|
||||
rejection: null,
|
||||
episode: 0,
|
||||
isOnline: false,
|
||||
};
|
||||
|
||||
describe("host-refusal-sheet-state", () => {
|
||||
beforeEach(() => {
|
||||
resetHostRefusalSheetState();
|
||||
});
|
||||
|
||||
it("auto-pops for the active host when refused and stays quiet when no host is active", () => {
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: null,
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays dismissed for the same refusal episode and re-pops on a new episode", () => {
|
||||
dismissHostRefusalSheet("srv_active", 1);
|
||||
const { dismissedEpisodes } = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 2 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 2,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("never cross-contaminates an online active host when another host has a stale manualOpen and refuses in background", () => {
|
||||
openHostRefusalSheet("srv_staging", 1);
|
||||
const state = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_local",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: state.manualOpen,
|
||||
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 3 },
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reopens a dismissed episode when opened explicitly and keeps submitting mounted across transient clears", () => {
|
||||
dismissHostRefusalSheet("srv_active", 1);
|
||||
openHostRefusalSheet("srv_active", 1);
|
||||
const state = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: state.manualOpen,
|
||||
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: true,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
|
||||
setHostRefusalSubmitting("srv_active");
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: "srv_active",
|
||||
submittingSnapshot: { rejection: null, episode: 1 },
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: null,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the sheet open with an actionable error after a failed retry or submit and expires once the host recovers", () => {
|
||||
setHostRefusalFailed({
|
||||
serverId: "srv_active",
|
||||
message: "Unable to connect to host",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
connectionEpoch: 1,
|
||||
});
|
||||
const { failedAction } = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 1, isOnline: false },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: true,
|
||||
actionErrorMessage: "Unable to connect to host",
|
||||
});
|
||||
|
||||
// Auto-closes once the host comes back online (connectionEpoch increments to 2).
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
// Even if that host later disconnects normally (still epoch 2, offline, no refusal), the stale
|
||||
// failedAction from epoch 1 never reactivates or blocks another host's refusal sheet.
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_other",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1, connectionEpoch: 0 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: false },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_other",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
|
||||
// Explicitly opening another host's sheet also clears any prior failedAction immediately.
|
||||
openHostRefusalSheet("srv_other", 1);
|
||||
expect(useHostRefusalSheetStore.getState().failedAction).toBeNull();
|
||||
});
|
||||
|
||||
it("defers when a HostConfirmationSheet is active and stacks active scopes cleanly", () => {
|
||||
const unregisterFirst = registerActiveRefusalHost("srv_local");
|
||||
const unregisterSecond = registerActiveRefusalHost("srv_staging");
|
||||
|
||||
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
|
||||
"srv_staging",
|
||||
);
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_staging",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
unregisterSecond();
|
||||
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
|
||||
"srv_local",
|
||||
);
|
||||
unregisterFirst();
|
||||
expect(
|
||||
getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,234 +0,0 @@
|
||||
import { useEffect } from "react";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { create } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
|
||||
export interface ActiveRefusalHostScope {
|
||||
id: number;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
export interface ManualRefusalSheetOpen {
|
||||
serverId: string;
|
||||
episode: number;
|
||||
}
|
||||
|
||||
export interface FailedRefusalSheetAction {
|
||||
serverId: string;
|
||||
message: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
connectionEpoch: number;
|
||||
}
|
||||
|
||||
export interface HostRefusalSnapshotSummary {
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
connectionEpoch?: number;
|
||||
isOnline?: boolean;
|
||||
}
|
||||
|
||||
export interface HostRefusalSheetState {
|
||||
activeScopes: ActiveRefusalHostScope[];
|
||||
manualOpen: ManualRefusalSheetOpen | null;
|
||||
submittingServerId: string | null;
|
||||
failedAction: FailedRefusalSheetAction | null;
|
||||
dismissedEpisodes: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface ResolveHostRefusalSheetTargetInput {
|
||||
activeServerId: string | null;
|
||||
activeSnapshot: HostRefusalSnapshotSummary;
|
||||
manualOpen: ManualRefusalSheetOpen | null;
|
||||
manualSnapshot: HostRefusalSnapshotSummary;
|
||||
submittingServerId: string | null;
|
||||
submittingSnapshot: HostRefusalSnapshotSummary;
|
||||
failedAction: FailedRefusalSheetAction | null;
|
||||
failedSnapshot: HostRefusalSnapshotSummary;
|
||||
dismissedEpisodes: Readonly<Record<string, number>>;
|
||||
hasPendingConfirmation: boolean;
|
||||
}
|
||||
|
||||
export interface HostRefusalSheetTarget {
|
||||
serverId: string;
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
isManual: boolean;
|
||||
actionErrorMessage: string | null;
|
||||
}
|
||||
|
||||
let nextScopeId = 1;
|
||||
|
||||
function createInitialState(): HostRefusalSheetState {
|
||||
return {
|
||||
activeScopes: [],
|
||||
manualOpen: null,
|
||||
submittingServerId: null,
|
||||
failedAction: null,
|
||||
dismissedEpisodes: {},
|
||||
};
|
||||
}
|
||||
|
||||
export const useHostRefusalSheetStore = create<HostRefusalSheetState>(() => createInitialState());
|
||||
|
||||
export function getActiveRefusalHostServerId(
|
||||
activeScopes: readonly ActiveRefusalHostScope[],
|
||||
): string | null {
|
||||
return activeScopes.length > 0 ? activeScopes[activeScopes.length - 1].serverId : null;
|
||||
}
|
||||
|
||||
export function resolveHostRefusalSheetTarget(
|
||||
input: ResolveHostRefusalSheetTargetInput,
|
||||
): HostRefusalSheetTarget | null {
|
||||
if (input.hasPendingConfirmation) return null;
|
||||
|
||||
if (input.submittingServerId) {
|
||||
return {
|
||||
serverId: input.submittingServerId,
|
||||
rejection: input.submittingSnapshot.rejection,
|
||||
episode: input.submittingSnapshot.episode,
|
||||
isManual: input.manualOpen?.serverId === input.submittingServerId,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.failedAction &&
|
||||
!input.failedSnapshot.isOnline &&
|
||||
(input.failedSnapshot.connectionEpoch ?? 0) === input.failedAction.connectionEpoch
|
||||
) {
|
||||
return {
|
||||
serverId: input.failedAction.serverId,
|
||||
rejection: input.failedSnapshot.rejection ?? input.failedAction.rejection,
|
||||
episode: input.failedSnapshot.episode,
|
||||
isManual: true,
|
||||
actionErrorMessage: input.failedAction.message,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.manualOpen &&
|
||||
input.manualSnapshot.rejection !== null &&
|
||||
input.manualSnapshot.episode === input.manualOpen.episode
|
||||
) {
|
||||
return {
|
||||
serverId: input.manualOpen.serverId,
|
||||
rejection: input.manualSnapshot.rejection,
|
||||
episode: input.manualSnapshot.episode,
|
||||
isManual: true,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.activeServerId &&
|
||||
input.activeSnapshot.rejection !== null &&
|
||||
input.dismissedEpisodes[input.activeServerId] !== input.activeSnapshot.episode
|
||||
) {
|
||||
return {
|
||||
serverId: input.activeServerId,
|
||||
rejection: input.activeSnapshot.rejection,
|
||||
episode: input.activeSnapshot.episode,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerActiveRefusalHost(serverId: string): () => void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return () => {};
|
||||
const id = nextScopeId++;
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
activeScopes: [...state.activeScopes, { id, serverId: normalized }],
|
||||
}));
|
||||
return () => {
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
activeScopes: state.activeScopes.filter((entry) => entry.id !== id),
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
export function useActiveRefusalHost(serverId: string | null | undefined, enabled = true): void {
|
||||
const normalized = serverId?.trim() ?? "";
|
||||
useEffect(() => {
|
||||
if (!enabled || !normalized) return;
|
||||
return registerActiveRefusalHost(normalized);
|
||||
}, [enabled, normalized]);
|
||||
}
|
||||
|
||||
export function openHostRefusalSheet(serverId: string, episode?: number): void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return;
|
||||
const resolvedEpisode =
|
||||
episode ?? getHostRuntimeStore().getSnapshot(normalized)?.helloRejectionEpisode ?? 0;
|
||||
useHostRefusalSheetStore.setState((state) => {
|
||||
const nextDismissed = { ...state.dismissedEpisodes };
|
||||
delete nextDismissed[normalized];
|
||||
return {
|
||||
manualOpen: { serverId: normalized, episode: resolvedEpisode },
|
||||
failedAction: null,
|
||||
dismissedEpisodes: nextDismissed,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function dismissHostRefusalSheet(serverId: string, episode: number): void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return;
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
manualOpen: state.manualOpen?.serverId === normalized ? null : state.manualOpen,
|
||||
submittingServerId: state.submittingServerId === normalized ? null : state.submittingServerId,
|
||||
failedAction: state.failedAction?.serverId === normalized ? null : state.failedAction,
|
||||
dismissedEpisodes: {
|
||||
...state.dismissedEpisodes,
|
||||
[normalized]: episode,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function setHostRefusalSubmitting(serverId: string | null): void {
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
submittingServerId: serverId,
|
||||
failedAction:
|
||||
serverId !== null && state.failedAction?.serverId === serverId ? null : state.failedAction,
|
||||
}));
|
||||
}
|
||||
|
||||
export function setHostRefusalFailed(input: {
|
||||
serverId: string;
|
||||
message: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
connectionEpoch?: number;
|
||||
}): void {
|
||||
const normalized = input.serverId.trim();
|
||||
if (!normalized) return;
|
||||
const connectionEpoch =
|
||||
input.connectionEpoch ?? getHostRuntimeStore().getSnapshot(normalized)?.connectionEpoch ?? 0;
|
||||
useHostRefusalSheetStore.setState({
|
||||
failedAction: {
|
||||
serverId: normalized,
|
||||
message: input.message,
|
||||
rejection: input.rejection,
|
||||
connectionEpoch,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function clearHostRefusalFailed(serverId: string): void {
|
||||
useHostRefusalSheetStore.setState((state) =>
|
||||
state.failedAction?.serverId === serverId ? { failedAction: null } : state,
|
||||
);
|
||||
}
|
||||
|
||||
export function clearManualHostRefusalOpen(serverId: string): void {
|
||||
useHostRefusalSheetStore.setState((state) =>
|
||||
state.manualOpen?.serverId === serverId ? { manualOpen: null } : state,
|
||||
);
|
||||
}
|
||||
|
||||
export function resetHostRefusalSheetState(): void {
|
||||
nextScopeId = 1;
|
||||
useHostRefusalSheetStore.setState(createInitialState());
|
||||
}
|
||||
@@ -1,611 +0,0 @@
|
||||
import { useCallback, useMemo, useReducer, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Text,
|
||||
View,
|
||||
type PressableStateCallbackType,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { AlertTriangle, Eye, EyeOff } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
SheetHeaderSubtitle,
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
CONTROL_HEIGHTS,
|
||||
createControlGeometry,
|
||||
resolveControlInteractionStyles,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { iconButtonChromeGlyphSize } from "@/components/ui/icon-button-chrome";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
getHostRefusalActionLabel,
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalAction,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { useHostRefusalAction } from "@/hosts/host-refusal-alert";
|
||||
import {
|
||||
clearHostRefusalFailed,
|
||||
clearManualHostRefusalOpen,
|
||||
dismissHostRefusalSheet,
|
||||
getActiveRefusalHostServerId,
|
||||
openHostRefusalSheet,
|
||||
resolveHostRefusalSheetTarget,
|
||||
setHostRefusalFailed,
|
||||
setHostRefusalSubmitting,
|
||||
useHostRefusalSheetStore,
|
||||
} from "@/hosts/host-refusal-sheet-state";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostConfirmation,
|
||||
useHostMutations,
|
||||
useHostRuntimeHelloRejection,
|
||||
useHostRuntimeSnapshot,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
const NO_SHORTCUT: ShortcutKey[] = [];
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle, (theme) => ({
|
||||
color: theme.colors.destructive,
|
||||
}));
|
||||
|
||||
function toRefusalSnapshotSummary(snapshot: ReturnType<typeof useHostRuntimeSnapshot>): {
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
connectionEpoch: number;
|
||||
isOnline: boolean;
|
||||
} {
|
||||
return {
|
||||
rejection: snapshot?.helloRejection ?? null,
|
||||
episode: snapshot?.helloRejectionEpisode ?? 0,
|
||||
connectionEpoch: snapshot?.connectionEpoch ?? 0,
|
||||
isOnline: snapshot?.connectionStatus === "online",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount once at the app root. Auto-pops for the active host when refused, stays quiet for
|
||||
* background hosts, and reopens on explicit user action.
|
||||
*/
|
||||
export function HostRefusalSheetHost() {
|
||||
const activeScopes = useHostRefusalSheetStore((state) => state.activeScopes);
|
||||
const manualOpen = useHostRefusalSheetStore((state) => state.manualOpen);
|
||||
const submittingServerId = useHostRefusalSheetStore((state) => state.submittingServerId);
|
||||
const failedAction = useHostRefusalSheetStore((state) => state.failedAction);
|
||||
const dismissedEpisodes = useHostRefusalSheetStore((state) => state.dismissedEpisodes);
|
||||
const { pending: pendingConfirmation } = useHostConfirmation();
|
||||
|
||||
const activeServerId = getActiveRefusalHostServerId(activeScopes);
|
||||
const activeSnapshot = useHostRuntimeSnapshot(activeServerId ?? "");
|
||||
const manualSnapshot = useHostRuntimeSnapshot(manualOpen?.serverId ?? "");
|
||||
const submittingSnapshot = useHostRuntimeSnapshot(submittingServerId ?? "");
|
||||
const failedSnapshot = useHostRuntimeSnapshot(failedAction?.serverId ?? "");
|
||||
|
||||
const target = resolveHostRefusalSheetTarget({
|
||||
activeServerId,
|
||||
activeSnapshot: toRefusalSnapshotSummary(activeSnapshot),
|
||||
manualOpen,
|
||||
manualSnapshot: toRefusalSnapshotSummary(manualSnapshot),
|
||||
submittingServerId,
|
||||
submittingSnapshot: toRefusalSnapshotSummary(submittingSnapshot),
|
||||
failedAction,
|
||||
failedSnapshot: toRefusalSnapshotSummary(failedSnapshot),
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: pendingConfirmation !== null,
|
||||
});
|
||||
|
||||
if (!target) return null;
|
||||
|
||||
return (
|
||||
<HostRefusalSheet
|
||||
key={target.serverId}
|
||||
serverId={target.serverId}
|
||||
rejection={target.rejection}
|
||||
episode={target.episode}
|
||||
actionErrorMessage={target.actionErrorMessage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Compact warning icon button in workspace headers that reopens `HostRefusalSheet`. */
|
||||
export function HostRefusalHeaderButton({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const rejection = useHostRuntimeHelloRejection(serverId);
|
||||
const hosts = useHosts();
|
||||
const hostName = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
|
||||
[hosts, serverId],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (serverId) openHostRefusalSheet(serverId);
|
||||
}, [serverId]);
|
||||
|
||||
if (!serverId || !rejection) return null;
|
||||
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
|
||||
return (
|
||||
<HeaderToggleButton
|
||||
onPress={handlePress}
|
||||
tooltipLabel={presentation.shortStatus}
|
||||
tooltipKeys={NO_SHORTCUT}
|
||||
tooltipSide="bottom"
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={presentation.shortStatus}
|
||||
testID="workspace-refusal-header-button"
|
||||
>
|
||||
<ThemedAlertTriangle size={iconButtonChromeGlyphSize("large")} />
|
||||
</HeaderToggleButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface HostRefusalSheetProps {
|
||||
serverId: string;
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
actionErrorMessage: string | null;
|
||||
}
|
||||
|
||||
function HostRefusalSheet({
|
||||
serverId,
|
||||
rejection,
|
||||
episode,
|
||||
actionErrorMessage,
|
||||
}: HostRefusalSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const hosts = useHosts();
|
||||
const { submitHostPassword } = useHostMutations();
|
||||
const runRefusalAction = useHostRefusalAction(serverId);
|
||||
const hostName = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const controlSize = isCompact ? "md" : "sm";
|
||||
|
||||
const [retainedRejection, setRetainedRejection] = useState<DaemonHelloRejection | null>(
|
||||
rejection,
|
||||
);
|
||||
if (rejection !== null && rejection !== retainedRejection) {
|
||||
setRetainedRejection(rejection);
|
||||
}
|
||||
const effectiveRejection = rejection ?? retainedRejection;
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [resetCount, bumpResetCount] = useReducer((count: number) => count + 1, 0);
|
||||
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
effectiveRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: effectiveRejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
})
|
||||
: null,
|
||||
[effectiveRejection, hostName, t],
|
||||
);
|
||||
|
||||
const showPasswordForm = effectiveRejection !== null && isPasswordRefusal(effectiveRejection);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
title: presentation?.title ?? "",
|
||||
titleTestID: "host-refusal-sheet-title",
|
||||
subtitle: <SheetHeaderSubtitle text={hostName} testID="host-refusal-sheet-host" />,
|
||||
}),
|
||||
[hostName, presentation?.title],
|
||||
);
|
||||
|
||||
const handleDismiss = useCallback(() => {
|
||||
if (isSubmitting) return;
|
||||
dismissHostRefusalSheet(serverId, episode);
|
||||
}, [episode, isSubmitting, serverId]);
|
||||
|
||||
const handlePasswordChange = useCallback((value: string) => {
|
||||
setPassword(value);
|
||||
setErrorMessage(null);
|
||||
}, []);
|
||||
|
||||
const handleToggleVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((visible) => !visible);
|
||||
}, []);
|
||||
|
||||
const handlePasswordSubmit = useCallback(async () => {
|
||||
if (isSubmitting) return;
|
||||
if (password.length === 0) {
|
||||
setErrorMessage(t("hostRefusal.passwordSheet.requiredError"));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
setHostRefusalSubmitting(serverId);
|
||||
setErrorMessage(null);
|
||||
try {
|
||||
const result = await submitHostPassword(serverId, password);
|
||||
if (result.status === "online") {
|
||||
clearManualHostRefusalOpen(serverId);
|
||||
clearHostRefusalFailed(serverId);
|
||||
return;
|
||||
}
|
||||
if (result.status === "rejected") {
|
||||
clearHostRefusalFailed(serverId);
|
||||
if (useHostRefusalSheetStore.getState().manualOpen?.serverId === serverId) {
|
||||
openHostRefusalSheet(serverId);
|
||||
}
|
||||
if (result.rejection.reason === "incorrect_password") {
|
||||
setPassword("");
|
||||
bumpResetCount();
|
||||
setErrorMessage(t("hostRefusal.incorrectPassword.title"));
|
||||
return;
|
||||
}
|
||||
setErrorMessage(null);
|
||||
return;
|
||||
}
|
||||
const message = result.message || t("pairing.direct.errors.unableToConnect");
|
||||
if (effectiveRejection) {
|
||||
setHostRefusalFailed({ serverId, message, rejection: effectiveRejection });
|
||||
}
|
||||
setErrorMessage(message);
|
||||
} finally {
|
||||
setHostRefusalSubmitting(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [effectiveRejection, isSubmitting, password, serverId, submitHostPassword, t]);
|
||||
|
||||
const handleSubmitPress = useCallback(() => {
|
||||
void handlePasswordSubmit();
|
||||
}, [handlePasswordSubmit]);
|
||||
|
||||
const executeNonPasswordAction = useCallback(
|
||||
async (action: HostRefusalAction) => {
|
||||
if (isSubmitting) return;
|
||||
if (action.kind === "retry") {
|
||||
setIsSubmitting(true);
|
||||
setHostRefusalSubmitting(serverId);
|
||||
try {
|
||||
await getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
const next = getHostRuntimeStore().getSnapshot(serverId);
|
||||
if (next?.connectionStatus === "online") {
|
||||
clearManualHostRefusalOpen(serverId);
|
||||
clearHostRefusalFailed(serverId);
|
||||
} else if (next?.helloRejection) {
|
||||
clearHostRefusalFailed(serverId);
|
||||
} else {
|
||||
const message = next?.lastError?.trim() || t("pairing.direct.errors.unableToConnect");
|
||||
if (effectiveRejection) {
|
||||
setHostRefusalFailed({
|
||||
serverId,
|
||||
message,
|
||||
rejection: effectiveRejection,
|
||||
connectionEpoch: next?.connectionEpoch,
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setHostRefusalSubmitting(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
dismissHostRefusalSheet(serverId, episode);
|
||||
runRefusalAction(action);
|
||||
},
|
||||
[effectiveRejection, episode, isSubmitting, runRefusalAction, serverId, t],
|
||||
);
|
||||
|
||||
const handlePrimaryPress = useCallback(() => {
|
||||
if (!presentation) return;
|
||||
void executeNonPasswordAction(presentation.primaryAction);
|
||||
}, [executeNonPasswordAction, presentation]);
|
||||
|
||||
const handleSecondaryPress = useCallback(() => {
|
||||
if (!presentation?.secondaryAction) return;
|
||||
void executeNonPasswordAction(presentation.secondaryAction);
|
||||
}, [executeNonPasswordAction, presentation]);
|
||||
|
||||
const primaryButtonLabel = useMemo(() => {
|
||||
if (isSubmitting) return t("hostRefusal.passwordSheet.connecting");
|
||||
if (showPasswordForm) return t("hostRefusal.passwordSheet.connect");
|
||||
return presentation ? getHostRefusalActionLabel(presentation.primaryAction, t) : "";
|
||||
}, [isSubmitting, presentation, showPasswordForm, t]);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
size={controlSize}
|
||||
onPress={handleDismiss}
|
||||
disabled={isSubmitting}
|
||||
testID="host-refusal-sheet-dismiss"
|
||||
>
|
||||
{t("common.actions.dismiss")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
size={controlSize}
|
||||
onPress={showPasswordForm ? handleSubmitPress : handlePrimaryPress}
|
||||
disabled={isSubmitting}
|
||||
testID={
|
||||
showPasswordForm ? "host-refusal-sheet-submit" : "host-refusal-sheet-primary-action"
|
||||
}
|
||||
>
|
||||
{primaryButtonLabel}
|
||||
</Button>
|
||||
</View>
|
||||
),
|
||||
[
|
||||
controlSize,
|
||||
handleDismiss,
|
||||
handlePrimaryPress,
|
||||
handleSubmitPress,
|
||||
isSubmitting,
|
||||
primaryButtonLabel,
|
||||
showPasswordForm,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
if (!effectiveRejection || !presentation) return null;
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible
|
||||
onClose={handleDismiss}
|
||||
footer={footer}
|
||||
testID="host-refusal-sheet"
|
||||
>
|
||||
<View style={styles.content}>
|
||||
{presentation.description ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
style={styles.description}
|
||||
testID="host-refusal-sheet-description"
|
||||
>
|
||||
{presentation.description}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{presentation.hostMessage ? (
|
||||
<View style={styles.hostMessageCard}>
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
style={styles.hostMessage}
|
||||
testID="host-refusal-sheet-host-message"
|
||||
>
|
||||
{presentation.hostMessage}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{showPasswordForm ? (
|
||||
<HostRefusalPasswordField
|
||||
serverId={serverId}
|
||||
controlSize={controlSize}
|
||||
resetCount={resetCount}
|
||||
errorMessage={errorMessage ?? actionErrorMessage}
|
||||
isPasswordVisible={isPasswordVisible}
|
||||
isSubmitting={isSubmitting}
|
||||
onChangeText={handlePasswordChange}
|
||||
onToggleVisibility={handleToggleVisibility}
|
||||
onSubmit={handleSubmitPress}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!showPasswordForm && actionErrorMessage ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={actionErrorMessage}
|
||||
testID="host-refusal-sheet-error"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!showPasswordForm && presentation.secondaryAction ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size={controlSize}
|
||||
onPress={handleSecondaryPress}
|
||||
disabled={isSubmitting}
|
||||
testID="host-refusal-sheet-secondary-action"
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function HostRefusalPasswordField({
|
||||
serverId,
|
||||
controlSize,
|
||||
resetCount,
|
||||
errorMessage,
|
||||
isPasswordVisible,
|
||||
isSubmitting,
|
||||
onChangeText,
|
||||
onToggleVisibility,
|
||||
onSubmit,
|
||||
}: {
|
||||
serverId: string;
|
||||
controlSize: "sm" | "md";
|
||||
resetCount: number;
|
||||
errorMessage: string | null;
|
||||
isPasswordVisible: boolean;
|
||||
isSubmitting: boolean;
|
||||
onChangeText: (value: string) => void;
|
||||
onToggleVisibility: () => void;
|
||||
onSubmit: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const iconButtonStyle = useCallback(
|
||||
(
|
||||
state: PressableStateCallbackType & { hovered?: boolean; focused?: boolean },
|
||||
): StyleProp<ViewStyle> => [
|
||||
styles.iconButton,
|
||||
controlSize === "sm" ? styles.iconButtonSm : styles.iconButtonMd,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: styles.controlRest,
|
||||
controlHover: styles.controlHover,
|
||||
controlActive: styles.controlActive,
|
||||
controlDisabled: styles.controlDisabled,
|
||||
},
|
||||
{
|
||||
hovered: state.hovered,
|
||||
pressed: state.pressed,
|
||||
focused: state.focused,
|
||||
disabled: isSubmitting,
|
||||
},
|
||||
),
|
||||
],
|
||||
[controlSize, isSubmitting],
|
||||
);
|
||||
|
||||
return (
|
||||
<Field
|
||||
label={t("hostRefusal.passwordSheet.label")}
|
||||
error={errorMessage}
|
||||
testID="host-password-field"
|
||||
>
|
||||
<View style={styles.passwordRow}>
|
||||
<View style={styles.passwordInputWrap}>
|
||||
<FormTextInput
|
||||
testID="host-password-input"
|
||||
nativeID="host-password-input"
|
||||
size={controlSize}
|
||||
resetKey={`host-password-${serverId}-${resetCount}`}
|
||||
initialValue=""
|
||||
accessibilityLabel={t("hostRefusal.passwordSheet.label")}
|
||||
placeholder={t("hostRefusal.passwordSheet.placeholder")}
|
||||
onChangeText={onChangeText}
|
||||
autoFocus
|
||||
secureTextEntry={!isPasswordVisible}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!isSubmitting}
|
||||
invalid={errorMessage !== null}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={onSubmit}
|
||||
/>
|
||||
</View>
|
||||
<PressHighlight
|
||||
style={iconButtonStyle}
|
||||
onPress={onToggleVisibility}
|
||||
disabled={isSubmitting}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
isPasswordVisible
|
||||
? t("pairing.direct.passwordVisibility.hide")
|
||||
: t("pairing.direct.passwordVisibility.show")
|
||||
}
|
||||
testID="host-password-visibility-toggle"
|
||||
>
|
||||
{isPasswordVisible ? <ThemedEyeOff size={18} /> : <ThemedEye size={18} />}
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
return {
|
||||
content: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: Math.round(theme.fontSize.base * 1.45),
|
||||
},
|
||||
hostMessageCard: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
hostMessage: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.45),
|
||||
},
|
||||
passwordRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "stretch",
|
||||
width: "100%",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
passwordInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
iconButton: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
iconButtonSm: {
|
||||
minHeight: CONTROL_HEIGHTS.sm,
|
||||
width: CONTROL_HEIGHTS.sm,
|
||||
},
|
||||
iconButtonMd: {
|
||||
minHeight: CONTROL_HEIGHTS.md,
|
||||
width: CONTROL_HEIGHTS.md,
|
||||
},
|
||||
controlRest: {
|
||||
...geometry.controlRest,
|
||||
},
|
||||
controlHover: {
|
||||
...geometry.controlHover,
|
||||
},
|
||||
controlActive: {
|
||||
...geometry.controlActive,
|
||||
},
|
||||
controlDisabled: {
|
||||
...geometry.controlDisabled,
|
||||
},
|
||||
footer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -1,231 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TFunction } from "i18next";
|
||||
import { en } from "@/i18n/resources/en";
|
||||
import {
|
||||
SUPPORTED_CREDENTIAL_KINDS,
|
||||
getHostRefusalActionLabel,
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
} from "./host-refusal";
|
||||
|
||||
function createTestT(): TFunction {
|
||||
const resolveKey = (key: string): string => {
|
||||
const parts = key.split(".");
|
||||
let current: unknown = en;
|
||||
for (const part of parts) {
|
||||
if (current && typeof current === "object" && part in current) {
|
||||
current = (current as Record<string, unknown>)[part];
|
||||
} else {
|
||||
throw new Error(`Missing i18n key in en: ${key}`);
|
||||
}
|
||||
}
|
||||
if (typeof current !== "string") {
|
||||
throw new Error(`Expected string for i18n key: ${key}`);
|
||||
}
|
||||
return current;
|
||||
};
|
||||
return ((key: string, params?: Record<string, unknown>) => {
|
||||
let text = resolveKey(key);
|
||||
if (params) {
|
||||
for (const [name, value] of Object.entries(params)) {
|
||||
text = text.replaceAll(`{{${name}}}`, String(value));
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}) as unknown as TFunction;
|
||||
}
|
||||
|
||||
describe("resolveHostRefusal", () => {
|
||||
const t = createTestT();
|
||||
|
||||
it("uses trusted localized copy and ignores host message for known reasons", () => {
|
||||
const passwordRequired = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "password_required",
|
||||
accepts: ["password"],
|
||||
message: "Visit https://evil.test for password",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
});
|
||||
expect(passwordRequired).toEqual({
|
||||
title: "Password required",
|
||||
description: "Enter this host's password to connect.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
|
||||
const incorrectPassword = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
message: "Phishing text",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
});
|
||||
expect(incorrectPassword).toEqual({
|
||||
title: "Incorrect password",
|
||||
description: "The saved password was rejected by this host.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
|
||||
const incompatibleDesktop = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
message: "Download from https://evil.test",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
canUpdateApp: true,
|
||||
});
|
||||
expect(incompatibleDesktop).toEqual({
|
||||
title: "Update Paseo to connect",
|
||||
description: "This host requires a newer version of Paseo.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Update required",
|
||||
primaryAction: { kind: "update_app" },
|
||||
});
|
||||
|
||||
const incompatibleWeb = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
canUpdateApp: false,
|
||||
});
|
||||
expect(incompatibleWeb.primaryAction).toEqual({ kind: "retry" });
|
||||
});
|
||||
|
||||
it("offers password recovery when an unknown reason accepts password", () => {
|
||||
const result = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "password_expired",
|
||||
accepts: ["password"],
|
||||
message: "Rotate your password.",
|
||||
},
|
||||
hostName: "Staging",
|
||||
t,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
title: "Password required",
|
||||
description: null,
|
||||
hostMessage: "Message from Staging: “Rotate your password.”",
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
expect(isPasswordRefusal({ reason: "password_expired", accepts: ["password"] })).toBe(true);
|
||||
});
|
||||
|
||||
it("asks to update Paseo when an unknown reason requires an unsupported credential kind", () => {
|
||||
expect(SUPPORTED_CREDENTIAL_KINDS).toEqual(["password"]);
|
||||
const result = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Visit https://evil.test",
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
canUpdateApp: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
title: "Update Paseo to connect",
|
||||
description: "This host requires a sign-in method this version of Paseo does not support.",
|
||||
hostMessage: "Message from Prod Box: “Visit https://evil.test”",
|
||||
shortStatus: "Update required",
|
||||
primaryAction: { kind: "update_app" },
|
||||
});
|
||||
expect(isPasswordRefusal({ reason: "pairing_required", accepts: ["invite"] })).toBe(false);
|
||||
});
|
||||
|
||||
it("automatically offers pairing actions once invite is in supportedCredentials", () => {
|
||||
const mobile = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite", "password"],
|
||||
message: "Device access expired.",
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
supportedCredentials: ["password", "invite"],
|
||||
canScanQr: true,
|
||||
});
|
||||
expect(mobile).toEqual({
|
||||
title: "Pairing required",
|
||||
description: null,
|
||||
hostMessage: "Message from Prod Box: “Device access expired.”",
|
||||
shortStatus: "Pairing required",
|
||||
primaryAction: { kind: "scan_qr" },
|
||||
secondaryAction: { kind: "pair_link" },
|
||||
});
|
||||
|
||||
const desktop = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite", "password"],
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
supportedCredentials: ["password", "invite"],
|
||||
canScanQr: false,
|
||||
});
|
||||
expect(desktop).toEqual({
|
||||
title: "Pairing required",
|
||||
description: "Pair this device with the host again to connect.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Pairing required",
|
||||
primaryAction: { kind: "pair_link" },
|
||||
secondaryAction: { kind: "enter_password" },
|
||||
});
|
||||
});
|
||||
|
||||
it("frames unknown non-credential refusals as host speech with Retry", () => {
|
||||
const withMessage = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
},
|
||||
hostName: "Build Server",
|
||||
t,
|
||||
});
|
||||
expect(withMessage).toEqual({
|
||||
title: "Connection refused by Build Server",
|
||||
description: null,
|
||||
hostMessage: "Message from Build Server: “Back in 5m”",
|
||||
shortStatus: "Refused",
|
||||
primaryAction: { kind: "retry" },
|
||||
});
|
||||
|
||||
const withoutMessage = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
},
|
||||
hostName: "Build Server",
|
||||
t,
|
||||
});
|
||||
expect(withoutMessage).toEqual({
|
||||
title: "Connection refused by Build Server",
|
||||
description: "Check this host's settings and try again.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Refused",
|
||||
primaryAction: { kind: "retry" },
|
||||
});
|
||||
});
|
||||
|
||||
it("maps every HostRefusalAction to a localized label", () => {
|
||||
expect(getHostRefusalActionLabel({ kind: "enter_password" }, t)).toBe("Enter password");
|
||||
expect(getHostRefusalActionLabel({ kind: "pair_link" }, t)).toBe("Paste pairing link");
|
||||
expect(getHostRefusalActionLabel({ kind: "scan_qr" }, t)).toBe("Scan QR code");
|
||||
expect(getHostRefusalActionLabel({ kind: "update_app" }, t)).toBe("Check for updates");
|
||||
expect(getHostRefusalActionLabel({ kind: "retry" }, t)).toBe("Retry");
|
||||
});
|
||||
});
|
||||
@@ -1,169 +0,0 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
export const SUPPORTED_CREDENTIAL_KINDS = ["password"] as const;
|
||||
export type SupportedCredentialKind = (typeof SUPPORTED_CREDENTIAL_KINDS)[number];
|
||||
|
||||
export type HostRefusalAction =
|
||||
| { kind: "enter_password" }
|
||||
| { kind: "pair_link" }
|
||||
| { kind: "scan_qr" }
|
||||
| { kind: "update_app" }
|
||||
| { kind: "retry" };
|
||||
|
||||
export interface HostRefusalPresentation {
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly hostMessage: string | null;
|
||||
readonly shortStatus: string;
|
||||
readonly primaryAction: HostRefusalAction;
|
||||
readonly secondaryAction?: HostRefusalAction;
|
||||
}
|
||||
|
||||
export interface ResolveHostRefusalOptions {
|
||||
readonly rejection: DaemonHelloRejection;
|
||||
readonly hostName: string;
|
||||
readonly t: TFunction;
|
||||
readonly supportedCredentials?: readonly string[];
|
||||
readonly canUpdateApp?: boolean;
|
||||
readonly canScanQr?: boolean;
|
||||
}
|
||||
|
||||
export function isPasswordRefusal(
|
||||
rejection: DaemonHelloRejection,
|
||||
supportedCredentials: readonly string[] = SUPPORTED_CREDENTIAL_KINDS,
|
||||
): boolean {
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return true;
|
||||
}
|
||||
if (rejection.reason === "incompatible_protocol") {
|
||||
return false;
|
||||
}
|
||||
return supportedCredentials.includes("password") && rejection.accepts.includes("password");
|
||||
}
|
||||
|
||||
function resolveKnownHostRefusal(
|
||||
reason: string,
|
||||
t: TFunction,
|
||||
canUpdateApp: boolean,
|
||||
): HostRefusalPresentation | null {
|
||||
// Known reasons ignore rejection.message completely and render only trusted client copy.
|
||||
if (reason === "password_required") {
|
||||
return {
|
||||
title: t("hostRefusal.passwordRequired.title"),
|
||||
description: t("hostRefusal.passwordRequired.description"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
if (reason === "incorrect_password") {
|
||||
return {
|
||||
title: t("hostRefusal.incorrectPassword.title"),
|
||||
description: t("hostRefusal.incorrectPassword.description"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
if (reason === "incompatible_protocol") {
|
||||
return {
|
||||
title: t("hostRefusal.updateRequired.title"),
|
||||
description: t("hostRefusal.updateRequired.incompatibleDescription"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
|
||||
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveInviteSecondaryAction(
|
||||
canScanQr: boolean,
|
||||
acceptsPassword: boolean,
|
||||
): HostRefusalAction | undefined {
|
||||
if (canScanQr) return { kind: "pair_link" };
|
||||
if (acceptsPassword) return { kind: "enter_password" };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveHostRefusal(options: ResolveHostRefusalOptions): HostRefusalPresentation {
|
||||
const {
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
supportedCredentials = SUPPORTED_CREDENTIAL_KINDS,
|
||||
canUpdateApp = false,
|
||||
canScanQr = false,
|
||||
} = options;
|
||||
|
||||
const known = resolveKnownHostRefusal(rejection.reason, t, canUpdateApp);
|
||||
if (known) return known;
|
||||
|
||||
const supportedSet = new Set<string>(supportedCredentials);
|
||||
const supportedAccepts = rejection.accepts.filter((kind) => supportedSet.has(kind));
|
||||
const hostMessage = rejection.message
|
||||
? t("hostRefusal.messageFromHost", { hostName, message: rejection.message })
|
||||
: null;
|
||||
|
||||
if (supportedAccepts.includes("invite")) {
|
||||
const primaryAction: HostRefusalAction = canScanQr
|
||||
? { kind: "scan_qr" }
|
||||
: { kind: "pair_link" };
|
||||
const secondaryAction = resolveInviteSecondaryAction(
|
||||
canScanQr,
|
||||
supportedAccepts.includes("password"),
|
||||
);
|
||||
return {
|
||||
title: t("hostRefusal.pairingRequired.title"),
|
||||
description: hostMessage ? null : t("hostRefusal.pairingRequired.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.pairingRequired"),
|
||||
primaryAction,
|
||||
...(secondaryAction ? { secondaryAction } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (supportedAccepts.includes("password")) {
|
||||
return {
|
||||
title: t("hostRefusal.passwordRequired.title"),
|
||||
description: hostMessage ? null : t("hostRefusal.passwordRequired.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
|
||||
if (rejection.accepts.length > 0 && supportedAccepts.length === 0) {
|
||||
return {
|
||||
title: t("hostRefusal.updateRequired.title"),
|
||||
description: t("hostRefusal.updateRequired.unsupportedAuthDescription"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
|
||||
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: t("hostRefusal.refusedByHost.title", { hostName }),
|
||||
description: hostMessage ? null : t("hostRefusal.refusedByHost.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.refused"),
|
||||
primaryAction: { kind: "retry" },
|
||||
};
|
||||
}
|
||||
|
||||
export function getHostRefusalActionLabel(action: HostRefusalAction, t: TFunction): string {
|
||||
switch (action.kind) {
|
||||
case "enter_password":
|
||||
return t("hostRefusal.actions.enterPassword");
|
||||
case "pair_link":
|
||||
return t("hostRefusal.actions.pairLink");
|
||||
case "scan_qr":
|
||||
return t("hostRefusal.actions.scanQr");
|
||||
case "update_app":
|
||||
return t("hostRefusal.actions.checkForUpdates");
|
||||
case "retry":
|
||||
return t("common.actions.retry");
|
||||
}
|
||||
}
|
||||
@@ -2019,56 +2019,6 @@ export const ar: TranslationResources = {
|
||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
||||
confirmAction: "إيقاف",
|
||||
},
|
||||
access: {
|
||||
title: "الوصول",
|
||||
passwordLabel: "كلمة المرور",
|
||||
passwordNotSetSummary: "غير مضبوطة",
|
||||
passwordNotSetHint: "يمكن لأي شخص لديه رابط اقتران الاتصال",
|
||||
passwordSetSummary: "مضبوطة",
|
||||
passwordSetHint: "مطلوبة للاتصالات البعيدة",
|
||||
passwordEnvSummary: "مضبوطة عبر البيئة",
|
||||
passwordEnvHint: "يتم التحكم بها عبر PASEO_PASSWORD على هذا المضيف",
|
||||
},
|
||||
password: {
|
||||
setTitle: "تعيين كلمة المرور",
|
||||
changeTitle: "تغيير كلمة المرور",
|
||||
removeTitle: "إزالة كلمة المرور",
|
||||
setAction: "تعيين كلمة المرور",
|
||||
setting: "جارٍ التعيين...",
|
||||
saveAction: "حفظ كلمة المرور",
|
||||
saving: "جارٍ الحفظ...",
|
||||
removeAction: "إزالة كلمة المرور",
|
||||
removing: "جارٍ الإزالة...",
|
||||
show: "إظهار كلمة المرور",
|
||||
hide: "إخفاء كلمة المرور",
|
||||
setInfo:
|
||||
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور هذه. سيبقى هذا الجهاز متصلًا.",
|
||||
changeInfo:
|
||||
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور الجديدة. سيبقى هذا الجهاز متصلًا.",
|
||||
removeWarning: "سيتمكن أي شخص لديه رابط اقتران أو وصول إلى الشبكة من الاتصال دون كلمة مرور.",
|
||||
fields: {
|
||||
current: "كلمة المرور الحالية",
|
||||
new: "كلمة المرور الجديدة",
|
||||
confirm: "تأكيد كلمة المرور",
|
||||
confirmNew: "تأكيد كلمة المرور الجديدة",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "أدخل كلمة المرور الحالية.",
|
||||
currentIncorrect: "كلمة المرور الحالية غير صحيحة.",
|
||||
tooShort: "استخدم 8 أحرف على الأقل.",
|
||||
tooLong: "يجب أن تكون كلمة المرور 72 بايت أو أقل.",
|
||||
mismatch: "كلمتا المرور غير متطابقتين.",
|
||||
},
|
||||
toast: {
|
||||
set: "تم تعيين كلمة المرور.",
|
||||
setDisconnectedOne: "تم تعيين كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
|
||||
setDisconnectedOther: "تم تعيين كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
|
||||
updated: "تم تحديث كلمة المرور.",
|
||||
updatedDisconnectedOne: "تم تحديث كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
|
||||
updatedDisconnectedOther: "تم تحديث كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
|
||||
removed: "تمت إزالة كلمة المرور.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "العملاء المتصلون",
|
||||
thisDevice: "هذا الجهاز",
|
||||
@@ -2135,50 +2085,6 @@ export const ar: TranslationResources = {
|
||||
daysAgo: "منذ {{count}} ي",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "كلمة المرور مطلوبة",
|
||||
description: "أدخل كلمة مرور هذا المضيف للاتصال.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "كلمة مرور غير صحيحة",
|
||||
description: "رفض هذا المضيف كلمة المرور المحفوظة.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "حدّث Paseo للاتصال",
|
||||
incompatibleDescription: "يتطلب هذا المضيف إصدارًا أحدث من Paseo.",
|
||||
unsupportedAuthDescription: "يتطلب هذا المضيف طريقة تسجيل دخول لا يدعمها هذا الإصدار من Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "الإقران مطلوب",
|
||||
description: "أعد إقران هذا الجهاز مع المضيف للاتصال.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "رفض {{hostName}} الاتصال",
|
||||
description: "تحقق من إعدادات هذا المضيف ثم حاول مجددًا.",
|
||||
},
|
||||
messageFromHost: "رسالة من {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "كلمة المرور مطلوبة",
|
||||
updateRequired: "التحديث مطلوب",
|
||||
pairingRequired: "الإقران مطلوب",
|
||||
refused: "مرفوض",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "إدخال كلمة المرور",
|
||||
pairLink: "لصق رابط الإقران",
|
||||
scanQr: "مسح رمز QR",
|
||||
checkForUpdates: "التحقق من التحديثات",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "كلمة مرور {{hostName}}",
|
||||
label: "كلمة المرور",
|
||||
placeholder: "أدخل كلمة مرور المضيف",
|
||||
connect: "اتصال",
|
||||
connecting: "جارٍ الاتصال...",
|
||||
requiredError: "أدخل كلمة مرور للمتابعة.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "كلمة المرور لـ {{host}}",
|
||||
@@ -2343,8 +2249,6 @@ export const ar: TranslationResources = {
|
||||
hint: "قم بمسح رمز QR هذا باستخدام Paseo على هاتفك، أو انسخ الرابط أدناه.",
|
||||
securityWarning:
|
||||
"تعامل مع رابط الاقتران هذا ككلمة مرور. يمكن لأي شخص يملكه الوصول إلى هذا البرنامج الخفي.",
|
||||
passwordProtected:
|
||||
"كلمة المرور مطلوبة. ستقوم الأجهزة التي تمسح هذا الرمز بإدخال كلمة مرور هذا المضيف.",
|
||||
qrUnavailable: "رمز QR غير متاح.",
|
||||
qrAccessibility: "رمز QR للإقران",
|
||||
retry: "أعد المحاولة",
|
||||
|
||||
@@ -2049,57 +2049,6 @@ export const en = {
|
||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
||||
confirmAction: "Turn off",
|
||||
},
|
||||
access: {
|
||||
title: "Access",
|
||||
passwordLabel: "Password",
|
||||
passwordNotSetSummary: "Not set",
|
||||
passwordNotSetHint: "Anyone with a pairing link can connect",
|
||||
passwordSetSummary: "Set",
|
||||
passwordSetHint: "Required for remote connections",
|
||||
passwordEnvSummary: "Set by environment",
|
||||
passwordEnvHint: "Controlled by PASEO_PASSWORD on this host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Set password",
|
||||
changeTitle: "Change password",
|
||||
removeTitle: "Remove password",
|
||||
setAction: "Set password",
|
||||
setting: "Setting...",
|
||||
saveAction: "Save password",
|
||||
saving: "Saving...",
|
||||
removeAction: "Remove password",
|
||||
removing: "Removing...",
|
||||
show: "Show password",
|
||||
hide: "Hide password",
|
||||
setInfo:
|
||||
"Other remote devices disconnect immediately and will need this password. This device stays connected.",
|
||||
changeInfo:
|
||||
"Other remote devices disconnect immediately and will need the new password. This device stays connected.",
|
||||
removeWarning:
|
||||
"Anyone with a pairing link or network access will be able to connect without a password.",
|
||||
fields: {
|
||||
current: "Current password",
|
||||
new: "New password",
|
||||
confirm: "Confirm password",
|
||||
confirmNew: "Confirm new password",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Enter the current password.",
|
||||
currentIncorrect: "Current password is incorrect.",
|
||||
tooShort: "Use at least 8 characters.",
|
||||
tooLong: "Password must be 72 bytes or fewer.",
|
||||
mismatch: "Passwords do not match.",
|
||||
},
|
||||
toast: {
|
||||
set: "Password set.",
|
||||
setDisconnectedOne: "Password set. Disconnected 1 other device.",
|
||||
setDisconnectedOther: "Password set. Disconnected {{count}} other devices.",
|
||||
updated: "Password updated.",
|
||||
updatedDisconnectedOne: "Password updated. Disconnected 1 other device.",
|
||||
updatedDisconnectedOther: "Password updated. Disconnected {{count}} other devices.",
|
||||
removed: "Password removed.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Connected clients",
|
||||
thisDevice: "This device",
|
||||
@@ -2166,51 +2115,6 @@ export const en = {
|
||||
daysAgo: "{{count}}d ago",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Password required",
|
||||
description: "Enter this host's password to connect.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Incorrect password",
|
||||
description: "The saved password was rejected by this host.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Update Paseo to connect",
|
||||
incompatibleDescription: "This host requires a newer version of Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"This host requires a sign-in method this version of Paseo does not support.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Pairing required",
|
||||
description: "Pair this device with the host again to connect.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Connection refused by {{hostName}}",
|
||||
description: "Check this host's settings and try again.",
|
||||
},
|
||||
messageFromHost: "Message from {{hostName}}: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "Password required",
|
||||
updateRequired: "Update required",
|
||||
pairingRequired: "Pairing required",
|
||||
refused: "Refused",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Enter password",
|
||||
pairLink: "Paste pairing link",
|
||||
scanQr: "Scan QR code",
|
||||
checkForUpdates: "Check for updates",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Password for {{hostName}}",
|
||||
label: "Password",
|
||||
placeholder: "Enter host password",
|
||||
connect: "Connect",
|
||||
connecting: "Connecting...",
|
||||
requiredError: "Enter a password to continue.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Password for {{host}}",
|
||||
@@ -2375,8 +2279,6 @@ export const en = {
|
||||
hint: "Scan this QR code with Paseo on your phone, or copy the link below.",
|
||||
securityWarning:
|
||||
"Treat this pairing link like a password. Anyone with it can access this daemon.",
|
||||
passwordProtected:
|
||||
"Password required. Devices scanning this code will enter this host's password.",
|
||||
qrUnavailable: "QR code unavailable.",
|
||||
qrAccessibility: "Pairing QR code",
|
||||
retry: "Retry",
|
||||
|
||||
@@ -2073,59 +2073,6 @@ export const es: TranslationResources = {
|
||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
||||
confirmAction: "Desactivar",
|
||||
},
|
||||
access: {
|
||||
title: "Acceso",
|
||||
passwordLabel: "Contraseña",
|
||||
passwordNotSetSummary: "Sin configurar",
|
||||
passwordNotSetHint: "Cualquiera con un enlace de emparejamiento puede conectarse",
|
||||
passwordSetSummary: "Configurada",
|
||||
passwordSetHint: "Obligatoria para conexiones remotas",
|
||||
passwordEnvSummary: "Definida por el entorno",
|
||||
passwordEnvHint: "Controlada por PASEO_PASSWORD en este host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Establecer contraseña",
|
||||
changeTitle: "Cambiar contraseña",
|
||||
removeTitle: "Eliminar contraseña",
|
||||
setAction: "Establecer contraseña",
|
||||
setting: "Estableciendo...",
|
||||
saveAction: "Guardar contraseña",
|
||||
saving: "Guardando...",
|
||||
removeAction: "Eliminar contraseña",
|
||||
removing: "Eliminando...",
|
||||
show: "Mostrar contraseña",
|
||||
hide: "Ocultar contraseña",
|
||||
setInfo:
|
||||
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán esta contraseña. Este dispositivo seguirá conectado.",
|
||||
changeInfo:
|
||||
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán la nueva contraseña. Este dispositivo seguirá conectado.",
|
||||
removeWarning:
|
||||
"Cualquiera con un enlace de emparejamiento o acceso a la red podrá conectarse sin contraseña.",
|
||||
fields: {
|
||||
current: "Contraseña actual",
|
||||
new: "Nueva contraseña",
|
||||
confirm: "Confirmar contraseña",
|
||||
confirmNew: "Confirmar nueva contraseña",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Introduce la contraseña actual.",
|
||||
currentIncorrect: "La contraseña actual es incorrecta.",
|
||||
tooShort: "Usa al menos 8 caracteres.",
|
||||
tooLong: "La contraseña debe tener 72 bytes o menos.",
|
||||
mismatch: "Las contraseñas no coinciden.",
|
||||
},
|
||||
toast: {
|
||||
set: "Contraseña establecida.",
|
||||
setDisconnectedOne: "Contraseña establecida. Se desconectó otro dispositivo.",
|
||||
setDisconnectedOther:
|
||||
"Contraseña establecida. Se desconectaron otros {{count}} dispositivos.",
|
||||
updated: "Contraseña actualizada.",
|
||||
updatedDisconnectedOne: "Contraseña actualizada. Se desconectó otro dispositivo.",
|
||||
updatedDisconnectedOther:
|
||||
"Contraseña actualizada. Se desconectaron otros {{count}} dispositivos.",
|
||||
removed: "Contraseña eliminada.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
thisDevice: "Este dispositivo",
|
||||
@@ -2192,51 +2139,6 @@ export const es: TranslationResources = {
|
||||
daysAgo: "hace {{count}} d",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Contraseña requerida",
|
||||
description: "Introduce la contraseña de este host para conectar.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Contraseña incorrecta",
|
||||
description: "Este host rechazó la contraseña guardada.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Actualiza Paseo para conectar",
|
||||
incompatibleDescription: "Este host requiere una versión más reciente de Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Este host requiere un método de inicio de sesión que esta versión de Paseo no admite.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Emparejamiento requerido",
|
||||
description: "Vuelve a emparejar este dispositivo con el host para conectar.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Conexión rechazada por {{hostName}}",
|
||||
description: "Revisa la configuración de este host e inténtalo de nuevo.",
|
||||
},
|
||||
messageFromHost: "Mensaje de {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "Contraseña requerida",
|
||||
updateRequired: "Actualización requerida",
|
||||
pairingRequired: "Emparejamiento requerido",
|
||||
refused: "Rechazado",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Introducir contraseña",
|
||||
pairLink: "Pegar enlace de emparejamiento",
|
||||
scanQr: "Escanear código QR",
|
||||
checkForUpdates: "Buscar actualizaciones",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Contraseña para {{hostName}}",
|
||||
label: "Contraseña",
|
||||
placeholder: "Introduce la contraseña del host",
|
||||
connect: "Conectar",
|
||||
connecting: "Conectando...",
|
||||
requiredError: "Introduce una contraseña para continuar.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Contraseña de {{host}}",
|
||||
@@ -2403,8 +2305,6 @@ export const es: TranslationResources = {
|
||||
hint: "Escanee este códigoQRconPaseoen su teléfono o copie el enlace a continuación.",
|
||||
securityWarning:
|
||||
"Trata este enlace de emparejamiento como una contraseña. Cualquiera que lo tenga puede acceder a este daemon.",
|
||||
passwordProtected:
|
||||
"Contraseña obligatoria. Los dispositivos que escaneen este código deberán introducir la contraseña de este host.",
|
||||
qrUnavailable: "CódigoQRno disponible.",
|
||||
qrAccessibility: "Código QR de emparejamiento",
|
||||
retry: "Rever",
|
||||
|
||||
@@ -2070,58 +2070,6 @@ export const fr: TranslationResources = {
|
||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
||||
confirmAction: "Désactiver",
|
||||
},
|
||||
access: {
|
||||
title: "Accès",
|
||||
passwordLabel: "Mot de passe",
|
||||
passwordNotSetSummary: "Non défini",
|
||||
passwordNotSetHint: "Toute personne disposant d’un lien d’association peut se connecter",
|
||||
passwordSetSummary: "Défini",
|
||||
passwordSetHint: "Requis pour les connexions distantes",
|
||||
passwordEnvSummary: "Défini par l’environnement",
|
||||
passwordEnvHint: "Contrôlé par PASEO_PASSWORD sur cet hôte",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Définir le mot de passe",
|
||||
changeTitle: "Modifier le mot de passe",
|
||||
removeTitle: "Supprimer le mot de passe",
|
||||
setAction: "Définir le mot de passe",
|
||||
setting: "Configuration...",
|
||||
saveAction: "Enregistrer le mot de passe",
|
||||
saving: "Enregistrement...",
|
||||
removeAction: "Supprimer le mot de passe",
|
||||
removing: "Suppression...",
|
||||
show: "Afficher le mot de passe",
|
||||
hide: "Masquer le mot de passe",
|
||||
setInfo:
|
||||
"Les autres appareils distants seront immédiatement déconnectés et devront saisir ce mot de passe. Cet appareil reste connecté.",
|
||||
changeInfo:
|
||||
"Les autres appareils distants seront immédiatement déconnectés et devront saisir le nouveau mot de passe. Cet appareil reste connecté.",
|
||||
removeWarning:
|
||||
"Toute personne disposant d’un lien d’association ou d’un accès réseau pourra se connecter sans mot de passe.",
|
||||
fields: {
|
||||
current: "Mot de passe actuel",
|
||||
new: "Nouveau mot de passe",
|
||||
confirm: "Confirmer le mot de passe",
|
||||
confirmNew: "Confirmer le nouveau mot de passe",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Saisissez le mot de passe actuel.",
|
||||
currentIncorrect: "Le mot de passe actuel est incorrect.",
|
||||
tooShort: "Utilisez au moins 8 caractères.",
|
||||
tooLong: "Le mot de passe doit faire 72 octets ou moins.",
|
||||
mismatch: "Les mots de passe ne correspondent pas.",
|
||||
},
|
||||
toast: {
|
||||
set: "Mot de passe défini.",
|
||||
setDisconnectedOne: "Mot de passe défini. 1 autre appareil déconnecté.",
|
||||
setDisconnectedOther: "Mot de passe défini. {{count}} autres appareils déconnectés.",
|
||||
updated: "Mot de passe mis à jour.",
|
||||
updatedDisconnectedOne: "Mot de passe mis à jour. 1 autre appareil déconnecté.",
|
||||
updatedDisconnectedOther:
|
||||
"Mot de passe mis à jour. {{count}} autres appareils déconnectés.",
|
||||
removed: "Mot de passe supprimé.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clients connectés",
|
||||
thisDevice: "Cet appareil",
|
||||
@@ -2188,51 +2136,6 @@ export const fr: TranslationResources = {
|
||||
daysAgo: "il y a {{count}} j",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Mot de passe requis",
|
||||
description: "Saisissez le mot de passe de cet hôte pour vous connecter.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Mot de passe incorrect",
|
||||
description: "Le mot de passe enregistré a été refusé par cet hôte.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Mettez à jour Paseo pour vous connecter",
|
||||
incompatibleDescription: "Cet hôte nécessite une version plus récente de Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Cet hôte nécessite une méthode de connexion non prise en charge par cette version de Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Appairage requis",
|
||||
description: "Associez de nouveau cet appareil à l'hôte pour vous connecter.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Connexion refusée par {{hostName}}",
|
||||
description: "Vérifiez les paramètres de cet hôte et réessayez.",
|
||||
},
|
||||
messageFromHost: "Message de {{hostName}} : « {{message}} »",
|
||||
shortStatus: {
|
||||
passwordRequired: "Mot de passe requis",
|
||||
updateRequired: "Mise à jour requise",
|
||||
pairingRequired: "Appairage requis",
|
||||
refused: "Refusé",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Saisir le mot de passe",
|
||||
pairLink: "Coller le lien d'appairage",
|
||||
scanQr: "Scanner le code QR",
|
||||
checkForUpdates: "Rechercher des mises à jour",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Mot de passe pour {{hostName}}",
|
||||
label: "Mot de passe",
|
||||
placeholder: "Saisissez le mot de passe de l'hôte",
|
||||
connect: "Se connecter",
|
||||
connecting: "Connexion…",
|
||||
requiredError: "Saisissez un mot de passe pour continuer.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Mot de passe pour {{host}}",
|
||||
@@ -2399,8 +2302,6 @@ export const fr: TranslationResources = {
|
||||
hint: "Scannez ce code QR avec Paseo sur votre téléphone, ou copiez le lien ci-dessous.",
|
||||
securityWarning:
|
||||
"Traitez ce lien d’association comme un mot de passe. Toute personne qui le possède peut accéder à ce daemon.",
|
||||
passwordProtected:
|
||||
"Mot de passe requis. Les appareils qui scannent ce code devront saisir le mot de passe de cet hôte.",
|
||||
qrUnavailable: "Code QR indisponible.",
|
||||
qrAccessibility: "Code QR d’association",
|
||||
retry: "Réessayer",
|
||||
|
||||
@@ -2040,58 +2040,6 @@ export const ja: TranslationResources = {
|
||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
||||
confirmAction: "オフにする",
|
||||
},
|
||||
access: {
|
||||
title: "アクセス",
|
||||
passwordLabel: "パスワード",
|
||||
passwordNotSetSummary: "未設定",
|
||||
passwordNotSetHint: "ペアリングリンクを知る誰でも接続できます",
|
||||
passwordSetSummary: "設定済み",
|
||||
passwordSetHint: "リモート接続に必須",
|
||||
passwordEnvSummary: "環境変数で設定",
|
||||
passwordEnvHint: "このホストの PASEO_PASSWORD で管理されています",
|
||||
},
|
||||
password: {
|
||||
setTitle: "パスワードを設定",
|
||||
changeTitle: "パスワードを変更",
|
||||
removeTitle: "パスワードを削除",
|
||||
setAction: "パスワードを設定",
|
||||
setting: "設定中...",
|
||||
saveAction: "パスワードを保存",
|
||||
saving: "保存中...",
|
||||
removeAction: "パスワードを削除",
|
||||
removing: "削除中...",
|
||||
show: "パスワードを表示",
|
||||
hide: "パスワードを隠す",
|
||||
setInfo:
|
||||
"他のリモートデバイスは即座に切断され、このパスワードが必要になります。このデバイスは接続を維持します。",
|
||||
changeInfo:
|
||||
"他のリモートデバイスは即座に切断され、新しいパスワードが必要になります。このデバイスは接続を維持します。",
|
||||
removeWarning:
|
||||
"ペアリングリンクまたはネットワークアクセスを持つ誰でもパスワードなしで接続できるようになります。",
|
||||
fields: {
|
||||
current: "現在のパスワード",
|
||||
new: "新しいパスワード",
|
||||
confirm: "パスワードの確認",
|
||||
confirmNew: "新しいパスワードの確認",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "現在のパスワードを入力してください。",
|
||||
currentIncorrect: "現在のパスワードが正しくありません。",
|
||||
tooShort: "8文字以上入力してください。",
|
||||
tooLong: "パスワードは72バイト以下にしてください。",
|
||||
mismatch: "パスワードが一致しません。",
|
||||
},
|
||||
toast: {
|
||||
set: "パスワードを設定しました。",
|
||||
setDisconnectedOne: "パスワードを設定しました。他の1台のデバイスを切断しました。",
|
||||
setDisconnectedOther: "パスワードを設定しました。他の{{count}}台のデバイスを切断しました。",
|
||||
updated: "パスワードを更新しました。",
|
||||
updatedDisconnectedOne: "パスワードを更新しました。他の1台のデバイスを切断しました。",
|
||||
updatedDisconnectedOther:
|
||||
"パスワードを更新しました。他の{{count}}台のデバイスを切断しました。",
|
||||
removed: "パスワードを削除しました。",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "接続中のクライアント",
|
||||
thisDevice: "このデバイス",
|
||||
@@ -2158,51 +2106,6 @@ export const ja: TranslationResources = {
|
||||
daysAgo: "{{count}}日前",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "パスワードが必要です",
|
||||
description: "接続するにはこのホストのパスワードを入力してください。",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "パスワードが正しくありません",
|
||||
description: "保存されたパスワードがこのホストによって拒否されました。",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "接続するにはPaseoを更新してください",
|
||||
incompatibleDescription: "このホストには新しいバージョンのPaseoが必要です。",
|
||||
unsupportedAuthDescription:
|
||||
"このホストには、このバージョンのPaseoでサポートされていないサインイン方法が必要です。",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "ペアリングが必要です",
|
||||
description: "接続するには、このデバイスをホストと再度ペアリングしてください。",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "{{hostName}} によって接続が拒否されました",
|
||||
description: "このホストの設定を確認して、もう一度お試しください。",
|
||||
},
|
||||
messageFromHost: "{{hostName}} からのメッセージ: 「{{message}}」",
|
||||
shortStatus: {
|
||||
passwordRequired: "パスワードが必要",
|
||||
updateRequired: "更新が必要",
|
||||
pairingRequired: "ペアリングが必要",
|
||||
refused: "拒否されました",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "パスワードを入力",
|
||||
pairLink: "ペアリングリンクを貼り付け",
|
||||
scanQr: "QRコードをスキャン",
|
||||
checkForUpdates: "アップデートを確認",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} のパスワード",
|
||||
label: "パスワード",
|
||||
placeholder: "ホストのパスワードを入力",
|
||||
connect: "接続",
|
||||
connecting: "接続中...",
|
||||
requiredError: "続行するにはパスワードを入力してください。",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} のパスワード",
|
||||
@@ -2369,8 +2272,6 @@ export const ja: TranslationResources = {
|
||||
hint: "スマートフォンのPaseoでこのQRコードをスキャンするか、以下のリンクをコピーしてください。",
|
||||
securityWarning:
|
||||
"このペアリングリンクはパスワードと同様に扱ってください。リンクを知っている人は誰でもこのデーモンにアクセスできます。",
|
||||
passwordProtected:
|
||||
"パスワードが必要です。このコードをスキャンしたデバイスはこのホストのパスワードを入力します。",
|
||||
qrUnavailable: "QRコードが利用できません。",
|
||||
qrAccessibility: "ペアリング QR コード",
|
||||
retry: "再試行",
|
||||
|
||||
@@ -2031,60 +2031,6 @@ export const ko: TranslationResources = {
|
||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
||||
confirmAction: "끄기",
|
||||
},
|
||||
access: {
|
||||
title: "접근",
|
||||
passwordLabel: "비밀번호",
|
||||
passwordNotSetSummary: "설정되지 않음",
|
||||
passwordNotSetHint: "페어링 링크를 가진 누구나 연결할 수 있습니다",
|
||||
passwordSetSummary: "설정됨",
|
||||
passwordSetHint: "원격 연결에 필요",
|
||||
passwordEnvSummary: "환경 변수로 설정됨",
|
||||
passwordEnvHint: "이 호스트의 PASEO_PASSWORD로 제어됩니다",
|
||||
},
|
||||
password: {
|
||||
setTitle: "비밀번호 설정",
|
||||
changeTitle: "비밀번호 변경",
|
||||
removeTitle: "비밀번호 제거",
|
||||
setAction: "비밀번호 설정",
|
||||
setting: "설정 중...",
|
||||
saveAction: "비밀번호 저장",
|
||||
saving: "저장 중...",
|
||||
removeAction: "비밀번호 제거",
|
||||
removing: "제거 중...",
|
||||
show: "비밀번호 표시",
|
||||
hide: "비밀번호 숨기기",
|
||||
setInfo:
|
||||
"다른 원격 기기는 즉시 연결이 해제되며 이 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
|
||||
changeInfo:
|
||||
"다른 원격 기기는 즉시 연결이 해제되며 새 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
|
||||
removeWarning:
|
||||
"페어링 링크나 네트워크 접근 권한이 있는 누구나 비밀번호 없이 연결할 수 있게 됩니다.",
|
||||
fields: {
|
||||
current: "현재 비밀번호",
|
||||
new: "새 비밀번호",
|
||||
confirm: "비밀번호 확인",
|
||||
confirmNew: "새 비밀번호 확인",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "현재 비밀번호를 입력하세요.",
|
||||
currentIncorrect: "현재 비밀번호가 올바르지 않습니다.",
|
||||
tooShort: "8자 이상 입력하세요.",
|
||||
tooLong: "비밀번호는 72바이트 이하여야 합니다.",
|
||||
mismatch: "비밀번호가 일치하지 않습니다.",
|
||||
},
|
||||
toast: {
|
||||
set: "비밀번호가 설정되었습니다.",
|
||||
setDisconnectedOne: "비밀번호가 설정되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
|
||||
setDisconnectedOther:
|
||||
"비밀번호가 설정되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
|
||||
updated: "비밀번호가 업데이트되었습니다.",
|
||||
updatedDisconnectedOne:
|
||||
"비밀번호가 업데이트되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
|
||||
updatedDisconnectedOther:
|
||||
"비밀번호가 업데이트되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
|
||||
removed: "비밀번호가 제거되었습니다.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "연결된 클라이언트",
|
||||
thisDevice: "이 기기",
|
||||
@@ -2151,51 +2097,6 @@ export const ko: TranslationResources = {
|
||||
daysAgo: "{{count}}일 전",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "비밀번호가 필요합니다",
|
||||
description: "연결하려면 이 호스트의 비밀번호를 입력하세요.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "비밀번호가 올바르지 않습니다",
|
||||
description: "저장된 비밀번호가 이 호스트에서 거부되었습니다.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "연결하려면 Paseo를 업데이트하세요",
|
||||
incompatibleDescription: "이 호스트에는 최신 버전의 Paseo가 필요합니다.",
|
||||
unsupportedAuthDescription:
|
||||
"이 호스트에는 현재 버전의 Paseo에서 지원하지 않는 로그인 방식이 필요합니다.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "페어링이 필요합니다",
|
||||
description: "연결하려면 이 기기를 호스트와 다시 페어링하세요.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "{{hostName}}에서 연결을 거부했습니다",
|
||||
description: "이 호스트의 설정을 확인한 후 다시 시도하세요.",
|
||||
},
|
||||
messageFromHost: "{{hostName}}의 메시지: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "비밀번호 필요",
|
||||
updateRequired: "업데이트 필요",
|
||||
pairingRequired: "페어링 필요",
|
||||
refused: "거부됨",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "비밀번호 입력",
|
||||
pairLink: "페어링 링크 붙여넣기",
|
||||
scanQr: "QR 코드 스캔",
|
||||
checkForUpdates: "업데이트 확인",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} 비밀번호",
|
||||
label: "비밀번호",
|
||||
placeholder: "호스트 비밀번호 입력",
|
||||
connect: "연결",
|
||||
connecting: "연결 중...",
|
||||
requiredError: "계속하려면 비밀번호를 입력하세요.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}}의 비밀번호",
|
||||
@@ -2360,8 +2261,6 @@ export const ko: TranslationResources = {
|
||||
hint: "휴대폰의 Paseo로 이 QR 코드를 스캔하거나 아래 링크를 복사하세요.",
|
||||
securityWarning:
|
||||
"이 페어링 링크는 비밀번호처럼 취급하세요. 링크를 가진 사람은 누구나 이 데몬에 접근할 수 있습니다.",
|
||||
passwordProtected:
|
||||
"비밀번호가 필요합니다. 이 코드를 스캔하는 기기는 이 호스트의 비밀번호를 입력해야 합니다.",
|
||||
qrUnavailable: "QR 코드를 사용할 수 없습니다.",
|
||||
qrAccessibility: "페어링 QR 코드",
|
||||
retry: "다시 시도",
|
||||
|
||||
@@ -2057,57 +2057,6 @@ export const ptBR: TranslationResources = {
|
||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
||||
confirmAction: "Desativar",
|
||||
},
|
||||
access: {
|
||||
title: "Acesso",
|
||||
passwordLabel: "Senha",
|
||||
passwordNotSetSummary: "Não definida",
|
||||
passwordNotSetHint: "Qualquer pessoa com um link de pareamento pode conectar",
|
||||
passwordSetSummary: "Definida",
|
||||
passwordSetHint: "Obrigatória para conexões remotas",
|
||||
passwordEnvSummary: "Definida pelo ambiente",
|
||||
passwordEnvHint: "Controlada por PASEO_PASSWORD neste host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Definir senha",
|
||||
changeTitle: "Alterar senha",
|
||||
removeTitle: "Remover senha",
|
||||
setAction: "Definir senha",
|
||||
setting: "Definindo...",
|
||||
saveAction: "Salvar senha",
|
||||
saving: "Salvando...",
|
||||
removeAction: "Remover senha",
|
||||
removing: "Removendo...",
|
||||
show: "Mostrar senha",
|
||||
hide: "Ocultar senha",
|
||||
setInfo:
|
||||
"Outros dispositivos remotos desconectam imediatamente e precisarão desta senha. Este dispositivo permanece conectado.",
|
||||
changeInfo:
|
||||
"Outros dispositivos remotos desconectam imediatamente e precisarão da nova senha. Este dispositivo permanece conectado.",
|
||||
removeWarning:
|
||||
"Qualquer pessoa com um link de pareamento ou acesso à rede poderá conectar sem senha.",
|
||||
fields: {
|
||||
current: "Senha atual",
|
||||
new: "Nova senha",
|
||||
confirm: "Confirmar senha",
|
||||
confirmNew: "Confirmar nova senha",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Digite a senha atual.",
|
||||
currentIncorrect: "A senha atual está incorreta.",
|
||||
tooShort: "Use pelo menos 8 caracteres.",
|
||||
tooLong: "A senha deve ter 72 bytes ou menos.",
|
||||
mismatch: "As senhas não coincidem.",
|
||||
},
|
||||
toast: {
|
||||
set: "Senha definida.",
|
||||
setDisconnectedOne: "Senha definida. 1 outro dispositivo desconectado.",
|
||||
setDisconnectedOther: "Senha definida. {{count}} outros dispositivos desconectados.",
|
||||
updated: "Senha atualizada.",
|
||||
updatedDisconnectedOne: "Senha atualizada. 1 outro dispositivo desconectado.",
|
||||
updatedDisconnectedOther: "Senha atualizada. {{count}} outros dispositivos desconectados.",
|
||||
removed: "Senha removida.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
thisDevice: "Este dispositivo",
|
||||
@@ -2174,51 +2123,6 @@ export const ptBR: TranslationResources = {
|
||||
daysAgo: "há {{count}}d",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Senha necessária",
|
||||
description: "Digite a senha deste host para conectar.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Senha incorreta",
|
||||
description: "A senha salva foi recusada por este host.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Atualize o Paseo para conectar",
|
||||
incompatibleDescription: "Este host requer uma versão mais recente do Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Este host requer um método de login não suportado por esta versão do Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Pareamento necessário",
|
||||
description: "Pareie este dispositivo novamente com o host para conectar.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Conexão recusada por {{hostName}}",
|
||||
description: "Verifique as configurações deste host e tente novamente.",
|
||||
},
|
||||
messageFromHost: "Mensagem de {{hostName}}: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "Senha necessária",
|
||||
updateRequired: "Atualização necessária",
|
||||
pairingRequired: "Pareamento necessário",
|
||||
refused: "Recusado",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Digitar senha",
|
||||
pairLink: "Colar link de pareamento",
|
||||
scanQr: "Escanear código QR",
|
||||
checkForUpdates: "Verificar atualizações",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Senha para {{hostName}}",
|
||||
label: "Senha",
|
||||
placeholder: "Digite a senha do host",
|
||||
connect: "Conectar",
|
||||
connecting: "Conectando...",
|
||||
requiredError: "Digite uma senha para continuar.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Senha de {{host}}",
|
||||
@@ -2385,8 +2289,6 @@ export const ptBR: TranslationResources = {
|
||||
hint: "Escaneie este QR code com o Paseo no seu celular ou copie o link abaixo.",
|
||||
securityWarning:
|
||||
"Trate este link de pareamento como uma senha. Qualquer pessoa com o link pode acessar este daemon.",
|
||||
passwordProtected:
|
||||
"Senha obrigatória. Os dispositivos que escanearem este código precisarão inserir a senha deste host.",
|
||||
qrUnavailable: "QR code indisponível.",
|
||||
qrAccessibility: "Código QR de pareamento",
|
||||
retry: "Tentar novamente",
|
||||
|
||||
@@ -2056,57 +2056,6 @@ export const ru: TranslationResources = {
|
||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
||||
confirmAction: "Выключить",
|
||||
},
|
||||
access: {
|
||||
title: "Доступ",
|
||||
passwordLabel: "Пароль",
|
||||
passwordNotSetSummary: "Не задан",
|
||||
passwordNotSetHint: "Подключиться может любой, у кого есть ссылка для сопряжения",
|
||||
passwordSetSummary: "Задан",
|
||||
passwordSetHint: "Требуется для удалённых подключений",
|
||||
passwordEnvSummary: "Задан через окружение",
|
||||
passwordEnvHint: "Управляется переменной PASEO_PASSWORD на этом хосте",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Задать пароль",
|
||||
changeTitle: "Изменить пароль",
|
||||
removeTitle: "Удалить пароль",
|
||||
setAction: "Задать пароль",
|
||||
setting: "Сохранение...",
|
||||
saveAction: "Сохранить пароль",
|
||||
saving: "Сохранение...",
|
||||
removeAction: "Удалить пароль",
|
||||
removing: "Удаление...",
|
||||
show: "Показать пароль",
|
||||
hide: "Скрыть пароль",
|
||||
setInfo:
|
||||
"Другие удалённые устройства немедленно отключатся и потребуют этот пароль. Это устройство останется подключённым.",
|
||||
changeInfo:
|
||||
"Другие удалённые устройства немедленно отключатся и потребуют новый пароль. Это устройство останется подключённым.",
|
||||
removeWarning:
|
||||
"Любой, у кого есть ссылка для сопряжения или доступ к сети, сможет подключаться без пароля.",
|
||||
fields: {
|
||||
current: "Текущий пароль",
|
||||
new: "Новый пароль",
|
||||
confirm: "Подтвердите пароль",
|
||||
confirmNew: "Подтвердите новый пароль",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Введите текущий пароль.",
|
||||
currentIncorrect: "Неверный текущий пароль.",
|
||||
tooShort: "Используйте не менее 8 символов.",
|
||||
tooLong: "Пароль должен быть не длиннее 72 байт.",
|
||||
mismatch: "Пароли не совпадают.",
|
||||
},
|
||||
toast: {
|
||||
set: "Пароль задан.",
|
||||
setDisconnectedOne: "Пароль задан. Отключено 1 другое устройство.",
|
||||
setDisconnectedOther: "Пароль задан. Отключено других устройств: {{count}}.",
|
||||
updated: "Пароль обновлён.",
|
||||
updatedDisconnectedOne: "Пароль обновлён. Отключено 1 другое устройство.",
|
||||
updatedDisconnectedOther: "Пароль обновлён. Отключено других устройств: {{count}}.",
|
||||
removed: "Пароль удалён.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Подключённые клиенты",
|
||||
thisDevice: "Это устройство",
|
||||
@@ -2173,51 +2122,6 @@ export const ru: TranslationResources = {
|
||||
daysAgo: "{{count}} дн назад",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Требуется пароль",
|
||||
description: "Введите пароль этого хоста для подключения.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Неверный пароль",
|
||||
description: "Сохранённый пароль был отклонён этим хостом.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Обновите Paseo для подключения",
|
||||
incompatibleDescription: "Для этого хоста требуется более новая версия Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Этот хост требует способ входа, который не поддерживается этой версией Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Требуется сопряжение",
|
||||
description: "Повторно выполните сопряжение этого устройства с хостом для подключения.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Подключение отклонено хостом {{hostName}}",
|
||||
description: "Проверьте настройки этого хоста и повторите попытку.",
|
||||
},
|
||||
messageFromHost: "Сообщение от {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "Требуется пароль",
|
||||
updateRequired: "Требуется обновление",
|
||||
pairingRequired: "Требуется сопряжение",
|
||||
refused: "Отклонено",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Ввести пароль",
|
||||
pairLink: "Вставить ссылку сопряжения",
|
||||
scanQr: "Сканировать QR-код",
|
||||
checkForUpdates: "Проверить обновления",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Пароль для {{hostName}}",
|
||||
label: "Пароль",
|
||||
placeholder: "Введите пароль хоста",
|
||||
connect: "Подключиться",
|
||||
connecting: "Подключение...",
|
||||
requiredError: "Введите пароль, чтобы продолжить.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Пароль для {{host}}",
|
||||
@@ -2385,8 +2289,6 @@ export const ru: TranslationResources = {
|
||||
hint: "Отсканируйте этот QR-код с помощью Paseo на телефоне или скопируйте ссылку ниже.",
|
||||
securityWarning:
|
||||
"Обращайтесь с этой ссылкой для сопряжения как с паролем. Любой, у кого она есть, может получить доступ к этому демону.",
|
||||
passwordProtected:
|
||||
"Требуется пароль. Устройства, сканирующие этот код, должны будут ввести пароль этого хоста.",
|
||||
qrUnavailable: "QR-код недоступен.",
|
||||
qrAccessibility: "QR-код сопряжения",
|
||||
retry: "Повторить попытку",
|
||||
|
||||
@@ -2001,54 +2001,6 @@ export const zhCN: TranslationResources = {
|
||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
||||
confirmAction: "关闭",
|
||||
},
|
||||
access: {
|
||||
title: "访问",
|
||||
passwordLabel: "密码",
|
||||
passwordNotSetSummary: "未设置",
|
||||
passwordNotSetHint: "任何拥有配对链接的人都可以连接",
|
||||
passwordSetSummary: "已设置",
|
||||
passwordSetHint: "远程连接必填",
|
||||
passwordEnvSummary: "由环境变量设置",
|
||||
passwordEnvHint: "由此主机上的 PASEO_PASSWORD 控制",
|
||||
},
|
||||
password: {
|
||||
setTitle: "设置密码",
|
||||
changeTitle: "更改密码",
|
||||
removeTitle: "移除密码",
|
||||
setAction: "设置密码",
|
||||
setting: "正在设置...",
|
||||
saveAction: "保存密码",
|
||||
saving: "正在保存...",
|
||||
removeAction: "移除密码",
|
||||
removing: "正在移除...",
|
||||
show: "显示密码",
|
||||
hide: "隐藏密码",
|
||||
setInfo: "其他远程设备会立即断开连接,并需要输入此密码。当前设备保持连接。",
|
||||
changeInfo: "其他远程设备会立即断开连接,并需要输入新密码。当前设备保持连接。",
|
||||
removeWarning: "任何拥有配对链接或网络访问权限的人都可以无需密码连接。",
|
||||
fields: {
|
||||
current: "当前密码",
|
||||
new: "新密码",
|
||||
confirm: "确认密码",
|
||||
confirmNew: "确认新密码",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "请输入当前密码。",
|
||||
currentIncorrect: "当前密码不正确。",
|
||||
tooShort: "请至少使用 8 个字符。",
|
||||
tooLong: "密码不能超过 72 字节。",
|
||||
mismatch: "两次输入的密码不一致。",
|
||||
},
|
||||
toast: {
|
||||
set: "密码已设置。",
|
||||
setDisconnectedOne: "密码已设置。已断开 1 台其他设备。",
|
||||
setDisconnectedOther: "密码已设置。已断开 {{count}} 台其他设备。",
|
||||
updated: "密码已更新。",
|
||||
updatedDisconnectedOne: "密码已更新。已断开 1 台其他设备。",
|
||||
updatedDisconnectedOther: "密码已更新。已断开 {{count}} 台其他设备。",
|
||||
removed: "密码已移除。",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "已连接的客户端",
|
||||
thisDevice: "此设备",
|
||||
@@ -2115,50 +2067,6 @@ export const zhCN: TranslationResources = {
|
||||
daysAgo: "{{count}} 天前",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "需要密码",
|
||||
description: "输入此主机的密码以连接。",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "密码错误",
|
||||
description: "已保存的密码被此主机拒绝。",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "更新 Paseo 以连接",
|
||||
incompatibleDescription: "此主机需要更新版本的 Paseo。",
|
||||
unsupportedAuthDescription: "此主机需要当前版本的 Paseo 不支持的登录方式。",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "需要配对",
|
||||
description: "请将此设备重新与此主机配对以连接。",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "连接被 {{hostName}} 拒绝",
|
||||
description: "请检查此主机的设置并重试。",
|
||||
},
|
||||
messageFromHost: "来自 {{hostName}} 的消息:“{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "需要密码",
|
||||
updateRequired: "需要更新",
|
||||
pairingRequired: "需要配对",
|
||||
refused: "已拒绝",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "输入密码",
|
||||
pairLink: "粘贴配对链接",
|
||||
scanQr: "扫描二维码",
|
||||
checkForUpdates: "检查更新",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} 的密码",
|
||||
label: "密码",
|
||||
placeholder: "输入主机密码",
|
||||
connect: "连接",
|
||||
connecting: "正在连接...",
|
||||
requiredError: "请输入密码以继续。",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} 的密码",
|
||||
@@ -2317,7 +2225,6 @@ export const zhCN: TranslationResources = {
|
||||
unavailable: "配对 offer 不可用。",
|
||||
hint: "用手机上的 Paseo 扫描此二维码,或复制下方链接。",
|
||||
securityWarning: "请像保管密码一样保管此配对链接。任何获得此链接的人都可以访问此守护进程。",
|
||||
passwordProtected: "需要密码。扫描此二维码的设备将输入此主机的密码。",
|
||||
qrUnavailable: "二维码不可用。",
|
||||
qrAccessibility: "配对二维码",
|
||||
retry: "重试",
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { Text, View } from "react-native";
|
||||
import { ArrowLeftToLine, RotateCw, Settings } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { HostRefusalEmptyState } from "@/hosts/host-refusal-alert";
|
||||
import type { AgentRouteResolution } from "@/navigation/agent-route-resolution";
|
||||
import { formatConnectionStatus } from "@/utils/daemons";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -21,20 +19,16 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
|
||||
export function AgentRouteResolutionView({
|
||||
serverId,
|
||||
resolution,
|
||||
hostName,
|
||||
lastHostError,
|
||||
helloRejection,
|
||||
onRetry,
|
||||
onManageHost,
|
||||
onBack,
|
||||
}: {
|
||||
serverId: string;
|
||||
resolution: VisibleAgentRouteResolution;
|
||||
hostName: string;
|
||||
lastHostError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
onRetry: () => void;
|
||||
onManageHost: () => void;
|
||||
onBack: () => void;
|
||||
@@ -76,20 +70,6 @@ export function AgentRouteResolutionView({
|
||||
|
||||
const isConnecting =
|
||||
resolution.connectionStatus === "connecting" || resolution.connectionStatus === "idle";
|
||||
|
||||
if (!isConnecting && helloRejection) {
|
||||
return (
|
||||
<HostRefusalEmptyState
|
||||
serverId={serverId}
|
||||
hostName={hostName}
|
||||
rejection={helloRejection}
|
||||
onManageHost={onManageHost}
|
||||
testID="agent-route-refusal"
|
||||
testIDPrefix="agent-route-refusal"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
let title = t("workspace.route.cannotReachHost", { hostName });
|
||||
if (isConnecting) {
|
||||
title = t("agentPanel.unavailable.connecting", { serverLabel: hostName });
|
||||
@@ -132,35 +112,36 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 420,
|
||||
maxWidth: 520,
|
||||
},
|
||||
title: {
|
||||
fontSize: theme.fontSize.lg,
|
||||
fontWeight: theme.fontWeight.semibold,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
textAlign: "center",
|
||||
},
|
||||
description: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "center",
|
||||
},
|
||||
error: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.destructive,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: Math.round(theme.fontSize.base * 1.4),
|
||||
textAlign: "center",
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexWrap: "wrap",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNativeSplashHold } from "@/native-splash";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import type { DaemonClient, DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { TFunction } from "i18next";
|
||||
import { SquarePen } from "lucide-react-native";
|
||||
import React, {
|
||||
@@ -79,12 +79,10 @@ import { PaneSubtitle } from "@/panels/pane-subtitle";
|
||||
import { definePanel } from "@/panels/panel-registry";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
import { buildDraftPanelDescriptor } from "@/panels/draft-panel-descriptor";
|
||||
import { HostRefusalAlert } from "@/hosts/host-refusal-alert";
|
||||
import {
|
||||
type HostRuntimeConnectionStatus,
|
||||
useHostRuntimeClient,
|
||||
useHostRuntimeConnectionStatus,
|
||||
useHostRuntimeHelloRejection,
|
||||
useHostRuntimeIsConnected,
|
||||
useHostRuntimeLastError,
|
||||
useHosts,
|
||||
@@ -468,7 +466,6 @@ function AgentPanelContent({
|
||||
const runtimeIsConnected = useHostRuntimeIsConnected(runtimeServerId);
|
||||
const runtimeConnectionStatus = useHostRuntimeConnectionStatus(runtimeServerId);
|
||||
const runtimeLastError = useHostRuntimeLastError(runtimeServerId);
|
||||
const runtimeHelloRejection = useHostRuntimeHelloRejection(runtimeServerId);
|
||||
const hasCachedAgent = useSessionStore((state) => {
|
||||
if (!resolvedServerId || !resolvedAgentId) return false;
|
||||
const session = state.sessions[resolvedServerId];
|
||||
@@ -493,11 +490,9 @@ function AgentPanelContent({
|
||||
if (target.kind === "agent" && (!resolvedServerId || (!runtimeClient && !hasCachedAgent))) {
|
||||
return (
|
||||
<AgentSessionUnavailableState
|
||||
serverId={resolvedServerId ?? null}
|
||||
serverLabel={serverLabel}
|
||||
connectionStatus={connectionStatus}
|
||||
lastError={lastConnectionError}
|
||||
helloRejection={runtimeHelloRejection}
|
||||
isUnknownDaemon={isUnknownDaemon}
|
||||
t={t}
|
||||
/>
|
||||
@@ -512,7 +507,6 @@ function AgentPanelContent({
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={runtimeClient}
|
||||
isConnected={runtimeIsConnected}
|
||||
isConnectionRefused={runtimeHelloRejection !== null}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
/>
|
||||
);
|
||||
@@ -525,7 +519,6 @@ function AgentPanelBody({
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
serverId: string;
|
||||
@@ -534,7 +527,6 @@ function AgentPanelBody({
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused: boolean;
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -666,7 +658,6 @@ function AgentPanelBody({
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={client}
|
||||
isConnected={isConnected}
|
||||
isConnectionRefused={isConnectionRefused}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
/>
|
||||
);
|
||||
@@ -719,7 +710,6 @@ function ChatAgentContent({
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
serverId: string;
|
||||
@@ -728,7 +718,6 @@ function ChatAgentContent({
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused: boolean;
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -889,7 +878,6 @@ function ChatAgentContent({
|
||||
isArchived: agentState.archivedAt !== null,
|
||||
missingAgentState,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
isArchivingCurrentAgent,
|
||||
isHistorySyncing,
|
||||
needsAuthoritativeSync,
|
||||
@@ -1892,19 +1880,15 @@ function ActiveAgentComposer({
|
||||
}
|
||||
|
||||
function AgentSessionUnavailableState({
|
||||
serverId,
|
||||
serverLabel,
|
||||
connectionStatus,
|
||||
lastError,
|
||||
helloRejection,
|
||||
isUnknownDaemon = false,
|
||||
t,
|
||||
}: {
|
||||
serverId: string | null;
|
||||
serverLabel: string;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
isUnknownDaemon?: boolean;
|
||||
t: TFunction;
|
||||
}) {
|
||||
@@ -1921,21 +1905,6 @@ function AgentSessionUnavailableState({
|
||||
);
|
||||
}
|
||||
|
||||
if (helloRejection && serverId) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.centerState}>
|
||||
<HostRefusalAlert
|
||||
serverId={serverId}
|
||||
hostName={serverLabel}
|
||||
rejection={helloRejection}
|
||||
testID="agent-panel-refusal-alert"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isConnecting = connectionStatus === "connecting";
|
||||
const isPreparingSession = connectionStatus === "online";
|
||||
|
||||
|
||||
@@ -10,11 +10,7 @@ import type {
|
||||
FetchAgentsEntry,
|
||||
FetchAgentsOptions,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonHelloRejectedError,
|
||||
type DaemonHelloRejection,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { DaemonAuthenticationError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostDirectory } from "@getpaseo/protocol/hosts";
|
||||
import type { ConnectionOffer } from "@getpaseo/protocol/connection-offer";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
@@ -70,7 +66,6 @@ class FakeDaemonClient {
|
||||
private state: ConnectionState = { status: "idle" };
|
||||
private listeners = new Set<(status: ConnectionState) => void>();
|
||||
private error: string | null = null;
|
||||
helloRejection: DaemonHelloRejection | null = null;
|
||||
authFailureReason: "password_required" | "incorrect_password" | null = null;
|
||||
private heartbeatRttMs: number | null = null;
|
||||
private latencyMeasurementFailure: Error | null = null;
|
||||
@@ -5609,12 +5604,12 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
client.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
client.authFailureReason = "incorrect_password";
|
||||
client.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
(snapshot) => snapshot?.authFailureReason === "incorrect_password",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.lastError).toBe("Incorrect password");
|
||||
expect(client.reconnectEnabledChanges.at(-1)).toBe(false);
|
||||
@@ -5668,12 +5663,12 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
relayClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
relayClient.authFailureReason = "incorrect_password";
|
||||
relayClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
(snapshot) => snapshot?.authFailureReason === "incorrect_password",
|
||||
);
|
||||
await store.runProbeCycleNow(host.serverId);
|
||||
await onceHostSnapshotMatches(
|
||||
@@ -5707,7 +5702,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
}
|
||||
for (let index = 1; index <= 5; index += 1) {
|
||||
@@ -5741,7 +5736,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_deep",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
expect(store.getSnapshot("srv_deep")?.connectionStatus).toBe("error");
|
||||
store.syncHosts([]);
|
||||
@@ -5799,419 +5794,18 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_test",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
expect(store.getSnapshot("srv_test")?.connectionStatus).toBe("error");
|
||||
await store.setHostPassword("srv_test", "correct-password");
|
||||
await waitForHostOnline(store, "srv_test");
|
||||
expect(store.getHosts()[0]?.password).toBe("correct-password");
|
||||
expect(store.getSnapshot("srv_test")?.helloRejection).toBeNull();
|
||||
expect(store.getSnapshot("srv_test")?.authFailureReason).toBeNull();
|
||||
await store.setHostPassword("srv_test", "");
|
||||
expect(store.getHosts()[0]?.password).toBeUndefined();
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("halts automatic probes on non-password refusals and recovers on explicit clearRefusals retry", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const recoveredClient = makeConnectedProbeClient(5);
|
||||
const host = makeHost({
|
||||
serverId: "srv_maintenance",
|
||||
connections: [{ id: "direct:maint:6767", type: "directTcp", endpoint: "maint:6767" }],
|
||||
});
|
||||
let allowConnect = false;
|
||||
let probeAttempts = 0;
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
probeAttempts += 1;
|
||||
if (!allowConnect) {
|
||||
throw new DaemonHelloRejectedError({
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
});
|
||||
}
|
||||
return {
|
||||
client: recoveredClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_maintenance",
|
||||
},
|
||||
});
|
||||
store.syncHosts([host], {
|
||||
initialConnectionByServerId: new Map([
|
||||
[
|
||||
host.serverId,
|
||||
{
|
||||
connectionId: "direct:maint:6767",
|
||||
existingClient: initialClient as unknown as DaemonClient,
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
|
||||
initialClient.helloRejection = {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
};
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Connection refused" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "maintenance",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Background probe cycle skips refused connection without bumping episode.
|
||||
await store.runProbeCycleNow(host.serverId);
|
||||
expect(probeAttempts).toBe(0);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Explicit user retry clears refusals and reconnects once the host accepts again.
|
||||
allowConnect = true;
|
||||
await store.runProbeCycleNow(host.serverId, { clearRefusals: true });
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
expect(probeAttempts).toBe(1);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejection).toBeNull();
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Re-refusing after a reconnect bumps helloRejectionEpisode monotonically.
|
||||
const activeClient = store.getSnapshot(host.serverId)?.client as unknown as FakeDaemonClient;
|
||||
activeClient.helloRejection = {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
};
|
||||
activeClient.setConnectionState({ status: "disconnected", reason: "Connection refused" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "maintenance",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(2);
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("submitHostPassword reports incorrect_password and closes cleanly once the right password succeeds", async () => {
|
||||
let activePassword = "old-password";
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ host: currentHost }) => {
|
||||
const client = makeConnectedProbeClient(5);
|
||||
const originalConnect = client.connect.bind(client);
|
||||
client.connect = async () => {
|
||||
if (currentHost.password !== activePassword) {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return originalConnect();
|
||||
};
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => {
|
||||
if (currentHost.password !== activePassword) {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return {
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_pw_sheet",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_sheet",
|
||||
endpoint: "pw:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_sheet");
|
||||
|
||||
// Daemon rotates password.
|
||||
activePassword = "new-secret";
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_sheet",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const wrongResult = await store.submitHostPassword("srv_pw_sheet", "still-wrong");
|
||||
expect(wrongResult).toEqual({
|
||||
status: "rejected",
|
||||
rejection: { reason: "incorrect_password", accepts: ["password"] },
|
||||
});
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.helloRejection?.reason).toBe("incorrect_password");
|
||||
|
||||
const okResult = await store.submitHostPassword("srv_pw_sheet", "new-secret");
|
||||
expect(okResult).toEqual({ status: "online" });
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.connectionStatus).toBe("online");
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.helloRejection).toBeNull();
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("submitHostPassword bounds the wait and returns failed if the host hangs unreachable", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
const client = new FakeDaemonClient();
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => ({
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
}),
|
||||
getClientId: async () => "cid_pw_timeout",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_timeout",
|
||||
endpoint: "pw-timeout:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_timeout");
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_timeout",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_pw_timeout", "new-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("superseding submitHostPassword closes a hanging password attempt and connects with the new password", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const hangingClients: FakeDaemonClient[] = [];
|
||||
const seenPasswords: Array<string | undefined> = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ host: currentHost }) => {
|
||||
seenPasswords.push(currentHost.password);
|
||||
const client = new FakeDaemonClient();
|
||||
if (currentHost.password === "stuck-password") {
|
||||
hangingClients.push(client);
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => ({
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
}),
|
||||
getClientId: async () => "cid_pw_supersede",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_supersede",
|
||||
endpoint: "pw-supersede:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_supersede");
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_supersede",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_pw_supersede", "stuck-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
expect(hangingClients).toHaveLength(1);
|
||||
|
||||
const recovered = await store.submitHostPassword("srv_pw_supersede", "working-password", {
|
||||
timeoutMs: 1_000,
|
||||
});
|
||||
expect(recovered).toEqual({ status: "online" });
|
||||
expect(hangingClients[0]?.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
expect(seenPasswords).toEqual(["stuck-password", "working-password"]);
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("removing an active connection closes a hanging update attempt and switches to the remaining route", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const hangingClients: FakeDaemonClient[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ connection }) => {
|
||||
const client = new FakeDaemonClient();
|
||||
if (connection.type === "directTcp" && connection.endpoint === "route-remove:6767") {
|
||||
hangingClients.push(client);
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost, connection }) => {
|
||||
if (connection.type === "directTcp" && connection.endpoint === "fallback:6767") {
|
||||
if (currentHost.password === "old-password") {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return {
|
||||
client: makeConnectedProbeClient(8) as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
}
|
||||
return {
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_route_remove",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove",
|
||||
endpoint: "route-remove:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_route_remove");
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove",
|
||||
endpoint: "fallback:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
const activeConnectionId = store.getSnapshot("srv_route_remove")?.activeConnectionId;
|
||||
expect(activeConnectionId).toBe("direct:route-remove:6767");
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_route_remove", "stuck-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
expect(hangingClients).toHaveLength(1);
|
||||
|
||||
await store.removeConnection("srv_route_remove", activeConnectionId!);
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove",
|
||||
(snapshot) =>
|
||||
snapshot?.connectionStatus === "online" &&
|
||||
snapshot.activeConnectionId === "direct:fallback:6767",
|
||||
);
|
||||
expect(hangingClients[0]?.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("removing an online active connection when remaining routes are unreachable marks the host offline", async () => {
|
||||
const activeClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: currentHost, connection }) => {
|
||||
if (connection.type === "directTcp" && connection.endpoint === "active:6767") {
|
||||
return {
|
||||
client: activeClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
}
|
||||
throw new Error("Connection refused");
|
||||
},
|
||||
getClientId: async () => "cid_route_remove_down",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove_down",
|
||||
endpoint: "active:6767",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_route_remove_down");
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove_down",
|
||||
endpoint: "down:6767",
|
||||
});
|
||||
expect(store.getSnapshot("srv_route_remove_down")?.activeConnectionId).toBe(
|
||||
"direct:active:6767",
|
||||
);
|
||||
|
||||
await store.removeConnection("srv_route_remove_down", "direct:active:6767");
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove_down",
|
||||
(snapshot) =>
|
||||
snapshot?.connectionStatus === "offline" &&
|
||||
snapshot.activeConnectionId === null &&
|
||||
snapshot.client === null,
|
||||
);
|
||||
expect(activeClient.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("importConnectionLink prompts for password only when refusal accepts password", async () => {
|
||||
let nextError: Error = new DaemonHelloRejectedError({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
throw nextError;
|
||||
},
|
||||
getClientId: async () => "cid_link_refusal",
|
||||
},
|
||||
});
|
||||
answerHostConfirmations(store, true);
|
||||
const link = "relay://relay.example:443/srv_refuse?key=AAAA&ssl=true";
|
||||
|
||||
await expect(store.importConnectionLink(link, "hostRoot")).rejects.toBeInstanceOf(
|
||||
DaemonHelloRejectedError,
|
||||
);
|
||||
|
||||
nextError = new DaemonHelloRejectedError({
|
||||
reason: "password_expired",
|
||||
accepts: ["password"],
|
||||
});
|
||||
await expect(store.importConnectionLink(link, "hostRoot")).resolves.toMatchObject({
|
||||
status: "password_required",
|
||||
link,
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("attempts the explicit initial connection hint before default localhost bootstrap", async () => {
|
||||
const seenProbes: { endpoint: string; useTls?: boolean }[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
@@ -6324,59 +5918,4 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await store.removeHost("srv_rotated");
|
||||
expect(resetHosts).toEqual(["srv_rotated", "srv_rotated"]);
|
||||
});
|
||||
|
||||
it("uses make-before-break when setHostPassword updates an online host so status never flashes offline", async () => {
|
||||
const serverId = "srv_mbb_password";
|
||||
const firstClient = makeConnectedProbeClient(5);
|
||||
const secondClient = new FakeDaemonClient();
|
||||
const connectSecond = new Deferred<void>();
|
||||
secondClient.connect = async () => {
|
||||
await connectSecond.promise;
|
||||
secondClient.setConnectionState({ status: "connected" });
|
||||
};
|
||||
let createCount = 0;
|
||||
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
createCount += 1;
|
||||
return secondClient as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async () => ({
|
||||
client: firstClient as unknown as DaemonClient,
|
||||
serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_mbb_password",
|
||||
},
|
||||
});
|
||||
|
||||
await store.upsertDirectConnection({ serverId, endpoint: "127.0.0.1:6767" });
|
||||
await waitForHostOnline(store, serverId);
|
||||
|
||||
const observedStatuses: string[] = [];
|
||||
const unsubscribe = store.subscribe(serverId, () => {
|
||||
const status = store.getSnapshot(serverId)?.connectionStatus;
|
||||
if (status) observedStatuses.push(status);
|
||||
});
|
||||
|
||||
const updatePromise = store.setHostPassword(serverId, "new-secret-123");
|
||||
// While replacement client is still connecting, host must stay online with zero flash.
|
||||
await vi.waitFor(() => expect(createCount).toBe(1));
|
||||
expect(store.getSnapshot(serverId)?.connectionStatus).toBe("online");
|
||||
expect(observedStatuses.every((status) => status === "online")).toBe(true);
|
||||
|
||||
connectSecond.resolve();
|
||||
await updatePromise;
|
||||
unsubscribe();
|
||||
|
||||
expect(store.getSnapshot(serverId)?.connectionStatus).toBe("online");
|
||||
expect(observedStatuses.every((status) => status === "online")).toBe(true);
|
||||
expect(store.getHosts().find((item) => item.serverId === serverId)?.password).toBe(
|
||||
"new-secret-123",
|
||||
);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,10 +10,8 @@ import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import equal from "fast-deep-equal/es6";
|
||||
import {
|
||||
DaemonClient,
|
||||
createHelloRejectedError,
|
||||
normalizeHelloRejection,
|
||||
DaemonAuthenticationError,
|
||||
type DaemonClientConfig,
|
||||
type DaemonHelloRejection,
|
||||
type ConnectionState,
|
||||
type FetchAgentsOptions,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -51,8 +49,7 @@ import { ConnectionOfferSchema, type ConnectionOffer } from "@getpaseo/protocol/
|
||||
import { HostConfirmations, type HostConfirmationRequest } from "./host-confirmation";
|
||||
import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { isPasswordRefusal } from "@/hosts/host-refusal";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
@@ -155,8 +152,7 @@ export interface HostRuntimeSnapshot {
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
client: DaemonClient | null;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
helloRejectionEpisode?: number;
|
||||
authFailureReason?: "password_required" | "incorrect_password" | null;
|
||||
lastOnlineAt: string | null;
|
||||
agentDirectoryStatus: HostRuntimeAgentDirectoryStatus;
|
||||
agentDirectoryError: string | null;
|
||||
@@ -336,7 +332,6 @@ type HostRuntimeConnectionMachineEvent =
|
||||
| { type: "select_connection"; connectionId: string; connection: ActiveConnection }
|
||||
| { type: "client_state"; state: ConnectionState; lastError: string | null }
|
||||
| { type: "connect_failed"; message: string }
|
||||
| { type: "active_connection_removed" }
|
||||
| { type: "no_connections" }
|
||||
| { type: "stopped" };
|
||||
|
||||
@@ -440,11 +435,7 @@ function nextConnectionMachineState(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
event.type === "no_connections" ||
|
||||
event.type === "stopped" ||
|
||||
event.type === "active_connection_removed"
|
||||
) {
|
||||
if (event.type === "no_connections" || event.type === "stopped") {
|
||||
return {
|
||||
tag: "offline",
|
||||
activeConnectionId: null,
|
||||
@@ -757,12 +748,10 @@ export class HostRuntimeController {
|
||||
private activeRttSamples: Array<{ at: number; rttMs: number }> = [];
|
||||
private clientIdPromise: Promise<string> | null = null;
|
||||
private clientIdHash: string | null = null;
|
||||
private hostUpdateVersion = 0;
|
||||
private switchRequestVersion = 0;
|
||||
private probeRequestVersion = 0;
|
||||
private probeCycleInFlight: Promise<void> | null = null;
|
||||
private hostUpdateInFlight: Promise<void> | null = null;
|
||||
private readonly refusedConnectionIds = new Set<string>();
|
||||
private readonly authRejectedConnectionIds = new Set<string>();
|
||||
|
||||
constructor(input: {
|
||||
host: HostProfile;
|
||||
@@ -781,8 +770,6 @@ export class HostRuntimeController {
|
||||
serverId: this.host.serverId,
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
helloRejection: null,
|
||||
helloRejectionEpisode: 0,
|
||||
agentDirectoryStatus: "idle",
|
||||
agentDirectoryError: null,
|
||||
hasEverLoadedAgentDirectory: false,
|
||||
@@ -834,7 +821,6 @@ export class HostRuntimeController {
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.hostUpdateVersion += 1;
|
||||
this.switchRequestVersion += 1;
|
||||
this.probeRequestVersion += 1;
|
||||
this.started = false;
|
||||
@@ -865,49 +851,23 @@ export class HostRuntimeController {
|
||||
});
|
||||
}
|
||||
|
||||
updateHost(host: HostProfile): Promise<void> {
|
||||
const updateVersion = ++this.hostUpdateVersion;
|
||||
const run = this.performUpdateHost(host, updateVersion).finally(() => {
|
||||
if (this.hostUpdateInFlight === run) {
|
||||
this.hostUpdateInFlight = null;
|
||||
}
|
||||
});
|
||||
this.hostUpdateInFlight = run;
|
||||
return run;
|
||||
}
|
||||
|
||||
async waitForHostUpdate(): Promise<void> {
|
||||
if (this.hostUpdateInFlight) {
|
||||
await this.hostUpdateInFlight;
|
||||
}
|
||||
}
|
||||
|
||||
private async performUpdateHost(host: HostProfile, updateVersion: number): Promise<void> {
|
||||
async updateHost(host: HostProfile): Promise<void> {
|
||||
const passwordChanged = this.host.password !== host.password;
|
||||
const connectionsChanged = !equal(this.host.connections, host.connections);
|
||||
if (passwordChanged || connectionsChanged) {
|
||||
if (passwordChanged) {
|
||||
this.probeRequestVersion += 1;
|
||||
this.probeCycleInFlight = null;
|
||||
this.refusedConnectionIds.clear();
|
||||
this.updateSnapshot({ helloRejection: null });
|
||||
this.authRejectedConnectionIds.clear();
|
||||
this.updateSnapshot({ authFailureReason: null });
|
||||
}
|
||||
if (passwordChanged || connectionsChanged) {
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
this.connectionLastProbedAt.clear();
|
||||
}
|
||||
const activeConnectionId = this.snapshot.activeConnectionId;
|
||||
const previousActiveConnection = findConnectionById(this.host, activeConnectionId);
|
||||
this.host = host;
|
||||
this.trackConnectionFirstSeen();
|
||||
const nextActiveConnection = findConnectionById(this.host, activeConnectionId);
|
||||
if (activeConnectionId && previousActiveConnection && !nextActiveConnection) {
|
||||
this.switchRequestVersion += 1;
|
||||
await this.disposePreviousActiveClient();
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
this.applyConnectionEvent({ type: "active_connection_removed" });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
});
|
||||
} else if (
|
||||
if (
|
||||
activeConnectionId &&
|
||||
previousActiveConnection &&
|
||||
nextActiveConnection &&
|
||||
@@ -919,13 +879,10 @@ export class HostRuntimeController {
|
||||
passwordChanged)
|
||||
) {
|
||||
this.connectionLastProbedAt.delete(activeConnectionId);
|
||||
await this.switchToConnection({
|
||||
connectionId: activeConnectionId,
|
||||
keepActiveUntilConnected: passwordChanged && this.snapshot.connectionStatus === "online",
|
||||
});
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
await this.switchToConnection({ connectionId: activeConnectionId });
|
||||
}
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
if (passwordChanged) this.connectionLastProbedAt.clear();
|
||||
if (passwordChanged) await this.probeCycleInFlight;
|
||||
await this.runProbeCycleNow();
|
||||
}
|
||||
|
||||
@@ -941,7 +898,7 @@ export class HostRuntimeController {
|
||||
(connection) =>
|
||||
connection.type === "routed" &&
|
||||
connection.originServerId === originServerId &&
|
||||
!this.refusedConnectionIds.has(connection.id),
|
||||
!this.authRejectedConnectionIds.has(connection.id),
|
||||
);
|
||||
if (routes.length === 0 || !this.started || isHostRuntimeConnected(this.snapshot)) return;
|
||||
if (routes.some((route) => route.id === this.snapshot.activeConnectionId))
|
||||
@@ -1050,14 +1007,8 @@ export class HostRuntimeController {
|
||||
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
|
||||
}
|
||||
|
||||
async runProbeCycleNow(options?: { clearRefusals?: boolean }): Promise<void> {
|
||||
if (options?.clearRefusals) {
|
||||
this.probeRequestVersion += 1;
|
||||
this.refusedConnectionIds.clear();
|
||||
this.connectionLastProbedAt.clear();
|
||||
this.updateSnapshot({ helloRejection: null });
|
||||
this.probeCycleInFlight = null;
|
||||
} else if (this.probeCycleInFlight) {
|
||||
async runProbeCycleNow(): Promise<void> {
|
||||
if (this.probeCycleInFlight) {
|
||||
return this.probeCycleInFlight;
|
||||
}
|
||||
|
||||
@@ -1091,7 +1042,7 @@ export class HostRuntimeController {
|
||||
|
||||
const inactiveOnlineIntervalMs = this.inactiveOnlineProbeIntervalMs();
|
||||
const connectionsToProbe = this.host.connections.filter((connection) => {
|
||||
if (this.refusedConnectionIds.has(connection.id)) return false;
|
||||
if (this.authRejectedConnectionIds.has(connection.id)) return false;
|
||||
const lastProbed = this.connectionLastProbedAt.get(connection.id);
|
||||
if (lastProbed == null) {
|
||||
return true;
|
||||
@@ -1128,7 +1079,7 @@ export class HostRuntimeController {
|
||||
this.updateSnapshot({ probeByConnectionId: initialProbes });
|
||||
|
||||
let remaining = connectionsToProbe.length;
|
||||
let probeHelloRejection: DaemonHelloRejection | null = null;
|
||||
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
|
||||
@@ -1144,7 +1095,7 @@ export class HostRuntimeController {
|
||||
connectionId: string,
|
||||
client: DaemonClient,
|
||||
): Promise<boolean> => {
|
||||
while (!this.snapshot.activeConnectionId || !this.snapshot.client) {
|
||||
while (!this.snapshot.activeConnectionId) {
|
||||
if (!activationLock) {
|
||||
activationLock = this.switchToConnection({
|
||||
connectionId,
|
||||
@@ -1154,9 +1105,7 @@ export class HostRuntimeController {
|
||||
activationLock = null;
|
||||
});
|
||||
await activationLock;
|
||||
return (
|
||||
this.snapshot.activeConnectionId === connectionId && this.snapshot.client === client
|
||||
);
|
||||
return this.snapshot.activeConnectionId === connectionId;
|
||||
}
|
||||
await activationLock;
|
||||
}
|
||||
@@ -1177,11 +1126,7 @@ export class HostRuntimeController {
|
||||
? probeByConnectionId.get(currentActiveConnectionId)
|
||||
: null;
|
||||
|
||||
if (
|
||||
!currentActiveConnectionId ||
|
||||
!this.snapshot.client ||
|
||||
!findConnectionById(this.host, currentActiveConnectionId)
|
||||
) {
|
||||
if (!currentActiveConnectionId || !findConnectionById(this.host, currentActiveConnectionId)) {
|
||||
const nextConnectionId = selectBestConnection({
|
||||
candidates: buildConnectionCandidates(this.host),
|
||||
probeByConnectionId,
|
||||
@@ -1191,12 +1136,12 @@ export class HostRuntimeController {
|
||||
connectionId: nextConnectionId,
|
||||
expectedProbeVersion: requestVersion,
|
||||
});
|
||||
} else if (probeHelloRejection) {
|
||||
const message = createHelloRejectedError(probeHelloRejection).message;
|
||||
} else if (probeAuthFailure) {
|
||||
const message = new DaemonAuthenticationError(probeAuthFailure).message;
|
||||
this.applyConnectionEvent({ type: "connect_failed", message });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
helloRejection: probeHelloRejection,
|
||||
authFailureReason: probeAuthFailure,
|
||||
});
|
||||
}
|
||||
return;
|
||||
@@ -1359,10 +1304,10 @@ export class HostRuntimeController {
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isCurrentProbeRequest(requestVersion)) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
this.refusedConnectionIds.add(connection.id);
|
||||
probeHelloRejection = rejection;
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
probeAuthFailure = authFailure;
|
||||
}
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "unavailable",
|
||||
@@ -1440,7 +1385,7 @@ export class HostRuntimeController {
|
||||
probeByConnectionId: Map<string, ConnectionProbeState>,
|
||||
): void {
|
||||
if (probeByConnectionId.get(connectionId)?.status !== "unavailable") return;
|
||||
if (this.refusedConnectionIds.has(connectionId)) return;
|
||||
if (this.authRejectedConnectionIds.has(connectionId)) return;
|
||||
const client = this.snapshot.client;
|
||||
if (!client || client.getConnectionState().status !== "connected") return;
|
||||
const rttMs = client.getLastLivenessRttMs();
|
||||
@@ -1457,22 +1402,14 @@ export class HostRuntimeController {
|
||||
connectionId: string,
|
||||
probe: ConnectionProbeState | null | undefined,
|
||||
): boolean {
|
||||
return probe?.status === "unavailable" || this.refusedConnectionIds.has(connectionId);
|
||||
return probe?.status === "unavailable" || this.authRejectedConnectionIds.has(connectionId);
|
||||
}
|
||||
|
||||
private updateSnapshot(patch: HostRuntimeSnapshotPatch): void {
|
||||
const preservedPatch: HostRuntimeSnapshotPatch = { ...patch };
|
||||
if (
|
||||
"helloRejection" in patch &&
|
||||
patch.helloRejection !== null &&
|
||||
patch.helloRejection !== undefined &&
|
||||
!equal(this.snapshot.helloRejection, patch.helloRejection)
|
||||
) {
|
||||
preservedPatch.helloRejectionEpisode = (this.snapshot.helloRejectionEpisode ?? 0) + 1;
|
||||
}
|
||||
let hasChanged = this.host.serverId !== this.snapshot.serverId;
|
||||
for (const key of Object.keys(preservedPatch) as (keyof HostRuntimeSnapshotPatch)[]) {
|
||||
const incomingValue = preservedPatch[key];
|
||||
for (const key of Object.keys(patch) as (keyof HostRuntimeSnapshotPatch)[]) {
|
||||
const incomingValue = patch[key];
|
||||
if (equal(this.snapshot[key], incomingValue)) {
|
||||
setSnapshotPatchField(preservedPatch, key, this.snapshot[key]);
|
||||
continue;
|
||||
@@ -1539,10 +1476,6 @@ export class HostRuntimeController {
|
||||
}
|
||||
}
|
||||
|
||||
private isCurrentHostUpdate(version: number): boolean {
|
||||
return version === this.hostUpdateVersion;
|
||||
}
|
||||
|
||||
private isCurrentSwitchRequest(version: number): boolean {
|
||||
return version === this.switchRequestVersion;
|
||||
}
|
||||
@@ -1731,9 +1664,9 @@ export class HostRuntimeController {
|
||||
try {
|
||||
await replacement.connect();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
this.refusedConnectionIds.add(connection.id);
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
@@ -1781,16 +1714,11 @@ export class HostRuntimeController {
|
||||
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
|
||||
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
|
||||
if (this.activeClient !== client) return;
|
||||
const clientRejection =
|
||||
client.helloRejection ??
|
||||
(client.authFailureReason
|
||||
? normalizeHelloRejection({ reason: client.authFailureReason, accepts: ["password"] })
|
||||
: null);
|
||||
if (clientRejection) {
|
||||
if (client.authFailureReason) {
|
||||
void this.failActiveConnection({
|
||||
client,
|
||||
connection,
|
||||
error: createHelloRejectedError(clientRejection),
|
||||
error: new DaemonAuthenticationError(client.authFailureReason),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1806,7 +1734,7 @@ export class HostRuntimeController {
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
...this.buildAgentDirectoryStatusPatch(),
|
||||
client,
|
||||
helloRejection: null,
|
||||
authFailureReason: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1818,9 +1746,8 @@ export class HostRuntimeController {
|
||||
}): Promise<void> {
|
||||
const { client, connection, error } = input;
|
||||
if (this.activeClient !== client) return;
|
||||
this.activeClient = null;
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) this.refusedConnectionIds.add(connection.id);
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
|
||||
this.unsubscribeClientStatus?.();
|
||||
this.unsubscribeClientStatus = null;
|
||||
this.unsubscribeClientHandlers?.();
|
||||
@@ -1830,14 +1757,14 @@ export class HostRuntimeController {
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
helloRejection: rejection,
|
||||
authFailureReason: authFailure,
|
||||
});
|
||||
if (rejection) {
|
||||
if (authFailure) {
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
for (const candidate of this.host.connections) {
|
||||
if (!this.refusedConnectionIds.has(candidate.id)) {
|
||||
if (!this.authRejectedConnectionIds.has(candidate.id)) {
|
||||
this.connectionLastProbedAt.delete(candidate.id);
|
||||
}
|
||||
}
|
||||
@@ -1848,8 +1775,8 @@ export class HostRuntimeController {
|
||||
/* Preserve the compatibility/connection error. */
|
||||
}
|
||||
if (
|
||||
rejection &&
|
||||
this.host.connections.some((candidate) => !this.refusedConnectionIds.has(candidate.id))
|
||||
authFailure &&
|
||||
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
|
||||
) {
|
||||
void this.runProbeCycleNow();
|
||||
}
|
||||
@@ -1896,7 +1823,6 @@ export class HostRuntimeController {
|
||||
const REGISTRY_STORAGE_KEY = "@paseo:daemon-registry";
|
||||
const LOCALHOST_FALLBACK_ENDPOINT = "localhost:6767";
|
||||
const DEFAULT_LOCALHOST_BOOTSTRAP_TIMEOUT_MS = 2500;
|
||||
const DEFAULT_PASSWORD_SUBMIT_TIMEOUT_MS = 10_000;
|
||||
const E2E_STORAGE_KEY = "@paseo:e2e";
|
||||
const INITIAL_DAEMON_CONNECTION_HINT_GLOBAL_KEY = "__PASEO_INITIAL_DAEMON_CONNECTION__";
|
||||
|
||||
@@ -1960,22 +1886,6 @@ function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function waitWithTimeout(promise: Promise<unknown>, timeoutMs: number): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
await Promise.race([
|
||||
promise,
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== null) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rekeyMap<V>(map: Map<string, V>, oldKey: string, newKey: string): void {
|
||||
const value = map.get(oldKey);
|
||||
if (value === undefined) {
|
||||
@@ -2487,8 +2397,7 @@ export class HostRuntimeStore {
|
||||
if (result.status === "cancelled") return result;
|
||||
return { status: "connected", serverId: result.serverId };
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (!rejection || !isPasswordRefusal(rejection)) throw error;
|
||||
if (!getConnectionAuthFailureReason(error)) throw error;
|
||||
return { status: "password_required", link: url, pairing };
|
||||
}
|
||||
}
|
||||
@@ -2587,37 +2496,6 @@ export class HostRuntimeStore {
|
||||
});
|
||||
}
|
||||
|
||||
async submitHostPassword(
|
||||
serverId: string,
|
||||
password: string,
|
||||
options?: { timeoutMs?: number },
|
||||
): Promise<HostPasswordSubmissionResult> {
|
||||
const existingHost = this.hosts.find((host) => host.serverId === serverId);
|
||||
if (!existingHost) {
|
||||
return { status: "failed", message: "Host not found" };
|
||||
}
|
||||
const previousPassword = existingHost.password ?? "";
|
||||
await this.setHostPassword(serverId, password);
|
||||
const controller = this.controllers.get(serverId);
|
||||
if (!controller) {
|
||||
return { status: "failed", message: "Host not found" };
|
||||
}
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_PASSWORD_SUBMIT_TIMEOUT_MS;
|
||||
const attempt =
|
||||
previousPassword === password
|
||||
? controller.runProbeCycleNow({ clearRefusals: true })
|
||||
: controller.waitForHostUpdate();
|
||||
await waitWithTimeout(attempt, timeoutMs);
|
||||
const snapshot = controller.getSnapshot();
|
||||
if (snapshot.connectionStatus === "online") {
|
||||
return { status: "online" };
|
||||
}
|
||||
if (snapshot.helloRejection) {
|
||||
return { status: "rejected", rejection: snapshot.helloRejection };
|
||||
}
|
||||
return { status: "failed", message: snapshot.lastError ?? "" };
|
||||
}
|
||||
|
||||
async setHostColor(serverId: string, color: HostColor): Promise<void> {
|
||||
await this.updateHostAppearance(serverId, (host) => ({
|
||||
...host,
|
||||
@@ -3144,12 +3022,12 @@ export class HostRuntimeStore {
|
||||
this.ensureConnectedAll({ verify: true });
|
||||
}
|
||||
|
||||
runProbeCycleNow(serverId?: string, options?: { clearRefusals?: boolean }): Promise<void> {
|
||||
runProbeCycleNow(serverId?: string): Promise<void> {
|
||||
if (serverId) {
|
||||
return this.controllers.get(serverId)?.runProbeCycleNow(options) ?? Promise.resolve();
|
||||
return this.controllers.get(serverId)?.runProbeCycleNow() ?? Promise.resolve();
|
||||
}
|
||||
return Promise.all(
|
||||
Array.from(this.controllers.values(), (controller) => controller.runProbeCycleNow(options)),
|
||||
Array.from(this.controllers.values(), (controller) => controller.runProbeCycleNow()),
|
||||
).then(() => undefined);
|
||||
}
|
||||
|
||||
@@ -3369,15 +3247,6 @@ export function useHostRuntimeLastError(serverId: string): string | null {
|
||||
);
|
||||
}
|
||||
|
||||
export function useHostRuntimeHelloRejection(serverId: string): DaemonHelloRejection | null {
|
||||
const store = getHostRuntimeStore();
|
||||
return useSyncExternalStore(
|
||||
(onStoreChange) => store.subscribe(serverId, onStoreChange),
|
||||
() => store.getSnapshot(serverId)?.helloRejection ?? null,
|
||||
() => store.getSnapshot(serverId)?.helloRejection ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useHostRuntimeAgentDirectoryStatus(
|
||||
serverId: string,
|
||||
): HostRuntimeAgentDirectoryStatus {
|
||||
@@ -3448,11 +3317,6 @@ export function useHostConfirmation(): {
|
||||
);
|
||||
}
|
||||
|
||||
export type HostPasswordSubmissionResult =
|
||||
| { status: "online" }
|
||||
| { status: "rejected"; rejection: DaemonHelloRejection }
|
||||
| { status: "failed"; message: string };
|
||||
|
||||
export interface HostMutations {
|
||||
upsertDirectConnection: (input: {
|
||||
serverId: string;
|
||||
@@ -3476,8 +3340,6 @@ export interface HostMutations {
|
||||
}) => Promise<{ profile: HostProfile; serverId: string; hostname: string | null }>;
|
||||
beginLinkPairing: () => LinkPairing;
|
||||
renameHost: (serverId: string, label: string) => Promise<void>;
|
||||
setHostPassword: (serverId: string, password: string) => Promise<void>;
|
||||
submitHostPassword: (serverId: string, password: string) => Promise<HostPasswordSubmissionResult>;
|
||||
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
|
||||
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
|
||||
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
|
||||
@@ -3494,8 +3356,6 @@ export function useHostMutations(): HostMutations {
|
||||
probeAndUpsertRemoteSshConnection: (input) => store.probeAndUpsertRemoteSshConnection(input),
|
||||
beginLinkPairing: () => store.beginLinkPairing(),
|
||||
renameHost: (serverId, label) => store.renameHost(serverId, label),
|
||||
setHostPassword: (serverId, password) => store.setHostPassword(serverId, password),
|
||||
submitHostPassword: (serverId, password) => store.submitHostPassword(serverId, password),
|
||||
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
|
||||
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
|
||||
setHostBadgeDisplay: (serverId, badgeDisplay) =>
|
||||
|
||||
@@ -25,7 +25,6 @@ import { useIsLocalDaemon, useLocalDaemonServerId } from "@/hooks/use-is-local-d
|
||||
import { resolveHostIcon } from "@/hosts/appearance";
|
||||
import { describeActiveConnection, describeHostConnection } from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { useHostMutations, useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { HostAppearanceSection } from "@/screens/settings/host-appearance-section";
|
||||
import { HostConnectionError } from "@/screens/settings/host-page";
|
||||
@@ -145,13 +144,7 @@ function ClientHostListRow({
|
||||
if (status === "online") {
|
||||
summary = formatDaemonVersion(serverInfo?.version ?? null);
|
||||
} else if (status === "offline" || status === "error") {
|
||||
summary = snapshot?.helloRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: snapshot.helloRejection,
|
||||
hostName: host.label,
|
||||
t,
|
||||
}).shortStatus
|
||||
: t("settings.about.offline");
|
||||
summary = t("settings.about.offline");
|
||||
}
|
||||
|
||||
const leading = useMemo(
|
||||
@@ -376,7 +369,7 @@ function ClientHostRoutesSection({
|
||||
hosts={hosts}
|
||||
latencyMs={probe?.status === "available" ? probe.latencyMs : undefined}
|
||||
latencyLoading={!probe || probe.status === "pending"}
|
||||
latencyError={probe?.status === "unavailable" && !snapshot?.helloRejection}
|
||||
latencyError={probe?.status === "unavailable"}
|
||||
onRemove={handleRequestRemove}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useIsFocused } from "expo-router/react-navigation";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } from "react-native";
|
||||
@@ -37,7 +36,6 @@ import {
|
||||
} from "@/screens/settings/terminal-profile-edit-modal";
|
||||
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
||||
import { ConnectedDevicesView } from "@/devices";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
@@ -60,7 +58,6 @@ import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { isVersionMismatch } from "@/desktop/updates/desktop-updates";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons";
|
||||
import { HostRefusalAlert } from "@/hosts/host-refusal-alert";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
@@ -214,23 +211,8 @@ function HostStatusBadges({ serverId }: { serverId: string }) {
|
||||
}
|
||||
|
||||
export function HostConnectionError({ serverId }: { serverId: string }) {
|
||||
const isFocused = useIsFocused();
|
||||
useActiveRefusalHost(serverId, isFocused);
|
||||
const { t } = useTranslation();
|
||||
const snapshot = useHostRuntimeSnapshot(serverId);
|
||||
const host = useHostProfile(serverId);
|
||||
const hostName = host?.label?.trim() || serverId;
|
||||
if (snapshot?.helloRejection) {
|
||||
return (
|
||||
<View style={styles.connectionError}>
|
||||
<HostRefusalAlert
|
||||
serverId={serverId}
|
||||
hostName={hostName}
|
||||
rejection={snapshot.helloRejection}
|
||||
testID="host-connection-error"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const lastError = snapshot?.lastError ?? null;
|
||||
const connectionError =
|
||||
typeof lastError === "string" && lastError.trim().length > 0 ? lastError.trim() : null;
|
||||
@@ -241,6 +223,7 @@ export function HostConnectionError({ serverId }: { serverId: string }) {
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={connectionError}
|
||||
description={snapshot?.authFailureReason ? t("settings.host.password.guidance") : undefined}
|
||||
testID="host-connection-error"
|
||||
/>
|
||||
</View>
|
||||
@@ -254,12 +237,7 @@ export function HostDevicesPage({ serverId }: { serverId: string }) {
|
||||
return <HostNotFound />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View>
|
||||
<HostConnectionError serverId={serverId} />
|
||||
<ConnectedDevicesView serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
return <ConnectedDevicesView serverId={serverId} />;
|
||||
}
|
||||
|
||||
export function HostToolsPage({ serverId }: { serverId: string }) {
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
WindowLayoutActions,
|
||||
} from "@/window-layout";
|
||||
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
|
||||
import { HostRefusalHeaderButton } from "@/hosts/host-refusal-sheet";
|
||||
|
||||
export { MobileWorkspaceTabSwitcher } from "./tab-switcher";
|
||||
|
||||
@@ -60,12 +59,9 @@ export function CompactWorkspaceHeader({
|
||||
overflow: children,
|
||||
explorer: explorerAction,
|
||||
};
|
||||
const actions = [
|
||||
<HostRefusalHeaderButton key="refusal" serverId={serverId} />,
|
||||
...resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
)),
|
||||
];
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
));
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { HostRefusalEmptyState } from "@/hosts/host-refusal-alert";
|
||||
import { formatConnectionStatus } from "@/utils/daemons";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
import type {
|
||||
@@ -29,7 +28,6 @@ interface WorkspaceRouteStateActions {
|
||||
}
|
||||
|
||||
export function renderWorkspaceRouteGate(input: {
|
||||
serverId: string;
|
||||
state: WorkspaceRouteState;
|
||||
actions: WorkspaceRouteStateActions;
|
||||
}): React.ReactNode {
|
||||
@@ -62,7 +60,6 @@ export function renderWorkspaceRouteGate(input: {
|
||||
case "unreachable":
|
||||
return (
|
||||
<WorkspaceUnreachable
|
||||
serverId={input.serverId}
|
||||
state={input.state}
|
||||
onRetry={input.actions.onRetryHost}
|
||||
onManageHost={input.actions.onManageHost}
|
||||
@@ -214,31 +211,15 @@ function WorkspaceRecoveryInspectionFailed({
|
||||
}
|
||||
|
||||
function WorkspaceUnreachable({
|
||||
serverId,
|
||||
state,
|
||||
onRetry,
|
||||
onManageHost,
|
||||
}: {
|
||||
serverId: string;
|
||||
state: Extract<WorkspaceRouteState, { kind: "unreachable" }>;
|
||||
onRetry: () => void;
|
||||
onManageHost: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (state.helloRejection) {
|
||||
return (
|
||||
<HostRefusalEmptyState
|
||||
serverId={serverId}
|
||||
hostName={state.hostName}
|
||||
rejection={state.helloRejection}
|
||||
onManageHost={onManageHost}
|
||||
testID="workspace-unreachable-refusal"
|
||||
testIDPrefix="workspace-refusal"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.emptyState}>
|
||||
<View style={styles.textStack}>
|
||||
|
||||
@@ -31,8 +31,7 @@ function createWorkspaceDescriptor(): WorkspaceDescriptor {
|
||||
|
||||
function resolve(input: {
|
||||
workspace?: WorkspaceDescriptor | null;
|
||||
connectionStatus?: "online" | "offline" | "connecting" | "idle" | "error";
|
||||
helloRejection?: { reason: string; accepts: readonly string[]; message?: string } | null;
|
||||
connectionStatus?: "online" | "offline" | "connecting" | "idle";
|
||||
hasHydratedWorkspaces?: boolean;
|
||||
hasRestoredCachedDirectory?: boolean;
|
||||
recovery?: WorkspaceRecoveryModel;
|
||||
@@ -40,11 +39,7 @@ function resolve(input: {
|
||||
return resolveWorkspaceRouteState({
|
||||
hostName: "Laptop",
|
||||
connectionStatus: input.connectionStatus ?? "online",
|
||||
lastError:
|
||||
input.connectionStatus === "offline" || input.connectionStatus === "error"
|
||||
? "transport closed"
|
||||
: null,
|
||||
helloRejection: input.helloRejection ?? null,
|
||||
lastError: input.connectionStatus === "offline" ? "transport closed" : null,
|
||||
workspace: input.workspace ?? null,
|
||||
hasHydratedWorkspaces: input.hasHydratedWorkspaces ?? true,
|
||||
hasRestoredCachedDirectory: input.hasRestoredCachedDirectory ?? true,
|
||||
@@ -72,31 +67,6 @@ describe("resolveWorkspaceRouteState", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "transport closed",
|
||||
helloRejection: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries helloRejection on reconnecting cached workspaces and unreachable routes", () => {
|
||||
const rejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
expect(
|
||||
resolve({
|
||||
workspace: createWorkspaceDescriptor(),
|
||||
connectionStatus: "error",
|
||||
helloRejection: rejection,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "reconnecting",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "error",
|
||||
lastError: "transport closed",
|
||||
helloRejection: rejection,
|
||||
});
|
||||
expect(resolve({ connectionStatus: "error", helloRejection: rejection })).toEqual({
|
||||
kind: "unreachable",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "error",
|
||||
lastError: "transport closed",
|
||||
helloRejection: rejection,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -134,7 +104,6 @@ describe("resolveWorkspaceRouteState", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "transport closed",
|
||||
helloRejection: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -505,15 +474,8 @@ describe("post-restore handoff state machine", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "closed",
|
||||
helloRejection: null,
|
||||
},
|
||||
{
|
||||
kind: "unreachable",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "closed",
|
||||
helloRejection: null,
|
||||
},
|
||||
{ kind: "unreachable", hostName: "Laptop", connectionStatus: "offline", lastError: "closed" },
|
||||
{ kind: "loading", hostName: "Laptop", waitingFor: "workspace" },
|
||||
{ kind: "missing", hostName: "Laptop" },
|
||||
{ kind: "recoveryUnavailable", hostName: "Laptop", message: "missing" },
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
|
||||
@@ -10,14 +9,12 @@ export type WorkspaceRouteState =
|
||||
hostName: string;
|
||||
connectionStatus: Exclude<HostRuntimeConnectionStatus, "online">;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
}
|
||||
| {
|
||||
kind: "unreachable";
|
||||
hostName: string;
|
||||
connectionStatus: Extract<HostRuntimeConnectionStatus, "offline" | "error">;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
}
|
||||
| { kind: "loading"; hostName: string; waitingFor: WorkspaceLoadingSource }
|
||||
| { kind: "missing"; hostName: string }
|
||||
@@ -40,14 +37,12 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: string;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
workspace: WorkspaceDescriptor | null;
|
||||
hasHydratedWorkspaces: boolean;
|
||||
/** The host's cached directory has been read, so a workspace it holds is in the store. */
|
||||
hasRestoredCachedDirectory: boolean;
|
||||
recovery: WorkspaceRecoveryModel;
|
||||
}): WorkspaceRouteState {
|
||||
const helloRejection = input.helloRejection ?? null;
|
||||
if (input.workspace) {
|
||||
if (input.connectionStatus === "online") {
|
||||
if (input.recovery.kind === "recoverable" && input.recovery.phase === "restoring") {
|
||||
@@ -61,7 +56,6 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: input.connectionStatus,
|
||||
lastError: input.lastError,
|
||||
helloRejection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,7 +74,6 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: input.connectionStatus,
|
||||
lastError: input.lastError,
|
||||
helloRejection,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -172,8 +172,6 @@ import {
|
||||
renderWorkspaceRouteGate,
|
||||
WorkspaceLoading,
|
||||
} from "@/screens/workspace/workspace-route-state-views";
|
||||
import { HostRefusalHeaderButton } from "@/hosts/host-refusal-sheet";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useWorkspaceRecovery } from "@/workspace-recovery/use-workspace-recovery";
|
||||
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
|
||||
import {
|
||||
@@ -302,7 +300,6 @@ function decodeSegment(value: string): string {
|
||||
function useSyncWorkspaceActiveBrowser(input: {
|
||||
workspaceLayout: WorkspaceLayout | null;
|
||||
isRouteFocused: boolean;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}) {
|
||||
const focusedBrowserId = useMemo(
|
||||
@@ -311,15 +308,14 @@ function useSyncWorkspaceActiveBrowser(input: {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getIsElectron() || !input.serverId || !input.workspaceId) {
|
||||
if (!getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
void getDesktopHost()?.browser?.setWorkspaceActiveBrowser?.({
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
browserId: focusedBrowserId,
|
||||
});
|
||||
}, [focusedBrowserId, input.serverId, input.workspaceId]);
|
||||
}, [focusedBrowserId, input.workspaceId]);
|
||||
}
|
||||
|
||||
function WorkspaceDocumentTitleEffect({
|
||||
@@ -671,7 +667,7 @@ function useWorkspaceRouteActions(normalizedServerId: string): {
|
||||
if (!normalizedServerId) {
|
||||
return;
|
||||
}
|
||||
void getHostRuntimeStore().runProbeCycleNow(normalizedServerId, { clearRefusals: true });
|
||||
void getHostRuntimeStore().runProbeCycleNow(normalizedServerId);
|
||||
}, [normalizedServerId]);
|
||||
const handleManageHost = useCallback(() => {
|
||||
if (!normalizedServerId) {
|
||||
@@ -724,7 +720,6 @@ function useResolvedWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: hostSnapshot?.connectionStatus ?? "connecting",
|
||||
lastError: hostSnapshot?.lastError ?? null,
|
||||
helloRejection: hostSnapshot?.helloRejection ?? null,
|
||||
workspace: input.workspace,
|
||||
hasHydratedWorkspaces: input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
@@ -734,7 +729,6 @@ function useResolvedWorkspaceRouteState(input: {
|
||||
input.hostName,
|
||||
hostSnapshot?.connectionStatus,
|
||||
hostSnapshot?.lastError,
|
||||
hostSnapshot?.helloRejection,
|
||||
input.workspace,
|
||||
input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
@@ -1042,7 +1036,6 @@ function WorkspaceScreenContent({
|
||||
const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode);
|
||||
|
||||
const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]);
|
||||
useActiveRefusalHost(normalizedServerId, isRouteFocused);
|
||||
|
||||
const normalizedWorkspaceId = useMemo(
|
||||
() => resolveWorkspaceRouteId({ routeWorkspaceId: workspaceId }) ?? "",
|
||||
@@ -1337,7 +1330,6 @@ function WorkspaceScreenContent({
|
||||
useSyncWorkspaceActiveBrowser({
|
||||
workspaceLayout,
|
||||
isRouteFocused,
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const openWorkspaceTabInBackground = useCallback(
|
||||
@@ -2893,7 +2885,6 @@ function WorkspaceScreenContent({
|
||||
const containerStyle = [styles.container, styles.containerWorkspaceBackground];
|
||||
|
||||
const workspaceScreenGate = renderWorkspaceRouteGate({
|
||||
serverId: normalizedServerId,
|
||||
state: displayedWorkspaceRouteState,
|
||||
actions: {
|
||||
onRetryHost: handleRetryHost,
|
||||
@@ -2918,7 +2909,6 @@ function WorkspaceScreenContent({
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
{workspaceActionsInBar ? null : <HostRefusalHeaderButton serverId={normalizedServerId} />}
|
||||
<PluginHeaderButtons serverId={normalizedServerId} workspaceId={normalizedWorkspaceId} />
|
||||
{workspaceDescriptor && workspaceDescriptor.scripts.length > 0 ? (
|
||||
<WorkspaceScriptsButton
|
||||
|
||||
@@ -920,56 +920,3 @@ describe("setAgentOverlay", () => {
|
||||
).toBe("low");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateSessionServerInfo", () => {
|
||||
it("preserves and updates password status, auth mode, and permissions", () => {
|
||||
const store = useSessionStore.getState();
|
||||
initializeTestSession();
|
||||
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: false,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
|
||||
const first = useSessionStore.getState().sessions["test-server"]?.serverInfo;
|
||||
expect(first?.passwordConfigured).toBe(false);
|
||||
expect(first?.passwordManagedByEnv).toBe(false);
|
||||
expect(first?.localCredentialAuth).toBe(true);
|
||||
expect(first?.permissions).toEqual(["daemon.manage", "access.manage"]);
|
||||
|
||||
// Content-equal update keeps session identity stable.
|
||||
const beforeSame = getTestSessionReferences();
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: false,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
expect(getTestSessionReferences().session).toBe(beforeSame.session);
|
||||
|
||||
// Live password change propagates immediately.
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: true,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
const updated = useSessionStore.getState().sessions["test-server"]?.serverInfo;
|
||||
expect(updated?.passwordConfigured).toBe(true);
|
||||
expect(updated?.localCredentialAuth).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -402,9 +402,6 @@ export interface DaemonServerInfo {
|
||||
version: string | null;
|
||||
machineKind?: string | null;
|
||||
desktopManaged?: boolean;
|
||||
passwordConfigured?: boolean;
|
||||
passwordManagedByEnv?: boolean;
|
||||
localCredentialAuth?: boolean;
|
||||
permissions?: ServerInfoStatusPayload["permissions"];
|
||||
capabilities?: ServerCapabilities;
|
||||
features?: ServerInfoStatusPayload["features"];
|
||||
@@ -419,15 +416,6 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
|
||||
...(serverInfo.desktopManaged !== undefined
|
||||
? { desktopManaged: serverInfo.desktopManaged }
|
||||
: {}),
|
||||
...(serverInfo.passwordConfigured !== undefined
|
||||
? { passwordConfigured: serverInfo.passwordConfigured }
|
||||
: {}),
|
||||
...(serverInfo.passwordManagedByEnv !== undefined
|
||||
? { passwordManagedByEnv: serverInfo.passwordManagedByEnv }
|
||||
: {}),
|
||||
...(serverInfo.localCredentialAuth !== undefined
|
||||
? { localCredentialAuth: serverInfo.localCredentialAuth }
|
||||
: {}),
|
||||
...(serverInfo.permissions ? { permissions: serverInfo.permissions } : {}),
|
||||
...(serverInfo.capabilities ? { capabilities: serverInfo.capabilities } : {}),
|
||||
...(serverInfo.features ? { features: serverInfo.features } : {}),
|
||||
@@ -951,62 +939,36 @@ function areServerInfoFeaturesEqual(
|
||||
return JSON.stringify(current ?? null) === JSON.stringify(next ?? null);
|
||||
}
|
||||
|
||||
function areServerInfoPermissionsEqual(
|
||||
left: ServerInfoStatusPayload["permissions"] | undefined,
|
||||
right: ServerInfoStatusPayload["permissions"] | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (!left || !right || left.length !== right.length) return false;
|
||||
return left.every((permission, index) => permission === right[index]);
|
||||
}
|
||||
|
||||
function areServerInfoAuthFieldsEqual(
|
||||
currentServerInfo: DaemonServerInfo,
|
||||
input: {
|
||||
nextPasswordConfigured: boolean | undefined;
|
||||
nextPasswordManagedByEnv: boolean | undefined;
|
||||
nextLocalCredentialAuth: boolean | undefined;
|
||||
nextPermissions: ServerInfoStatusPayload["permissions"] | undefined;
|
||||
},
|
||||
): boolean {
|
||||
return (
|
||||
currentServerInfo.passwordConfigured === input.nextPasswordConfigured &&
|
||||
currentServerInfo.passwordManagedByEnv === input.nextPasswordManagedByEnv &&
|
||||
currentServerInfo.localCredentialAuth === input.nextLocalCredentialAuth &&
|
||||
areServerInfoPermissionsEqual(currentServerInfo.permissions, input.nextPermissions)
|
||||
);
|
||||
}
|
||||
|
||||
function isSessionServerInfoUnchanged(input: {
|
||||
currentServerInfo: SessionState["serverInfo"] | undefined;
|
||||
nextHostname: string | null;
|
||||
nextVersion: string | null;
|
||||
nextMachineKind: string | null;
|
||||
nextDesktopManaged: boolean | undefined;
|
||||
nextPasswordConfigured: boolean | undefined;
|
||||
nextPasswordManagedByEnv: boolean | undefined;
|
||||
nextLocalCredentialAuth: boolean | undefined;
|
||||
nextPermissions: ServerInfoStatusPayload["permissions"] | undefined;
|
||||
nextCapabilities: ServerCapabilities | undefined;
|
||||
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
|
||||
nextServerId: string;
|
||||
}): boolean {
|
||||
const { currentServerInfo } = input;
|
||||
if (!currentServerInfo) {
|
||||
return false;
|
||||
}
|
||||
const prevHostname = currentServerInfo.hostname?.trim() || null;
|
||||
const prevVersion = currentServerInfo.version?.trim() || null;
|
||||
const prevMachineKind = currentServerInfo.machineKind?.trim() || null;
|
||||
const {
|
||||
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 === input.nextHostname &&
|
||||
prevVersion === input.nextVersion &&
|
||||
prevMachineKind === input.nextMachineKind &&
|
||||
currentServerInfo.desktopManaged === input.nextDesktopManaged &&
|
||||
areServerInfoAuthFieldsEqual(currentServerInfo, input) &&
|
||||
areServerCapabilitiesEqual(currentServerInfo.capabilities, input.nextCapabilities) &&
|
||||
areServerInfoFeaturesEqual(currentServerInfo.features, input.nextFeatures)
|
||||
currentServerInfo?.serverId === input.nextServerId &&
|
||||
prevHostname === nextHostname &&
|
||||
prevVersion === nextVersion &&
|
||||
prevMachineKind === nextMachineKind &&
|
||||
currentServerInfo?.desktopManaged === nextDesktopManaged &&
|
||||
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
|
||||
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1144,10 +1106,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
const nextVersion = info.version?.trim() || null;
|
||||
const nextMachineKind = info.machineKind?.trim() || null;
|
||||
const nextDesktopManaged = info.desktopManaged;
|
||||
const nextPasswordConfigured = info.passwordConfigured;
|
||||
const nextPasswordManagedByEnv = info.passwordManagedByEnv;
|
||||
const nextLocalCredentialAuth = info.localCredentialAuth;
|
||||
const nextPermissions = info.permissions;
|
||||
const nextCapabilities = info.capabilities;
|
||||
const nextFeatures = info.features;
|
||||
|
||||
@@ -1158,10 +1116,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextPasswordConfigured,
|
||||
nextPasswordManagedByEnv,
|
||||
nextLocalCredentialAuth,
|
||||
nextPermissions,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
nextServerId: info.serverId,
|
||||
@@ -1184,16 +1138,6 @@ export const useSessionStore = create<SessionStore>()(
|
||||
...(nextDesktopManaged !== undefined
|
||||
? { desktopManaged: nextDesktopManaged }
|
||||
: {}),
|
||||
...(nextPasswordConfigured !== undefined
|
||||
? { passwordConfigured: nextPasswordConfigured }
|
||||
: {}),
|
||||
...(nextPasswordManagedByEnv !== undefined
|
||||
? { passwordManagedByEnv: nextPasswordManagedByEnv }
|
||||
: {}),
|
||||
...(nextLocalCredentialAuth !== undefined
|
||||
? { localCredentialAuth: nextLocalCredentialAuth }
|
||||
: {}),
|
||||
...(nextPermissions ? { permissions: nextPermissions } : {}),
|
||||
...(nextCapabilities ? { capabilities: nextCapabilities } : {}),
|
||||
...(nextFeatures ? { features: nextFeatures } : {}),
|
||||
},
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonHelloRejectedError,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { DaemonAuthenticationError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonConnectionDependencies, DaemonProbeClient } from "./test-daemon-connection";
|
||||
import { createHostLogger } from "@/runtime/host-logger";
|
||||
|
||||
@@ -338,37 +335,6 @@ describe("test-daemon-connection connectToDaemon", () => {
|
||||
).rejects.toMatchObject({
|
||||
message: "Incorrect password",
|
||||
authFailureReason: "incorrect_password",
|
||||
helloRejection: { reason: "incorrect_password", accepts: ["password"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("propagates non-password hello.rejected refusals via getConnectionHelloRejection", async () => {
|
||||
const { connectToDaemon, getConnectionAuthFailureReason, getConnectionHelloRejection } =
|
||||
await import("./test-daemon-connection");
|
||||
probe.failNextConnection(
|
||||
new DaemonHelloRejectedError({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
}),
|
||||
"Connection refused (pairing_required)",
|
||||
);
|
||||
|
||||
const error = await connectToDaemon(
|
||||
{
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
},
|
||||
{},
|
||||
probe.deps,
|
||||
).catch((caught: unknown) => caught);
|
||||
|
||||
expect(getConnectionAuthFailureReason(error)).toBeNull();
|
||||
expect(getConnectionHelloRejection(error)).toEqual({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonClient,
|
||||
createHelloRejectedError,
|
||||
getDaemonAuthFailureReason,
|
||||
getDaemonHelloRejection,
|
||||
normalizeHelloRejection,
|
||||
type DaemonAuthFailureReason,
|
||||
type DaemonHelloRejection,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
@@ -26,7 +23,6 @@ import type { DesktopDaemonTransportTarget } from "@/desktop/daemon/desktop-daem
|
||||
|
||||
export interface DaemonProbeClient {
|
||||
readonly lastError: string | null;
|
||||
readonly helloRejection?: DaemonHelloRejection | null;
|
||||
readonly authFailureReason?: DaemonAuthFailureReason | null;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
@@ -98,20 +94,9 @@ function pickBestReason(reason: string | null, lastError: string | null): string
|
||||
return "Unable to connect";
|
||||
}
|
||||
|
||||
function deriveAuthFailureReason(
|
||||
rejection: DaemonHelloRejection | null,
|
||||
): DaemonAuthFailureReason | null {
|
||||
if (!rejection) return null;
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return rejection.reason;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export class DaemonConnectionTestError extends Error {
|
||||
reason: string | null;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
authFailureReason: DaemonAuthFailureReason | null;
|
||||
|
||||
constructor(
|
||||
@@ -119,7 +104,6 @@ export class DaemonConnectionTestError extends Error {
|
||||
details: {
|
||||
reason: string | null;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
authFailureReason?: DaemonAuthFailureReason | null;
|
||||
},
|
||||
) {
|
||||
@@ -127,21 +111,10 @@ export class DaemonConnectionTestError extends Error {
|
||||
this.name = "DaemonConnectionTestError";
|
||||
this.reason = details.reason;
|
||||
this.lastError = details.lastError;
|
||||
this.helloRejection =
|
||||
details.helloRejection ??
|
||||
(details.authFailureReason
|
||||
? normalizeHelloRejection({ reason: details.authFailureReason, accepts: ["password"] })
|
||||
: null);
|
||||
this.authFailureReason =
|
||||
details.authFailureReason ?? deriveAuthFailureReason(this.helloRejection);
|
||||
this.authFailureReason = details.authFailureReason ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getConnectionHelloRejection(error: unknown): DaemonHelloRejection | null {
|
||||
if (error instanceof DaemonConnectionTestError) return error.helloRejection;
|
||||
return getDaemonHelloRejection(error);
|
||||
}
|
||||
|
||||
export function getConnectionAuthFailureReason(error: unknown): DaemonAuthFailureReason | null {
|
||||
if (error instanceof DaemonConnectionTestError) return error.authFailureReason;
|
||||
return getDaemonAuthFailureReason(error);
|
||||
@@ -303,27 +276,13 @@ export function connectAndProbe(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
const lastError = normalizeNonEmptyString(client.lastError);
|
||||
const legacyAuthFailure =
|
||||
const authFailureReason =
|
||||
getDaemonAuthFailureReason(error) ?? client.authFailureReason ?? null;
|
||||
const helloRejection =
|
||||
getDaemonHelloRejection(error) ??
|
||||
client.helloRejection ??
|
||||
(legacyAuthFailure
|
||||
? normalizeHelloRejection({ reason: legacyAuthFailure, accepts: ["password"] })
|
||||
: null);
|
||||
const authFailureReason = deriveAuthFailureReason(helloRejection);
|
||||
const message = helloRejection
|
||||
? createHelloRejectedError(helloRejection).message
|
||||
const message = authFailureReason
|
||||
? new DaemonAuthenticationError(authFailureReason).message
|
||||
: pickBestReason(reason, lastError);
|
||||
void client.close().catch(() => undefined);
|
||||
reject(
|
||||
new DaemonConnectionTestError(message, {
|
||||
reason,
|
||||
lastError,
|
||||
helloRejection,
|
||||
authFailureReason,
|
||||
}),
|
||||
);
|
||||
reject(new DaemonConnectionTestError(message, { reason, lastError, authFailureReason }));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Command } from "commander";
|
||||
import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { shortenHomePath } from "../../utils/paths.js";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
|
||||
import { resolveDisplayModel } from "./display-model.js";
|
||||
@@ -80,6 +79,15 @@ function createInspectSchema(agent: AgentInspect): OutputSchema<InspectRow> {
|
||||
};
|
||||
}
|
||||
|
||||
/** Shorten home directory in path */
|
||||
function shortenPath(path: string): string {
|
||||
const home = process.env.HOME;
|
||||
if (home && path.startsWith(home)) {
|
||||
return "~" + path.slice(home.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Format cost in USD */
|
||||
function formatCost(costUsd: number): string {
|
||||
if (costUsd === 0) return "$0.00";
|
||||
@@ -148,7 +156,7 @@ function toInspectRows(agent: AgentInspect): InspectRow[] {
|
||||
{ key: "Archived", value: String(agent.Archived) },
|
||||
{ key: "ArchivedAt", value: agent.ArchivedAt ?? "null" },
|
||||
{ key: "Mode", value: agent.Mode },
|
||||
{ key: "Cwd", value: shortenHomePath(agent.Cwd) },
|
||||
{ key: "Cwd", value: shortenPath(agent.Cwd) },
|
||||
{ key: "CreatedAt", value: agent.CreatedAt },
|
||||
{ key: "UpdatedAt", value: agent.UpdatedAt },
|
||||
];
|
||||
|
||||
@@ -4,7 +4,7 @@ import { connectToDaemon } from "../../utils/client.js";
|
||||
import { fetchAllAgents } from "../../utils/agent-directory.js";
|
||||
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
|
||||
import { collectMultiple } from "../../utils/command-options.js";
|
||||
import { isSameOrDescendantPath, shortenHomePath } from "../../utils/paths.js";
|
||||
import { isSameOrDescendantPath } from "../../utils/paths.js";
|
||||
import { resolveDisplayModel } from "./display-model.js";
|
||||
|
||||
type FetchAgentsOptions = NonNullable<
|
||||
@@ -56,6 +56,15 @@ function relativeTime(date: Date | string): string {
|
||||
return `${Math.floor(seconds / 86400)} days ago`;
|
||||
}
|
||||
|
||||
/** Shorten home directory in path */
|
||||
function shortenPath(path: string): string {
|
||||
const home = process.env.HOME;
|
||||
if (home && path.startsWith(home)) {
|
||||
return "~" + path.slice(home.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Schema for agent ls output */
|
||||
export const agentLsSchema: OutputSchema<AgentListItem> = {
|
||||
idField: "shortId",
|
||||
@@ -99,7 +108,7 @@ function toListItem(agent: AgentSnapshotPayload): AgentListItem {
|
||||
provider: model ? `${agent.provider}/${model}` : agent.provider,
|
||||
thinking: agent.effectiveThinkingOptionId ?? "auto",
|
||||
status: agent.status,
|
||||
cwd: shortenHomePath(agent.cwd),
|
||||
cwd: shortenPath(agent.cwd),
|
||||
created: relativeTime(agent.createdAt),
|
||||
createdAt: agent.createdAt,
|
||||
updatedAt: agent.updatedAt,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Command } from "commander";
|
||||
import { isCompleteGitRemote } from "@getpaseo/protocol/git-remote";
|
||||
import { connectToDaemon } from "../utils/client.js";
|
||||
import { resolveCallerPath } from "../utils/paths.js";
|
||||
import type { CommandError, OutputSchema, SingleResult } from "../output/index.js";
|
||||
import type { CommandOptions } from "../output/with-output.js";
|
||||
|
||||
@@ -59,7 +58,7 @@ export async function runCloneCommand(
|
||||
try {
|
||||
const response = await client.cloneGithubProject({
|
||||
repo,
|
||||
targetDirectory: resolveCallerPath(targetDirectory, options.daemonTarget),
|
||||
targetDirectory,
|
||||
...(repoIsCompleteRemote ? {} : { cloneProtocol: options.protocol }),
|
||||
});
|
||||
if (response.error || !response.project || !response.checkoutPath) {
|
||||
|
||||
@@ -25,10 +25,7 @@ export function createDaemonCommand(): Command {
|
||||
daemon.addCommand(command);
|
||||
addJsonOption(
|
||||
addLocalDaemonOptions(
|
||||
daemon
|
||||
.command("set-password")
|
||||
.description("Set, change, or remove the daemon password")
|
||||
.option("--remove", "Remove the daemon password"),
|
||||
daemon.command("set-password").description("Save a hashed daemon password (local operation)"),
|
||||
),
|
||||
).action(withOutput(runSetPasswordCommand));
|
||||
return daemon;
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { hostname, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { readPersistedConfig } from "@getpaseo/server/configuration";
|
||||
import { readDaemonInstance } from "@getpaseo/server/daemon-control";
|
||||
import { isBearerTokenValidAsync } from "@getpaseo/server/auth";
|
||||
import {
|
||||
persistDaemonPasswordHash,
|
||||
runSetPasswordCommand,
|
||||
type PromptPassword,
|
||||
} from "./set-password.js";
|
||||
|
||||
function promptSequence(values: string[]): PromptPassword {
|
||||
return async () => {
|
||||
const value = values.shift();
|
||||
if (value === undefined) {
|
||||
throw new Error("prompt called too many times");
|
||||
}
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe("daemon set-password command", () => {
|
||||
const homes: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (homes.length > 0) {
|
||||
await rm(homes.pop()!, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("sets and removes password offline when daemon is stopped without telling user to restart", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-"));
|
||||
homes.push(home);
|
||||
|
||||
const setRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["offline-secret", "offline-secret"]),
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(setRes.data.action).toBe("password_set");
|
||||
expect(setRes.data.appliedLive).toBe(false);
|
||||
expect(setRes.data.message).not.toMatch(/Restart the daemon/i);
|
||||
const hash = readPersistedConfig(home).daemon?.auth?.password;
|
||||
expect(hash).toBeTruthy();
|
||||
expect(await isBearerTokenValidAsync({ password: hash, token: "offline-secret" })).toBe(true);
|
||||
|
||||
const removeRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
remove: true,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(removeRes.data.action).toBe("password_removed");
|
||||
expect(removeRes.data.appliedLive).toBe(false);
|
||||
expect(removeRes.data.message).not.toMatch(/Restart the daemon/i);
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBeUndefined();
|
||||
});
|
||||
|
||||
test("rejects passwords over 72 UTF-8 bytes", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-len-"));
|
||||
homes.push(home);
|
||||
|
||||
const tooLong = "🔐".repeat(19);
|
||||
await expect(
|
||||
runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence([tooLong, tooLong]),
|
||||
},
|
||||
{} as Command,
|
||||
),
|
||||
).rejects.toMatchObject({ code: "INVALID_PASSWORD" });
|
||||
});
|
||||
|
||||
test("applies live via RPC when a daemon client is reachable", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-live-"));
|
||||
homes.push(home);
|
||||
const calls: Array<{ password: string | null }> = [];
|
||||
let closed = false;
|
||||
|
||||
const fakeClient = {
|
||||
getLastServerInfoMessage: () => ({
|
||||
features: { daemonPasswordManagement: true },
|
||||
}),
|
||||
setDaemonPassword: async (input: { password: string | null }) => {
|
||||
calls.push(input);
|
||||
return {
|
||||
requestId: "req-1",
|
||||
passwordConfigured: input.password !== null,
|
||||
disconnectedSessionCount: input.password !== null ? 2 : 0,
|
||||
};
|
||||
},
|
||||
close: async () => {
|
||||
closed = true;
|
||||
},
|
||||
};
|
||||
|
||||
const setRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["live-secret", "live-secret"]),
|
||||
connectLiveClient: async () => fakeClient,
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(setRes.data.action).toBe("password_set");
|
||||
expect(setRes.data.appliedLive).toBe(true);
|
||||
expect(setRes.data.disconnectedSessionCount).toBe(2);
|
||||
expect(setRes.data.message).toContain("Disconnected 2 other remote sessions.");
|
||||
expect(closed).toBe(true);
|
||||
|
||||
const removeRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
remove: true,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
connectLiveClient: async () => fakeClient,
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(removeRes.data.action).toBe("password_removed");
|
||||
expect(removeRes.data.appliedLive).toBe(true);
|
||||
expect(calls).toEqual([{ password: "live-secret" }, { password: null }]);
|
||||
});
|
||||
|
||||
test("persistDaemonPasswordHash removes empty auth object cleanly", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-persist-"));
|
||||
homes.push(home);
|
||||
|
||||
const validHash = "$2b$12$OLxyuuP9uLK30Uzc4wQX0O6liuU/Q1t5P2b0Ebf36mULvpVK3DRZW";
|
||||
persistDaemonPasswordHash(home, validHash);
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBe(validHash);
|
||||
|
||||
persistDaemonPasswordHash(home, null);
|
||||
expect(readPersistedConfig(home).daemon?.auth).toBeUndefined();
|
||||
});
|
||||
|
||||
test("does not silently write offline config when a daemon process is running but unreachable", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-running-fail-"));
|
||||
homes.push(home);
|
||||
|
||||
// Write a valid live PID lock (current process PID) pointing to an unreachable loopback port.
|
||||
await writeFile(
|
||||
path.join(home, "paseo.pid"),
|
||||
JSON.stringify({
|
||||
pid: process.pid,
|
||||
startedAt: new Date().toISOString(),
|
||||
hostname: hostname(),
|
||||
uid: typeof process.getuid === "function" ? process.getuid() : 0,
|
||||
listen: "127.0.0.1:1",
|
||||
}),
|
||||
);
|
||||
expect(await readDaemonInstance(home)).toMatchObject({
|
||||
pid: process.pid,
|
||||
listen: "127.0.0.1:1",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["never-written", "never-written"]),
|
||||
},
|
||||
{} as Command,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
code: "DAEMON_UNREACHABLE",
|
||||
message: expect.stringContaining("Cannot connect to daemon"),
|
||||
});
|
||||
|
||||
// Persisted config must NOT have been silently mutated on connection failure.
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,13 @@
|
||||
import path from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { isCancel, password as passwordPrompt } from "@clack/prompts";
|
||||
import { DaemonRpcError } from "@getpaseo/client";
|
||||
import { DAEMON_PASSWORD_MAX_UTF8_BYTES, hashDaemonPassword } from "@getpaseo/server/auth";
|
||||
import { hashDaemonPassword } from "@getpaseo/server/auth";
|
||||
import {
|
||||
readPersistedConfig,
|
||||
savePersistedConfig,
|
||||
type PersistedConfig,
|
||||
} from "@getpaseo/server/configuration";
|
||||
import { readDaemonInstance, resolvePaseoHome } from "@getpaseo/server/daemon-control";
|
||||
import { connectToDaemon, resolveDaemonPassword } from "../../utils/client.js";
|
||||
import { resolvePaseoHome } from "@getpaseo/server/daemon-control";
|
||||
import type {
|
||||
CommandError,
|
||||
CommandOptions,
|
||||
@@ -20,30 +18,15 @@ import type {
|
||||
|
||||
const CONFIG_FILENAME = "config.json";
|
||||
|
||||
export interface SetPasswordResult {
|
||||
action: "password_set" | "password_removed";
|
||||
appliedLive: boolean;
|
||||
passwordConfigured: boolean;
|
||||
disconnectedSessionCount: number;
|
||||
interface SetPasswordResult {
|
||||
action: "password_set";
|
||||
configPath: string;
|
||||
restartCommand?: string;
|
||||
restartCommand: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type PromptPassword = (message: string) => Promise<string | symbol>;
|
||||
|
||||
export interface LivePasswordClient {
|
||||
getLastServerInfoMessage(): {
|
||||
localCredentialAuth?: boolean;
|
||||
features?: { daemonPasswordManagement?: boolean };
|
||||
} | null;
|
||||
setDaemonPassword(input: {
|
||||
password: string | null;
|
||||
currentPassword?: string;
|
||||
}): Promise<{ passwordConfigured: boolean; disconnectedSessionCount: number }>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface SetPasswordOptions {
|
||||
home?: string;
|
||||
promptPassword?: PromptPassword;
|
||||
@@ -54,14 +37,16 @@ const setPasswordResultSchema: OutputSchema<SetPasswordResult> = {
|
||||
columns: [
|
||||
{ header: "STATUS", field: "action", color: () => "green" },
|
||||
{ header: "CONFIG", field: "configPath" },
|
||||
{ header: "RESTART", field: "restartCommand" },
|
||||
],
|
||||
renderHuman: (result, options: OutputOptions) => {
|
||||
const data = result.data as SetPasswordResult;
|
||||
const rows = [
|
||||
`Password written to ${data.configPath}`,
|
||||
"Restart the daemon for the change to take effect.",
|
||||
`Run: ${data.restartCommand}`,
|
||||
];
|
||||
if (options.format === "table") {
|
||||
const rows = [data.message];
|
||||
if (data.restartCommand && !data.appliedLive) {
|
||||
rows.push(`Run: ${data.restartCommand}`);
|
||||
}
|
||||
return rows.join("\n");
|
||||
}
|
||||
return data.message;
|
||||
@@ -83,19 +68,6 @@ function terminalPasswordPrompt(): PromptPassword {
|
||||
return (message) => passwordPrompt({ message });
|
||||
}
|
||||
|
||||
function validatePasswordBytes(password: string): void {
|
||||
const bytes = Buffer.byteLength(password, "utf8");
|
||||
if (bytes < 1) {
|
||||
throw createCommandError("PASSWORD_REQUIRED", "Password cannot be empty");
|
||||
}
|
||||
if (bytes > DAEMON_PASSWORD_MAX_UTF8_BYTES) {
|
||||
throw createCommandError(
|
||||
"INVALID_PASSWORD",
|
||||
`Password must be ${DAEMON_PASSWORD_MAX_UTF8_BYTES} bytes or fewer`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function promptForPassword(promptPassword: PromptPassword): Promise<string> {
|
||||
const first = await promptPassword("New daemon password");
|
||||
if (isCancel(first)) {
|
||||
@@ -104,7 +76,6 @@ async function promptForPassword(promptPassword: PromptPassword): Promise<string
|
||||
if (typeof first !== "string" || first.length === 0) {
|
||||
throw createCommandError("PASSWORD_REQUIRED", "Password cannot be empty");
|
||||
}
|
||||
validatePasswordBytes(first);
|
||||
|
||||
const second = await promptPassword("Confirm daemon password");
|
||||
if (isCancel(second)) {
|
||||
@@ -117,197 +88,47 @@ async function promptForPassword(promptPassword: PromptPassword): Promise<string
|
||||
return first;
|
||||
}
|
||||
|
||||
export function persistDaemonPasswordHash(paseoHome: string, hash: string | null): string {
|
||||
export async function setDaemonPasswordInConfig(
|
||||
newPassword: string,
|
||||
options: SetPasswordOptions = {},
|
||||
): Promise<SetPasswordResult> {
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: options.home });
|
||||
const configPath = path.join(paseoHome, CONFIG_FILENAME);
|
||||
const persisted = readPersistedConfig(paseoHome);
|
||||
const nextDaemon: NonNullable<PersistedConfig["daemon"]> = { ...persisted.daemon };
|
||||
if (hash !== null) {
|
||||
nextDaemon.auth = { ...nextDaemon.auth, password: hash };
|
||||
} else if (nextDaemon.auth) {
|
||||
const { password: _removed, ...restAuth } = nextDaemon.auth;
|
||||
if (Object.keys(restAuth).length > 0) {
|
||||
nextDaemon.auth = restAuth;
|
||||
} else {
|
||||
delete nextDaemon.auth;
|
||||
}
|
||||
}
|
||||
const { daemon: _prevDaemon, ...restPersisted } = persisted;
|
||||
const nextConfig: PersistedConfig =
|
||||
Object.keys(nextDaemon).length > 0
|
||||
? { ...restPersisted, daemon: nextDaemon }
|
||||
: (restPersisted as PersistedConfig);
|
||||
const nextConfig: PersistedConfig = {
|
||||
...persisted,
|
||||
daemon: {
|
||||
...persisted.daemon,
|
||||
auth: {
|
||||
...persisted.daemon?.auth,
|
||||
password: hashDaemonPassword(newPassword),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
savePersistedConfig(paseoHome, nextConfig);
|
||||
return configPath;
|
||||
}
|
||||
|
||||
export async function setDaemonPasswordInConfig(
|
||||
newPassword: string | null,
|
||||
options: SetPasswordOptions & { daemonRunning?: boolean } = {},
|
||||
): Promise<SetPasswordResult> {
|
||||
if (newPassword !== null) {
|
||||
validatePasswordBytes(newPassword);
|
||||
}
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: options.home });
|
||||
const configPath = persistDaemonPasswordHash(
|
||||
paseoHome,
|
||||
newPassword === null ? null : hashDaemonPassword(newPassword),
|
||||
);
|
||||
const restartCommand = `paseo daemon restart --home ${JSON.stringify(paseoHome)}`;
|
||||
const isRemove = newPassword === null;
|
||||
const baseLine = isRemove
|
||||
? `Password removed from ${configPath}`
|
||||
: `Password written to ${configPath}`;
|
||||
const message = options.daemonRunning
|
||||
? `${baseLine}\nRestart the daemon for the change to take effect.\nRun: ${restartCommand}`
|
||||
: baseLine;
|
||||
|
||||
return {
|
||||
action: isRemove ? "password_removed" : "password_set",
|
||||
appliedLive: false,
|
||||
passwordConfigured: !isRemove,
|
||||
disconnectedSessionCount: 0,
|
||||
action: "password_set",
|
||||
configPath,
|
||||
restartCommand,
|
||||
message,
|
||||
restartCommand: `paseo daemon restart --home ${JSON.stringify(paseoHome)}`,
|
||||
message: `Password written to ${configPath}\nRestart the daemon for the change to take effect.\nRun: paseo daemon restart --home ${JSON.stringify(paseoHome)}`,
|
||||
};
|
||||
}
|
||||
|
||||
function formatLiveMessage(isRemove: boolean, disconnectedSessionCount: number): string {
|
||||
if (isRemove) {
|
||||
return "Daemon password removed.";
|
||||
}
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return "Daemon password updated.\nDisconnected 1 other remote session.";
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return `Daemon password updated.\nDisconnected ${disconnectedSessionCount} other remote sessions.`;
|
||||
}
|
||||
return "Daemon password updated.";
|
||||
}
|
||||
|
||||
interface LivePasswordConnection {
|
||||
client: LivePasswordClient;
|
||||
connectedPassword?: string;
|
||||
}
|
||||
|
||||
async function tryConnectLiveClient(
|
||||
options: CommandOptions,
|
||||
): Promise<LivePasswordConnection | null> {
|
||||
if (typeof options.connectLiveClient === "function") {
|
||||
const client = await (options.connectLiveClient as () => Promise<LivePasswordClient | null>)();
|
||||
return client ? { client } : null;
|
||||
}
|
||||
const target = options.daemonTarget;
|
||||
if (target.kind === "instance") {
|
||||
const instance = await readDaemonInstance(target.home);
|
||||
if (!instance) {
|
||||
return null;
|
||||
}
|
||||
const client = await connectToDaemon({
|
||||
target,
|
||||
instance,
|
||||
timeout: 2_000,
|
||||
preferLocalCredential: true,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
connectedPassword: instance.listen ? resolveDaemonPassword(instance.listen) : undefined,
|
||||
};
|
||||
}
|
||||
const client = await connectToDaemon({
|
||||
target,
|
||||
timeout: 2_000,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
connectedPassword: resolveDaemonPassword(target.host),
|
||||
};
|
||||
}
|
||||
|
||||
function toPasswordRpcCommandError(error: DaemonRpcError): CommandError {
|
||||
if (error.code === "managed_by_env") {
|
||||
return createCommandError(
|
||||
"PASSWORD_MANAGED_BY_ENV",
|
||||
"Daemon password is controlled by PASEO_PASSWORD",
|
||||
"Update or unset PASEO_PASSWORD in the daemon's environment and restart.",
|
||||
);
|
||||
}
|
||||
return createCommandError(
|
||||
(error.code ?? "PASSWORD_UPDATE_FAILED").toUpperCase(),
|
||||
error.userMessage || error.message,
|
||||
);
|
||||
}
|
||||
|
||||
export async function runSetPasswordCommand(
|
||||
options: CommandOptions,
|
||||
_command: Command,
|
||||
): Promise<SingleResult<SetPasswordResult>> {
|
||||
const isRemove = options.remove === true;
|
||||
const newPassword = isRemove
|
||||
? null
|
||||
: await promptForPassword(
|
||||
typeof options.promptPassword === "function"
|
||||
? (options.promptPassword as PromptPassword)
|
||||
: terminalPasswordPrompt(),
|
||||
);
|
||||
const promptPassword =
|
||||
typeof options.promptPassword === "function"
|
||||
? (options.promptPassword as PromptPassword)
|
||||
: terminalPasswordPrompt();
|
||||
const newPassword = await promptForPassword(promptPassword);
|
||||
const result = await setDaemonPasswordInConfig(newPassword, {
|
||||
home: options.daemonTarget.kind === "instance" ? options.daemonTarget.home : undefined,
|
||||
});
|
||||
|
||||
const home = options.daemonTarget.kind === "instance" ? options.daemonTarget.home : undefined;
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: home });
|
||||
const configPath = path.join(paseoHome, CONFIG_FILENAME);
|
||||
|
||||
const liveConnection = await tryConnectLiveClient(options);
|
||||
if (liveConnection) {
|
||||
const { client: liveClient, connectedPassword } = liveConnection;
|
||||
try {
|
||||
const serverInfo = liveClient.getLastServerInfoMessage();
|
||||
if (serverInfo?.features?.daemonPasswordManagement === true) {
|
||||
const res = await liveClient.setDaemonPassword({
|
||||
password: newPassword,
|
||||
...(serverInfo.localCredentialAuth !== true && connectedPassword
|
||||
? { currentPassword: connectedPassword }
|
||||
: {}),
|
||||
});
|
||||
return {
|
||||
type: "single",
|
||||
data: {
|
||||
action: isRemove ? "password_removed" : "password_set",
|
||||
appliedLive: true,
|
||||
passwordConfigured: res.passwordConfigured,
|
||||
disconnectedSessionCount: res.disconnectedSessionCount,
|
||||
configPath,
|
||||
message: formatLiveMessage(isRemove, res.disconnectedSessionCount),
|
||||
},
|
||||
schema: setPasswordResultSchema,
|
||||
};
|
||||
}
|
||||
if (options.daemonTarget.kind === "endpoint") {
|
||||
throw createCommandError(
|
||||
"DAEMON_UPDATE_REQUIRED",
|
||||
"Remote daemon does not support live password updates",
|
||||
"Update the remote daemon or run paseo daemon set-password directly on that host.",
|
||||
);
|
||||
}
|
||||
// Older running daemon does not support live password management; write config.json and advise restart.
|
||||
const fallback = await setDaemonPasswordInConfig(newPassword, {
|
||||
home,
|
||||
daemonRunning: true,
|
||||
});
|
||||
return {
|
||||
type: "single",
|
||||
data: fallback,
|
||||
schema: setPasswordResultSchema,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof DaemonRpcError) {
|
||||
throw toPasswordRpcCommandError(error);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await liveClient.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const result = await setDaemonPasswordInConfig(newPassword, { home, daemonRunning: false });
|
||||
return {
|
||||
type: "single",
|
||||
data: result,
|
||||
|
||||
@@ -11,11 +11,7 @@ import {
|
||||
resolveConfigFromPersisted,
|
||||
getMainListenAddress,
|
||||
} from "@getpaseo/server/configuration";
|
||||
import {
|
||||
connectToDaemon,
|
||||
defaultConnectTimeout,
|
||||
buildDaemonConnectionCommandError,
|
||||
} from "../../utils/client.js";
|
||||
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
|
||||
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
|
||||
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
|
||||
import { describeDaemonTarget, type DaemonTarget } from "../../utils/daemon-target.js";
|
||||
@@ -61,17 +57,12 @@ async function probeDaemonStatus(
|
||||
instance: Awaited<ReturnType<typeof readDaemonInstance>>,
|
||||
local: Record<string, unknown>,
|
||||
) {
|
||||
const timeout = defaultConnectTimeout(target, 1_500);
|
||||
let connectedDaemon = "unreachable";
|
||||
let note: string | undefined;
|
||||
let live: Record<string, unknown> = {};
|
||||
let client: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
|
||||
try {
|
||||
client = await connectToDaemon({
|
||||
target,
|
||||
instance: instance ?? undefined,
|
||||
timeout,
|
||||
});
|
||||
client = await connectToDaemon({ target, instance: instance ?? undefined, timeout: 1_500 });
|
||||
} catch (error) {
|
||||
const failure = buildDaemonConnectionCommandError({ target, error });
|
||||
if (target.kind === "endpoint") throw failure;
|
||||
@@ -83,7 +74,7 @@ async function probeDaemonStatus(
|
||||
if (!client) return { connectedDaemon, note };
|
||||
try {
|
||||
let requestError: unknown;
|
||||
const status = await client.getDaemonStatus({ timeout }).catch((error: unknown) => {
|
||||
const status = await client.getDaemonStatus({ timeout: 1_500 }).catch((error: unknown) => {
|
||||
requestError = error;
|
||||
return null;
|
||||
});
|
||||
|
||||
@@ -45,28 +45,20 @@ export async function resolveWorkspaceScriptWorkspaceId(
|
||||
}
|
||||
|
||||
const cwd = resolve(options.cwd ?? process.cwd());
|
||||
let match: string | undefined;
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const payload = await client.fetchWorkspaces({
|
||||
// Activity changes should not move a workspace across the cursor.
|
||||
sort: [{ key: "project_id", direction: "asc" }],
|
||||
page: { limit: 200, cursor },
|
||||
});
|
||||
for (const workspace of payload.entries) {
|
||||
if (resolve(workspace.workspaceDirectory) !== cwd) continue;
|
||||
if (match) {
|
||||
throw {
|
||||
code: "WORKSPACE_AMBIGUOUS",
|
||||
message: `Multiple workspaces use ${cwd}`,
|
||||
details: "Pass --workspace <workspace-id> to select one.",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
match = workspace.id;
|
||||
}
|
||||
cursor = payload.pageInfo.nextCursor ?? undefined;
|
||||
} while (cursor);
|
||||
if (match) return match;
|
||||
const payload = await client.fetchWorkspaces({ page: { limit: 200 } });
|
||||
const matches = payload.entries.filter(
|
||||
(workspace) => resolve(workspace.workspaceDirectory) === cwd,
|
||||
);
|
||||
if (matches.length === 1) {
|
||||
return matches[0]!.id;
|
||||
}
|
||||
if (matches.length > 1) {
|
||||
throw {
|
||||
code: "WORKSPACE_AMBIGUOUS",
|
||||
message: `Multiple workspaces use ${cwd}`,
|
||||
details: "Pass --workspace <workspace-id> to select one.",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
throw {
|
||||
code: "WORKSPACE_NOT_FOUND",
|
||||
message: `No Paseo workspace found for ${cwd}`,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
|
||||
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
|
||||
import { resolve } from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import { resolveCallerPath } from "../../utils/paths.js";
|
||||
import type { DaemonTarget } from "../../utils/daemon-target.js";
|
||||
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
@@ -122,6 +125,18 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
|
||||
}
|
||||
}
|
||||
|
||||
// A relative --path names a directory relative to where the command runs, so
|
||||
// it is made absolute here for a local daemon, which would otherwise resolve
|
||||
// it against its own working directory. For an explicit endpoint the path is
|
||||
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
|
||||
// path can target a daemon on a different operating system, and the daemon
|
||||
// expands a leading ~ to its own home directory.
|
||||
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
|
||||
const isHomeRelative = input === "~" || input.startsWith("~/");
|
||||
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
|
||||
return daemonTarget.kind === "instance" ? resolve(input) : input;
|
||||
}
|
||||
|
||||
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
|
||||
const callerPath =
|
||||
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { Command } from "commander";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import type { CommandError, OutputSchema, SingleResult } from "../../output/index.js";
|
||||
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
|
||||
import { resolveRepositoryDirectory } from "./repository-directory.js";
|
||||
|
||||
export interface WorktreeCreateResult {
|
||||
name: string;
|
||||
@@ -39,7 +38,7 @@ export async function runCreateCommandWithDeps(
|
||||
): Promise<Pick<Awaited<ReturnType<typeof connectToDaemon>>, "createPaseoWorktree" | "close">>;
|
||||
},
|
||||
): Promise<SingleResult<WorktreeCreateResult>> {
|
||||
const cwd = resolveRepositoryDirectory(options);
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const request = buildCreateWorktreeRequest(options, cwd);
|
||||
|
||||
const client = await deps.connectToDaemon({ target: options.daemonTarget });
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Command } from "commander";
|
||||
import { basename } from "node:path";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import { shortenHomePath } from "../../utils/paths.js";
|
||||
import { resolveRepositoryDirectory } from "./repository-directory.js";
|
||||
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
|
||||
|
||||
@@ -13,6 +12,15 @@ export interface WorktreeListItem {
|
||||
agent: string;
|
||||
}
|
||||
|
||||
/** Shorten home directory in path */
|
||||
function shortenPath(path: string): string {
|
||||
const home = process.env.HOME;
|
||||
if (home && path.startsWith(home)) {
|
||||
return "~" + path.slice(home.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Extract worktree name from path */
|
||||
function extractWorktreeName(path: string): string {
|
||||
return basename(path);
|
||||
@@ -69,7 +77,7 @@ export async function runLsCommand(
|
||||
const items: WorktreeListItem[] = response.worktrees.map((wt) => ({
|
||||
name: extractWorktreeName(wt.worktreePath),
|
||||
branch: wt.branchName ?? "-",
|
||||
cwd: shortenHomePath(wt.worktreePath),
|
||||
cwd: shortenPath(wt.worktreePath),
|
||||
agent: worktreeAgentMap.get(wt.worktreePath) ?? "-",
|
||||
}));
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ export interface ConnectOptions {
|
||||
target: DaemonTarget;
|
||||
timeout?: number;
|
||||
instance?: DaemonInstance;
|
||||
preferLocalCredential?: boolean;
|
||||
}
|
||||
export function resolveClientPaseoHome(
|
||||
target: DaemonTarget,
|
||||
@@ -33,13 +32,7 @@ export function resolveClientPaseoHome(
|
||||
): string {
|
||||
return target.kind === "instance" ? target.home : resolvePaseoHome(env);
|
||||
}
|
||||
export function defaultConnectTimeout(target: DaemonTarget, directTimeout = 15_000): number {
|
||||
if (target.kind === "endpoint") {
|
||||
const host = parseHostTarget(target.host);
|
||||
if (host.kind === "socket" && host.offer) return 90_000;
|
||||
}
|
||||
return directTimeout;
|
||||
}
|
||||
const DEFAULT_TIMEOUT = 15000;
|
||||
type TransportTarget =
|
||||
| { type: "tcp"; url: string }
|
||||
| { type: "ipc"; url: string; socketPath: string };
|
||||
@@ -202,14 +195,7 @@ export function resolveDaemonPassword(host: string): string | undefined {
|
||||
export function resolveDaemonCredential(
|
||||
host: string,
|
||||
home: string,
|
||||
options?: { preferLocalCredential?: boolean },
|
||||
): { kind: "password"; password: string } | { kind: "localCredential"; token: string } | null {
|
||||
if (options?.preferLocalCredential) {
|
||||
const token = readLocalCredentialForTarget(home, host);
|
||||
if (token) return { kind: "localCredential", token };
|
||||
const password = resolveDaemonPassword(host);
|
||||
return password ? { kind: "password", password } : null;
|
||||
}
|
||||
const password = resolveDaemonPassword(host);
|
||||
if (password) return { kind: "password", password };
|
||||
const token = readLocalCredentialForTarget(home, host);
|
||||
@@ -217,7 +203,7 @@ export function resolveDaemonCredential(
|
||||
}
|
||||
|
||||
async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonClient> {
|
||||
const timeout = options.timeout ?? defaultConnectTimeout(options.target);
|
||||
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
||||
const host =
|
||||
options.target.kind === "endpoint"
|
||||
? options.target.host
|
||||
@@ -228,9 +214,7 @@ async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonCli
|
||||
})
|
||||
).listen;
|
||||
const home = resolveClientPaseoHome(options.target);
|
||||
const credential = resolveDaemonCredential(host, home, {
|
||||
preferLocalCredential: options.preferLocalCredential,
|
||||
});
|
||||
const credential = resolveDaemonCredential(host, home);
|
||||
const client = createLeanHostClient(host, {
|
||||
clientId: await getOrCreateCliClientId(home),
|
||||
clientType: "cli",
|
||||
|
||||
@@ -3,7 +3,6 @@ import { test, expect } from "vitest";
|
||||
import { selectDaemonTarget, describeDaemonTarget } from "./daemon-target.js";
|
||||
import {
|
||||
resolveDaemonCredential,
|
||||
defaultConnectTimeout,
|
||||
resolveClientPaseoHome,
|
||||
buildDaemonConnectionCommandError,
|
||||
} from "./client.js";
|
||||
@@ -22,15 +21,6 @@ test("explicit selectors win over both environment selectors", () => {
|
||||
expect(() => selectDaemonTarget({ home: "/tmp/b", host: "chosen:23456" }, {})).toThrow();
|
||||
});
|
||||
|
||||
test("slow relay connections get the full handshake budget, including status probes", () => {
|
||||
const relay = { kind: "endpoint", host: "relay://relay.example:443/srv?key=key" } as const;
|
||||
const direct = { kind: "endpoint", host: "127.0.0.1:6767" } as const;
|
||||
expect(defaultConnectTimeout(relay)).toBe(90_000);
|
||||
expect(defaultConnectTimeout(relay, 1_500)).toBe(90_000);
|
||||
expect(defaultConnectTimeout(direct)).toBe(15_000);
|
||||
expect(defaultConnectTimeout(direct, 1_500)).toBe(1_500);
|
||||
});
|
||||
|
||||
test("endpoint connections resolve local credentials from PASEO_HOME", () => {
|
||||
expect(
|
||||
resolveClientPaseoHome(
|
||||
@@ -109,19 +99,6 @@ test("CLI selects an explicit password before a matching local credential and ne
|
||||
kind: "password",
|
||||
password: "explicit",
|
||||
});
|
||||
process.env.PASEO_PASSWORD = "from-env";
|
||||
expect(
|
||||
resolveDaemonCredential("tcp://localhost:6767", home, { preferLocalCredential: true }),
|
||||
).toEqual({
|
||||
kind: "localCredential",
|
||||
token,
|
||||
});
|
||||
expect(
|
||||
resolveDaemonCredential("tcp://remote.example:6767", home, { preferLocalCredential: true }),
|
||||
).toEqual({
|
||||
kind: "password",
|
||||
password: "from-env",
|
||||
});
|
||||
} finally {
|
||||
if (previousPassword === undefined) delete process.env.PASEO_PASSWORD;
|
||||
else process.env.PASEO_PASSWORD = previousPassword;
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
|
||||
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
|
||||
import { resolve } from "node:path";
|
||||
import type { DaemonTarget } from "./daemon-target.js";
|
||||
|
||||
// Explicit endpoints interpret paths on their host. The daemon also expands ~.
|
||||
export function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
|
||||
const isHomeRelative = input === "~" || input.startsWith("~/");
|
||||
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
|
||||
return daemonTarget.kind === "instance" ? resolve(input) : input;
|
||||
}
|
||||
/**
|
||||
* Path utilities for cwd filtering in agent commands.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if `candidatePath` is the same directory as `basePath` or a descendant of it.
|
||||
@@ -32,15 +24,3 @@ export function isSameOrDescendantPath(basePath: string, candidatePath: string):
|
||||
normalizedCandidate === normalizedBase || normalizedCandidate.startsWith(normalizedBase + "/")
|
||||
);
|
||||
}
|
||||
|
||||
/** Shorten home directory in path */
|
||||
export function shortenHomePath(path: string, home = process.env.HOME): string {
|
||||
if (!home) return path;
|
||||
const windows = process.platform === "win32";
|
||||
const base = home.replace(windows ? /[\\/]+$/ : /\/+$/, "");
|
||||
if (path === home || path === base) return "~";
|
||||
if (path.startsWith(base + "/") || (windows && path.startsWith(base + "\\"))) {
|
||||
return "~" + path.slice(base.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
import assert from "node:assert";
|
||||
import { getAvailablePort } from "./helpers/network.ts";
|
||||
import { $ } from "zx";
|
||||
import { mkdtemp, rm, mkdir, realpath, writeFile } from "fs/promises";
|
||||
import { mkdtemp, rm, mkdir } from "fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { runPaseoCli, startTestDaemon, type TestDaemonContext } from "./helpers/test-daemon.ts";
|
||||
@@ -181,7 +181,7 @@ const git = promisify(execFile);
|
||||
let daemon: TestDaemonContext | undefined;
|
||||
try {
|
||||
await mkdir(repo);
|
||||
await git("git", ["init", "-b", "main", repo]);
|
||||
await git("git", ["init", repo]);
|
||||
await git("git", [
|
||||
"-C",
|
||||
repo,
|
||||
@@ -195,37 +195,8 @@ try {
|
||||
"Initial commit",
|
||||
]);
|
||||
|
||||
const home = join(await realpath(fixtureDir), "home");
|
||||
await mkdir(home);
|
||||
await writeFile(
|
||||
join(home, "config.json"),
|
||||
JSON.stringify({ version: 1, worktrees: { root: home + "-worktrees" } }),
|
||||
);
|
||||
// With an explicit endpoint, relative paths resolve from the daemon cwd.
|
||||
daemon = await startTestDaemon({ cwd: repo, paseoHome: home, workDir: repo });
|
||||
|
||||
const created = await runPaseoCli(
|
||||
daemon,
|
||||
[
|
||||
"worktree",
|
||||
"create",
|
||||
"--cwd",
|
||||
"./repository",
|
||||
"--mode",
|
||||
"branch-off",
|
||||
"--new-branch",
|
||||
"topic",
|
||||
"--base",
|
||||
"main",
|
||||
"--json",
|
||||
],
|
||||
{ cwd: fixtureDir },
|
||||
);
|
||||
assert.strictEqual(created.exitCode, 0, created.stderr);
|
||||
const { worktreePath } = JSON.parse(created.stdout);
|
||||
const source = await git("git", ["-C", repo, "rev-parse", "HEAD"]);
|
||||
const checkout = await git("git", ["-C", worktreePath, "rev-parse", "HEAD"]);
|
||||
assert.strictEqual(checkout.stdout, source.stdout);
|
||||
daemon = await startTestDaemon({ cwd: repo });
|
||||
|
||||
for (const args of [
|
||||
["worktree", "ls", "--json"],
|
||||
@@ -239,10 +210,7 @@ try {
|
||||
env: { FORCE_COLOR: undefined },
|
||||
});
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(result.stdout).map((row: { cwd: string }) => row.cwd),
|
||||
[worktreePath],
|
||||
);
|
||||
assert.deepStrictEqual(JSON.parse(result.stdout), []);
|
||||
}
|
||||
|
||||
for (const args of [
|
||||
|
||||
@@ -213,16 +213,7 @@ try {
|
||||
return session;
|
||||
});
|
||||
|
||||
// Exit just this provider during a turn while the host is up to prove failure reporting
|
||||
// remains active. An idle exit of a resumable session closes cleanly instead.
|
||||
await daemon.client.sendMessage(crashing.id, "Hold the turn open.");
|
||||
// Wait for the provider itself to log the prompt, not just for the agent to report running.
|
||||
await waitFor(async () => {
|
||||
const events = await readEvents();
|
||||
return events.find(
|
||||
(event) => event.type === "prompt" && event.sessionId === sessions[2].sessionId,
|
||||
);
|
||||
}, "crashing provider did not receive its prompt");
|
||||
// Exit just this provider while the host is up to prove failure reporting remains active.
|
||||
process.kill(sessions[2].pid, "SIGTERM");
|
||||
await waitFor(async () => {
|
||||
const { agent } = (await daemon!.client.fetchAgent(crashing.id)) ?? {};
|
||||
@@ -269,11 +260,6 @@ try {
|
||||
assert.deepEqual(
|
||||
(await readEvents()).filter((event) => event.type === "prompt"),
|
||||
[
|
||||
{
|
||||
type: "prompt",
|
||||
sessionId: sessions[2].sessionId,
|
||||
text: "Hold the turn open.",
|
||||
},
|
||||
{
|
||||
type: "prompt",
|
||||
sessionId: sessions[1].sessionId,
|
||||
|
||||
@@ -16,20 +16,10 @@
|
||||
*/
|
||||
|
||||
import assert from "node:assert";
|
||||
import { join, sep } from "node:path";
|
||||
import { isSameOrDescendantPath, shortenHomePath } from "../src/utils/paths.ts";
|
||||
import { isSameOrDescendantPath } from "../src/utils/paths.ts";
|
||||
|
||||
console.log("=== CWD Filter Path Tests ===\n");
|
||||
|
||||
{
|
||||
const home = join(sep, "users", "alex");
|
||||
const sibling = join(home + "-backup", "repo");
|
||||
assert.equal(shortenHomePath(sibling, home), sibling);
|
||||
assert.equal(shortenHomePath(home, home), "~");
|
||||
assert.equal(shortenHomePath(join(home, "repo"), home), `~${sep}repo`);
|
||||
assert.equal(shortenHomePath(join(home, "repo"), home + sep), `~${sep}repo`);
|
||||
}
|
||||
|
||||
// Test 1: Unix exact match
|
||||
{
|
||||
console.log("Test 1: Unix exact match");
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, realpath } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createTempDirs, runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts";
|
||||
|
||||
const dirs = await createTempDirs();
|
||||
const caller = join(dirs.workDir, "caller");
|
||||
const source = join(dirs.workDir, "source.git");
|
||||
const gitConfig = join(dirs.paseoHome, ".gitconfig");
|
||||
const remote = "https://example.test/team/fixture.git";
|
||||
await mkdir(caller);
|
||||
execFileSync("git", ["init", "--bare", "--quiet", source]);
|
||||
execFileSync("git", [
|
||||
"config",
|
||||
"--file",
|
||||
gitConfig,
|
||||
`url.${source.replaceAll("\\", "/")}.insteadOf`,
|
||||
remote,
|
||||
]);
|
||||
const ctx = await startTestDaemon({
|
||||
...dirs,
|
||||
cwd: dirs.workDir,
|
||||
env: { GIT_CONFIG_GLOBAL: gitConfig },
|
||||
});
|
||||
try {
|
||||
for (const [args, parent] of [
|
||||
[[], caller],
|
||||
[["--host", ctx.wsUrl], dirs.workDir],
|
||||
] as const) {
|
||||
const result = await runPaseoCli(
|
||||
ctx,
|
||||
["clone", remote, "--dir", "./repos", "--json", ...args],
|
||||
{ cwd: caller },
|
||||
);
|
||||
assert.equal(result.exitCode, 0, result.stderr);
|
||||
const checkout = JSON.parse(result.stdout).checkoutPath;
|
||||
assert.equal(await realpath(checkout), join(await realpath(parent), "repos", "fixture"));
|
||||
assert.equal(
|
||||
execFileSync("git", ["-C", checkout, "rev-parse", "--is-inside-work-tree"], {
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
"true",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await ctx.stop();
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createPaseoClient } from "@getpaseo/client";
|
||||
import { createE2ETestContext } from "./helpers/test-daemon.ts";
|
||||
|
||||
const ctx = await createE2ETestContext();
|
||||
const sdk = createPaseoClient({ url: `${ctx.wsUrl}/ws`, reconnect: { enabled: false } });
|
||||
|
||||
try {
|
||||
await sdk.connect();
|
||||
for (let i = 0; i < 201; i++) {
|
||||
const path = join(ctx.workDir, String(i));
|
||||
await mkdir(path);
|
||||
await writeFile(
|
||||
join(path, "paseo.json"),
|
||||
JSON.stringify({ scripts: { check: { command: "echo ok" } } }),
|
||||
);
|
||||
await sdk.workspaces.create({ source: { kind: "directory", path } });
|
||||
}
|
||||
|
||||
const first = await sdk.workspaces.list({ page: { limit: 200 } });
|
||||
assert.ok(first.pageInfo.nextCursor);
|
||||
const next = await sdk.workspaces.list({
|
||||
page: { cursor: first.pageInfo.nextCursor, limit: 200 },
|
||||
});
|
||||
assert.equal(next.entries.length, 1);
|
||||
const { id, workspaceDirectory } = next.entries[0]!;
|
||||
const listByCwd = () => ctx.paseo(["script", "ls", "--cwd", workspaceDirectory, "--json"]);
|
||||
const unique = await listByCwd();
|
||||
assert.equal(unique.exitCode, 0, unique.stderr);
|
||||
assert.deepEqual(
|
||||
JSON.parse(unique.stdout).map((script: { scriptName: string }) => script.scriptName),
|
||||
["check"],
|
||||
);
|
||||
|
||||
await sdk.workspaces.create({
|
||||
source: { kind: "directory", path: workspaceDirectory },
|
||||
title: "Second workspace",
|
||||
});
|
||||
const ambiguous = await listByCwd();
|
||||
assert.equal(ambiguous.exitCode, 1);
|
||||
assert.equal(JSON.parse(ambiguous.stderr).error.code, "WORKSPACE_AMBIGUOUS");
|
||||
const explicit = await ctx.paseo(["script", "ls", "--workspace", id, "--json"]);
|
||||
assert.equal(explicit.exitCode, 0, explicit.stderr);
|
||||
assert.deepEqual(JSON.parse(explicit.stdout), JSON.parse(unique.stdout));
|
||||
} finally {
|
||||
await sdk.close();
|
||||
await ctx.stop();
|
||||
}
|
||||
@@ -56,8 +56,6 @@ function spawnRelayDevServer(port: number): ChildProcess {
|
||||
String(port),
|
||||
"--live-reload=false",
|
||||
"--show-interactive-dev-session=false",
|
||||
"--var",
|
||||
"PASEO_RELAY_UPSTREAM:",
|
||||
],
|
||||
{
|
||||
cwd: relayDir,
|
||||
@@ -119,41 +117,6 @@ async function stopRelayProcess(relayProcess: ChildProcess): Promise<void> {
|
||||
await waitForProcessExit(relayProcess, Date.now() + 2000);
|
||||
}
|
||||
|
||||
async function withSlowRelay<T>(
|
||||
relayPort: number,
|
||||
run: (endpoint: string) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const clients = new Set<net.Socket>();
|
||||
const proxy = net.createServer((client) => {
|
||||
clients.add(client);
|
||||
// Delay the client handshake past the old 15-second command deadline.
|
||||
const connect = setTimeout(() => {
|
||||
const relay = net.connect(relayPort, "127.0.0.1");
|
||||
relay.on("error", () => client.destroy());
|
||||
relay.on("close", () => client.destroy());
|
||||
client.on("close", () => relay.destroy());
|
||||
client.pipe(relay).pipe(client);
|
||||
}, 17_000);
|
||||
client.on("error", () => client.destroy());
|
||||
client.on("close", () => {
|
||||
clearTimeout(connect);
|
||||
clients.delete(client);
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
proxy.once("error", reject);
|
||||
proxy.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
try {
|
||||
const address = proxy.address();
|
||||
if (!address || typeof address === "string") throw new Error("Relay proxy did not bind TCP");
|
||||
return await run(`127.0.0.1:${address.port}`);
|
||||
} finally {
|
||||
for (const client of clients) client.destroy();
|
||||
await new Promise<void>((resolve) => proxy.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
async function probeRelayConnection(offerUrl: string): Promise<boolean> {
|
||||
const offer = parseConnectionOfferFromUrl(offerUrl);
|
||||
if (!offer) return false;
|
||||
@@ -264,30 +227,4 @@ async function waitForDaemonRelayRegistered(offerUrl: string, timeoutMs = 30_000
|
||||
expect(Array.isArray(relayAgents)).toBe(true);
|
||||
expect(relayAgents.length).toBe(directAgents.length);
|
||||
}, 60_000);
|
||||
|
||||
it("runs status and ls when the relay handshake takes longer than 15 seconds", async () => {
|
||||
const context = ctx;
|
||||
if (!context) throw new Error("test context not initialized");
|
||||
|
||||
const direct = await context.paseo(["ls", "--json"]);
|
||||
expect(direct.exitCode, direct.stderr).toBe(0);
|
||||
await withSlowRelay(relayPort, async (endpoint) => {
|
||||
const offer = await generateLocalPairingOffer({
|
||||
paseoHome: context.paseoHome,
|
||||
relayEnabled: true,
|
||||
relayEndpoint: `127.0.0.1:${relayPort}`,
|
||||
relayPublicEndpoint: endpoint,
|
||||
includeQr: false,
|
||||
});
|
||||
if (!offer.url) throw new Error("generateLocalPairingOffer returned no URL");
|
||||
const [status, agents] = await Promise.all([
|
||||
context.paseo(["--host", offer.url, "daemon", "status", "--json"], { timeout: 35_000 }),
|
||||
context.paseo(["--host", offer.url, "ls", "--json"], { timeout: 35_000 }),
|
||||
]);
|
||||
expect(status.exitCode, status.stdout || status.stderr).toBe(0);
|
||||
expect(JSON.parse(status.stdout).connectedDaemon).toBe("reachable");
|
||||
expect(agents.exitCode, agents.stdout || agents.stderr).toBe(0);
|
||||
expect(JSON.parse(agents.stdout)).toEqual(JSON.parse(direct.stdout));
|
||||
});
|
||||
}, 45_000);
|
||||
});
|
||||
|
||||
@@ -135,7 +135,6 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.terminalChunkedReplay]: true,
|
||||
[CLIENT_CAPS.binaryChunkingV1]: true,
|
||||
[CLIENT_CAPS.helloRejection]: true,
|
||||
[CLIENT_CAPS.evolvableHelloRejection]: true,
|
||||
[CLIENT_CAPS.ownedSubscriptions]: true,
|
||||
[CLIENT_CAPS.allProviders]: true,
|
||||
[CLIENT_CAPS.selectiveAgentTimeline]: true,
|
||||
|
||||
@@ -139,7 +139,6 @@ import type {
|
||||
DaemonTailscaleSetResponse,
|
||||
DaemonGetPairingOfferResponse,
|
||||
DaemonConfigReloadResponse,
|
||||
DaemonAuthPasswordSetResponse,
|
||||
DiagnosticsResponse,
|
||||
AgentRewindResponseMessage,
|
||||
AgentProviderSwitchRequest,
|
||||
@@ -293,194 +292,26 @@ type HelloAuth =
|
||||
| { kind: "localCredential"; token: string }
|
||||
| undefined;
|
||||
|
||||
export interface DaemonHelloRejection {
|
||||
readonly reason: string;
|
||||
readonly accepts: readonly string[];
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
export type DaemonAuthFailureReason = "password_required" | "incorrect_password";
|
||||
|
||||
const MAX_HELLO_REJECTION_TOKEN_CODE_POINTS = 64;
|
||||
const MAX_HELLO_REJECTION_ACCEPTS = 16;
|
||||
const MAX_HELLO_REJECTION_MESSAGE_CODE_POINTS = 200;
|
||||
export class DaemonAuthenticationError extends Error {
|
||||
readonly reason: DaemonAuthFailureReason;
|
||||
|
||||
// Strip ANSI CSI sequences without control-character regex literals.
|
||||
function stripAnsiCsi(input: string): string {
|
||||
let out = "";
|
||||
let i = 0;
|
||||
while (i < input.length) {
|
||||
if (input.charCodeAt(i) === 0x1b && input.charCodeAt(i + 1) === 0x5b) {
|
||||
i += 2;
|
||||
while (i < input.length) {
|
||||
const code = input.charCodeAt(i);
|
||||
i += 1;
|
||||
if (code >= 0x40 && code <= 0x7e) break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out += input[i]!;
|
||||
i += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isBidiOrFormatCodePoint(cp: number): boolean {
|
||||
return (
|
||||
(cp >= 0x200b && cp <= 0x200f) ||
|
||||
(cp >= 0x202a && cp <= 0x202e) ||
|
||||
(cp >= 0x2060 && cp <= 0x2069) ||
|
||||
cp === 0x061c ||
|
||||
cp === 0xfeff
|
||||
);
|
||||
}
|
||||
|
||||
function stripControlAndFormat(input: string, replaceWhitespaceControlsWithSpace: boolean): string {
|
||||
let out = "";
|
||||
for (const ch of stripAnsiCsi(input)) {
|
||||
const cp = ch.codePointAt(0);
|
||||
if (cp === undefined) continue;
|
||||
if (
|
||||
replaceWhitespaceControlsWithSpace &&
|
||||
(cp === 0x09 || cp === 0x0a || cp === 0x0b || cp === 0x0c || cp === 0x0d)
|
||||
) {
|
||||
out += " ";
|
||||
continue;
|
||||
}
|
||||
if (cp <= 0x1f || cp === 0x7f || isBidiOrFormatCodePoint(cp)) {
|
||||
continue;
|
||||
}
|
||||
out += ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function truncateCodePoints(text: string, maxCodePoints: number, ellipsis?: string): string {
|
||||
const codePoints = Array.from(text);
|
||||
if (codePoints.length <= maxCodePoints) return text;
|
||||
if (!ellipsis) return codePoints.slice(0, maxCodePoints).join("");
|
||||
const ellipsisLen = Array.from(ellipsis).length;
|
||||
const keep = Math.max(0, maxCodePoints - ellipsisLen);
|
||||
return `${codePoints.slice(0, keep).join("").trimEnd()}${ellipsis}`;
|
||||
}
|
||||
|
||||
function sanitizeHelloRejectionToken(raw: string): string {
|
||||
const cleaned = stripControlAndFormat(raw, false).trim();
|
||||
return truncateCodePoints(cleaned, MAX_HELLO_REJECTION_TOKEN_CODE_POINTS);
|
||||
}
|
||||
|
||||
function sanitizeHelloRejectionMessage(raw: string | undefined): string | undefined {
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const cleaned = stripControlAndFormat(raw, true).replace(/\s+/g, " ").trim();
|
||||
if (cleaned.length === 0) return undefined;
|
||||
return truncateCodePoints(cleaned, MAX_HELLO_REJECTION_MESSAGE_CODE_POINTS, "…");
|
||||
}
|
||||
|
||||
export function normalizeHelloRejection(raw: {
|
||||
reason: string;
|
||||
accepts?: readonly string[];
|
||||
message?: string;
|
||||
}): DaemonHelloRejection {
|
||||
const reason = sanitizeHelloRejectionToken(raw.reason) || "connection_refused";
|
||||
const accepts: string[] = [];
|
||||
if (reason !== "incompatible_protocol" && Array.isArray(raw.accepts)) {
|
||||
const seen = new Set<string>();
|
||||
for (const entry of raw.accepts) {
|
||||
if (typeof entry !== "string") continue;
|
||||
const token = sanitizeHelloRejectionToken(entry);
|
||||
if (token.length === 0 || seen.has(token)) continue;
|
||||
seen.add(token);
|
||||
accepts.push(token);
|
||||
if (accepts.length >= MAX_HELLO_REJECTION_ACCEPTS) break;
|
||||
}
|
||||
}
|
||||
const message = sanitizeHelloRejectionMessage(raw.message);
|
||||
return message !== undefined ? { reason, accepts, message } : { reason, accepts };
|
||||
}
|
||||
|
||||
function describeHelloRejection(rejection: DaemonHelloRejection): string {
|
||||
switch (rejection.reason) {
|
||||
case "password_required":
|
||||
return "Password required";
|
||||
case "incorrect_password":
|
||||
return "Incorrect password";
|
||||
case "incompatible_protocol":
|
||||
return "Incompatible protocol version";
|
||||
default:
|
||||
return `Connection refused (${rejection.reason})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DaemonHelloRejectedError extends Error {
|
||||
readonly rejection: DaemonHelloRejection;
|
||||
readonly reason: string;
|
||||
readonly accepts: readonly string[];
|
||||
|
||||
constructor(rejection: DaemonHelloRejection, message?: string) {
|
||||
super(message ?? describeHelloRejection(rejection));
|
||||
this.name = "DaemonHelloRejectedError";
|
||||
this.rejection = rejection;
|
||||
this.reason = rejection.reason;
|
||||
this.accepts = rejection.accepts;
|
||||
}
|
||||
}
|
||||
|
||||
export class DaemonAuthenticationError extends DaemonHelloRejectedError {
|
||||
override readonly reason: DaemonAuthFailureReason;
|
||||
|
||||
constructor(reason: DaemonAuthFailureReason, rejection?: DaemonHelloRejection) {
|
||||
const normalized = rejection ?? normalizeHelloRejection({ reason, accepts: ["password"] });
|
||||
super(normalized, reason === "password_required" ? "Password required" : "Incorrect password");
|
||||
constructor(reason: DaemonAuthFailureReason) {
|
||||
super(reason === "password_required" ? "Password required" : "Incorrect password");
|
||||
this.name = "DaemonAuthenticationError";
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
export function createHelloRejectedError(
|
||||
rejection: DaemonHelloRejection,
|
||||
): DaemonHelloRejectedError {
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return new DaemonAuthenticationError(rejection.reason, rejection);
|
||||
}
|
||||
return new DaemonHelloRejectedError(rejection);
|
||||
}
|
||||
|
||||
export function getDaemonHelloRejection(error: unknown): DaemonHelloRejection | null {
|
||||
return error instanceof DaemonHelloRejectedError ? error.rejection : null;
|
||||
}
|
||||
|
||||
export function getDaemonAuthFailureReason(error: unknown): DaemonAuthFailureReason | null {
|
||||
return error instanceof DaemonAuthenticationError ? error.reason : null;
|
||||
}
|
||||
|
||||
function toAuthFailureReason(
|
||||
rejection: DaemonHelloRejection | null,
|
||||
): DaemonAuthFailureReason | null {
|
||||
if (!rejection) return null;
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return rejection.reason;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function helloRejectionFromLegacyClose(event: unknown): DaemonHelloRejection | null {
|
||||
if (!event || typeof event !== "object") return null;
|
||||
const reason = "reason" in event && typeof event.reason === "string" ? event.reason : "";
|
||||
const code = "code" in event && typeof event.code === "number" ? event.code : null;
|
||||
if (reason === "Password required") {
|
||||
return normalizeHelloRejection({ reason: "password_required", accepts: ["password"] });
|
||||
}
|
||||
if (reason === "Incorrect password") {
|
||||
return normalizeHelloRejection({ reason: "incorrect_password", accepts: ["password"] });
|
||||
}
|
||||
// COMPAT(evolvableHelloRejection): added in v0.20.0, remove after 2027-06-03.
|
||||
// Daemons older than evolvable_hello_rejection close with 4003 without a hello.rejected frame.
|
||||
if (
|
||||
reason === "Incompatible protocol version" ||
|
||||
(code === 4003 && reason.toLowerCase().includes("incompatible protocol"))
|
||||
) {
|
||||
return normalizeHelloRejection({ reason: "incompatible_protocol", accepts: [] });
|
||||
}
|
||||
function authFailureFromLegacyClose(event: unknown): DaemonAuthFailureReason | null {
|
||||
if (!event || typeof event !== "object" || !("reason" in event)) return null;
|
||||
if (event.reason === "Password required") return "password_required";
|
||||
if (event.reason === "Incorrect password") return "incorrect_password";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1374,7 +1205,7 @@ export class DaemonConnectionError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class DaemonRpcError extends Error {
|
||||
class DaemonRpcError extends Error {
|
||||
readonly requestId: string;
|
||||
readonly requestType?: string;
|
||||
readonly code?: string;
|
||||
@@ -1765,7 +1596,7 @@ export class DaemonClientCore {
|
||||
private lastErrorValue: string | null = null;
|
||||
private destinationServerId: string | undefined;
|
||||
private connectionFailure: Error | undefined;
|
||||
private helloRejectionValue: DaemonHelloRejection | null = null;
|
||||
private authFailureReasonValue: DaemonAuthFailureReason | null = null;
|
||||
private connectionState: ConnectionState = { status: "idle" };
|
||||
private readonly diffStreams = new DiffStreamRouter({
|
||||
modern: (compare) =>
|
||||
@@ -1937,7 +1768,7 @@ export class DaemonClientCore {
|
||||
trigger === "STALE_CONNECT_ON_FOREGROUND" ? "Stale connection attempt" : "Reconnecting",
|
||||
);
|
||||
this.lastServerInfoMessage = null;
|
||||
this.helloRejectionValue = null;
|
||||
this.authFailureReasonValue = null;
|
||||
const attempt: ConnectionAttempt = { startedAt: Date.now(), timeout: null };
|
||||
this.connectionAttempt = attempt;
|
||||
this.updateConnectionState(
|
||||
@@ -2022,14 +1853,14 @@ export class DaemonClientCore {
|
||||
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
||||
this.pendingGenericTransportErrorTimeout = null;
|
||||
}
|
||||
this.helloRejectionValue ??= helloRejectionFromLegacyClose(event);
|
||||
this.authFailureReasonValue ??= authFailureFromLegacyClose(event);
|
||||
// An endpoint security policy close cannot be fixed by retrying.
|
||||
const securityFailure = describeEndpointSecurityClose(event);
|
||||
if (securityFailure) this.setReconnectEnabled(false);
|
||||
// A transport error may already have scheduled this socket's retry before its close.
|
||||
if (this.reconnectTimeout && !securityFailure && !this.helloRejectionValue) return;
|
||||
const reason = this.helloRejectionValue
|
||||
? describeHelloRejection(this.helloRejectionValue)
|
||||
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
|
||||
const reason = this.authFailureReasonValue
|
||||
? new DaemonAuthenticationError(this.authFailureReasonValue).message
|
||||
: (securityFailure ?? describeTransportClose(event));
|
||||
if (reason) {
|
||||
this.lastErrorValue = reason;
|
||||
@@ -2397,12 +2228,8 @@ export class DaemonClientCore {
|
||||
return this.lastErrorValue;
|
||||
}
|
||||
|
||||
get helloRejection(): DaemonHelloRejection | null {
|
||||
return this.helloRejectionValue;
|
||||
}
|
||||
|
||||
get authFailureReason(): DaemonAuthFailureReason | null {
|
||||
return toAuthFailureReason(this.helloRejectionValue);
|
||||
return this.authFailureReasonValue;
|
||||
}
|
||||
|
||||
getLastLivenessRttMs(): number | null {
|
||||
@@ -6861,21 +6688,6 @@ export class DaemonClientCore {
|
||||
});
|
||||
}
|
||||
|
||||
async setDaemonPassword(
|
||||
input: { password: string | null; currentPassword?: string },
|
||||
requestId?: string,
|
||||
): Promise<DaemonAuthPasswordSetResponse["payload"]> {
|
||||
this.requireDaemonPasswordManagementSupport();
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"daemon.auth.password.set.response">({
|
||||
requestId,
|
||||
message: {
|
||||
type: "daemon.auth.password.set.request",
|
||||
password: input.password,
|
||||
...(input.currentPassword !== undefined ? { currentPassword: input.currentPassword } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async connectHub(
|
||||
hubUrl: string,
|
||||
token: string,
|
||||
@@ -8209,13 +8021,6 @@ export class DaemonClientCore {
|
||||
}
|
||||
}
|
||||
|
||||
private requireDaemonPasswordManagementSupport(): void {
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
if (this.lastServerInfoMessage?.features?.daemonPasswordManagement !== true) {
|
||||
throw new Error("Update the host to manage the daemon password.");
|
||||
}
|
||||
}
|
||||
|
||||
private resolveTransportUrlForAttempt(): string {
|
||||
return this.config.url;
|
||||
}
|
||||
@@ -8430,10 +8235,15 @@ export class DaemonClientCore {
|
||||
}
|
||||
|
||||
if (parsed.data.type === "hello.rejected") {
|
||||
const rejection = normalizeHelloRejection(parsed.data);
|
||||
this.traceInstant("paseo.connection.rejected", { reason: rejection.reason });
|
||||
this.helloRejectionValue = rejection;
|
||||
this.lastErrorValue = describeHelloRejection(rejection);
|
||||
this.traceInstant("paseo.connection.rejected", { reason: parsed.data.reason });
|
||||
const reasonMessage = {
|
||||
password_required: "Password required",
|
||||
incorrect_password: "Incorrect password",
|
||||
incompatible_protocol: "Incompatible protocol version",
|
||||
};
|
||||
this.lastErrorValue = reasonMessage[parsed.data.reason];
|
||||
this.authFailureReasonValue =
|
||||
parsed.data.reason === "incompatible_protocol" ? null : parsed.data.reason;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -8707,7 +8517,7 @@ export class DaemonClientCore {
|
||||
this.terminalStreams.clearSlots();
|
||||
this.lastServerInfoMessage = null;
|
||||
|
||||
if (this.helloRejectionValue) this.setReconnectEnabled(false);
|
||||
if (this.authFailureReasonValue) this.setReconnectEnabled(false);
|
||||
|
||||
if (wasDisposed) {
|
||||
this.rejectConnect(new Error(reason ?? "Daemon client is disposed"));
|
||||
@@ -8716,8 +8526,8 @@ export class DaemonClientCore {
|
||||
this.emitDisconnectedStateForReconnect(reason, input);
|
||||
if (!this.shouldReconnect || this.config.reconnect?.enabled === false) {
|
||||
this.rejectConnect(
|
||||
this.helloRejectionValue
|
||||
? createHelloRejectedError(this.helloRejectionValue)
|
||||
this.authFailureReasonValue
|
||||
? new DaemonAuthenticationError(this.authFailureReasonValue)
|
||||
: (input?.failure ?? new Error(reason ?? "Transport disconnected before connect")),
|
||||
);
|
||||
return;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user